repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
kaazing/netx
ws/src/test/java/org/kaazing/netx/ws/specification/ext/primary/PrimaryExtensionSpi.java
// Path: ws/src/main/java/org/kaazing/netx/ws/internal/ext/flyweight/Opcode.java // public enum Opcode { // BINARY, CLOSE, CONTINUATION, PING, PONG, TEXT; // // public static Opcode fromInt(int value) { // switch (value) { // case 0x00: // return CONTINUATION; // case 0x01: // return TEXT; // case 0x02: // return BINARY; // case 0x08: // return CLOSE; // case 0x09: // return PING; // case 0x0A: // return PONG; // default: // throw new IllegalStateException(format("Unrecognized WebSocket OpCode %x", value)); // } // }; // // public static int toInt(Opcode value) { // switch (value) { // case CONTINUATION: // return 0x00; // case TEXT: // return 0x01; // case BINARY: // return 0x02; // case CLOSE: // return 0x08; // case PING: // return 0x09; // case PONG: // return 0x0A; // default: // throw new IllegalStateException(format("Unrecognised OpCode %s", value)); // } // }; // }
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.kaazing.netx.ws.internal.ext.WebSocketContext; import org.kaazing.netx.ws.internal.ext.WebSocketExtensionSpi; import org.kaazing.netx.ws.internal.ext.flyweight.Frame; import org.kaazing.netx.ws.internal.ext.flyweight.FrameRW; import org.kaazing.netx.ws.internal.ext.flyweight.Opcode; import org.kaazing.netx.ws.internal.ext.function.WebSocketFrameConsumer;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.specification.ext.primary; public class PrimaryExtensionSpi extends WebSocketExtensionSpi { private static final Charset UTF_8 = Charset.forName("UTF-8"); private final FrameRW outgoingFrame = new FrameRW().wrap(ByteBuffer.allocate(1024), 0); private final FrameRW incomingFrame = new FrameRW().wrap(ByteBuffer.allocate(1024), 0); { onTextReceived = new WebSocketFrameConsumer() { @Override public void accept(WebSocketContext context, Frame frame) throws IOException {
// Path: ws/src/main/java/org/kaazing/netx/ws/internal/ext/flyweight/Opcode.java // public enum Opcode { // BINARY, CLOSE, CONTINUATION, PING, PONG, TEXT; // // public static Opcode fromInt(int value) { // switch (value) { // case 0x00: // return CONTINUATION; // case 0x01: // return TEXT; // case 0x02: // return BINARY; // case 0x08: // return CLOSE; // case 0x09: // return PING; // case 0x0A: // return PONG; // default: // throw new IllegalStateException(format("Unrecognized WebSocket OpCode %x", value)); // } // }; // // public static int toInt(Opcode value) { // switch (value) { // case CONTINUATION: // return 0x00; // case TEXT: // return 0x01; // case BINARY: // return 0x02; // case CLOSE: // return 0x08; // case PING: // return 0x09; // case PONG: // return 0x0A; // default: // throw new IllegalStateException(format("Unrecognised OpCode %s", value)); // } // }; // } // Path: ws/src/test/java/org/kaazing/netx/ws/specification/ext/primary/PrimaryExtensionSpi.java import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import org.kaazing.netx.ws.internal.ext.WebSocketContext; import org.kaazing.netx.ws.internal.ext.WebSocketExtensionSpi; import org.kaazing.netx.ws.internal.ext.flyweight.Frame; import org.kaazing.netx.ws.internal.ext.flyweight.FrameRW; import org.kaazing.netx.ws.internal.ext.flyweight.Opcode; import org.kaazing.netx.ws.internal.ext.function.WebSocketFrameConsumer; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.specification.ext.primary; public class PrimaryExtensionSpi extends WebSocketExtensionSpi { private static final Charset UTF_8 = Charset.forName("UTF-8"); private final FrameRW outgoingFrame = new FrameRW().wrap(ByteBuffer.allocate(1024), 0); private final FrameRW incomingFrame = new FrameRW().wrap(ByteBuffer.allocate(1024), 0); { onTextReceived = new WebSocketFrameConsumer() { @Override public void accept(WebSocketContext context, Frame frame) throws IOException {
Opcode opcode = frame.opcode();
kaazing/netx
ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/DataTest.java
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTestUtil.java // public static byte[] fromHex(final String string) { // return fromHexByteArray(string.getBytes(UTF8_CHARSET)); // }
import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.kaazing.netx.ws.internal.ext.flyweight.FrameTestUtil.fromHex; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.BINARY; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.CONTINUATION; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.TEXT; import java.nio.ByteBuffer; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theory;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; public class DataTest extends FrameTest { enum Fin { SET, UNSET; } @DataPoint public static final Fin FIN_SET = Fin.SET; @DataPoint public static final Fin FIN_UNSET = Fin.UNSET; @Theory public void shouldDecodeTextWithEmptyPayload(int offset, Fin fin) throws Exception { FrameRW textFrame = new FrameRW().wrap(buffer, offset); textFrame.fin((fin == Fin.SET) ? true : false); textFrame.opcode(TEXT); textFrame.payloadPut((ByteBuffer) null, offset, 0); assertEquals(Opcode.TEXT, textFrame.opcode()); assertEquals(0, textFrame.payloadLength()); assertEquals(fin == Fin.SET, textFrame.fin()); } @Theory public void shouldDecodeTextWithValidPayload(int offset, Fin fin) throws Exception { FrameRW textFrame = new FrameRW().wrap(buffer, offset); ByteBuffer bytes = ByteBuffer.allocate(1000); bytes.put("e acute (0xE9 or 0x11101001): ".getBytes(UTF_8)); bytes.put((byte) 0xC3).put((byte) 0xA9); bytes.put(", Euro sign: ".getBytes(UTF_8));
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTestUtil.java // public static byte[] fromHex(final String string) { // return fromHexByteArray(string.getBytes(UTF8_CHARSET)); // } // Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/DataTest.java import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.kaazing.netx.ws.internal.ext.flyweight.FrameTestUtil.fromHex; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.BINARY; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.CONTINUATION; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.TEXT; import java.nio.ByteBuffer; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theory; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; public class DataTest extends FrameTest { enum Fin { SET, UNSET; } @DataPoint public static final Fin FIN_SET = Fin.SET; @DataPoint public static final Fin FIN_UNSET = Fin.UNSET; @Theory public void shouldDecodeTextWithEmptyPayload(int offset, Fin fin) throws Exception { FrameRW textFrame = new FrameRW().wrap(buffer, offset); textFrame.fin((fin == Fin.SET) ? true : false); textFrame.opcode(TEXT); textFrame.payloadPut((ByteBuffer) null, offset, 0); assertEquals(Opcode.TEXT, textFrame.opcode()); assertEquals(0, textFrame.payloadLength()); assertEquals(fin == Fin.SET, textFrame.fin()); } @Theory public void shouldDecodeTextWithValidPayload(int offset, Fin fin) throws Exception { FrameRW textFrame = new FrameRW().wrap(buffer, offset); ByteBuffer bytes = ByteBuffer.allocate(1000); bytes.put("e acute (0xE9 or 0x11101001): ".getBytes(UTF_8)); bytes.put((byte) 0xC3).put((byte) 0xA9); bytes.put(", Euro sign: ".getBytes(UTF_8));
bytes.put(fromHex("e282ac"));
kaazing/netx
http.bridge/itest/src/main/java/org/kaazing/netx/http/bridge/itest/internal/TestApplet.java
// Path: api/src/main/java/org/kaazing/netx/URLConnectionHelper.java // public final class URLConnectionHelper { // // private final Map<String, URLConnectionHelperSpi> helpers; // // /** // * Converts a {@code URI} to an {@code URL} with behavior registered by protocol scheme. // * // * If no behavior has been registered, then the default Java behavior is used instead. // * Requires the security permission {@code NetPermission("specifyStreamHandler")} for non-default behavior. // * // * @param location the location to convert // * // * @return a URL with behavior registered by protocol scheme // * // * @throws IOException if an I/O error occurs while creating the {@code URLStreamHandler} // * @throws SecurityException if the security permission {@code NetPermission("specifyStreamHandler")} has not been granted // * (for non-default behavior) // */ // public URL toURL(URI location) throws IOException, SecurityException { // String scheme = location.getScheme(); // URLConnectionHelperSpi helper = helpers.get(scheme); // if (helper != null) { // URLStreamHandler handler = helper.newStreamHandler(); // return new URL(null, location.toString(), handler); // } // return location.toURL(); // } // // /** // * Opens a connection to a {@code URI} with behavior registered by protocol scheme. // * // * If no behavior has been registered, then the default Java behavior is used instead. // * // * @param location the location to open // * // * @return a newly opened {@code URLConnection} // * // * @throws IOException if an I/O error occurs while opening the connection // */ // public URLConnection openConnection(URI location) throws IOException { // String scheme = location.getScheme(); // URLConnectionHelperSpi helper = helpers.get(scheme); // if (helper != null) { // return helper.openConnection(location); // } // return location.toURL().openConnection(); // } // // /** // * Creates a new {@code URLConnectionHelper}. // * // * Discovery of {@code URLConnectionHelperSpi} service implementations uses the current thread's context class loader. // * // * @return a new {@code URLConnectionHelper} // */ // public static URLConnectionHelper newInstance() { // Class<URLConnectionHelperSpi> clazz = URLConnectionHelperSpi.class; // ServiceLoader<URLConnectionHelperSpi> loader = ServiceLoader.load(clazz); // return newInstance(loader); // } // // /** // * Creates a new {@code URLConnectionHelper}. // * // * Discovery of {@code URLConnectionHelperSpi} service implementations use the specified class loader. // * // * @param cl the service discovery class loader // * // * @return a new {@code URLConnectionHelper} // */ // public static URLConnectionHelper newInstance(ClassLoader cl) { // Class<URLConnectionHelperSpi> clazz = URLConnectionHelperSpi.class; // ServiceLoader<URLConnectionHelperSpi> loader = ServiceLoader.load(clazz, cl); // return newInstance(loader); // } // // private URLConnectionHelper(Map<String, URLConnectionHelperSpi> helpers) { // this.helpers = helpers; // } // // private static URLConnectionHelper newInstance(ServiceLoader<URLConnectionHelperSpi> loader) { // Map<String, URLConnectionHelperSpi> helpers = new HashMap<String, URLConnectionHelperSpi>(); // // for (URLConnectionHelperSpi factory : loader) { // Collection<String> protocols = factory.getSupportedProtocols(); // // if (protocols != null && !protocols.isEmpty()) { // for (String protocol : protocols) { // helpers.put(protocol, factory); // } // } // } // // URLConnectionHelper helper = new URLConnectionHelper(unmodifiableMap(helpers)); // // for (URLConnectionHelperSpi factory : helpers.values()) { // inject(factory, URLConnectionHelper.class, helper); // } // // return helper; // } // // private static <T> void inject(Object target, Class<T> type, T instance) { // try { // Class<? extends Object> targetClass = target.getClass(); // Method[] targetMethods = targetClass.getMethods(); // for (Method targetMethod : targetMethods) { // // if (targetMethod.getAnnotation(Resource.class) == null) { // continue; // } // // if (!isPublic(targetMethod.getModifiers()) || isStatic(targetMethod.getModifiers())) { // continue; // } // // Class<?>[] targetMethodParameterTypes = targetMethod.getParameterTypes(); // if (targetMethodParameterTypes.length != 1 || targetMethodParameterTypes[0] != type) { // continue; // } // // try { // targetMethod.invoke(target, instance); // } // catch (IllegalArgumentException e) { // // failed to inject // } // catch (IllegalAccessException e) { // // failed to inject // } // catch (InvocationTargetException e) { // // failed to inject // } // } // } // catch (SecurityException e) { // // failed to reflect // } // } // // }
import static java.lang.String.format; import static java.util.Objects.requireNonNull; import java.applet.Applet; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import org.kaazing.netx.URLConnectionHelper;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.bridge.itest.internal; @SuppressWarnings("serial") public class TestApplet extends Applet { @Override public void init() { } @Override public void start() { try { String location = getParameter("location"); requireNonNull(location, "Missing Applet parameter \"location\""); System.out.println(format("Applet parameter \"location\" = %s", location)); URI locationURI = URI.create(location);
// Path: api/src/main/java/org/kaazing/netx/URLConnectionHelper.java // public final class URLConnectionHelper { // // private final Map<String, URLConnectionHelperSpi> helpers; // // /** // * Converts a {@code URI} to an {@code URL} with behavior registered by protocol scheme. // * // * If no behavior has been registered, then the default Java behavior is used instead. // * Requires the security permission {@code NetPermission("specifyStreamHandler")} for non-default behavior. // * // * @param location the location to convert // * // * @return a URL with behavior registered by protocol scheme // * // * @throws IOException if an I/O error occurs while creating the {@code URLStreamHandler} // * @throws SecurityException if the security permission {@code NetPermission("specifyStreamHandler")} has not been granted // * (for non-default behavior) // */ // public URL toURL(URI location) throws IOException, SecurityException { // String scheme = location.getScheme(); // URLConnectionHelperSpi helper = helpers.get(scheme); // if (helper != null) { // URLStreamHandler handler = helper.newStreamHandler(); // return new URL(null, location.toString(), handler); // } // return location.toURL(); // } // // /** // * Opens a connection to a {@code URI} with behavior registered by protocol scheme. // * // * If no behavior has been registered, then the default Java behavior is used instead. // * // * @param location the location to open // * // * @return a newly opened {@code URLConnection} // * // * @throws IOException if an I/O error occurs while opening the connection // */ // public URLConnection openConnection(URI location) throws IOException { // String scheme = location.getScheme(); // URLConnectionHelperSpi helper = helpers.get(scheme); // if (helper != null) { // return helper.openConnection(location); // } // return location.toURL().openConnection(); // } // // /** // * Creates a new {@code URLConnectionHelper}. // * // * Discovery of {@code URLConnectionHelperSpi} service implementations uses the current thread's context class loader. // * // * @return a new {@code URLConnectionHelper} // */ // public static URLConnectionHelper newInstance() { // Class<URLConnectionHelperSpi> clazz = URLConnectionHelperSpi.class; // ServiceLoader<URLConnectionHelperSpi> loader = ServiceLoader.load(clazz); // return newInstance(loader); // } // // /** // * Creates a new {@code URLConnectionHelper}. // * // * Discovery of {@code URLConnectionHelperSpi} service implementations use the specified class loader. // * // * @param cl the service discovery class loader // * // * @return a new {@code URLConnectionHelper} // */ // public static URLConnectionHelper newInstance(ClassLoader cl) { // Class<URLConnectionHelperSpi> clazz = URLConnectionHelperSpi.class; // ServiceLoader<URLConnectionHelperSpi> loader = ServiceLoader.load(clazz, cl); // return newInstance(loader); // } // // private URLConnectionHelper(Map<String, URLConnectionHelperSpi> helpers) { // this.helpers = helpers; // } // // private static URLConnectionHelper newInstance(ServiceLoader<URLConnectionHelperSpi> loader) { // Map<String, URLConnectionHelperSpi> helpers = new HashMap<String, URLConnectionHelperSpi>(); // // for (URLConnectionHelperSpi factory : loader) { // Collection<String> protocols = factory.getSupportedProtocols(); // // if (protocols != null && !protocols.isEmpty()) { // for (String protocol : protocols) { // helpers.put(protocol, factory); // } // } // } // // URLConnectionHelper helper = new URLConnectionHelper(unmodifiableMap(helpers)); // // for (URLConnectionHelperSpi factory : helpers.values()) { // inject(factory, URLConnectionHelper.class, helper); // } // // return helper; // } // // private static <T> void inject(Object target, Class<T> type, T instance) { // try { // Class<? extends Object> targetClass = target.getClass(); // Method[] targetMethods = targetClass.getMethods(); // for (Method targetMethod : targetMethods) { // // if (targetMethod.getAnnotation(Resource.class) == null) { // continue; // } // // if (!isPublic(targetMethod.getModifiers()) || isStatic(targetMethod.getModifiers())) { // continue; // } // // Class<?>[] targetMethodParameterTypes = targetMethod.getParameterTypes(); // if (targetMethodParameterTypes.length != 1 || targetMethodParameterTypes[0] != type) { // continue; // } // // try { // targetMethod.invoke(target, instance); // } // catch (IllegalArgumentException e) { // // failed to inject // } // catch (IllegalAccessException e) { // // failed to inject // } // catch (InvocationTargetException e) { // // failed to inject // } // } // } // catch (SecurityException e) { // // failed to reflect // } // } // // } // Path: http.bridge/itest/src/main/java/org/kaazing/netx/http/bridge/itest/internal/TestApplet.java import static java.lang.String.format; import static java.util.Objects.requireNonNull; import java.applet.Applet; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import org.kaazing.netx.URLConnectionHelper; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.bridge.itest.internal; @SuppressWarnings("serial") public class TestApplet extends Applet { @Override public void init() { } @Override public void start() { try { String location = getParameter("location"); requireNonNull(location, "Missing Applet parameter \"location\""); System.out.println(format("Applet parameter \"location\" = %s", location)); URI locationURI = URI.create(location);
URLConnectionHelper helper = URLConnectionHelper.newInstance();
kaazing/netx
ws/src/main/java/org/kaazing/netx/ws/internal/WebSocketOutputStateMachine.java
// Path: ws/src/main/java/org/kaazing/netx/ws/internal/ext/flyweight/Opcode.java // public enum Opcode { // BINARY, CLOSE, CONTINUATION, PING, PONG, TEXT; // // public static Opcode fromInt(int value) { // switch (value) { // case 0x00: // return CONTINUATION; // case 0x01: // return TEXT; // case 0x02: // return BINARY; // case 0x08: // return CLOSE; // case 0x09: // return PING; // case 0x0A: // return PONG; // default: // throw new IllegalStateException(format("Unrecognized WebSocket OpCode %x", value)); // } // }; // // public static int toInt(Opcode value) { // switch (value) { // case CONTINUATION: // return 0x00; // case TEXT: // return 0x01; // case BINARY: // return 0x02; // case CLOSE: // return 0x08; // case PING: // return 0x09; // case PONG: // return 0x0A; // default: // throw new IllegalStateException(format("Unrecognised OpCode %s", value)); // } // }; // }
import static java.lang.String.format; import static java.util.EnumSet.allOf; import static org.kaazing.netx.ws.internal.WebSocketState.CLOSED; import static org.kaazing.netx.ws.internal.WebSocketState.OPEN; import static org.kaazing.netx.ws.internal.WebSocketTransition.ERROR; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_BINARY_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_CLOSE_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_CONTINUATION_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_PONG_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_TEXT_FRAME; import java.io.IOException; import org.kaazing.netx.ws.internal.ext.flyweight.Frame; import org.kaazing.netx.ws.internal.ext.flyweight.Opcode;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal; public final class WebSocketOutputStateMachine { private static final WebSocketState[][] STATE_MACHINE; static { int stateCount = WebSocketState.values().length; int transitionCount = WebSocketTransition.values().length; WebSocketState[][] stateMachine = new WebSocketState[stateCount][transitionCount]; for (WebSocketState state : allOf(WebSocketState.class)) { for (WebSocketTransition transition : allOf(WebSocketTransition.class)) { stateMachine[state.ordinal()][transition.ordinal()] = CLOSED; } stateMachine[state.ordinal()][ERROR.ordinal()] = CLOSED; } stateMachine[OPEN.ordinal()][SEND_PONG_FRAME.ordinal()] = OPEN; stateMachine[OPEN.ordinal()][SEND_CLOSE_FRAME.ordinal()] = CLOSED; stateMachine[OPEN.ordinal()][SEND_BINARY_FRAME.ordinal()] = OPEN; stateMachine[OPEN.ordinal()][SEND_CONTINUATION_FRAME.ordinal()] = OPEN; stateMachine[OPEN.ordinal()][SEND_TEXT_FRAME.ordinal()] = OPEN; STATE_MACHINE = stateMachine; } public WebSocketOutputStateMachine() { } public void start(WsURLConnectionImpl connection) { connection.setOutputState(WebSocketState.START); } public void processFrame(final WsURLConnectionImpl connection, final Frame frame) throws IOException { try { connection.getWriteLock().lock(); DefaultWebSocketContext context = connection.getOutgoingContext(); WebSocketState state = connection.getOutputState();
// Path: ws/src/main/java/org/kaazing/netx/ws/internal/ext/flyweight/Opcode.java // public enum Opcode { // BINARY, CLOSE, CONTINUATION, PING, PONG, TEXT; // // public static Opcode fromInt(int value) { // switch (value) { // case 0x00: // return CONTINUATION; // case 0x01: // return TEXT; // case 0x02: // return BINARY; // case 0x08: // return CLOSE; // case 0x09: // return PING; // case 0x0A: // return PONG; // default: // throw new IllegalStateException(format("Unrecognized WebSocket OpCode %x", value)); // } // }; // // public static int toInt(Opcode value) { // switch (value) { // case CONTINUATION: // return 0x00; // case TEXT: // return 0x01; // case BINARY: // return 0x02; // case CLOSE: // return 0x08; // case PING: // return 0x09; // case PONG: // return 0x0A; // default: // throw new IllegalStateException(format("Unrecognised OpCode %s", value)); // } // }; // } // Path: ws/src/main/java/org/kaazing/netx/ws/internal/WebSocketOutputStateMachine.java import static java.lang.String.format; import static java.util.EnumSet.allOf; import static org.kaazing.netx.ws.internal.WebSocketState.CLOSED; import static org.kaazing.netx.ws.internal.WebSocketState.OPEN; import static org.kaazing.netx.ws.internal.WebSocketTransition.ERROR; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_BINARY_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_CLOSE_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_CONTINUATION_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_PONG_FRAME; import static org.kaazing.netx.ws.internal.WebSocketTransition.SEND_TEXT_FRAME; import java.io.IOException; import org.kaazing.netx.ws.internal.ext.flyweight.Frame; import org.kaazing.netx.ws.internal.ext.flyweight.Opcode; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal; public final class WebSocketOutputStateMachine { private static final WebSocketState[][] STATE_MACHINE; static { int stateCount = WebSocketState.values().length; int transitionCount = WebSocketTransition.values().length; WebSocketState[][] stateMachine = new WebSocketState[stateCount][transitionCount]; for (WebSocketState state : allOf(WebSocketState.class)) { for (WebSocketTransition transition : allOf(WebSocketTransition.class)) { stateMachine[state.ordinal()][transition.ordinal()] = CLOSED; } stateMachine[state.ordinal()][ERROR.ordinal()] = CLOSED; } stateMachine[OPEN.ordinal()][SEND_PONG_FRAME.ordinal()] = OPEN; stateMachine[OPEN.ordinal()][SEND_CLOSE_FRAME.ordinal()] = CLOSED; stateMachine[OPEN.ordinal()][SEND_BINARY_FRAME.ordinal()] = OPEN; stateMachine[OPEN.ordinal()][SEND_CONTINUATION_FRAME.ordinal()] = OPEN; stateMachine[OPEN.ordinal()][SEND_TEXT_FRAME.ordinal()] = OPEN; STATE_MACHINE = stateMachine; } public WebSocketOutputStateMachine() { } public void start(WsURLConnectionImpl connection) { connection.setOutputState(WebSocketState.START); } public void processFrame(final WsURLConnectionImpl connection, final Frame frame) throws IOException { try { connection.getWriteLock().lock(); DefaultWebSocketContext context = connection.getOutgoingContext(); WebSocketState state = connection.getOutputState();
Opcode opcode = frame.opcode();
kaazing/netx
http/src/main/java/org/kaazing/netx/http/internal/auth/DefaultApplicationBasicChallengeHandler.java
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandler.java // public abstract class LoginHandler { // // /** // * Default constructor. // */ // protected LoginHandler() { // } // // /** // * Gets the password authentication credentials from an arbitrary source. // * @return the password authentication obtained. // */ // public abstract PasswordAuthentication getCredentials(); // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandlerProvider.java // public interface LoginHandlerProvider { // // /** // * Get the login handler associated with this challenge handler. // * A login handler is used to assist in obtaining credentials to respond to challenge requests. // * // * @return a login handler to assist in providing credentials, or {@code null} if none has been established yet. // */ // LoginHandler getLoginHandler(); // }
import java.net.PasswordAuthentication; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.kaazing.netx.http.auth.ApplicationBasicChallengeHandler; import org.kaazing.netx.http.auth.ChallengeRequest; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.auth.LoginHandler; import org.kaazing.netx.http.auth.LoginHandlerProvider;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.internal.auth; /** * Challenge handler for Basic authentication. See RFC 2617. */ public class DefaultApplicationBasicChallengeHandler extends ApplicationBasicChallengeHandler implements LoginHandlerProvider { // ------------------------------ FIELDS ------------------------------ private static final String CLASS_NAME = DefaultApplicationBasicChallengeHandler.class.getName(); private static final Logger LOG = Logger.getLogger(CLASS_NAME); private static final String AUTHENTICATION_SCHEME = "Application Basic";
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandler.java // public abstract class LoginHandler { // // /** // * Default constructor. // */ // protected LoginHandler() { // } // // /** // * Gets the password authentication credentials from an arbitrary source. // * @return the password authentication obtained. // */ // public abstract PasswordAuthentication getCredentials(); // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandlerProvider.java // public interface LoginHandlerProvider { // // /** // * Get the login handler associated with this challenge handler. // * A login handler is used to assist in obtaining credentials to respond to challenge requests. // * // * @return a login handler to assist in providing credentials, or {@code null} if none has been established yet. // */ // LoginHandler getLoginHandler(); // } // Path: http/src/main/java/org/kaazing/netx/http/internal/auth/DefaultApplicationBasicChallengeHandler.java import java.net.PasswordAuthentication; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.kaazing.netx.http.auth.ApplicationBasicChallengeHandler; import org.kaazing.netx.http.auth.ChallengeRequest; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.auth.LoginHandler; import org.kaazing.netx.http.auth.LoginHandlerProvider; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.internal.auth; /** * Challenge handler for Basic authentication. See RFC 2617. */ public class DefaultApplicationBasicChallengeHandler extends ApplicationBasicChallengeHandler implements LoginHandlerProvider { // ------------------------------ FIELDS ------------------------------ private static final String CLASS_NAME = DefaultApplicationBasicChallengeHandler.class.getName(); private static final Logger LOG = Logger.getLogger(CLASS_NAME); private static final String AUTHENTICATION_SCHEME = "Application Basic";
private final Map<String, LoginHandler> loginHandlersByRealm = new ConcurrentHashMap<String, LoginHandler>();
kaazing/netx
http/src/main/java/org/kaazing/netx/http/internal/auth/DefaultApplicationBasicChallengeHandler.java
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandler.java // public abstract class LoginHandler { // // /** // * Default constructor. // */ // protected LoginHandler() { // } // // /** // * Gets the password authentication credentials from an arbitrary source. // * @return the password authentication obtained. // */ // public abstract PasswordAuthentication getCredentials(); // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandlerProvider.java // public interface LoginHandlerProvider { // // /** // * Get the login handler associated with this challenge handler. // * A login handler is used to assist in obtaining credentials to respond to challenge requests. // * // * @return a login handler to assist in providing credentials, or {@code null} if none has been established yet. // */ // LoginHandler getLoginHandler(); // }
import java.net.PasswordAuthentication; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.kaazing.netx.http.auth.ApplicationBasicChallengeHandler; import org.kaazing.netx.http.auth.ChallengeRequest; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.auth.LoginHandler; import org.kaazing.netx.http.auth.LoginHandlerProvider;
/** * Provide a login handler to be used in association with this challenge handler. * The login handler is used to assist in obtaining credentials to respond to challenge requests. * * @param loginHandler a login handler for credentials. */ @Override public ApplicationBasicChallengeHandler setLoginHandler(LoginHandler loginHandler) { this.loginHandler = loginHandler; return this; } /** * Get the login handler associated with this challenge handler. * A login handler is used to assist in obtaining credentials to respond to challenge requests. * * @return a login handler to assist in providing credentials, or {@code null} if none has been established yet. */ @Override public LoginHandler getLoginHandler() { return loginHandler; } @Override public boolean canHandle(ChallengeRequest challengeRequest) { return challengeRequest != null && AUTHENTICATION_SCHEME.equals(challengeRequest.getAuthenticationScheme()); } @Override
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandler.java // public abstract class LoginHandler { // // /** // * Default constructor. // */ // protected LoginHandler() { // } // // /** // * Gets the password authentication credentials from an arbitrary source. // * @return the password authentication obtained. // */ // public abstract PasswordAuthentication getCredentials(); // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/LoginHandlerProvider.java // public interface LoginHandlerProvider { // // /** // * Get the login handler associated with this challenge handler. // * A login handler is used to assist in obtaining credentials to respond to challenge requests. // * // * @return a login handler to assist in providing credentials, or {@code null} if none has been established yet. // */ // LoginHandler getLoginHandler(); // } // Path: http/src/main/java/org/kaazing/netx/http/internal/auth/DefaultApplicationBasicChallengeHandler.java import java.net.PasswordAuthentication; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.kaazing.netx.http.auth.ApplicationBasicChallengeHandler; import org.kaazing.netx.http.auth.ChallengeRequest; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.auth.LoginHandler; import org.kaazing.netx.http.auth.LoginHandlerProvider; /** * Provide a login handler to be used in association with this challenge handler. * The login handler is used to assist in obtaining credentials to respond to challenge requests. * * @param loginHandler a login handler for credentials. */ @Override public ApplicationBasicChallengeHandler setLoginHandler(LoginHandler loginHandler) { this.loginHandler = loginHandler; return this; } /** * Get the login handler associated with this challenge handler. * A login handler is used to assist in obtaining credentials to respond to challenge requests. * * @return a login handler to assist in providing credentials, or {@code null} if none has been established yet. */ @Override public LoginHandler getLoginHandler() { return loginHandler; } @Override public boolean canHandle(ChallengeRequest challengeRequest) { return challengeRequest != null && AUTHENTICATION_SCHEME.equals(challengeRequest.getAuthenticationScheme()); } @Override
public ChallengeResponse handle(ChallengeRequest challengeRequest) {
kaazing/netx
http/src/main/java/org/kaazing/netx/http/HttpURLConnection.java
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeHandler.java // public abstract class ChallengeHandler { // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} using // * the {@link ServiceLoader} API with the implementation specified under // * META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz) { // return load0(clazz, ServiceLoader.load(clazz)); // } // // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} with // * specified {@link ClassLoader} using the {@link ServiceLoader} API with // * the implementation specified under META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @param classLoader ClassLoader to be used to instantiate // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz, // ClassLoader classLoader) { // return load0(clazz, ServiceLoader.load(clazz, classLoader)); // } // // /** // * Can the presented challenge be potentially handled by this challenge handler? // * // * @param challengeRequest a challenge request object containing a challenge // * @return true iff this challenge handler could potentially respond meaningfully to the challenge. // */ // public abstract boolean canHandle(ChallengeRequest challengeRequest); // // /** // * Handle the presented challenge by creating a challenge response or returning {@code null}. // * This responsibility is usually achieved // * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials // * into a {@link ChallengeResponse}. // * <p> // * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}. // * // * @param challengeRequest a challenge object // * @return a challenge response object or {@code null} if no response is possible. // */ // public abstract ChallengeResponse handle(ChallengeRequest challengeRequest); // // // ----------------------- Private Methods ------------------------------- // // private static <T extends ChallengeHandler> T load0(Class<T> clazz, // ServiceLoader<T> serviceLoader) { // for (ChallengeHandler challengeHandler: serviceLoader) { // Class<?> c = challengeHandler.getClass(); // if ((clazz != null) && clazz.isAssignableFrom(c)) { // try { // return clazz.cast(c.newInstance()); // } catch (InstantiationException e) { // String s = "Failed to instantiate class " + c; // throw new RuntimeException(s, e); // } catch (IllegalAccessException e) { // String s = "Failed to access and instantiate class " + c; // throw new RuntimeException(s, e); // } // } // } // return null; // } // // }
import static org.kaazing.netx.http.HttpRedirectPolicy.ORIGIN; import java.net.URL; import org.kaazing.netx.http.auth.ChallengeHandler;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http; /** * {@code HttpURLConnection} enhances the built-in HTTP-based {@code URLConnection}. * * Support is added for HTTP upgrade, an origin-aware HTTP redirect policy, and an application-level security challenge handler. */ public abstract class HttpURLConnection extends java.net.HttpURLConnection { /** * HTTP Status-Code 101: Switching Protocols. */ public static final int HTTP_SWITCHING_PROTOCOLS = 101;
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeHandler.java // public abstract class ChallengeHandler { // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} using // * the {@link ServiceLoader} API with the implementation specified under // * META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz) { // return load0(clazz, ServiceLoader.load(clazz)); // } // // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} with // * specified {@link ClassLoader} using the {@link ServiceLoader} API with // * the implementation specified under META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @param classLoader ClassLoader to be used to instantiate // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz, // ClassLoader classLoader) { // return load0(clazz, ServiceLoader.load(clazz, classLoader)); // } // // /** // * Can the presented challenge be potentially handled by this challenge handler? // * // * @param challengeRequest a challenge request object containing a challenge // * @return true iff this challenge handler could potentially respond meaningfully to the challenge. // */ // public abstract boolean canHandle(ChallengeRequest challengeRequest); // // /** // * Handle the presented challenge by creating a challenge response or returning {@code null}. // * This responsibility is usually achieved // * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials // * into a {@link ChallengeResponse}. // * <p> // * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}. // * // * @param challengeRequest a challenge object // * @return a challenge response object or {@code null} if no response is possible. // */ // public abstract ChallengeResponse handle(ChallengeRequest challengeRequest); // // // ----------------------- Private Methods ------------------------------- // // private static <T extends ChallengeHandler> T load0(Class<T> clazz, // ServiceLoader<T> serviceLoader) { // for (ChallengeHandler challengeHandler: serviceLoader) { // Class<?> c = challengeHandler.getClass(); // if ((clazz != null) && clazz.isAssignableFrom(c)) { // try { // return clazz.cast(c.newInstance()); // } catch (InstantiationException e) { // String s = "Failed to instantiate class " + c; // throw new RuntimeException(s, e); // } catch (IllegalAccessException e) { // String s = "Failed to access and instantiate class " + c; // throw new RuntimeException(s, e); // } // } // } // return null; // } // // } // Path: http/src/main/java/org/kaazing/netx/http/HttpURLConnection.java import static org.kaazing.netx.http.HttpRedirectPolicy.ORIGIN; import java.net.URL; import org.kaazing.netx.http.auth.ChallengeHandler; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http; /** * {@code HttpURLConnection} enhances the built-in HTTP-based {@code URLConnection}. * * Support is added for HTTP upgrade, an origin-aware HTTP redirect policy, and an application-level security challenge handler. */ public abstract class HttpURLConnection extends java.net.HttpURLConnection { /** * HTTP Status-Code 101: Switching Protocols. */ public static final int HTTP_SWITCHING_PROTOCOLS = 101;
private ChallengeHandler challengeHandler;
kaazing/netx
http/src/test/java/org/kaazing/netx/http/auth/ChallengeRequestTest.java
// Path: http/src/main/java/org/kaazing/netx/http/internal/auth/RealmUtils.java // public final class RealmUtils { // // private RealmUtils() { // // prevent object creation // } // // private static final String REALM_REGEX = "(.*)\\s?(?i:realm=)(\"(.*)\")(.*)"; // private static final Pattern REALM_PATTERN = Pattern.compile(REALM_REGEX); // // /** // * A realm parameter is a valid authentication parameter for all authentication schemes // * according to <a href="http://tools.ietf.org/html/rfc2617#section-2.1">RFC 2617 Section 2.1"</a>. // * // * {@code} // * The realm directive (case-insensitive) is required for all // * authentication schemes that issue a challenge. The realm value // * (case-sensitive), in combination with the canonical root URL (the // * absoluteURI for the server whose abs_path is empty) of the server // * being accessed, defines the protection space. // * {@code} // * // * @param challengeRequest the challenge request to extract a realm from // * // * @return the unquoted realm parameter value if present, or {@code null} if no such parameter exists. // */ // public static String getRealm(ChallengeRequest challengeRequest) { // String authenticationParameters = challengeRequest.getAuthenticationParameters(); // if (authenticationParameters == null) { // return null; // } // Matcher m = REALM_PATTERN.matcher(authenticationParameters); // if (m.matches() && m.groupCount() >= 3) { // return m.group(3); // } // return null; // } // }
import org.junit.Assert; import org.junit.Test; import org.kaazing.netx.http.internal.auth.RealmUtils;
ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, null); Assert.assertNull(challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); } @Test public void testEmptyChallenge() throws Exception { ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, ""); Assert.assertNull(challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); } @Test public void testBasicChallenge() throws Exception { ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic"); Assert.assertEquals("Application Basic", challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic "); Assert.assertEquals("Application Basic", challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic AuthData"); Assert.assertEquals("Application Basic", challengeRequest.getAuthenticationScheme()); Assert.assertEquals("AuthData", challengeRequest.getAuthenticationParameters()); } @Test public void testRealmParameter() throws Exception { ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic");
// Path: http/src/main/java/org/kaazing/netx/http/internal/auth/RealmUtils.java // public final class RealmUtils { // // private RealmUtils() { // // prevent object creation // } // // private static final String REALM_REGEX = "(.*)\\s?(?i:realm=)(\"(.*)\")(.*)"; // private static final Pattern REALM_PATTERN = Pattern.compile(REALM_REGEX); // // /** // * A realm parameter is a valid authentication parameter for all authentication schemes // * according to <a href="http://tools.ietf.org/html/rfc2617#section-2.1">RFC 2617 Section 2.1"</a>. // * // * {@code} // * The realm directive (case-insensitive) is required for all // * authentication schemes that issue a challenge. The realm value // * (case-sensitive), in combination with the canonical root URL (the // * absoluteURI for the server whose abs_path is empty) of the server // * being accessed, defines the protection space. // * {@code} // * // * @param challengeRequest the challenge request to extract a realm from // * // * @return the unquoted realm parameter value if present, or {@code null} if no such parameter exists. // */ // public static String getRealm(ChallengeRequest challengeRequest) { // String authenticationParameters = challengeRequest.getAuthenticationParameters(); // if (authenticationParameters == null) { // return null; // } // Matcher m = REALM_PATTERN.matcher(authenticationParameters); // if (m.matches() && m.groupCount() >= 3) { // return m.group(3); // } // return null; // } // } // Path: http/src/test/java/org/kaazing/netx/http/auth/ChallengeRequestTest.java import org.junit.Assert; import org.junit.Test; import org.kaazing.netx.http.internal.auth.RealmUtils; ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, null); Assert.assertNull(challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); } @Test public void testEmptyChallenge() throws Exception { ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, ""); Assert.assertNull(challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); } @Test public void testBasicChallenge() throws Exception { ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic"); Assert.assertEquals("Application Basic", challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic "); Assert.assertEquals("Application Basic", challengeRequest.getAuthenticationScheme()); Assert.assertNull(challengeRequest.getAuthenticationParameters()); challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic AuthData"); Assert.assertEquals("Application Basic", challengeRequest.getAuthenticationScheme()); Assert.assertEquals("AuthData", challengeRequest.getAuthenticationParameters()); } @Test public void testRealmParameter() throws Exception { ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Application Basic");
Assert.assertNull(RealmUtils.getRealm(challengeRequest));
kaazing/netx
ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTest.java
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/DataTest.java // enum Fin { // SET, UNSET; // }
import java.nio.ByteBuffer; import java.util.Random; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.kaazing.netx.ws.internal.ext.flyweight.DataTest.Fin;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; @RunWith(Theories.class) public class FrameTest { private static final int BUFFER_CAPACITY = 64 * 1024; private static final int WS_MAX_MESSAGE_SIZE = 20 * 1024; @DataPoint public static final int ZERO_OFFSET = 0; @DataPoint public static final int NON_ZERO_OFFSET = new Random().nextInt(BUFFER_CAPACITY - WS_MAX_MESSAGE_SIZE); @DataPoint public static final boolean MASKED = true; @DataPoint public static final boolean UNMASKED = false; protected final ByteBuffer buffer = ByteBuffer.wrap(new byte[BUFFER_CAPACITY]); @Theory
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/DataTest.java // enum Fin { // SET, UNSET; // } // Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTest.java import java.nio.ByteBuffer; import java.util.Random; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.kaazing.netx.ws.internal.ext.flyweight.DataTest.Fin; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; @RunWith(Theories.class) public class FrameTest { private static final int BUFFER_CAPACITY = 64 * 1024; private static final int WS_MAX_MESSAGE_SIZE = 20 * 1024; @DataPoint public static final int ZERO_OFFSET = 0; @DataPoint public static final int NON_ZERO_OFFSET = new Random().nextInt(BUFFER_CAPACITY - WS_MAX_MESSAGE_SIZE); @DataPoint public static final boolean MASKED = true; @DataPoint public static final boolean UNMASKED = false; protected final ByteBuffer buffer = ByteBuffer.wrap(new byte[BUFFER_CAPACITY]); @Theory
public void dummyTest(int offset, boolean masked, Fin fin) throws Exception {
kaazing/netx
bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshURLConnection.java
// Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Polling extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("polling;interval=([0-9]+)s"); // // private final int interval; // private final TimeUnit intervalUnit; // // /** // * Creates a new {@code Polling} BBOSH connection strategy. // * // * @param interval the time interval count // * @param intervalUnit the time interval unit // */ // public Polling(int interval, TimeUnit intervalUnit) { // this.interval = interval; // this.intervalUnit = intervalUnit; // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.POLLING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return a string representation such as {@code "polling;interval=30s"} // */ // public String toString() { // return format("polling;interval=%d%s", interval, toLowerCase(intervalUnit.name().charAt(0))); // } // } // // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Streaming extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("streaming;request=chunked"); // // /** // * Creates a new {@code Streaming} BBOSH connections strategy. // */ // public Streaming() { // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.STREAMING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return the string representation {@code "streaming;request=chunked"} // */ // public String toString() { // return "streaming;request=chunked"; // } // }
import static java.util.concurrent.TimeUnit.SECONDS; import java.io.Closeable; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.kaazing.netx.bbosh.BBoshStrategy.Polling; import org.kaazing.netx.bbosh.BBoshStrategy.Streaming;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.bbosh; /** * Provides BBOSH support for {@code URLConnection}. */ public abstract class BBoshURLConnection extends URLConnection implements Closeable { private final List<BBoshStrategy> supportedStrategies; private BBoshStrategy negotiatedStrategy; /** * Creates a new {@code BBoshURLConnection}. * * @param url the location for this {@code BBoshURLConnection} */ protected BBoshURLConnection(URL url) { super(url); supportedStrategies = new ArrayList<BBoshStrategy>();
// Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Polling extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("polling;interval=([0-9]+)s"); // // private final int interval; // private final TimeUnit intervalUnit; // // /** // * Creates a new {@code Polling} BBOSH connection strategy. // * // * @param interval the time interval count // * @param intervalUnit the time interval unit // */ // public Polling(int interval, TimeUnit intervalUnit) { // this.interval = interval; // this.intervalUnit = intervalUnit; // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.POLLING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return a string representation such as {@code "polling;interval=30s"} // */ // public String toString() { // return format("polling;interval=%d%s", interval, toLowerCase(intervalUnit.name().charAt(0))); // } // } // // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Streaming extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("streaming;request=chunked"); // // /** // * Creates a new {@code Streaming} BBOSH connections strategy. // */ // public Streaming() { // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.STREAMING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return the string representation {@code "streaming;request=chunked"} // */ // public String toString() { // return "streaming;request=chunked"; // } // } // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshURLConnection.java import static java.util.concurrent.TimeUnit.SECONDS; import java.io.Closeable; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.kaazing.netx.bbosh.BBoshStrategy.Polling; import org.kaazing.netx.bbosh.BBoshStrategy.Streaming; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.bbosh; /** * Provides BBOSH support for {@code URLConnection}. */ public abstract class BBoshURLConnection extends URLConnection implements Closeable { private final List<BBoshStrategy> supportedStrategies; private BBoshStrategy negotiatedStrategy; /** * Creates a new {@code BBoshURLConnection}. * * @param url the location for this {@code BBoshURLConnection} */ protected BBoshURLConnection(URL url) { super(url); supportedStrategies = new ArrayList<BBoshStrategy>();
supportedStrategies.add(new Polling(5, SECONDS));
kaazing/netx
bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshURLConnection.java
// Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Polling extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("polling;interval=([0-9]+)s"); // // private final int interval; // private final TimeUnit intervalUnit; // // /** // * Creates a new {@code Polling} BBOSH connection strategy. // * // * @param interval the time interval count // * @param intervalUnit the time interval unit // */ // public Polling(int interval, TimeUnit intervalUnit) { // this.interval = interval; // this.intervalUnit = intervalUnit; // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.POLLING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return a string representation such as {@code "polling;interval=30s"} // */ // public String toString() { // return format("polling;interval=%d%s", interval, toLowerCase(intervalUnit.name().charAt(0))); // } // } // // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Streaming extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("streaming;request=chunked"); // // /** // * Creates a new {@code Streaming} BBOSH connections strategy. // */ // public Streaming() { // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.STREAMING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return the string representation {@code "streaming;request=chunked"} // */ // public String toString() { // return "streaming;request=chunked"; // } // }
import static java.util.concurrent.TimeUnit.SECONDS; import java.io.Closeable; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.kaazing.netx.bbosh.BBoshStrategy.Polling; import org.kaazing.netx.bbosh.BBoshStrategy.Streaming;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.bbosh; /** * Provides BBOSH support for {@code URLConnection}. */ public abstract class BBoshURLConnection extends URLConnection implements Closeable { private final List<BBoshStrategy> supportedStrategies; private BBoshStrategy negotiatedStrategy; /** * Creates a new {@code BBoshURLConnection}. * * @param url the location for this {@code BBoshURLConnection} */ protected BBoshURLConnection(URL url) { super(url); supportedStrategies = new ArrayList<BBoshStrategy>(); supportedStrategies.add(new Polling(5, SECONDS));
// Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Polling extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("polling;interval=([0-9]+)s"); // // private final int interval; // private final TimeUnit intervalUnit; // // /** // * Creates a new {@code Polling} BBOSH connection strategy. // * // * @param interval the time interval count // * @param intervalUnit the time interval unit // */ // public Polling(int interval, TimeUnit intervalUnit) { // this.interval = interval; // this.intervalUnit = intervalUnit; // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.POLLING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return a string representation such as {@code "polling;interval=30s"} // */ // public String toString() { // return format("polling;interval=%d%s", interval, toLowerCase(intervalUnit.name().charAt(0))); // } // } // // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public static final class Streaming extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("streaming;request=chunked"); // // /** // * Creates a new {@code Streaming} BBOSH connections strategy. // */ // public Streaming() { // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.STREAMING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return the string representation {@code "streaming;request=chunked"} // */ // public String toString() { // return "streaming;request=chunked"; // } // } // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshURLConnection.java import static java.util.concurrent.TimeUnit.SECONDS; import java.io.Closeable; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.kaazing.netx.bbosh.BBoshStrategy.Polling; import org.kaazing.netx.bbosh.BBoshStrategy.Streaming; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.bbosh; /** * Provides BBOSH support for {@code URLConnection}. */ public abstract class BBoshURLConnection extends URLConnection implements Closeable { private final List<BBoshStrategy> supportedStrategies; private BBoshStrategy negotiatedStrategy; /** * Creates a new {@code BBoshURLConnection}. * * @param url the location for this {@code BBoshURLConnection} */ protected BBoshURLConnection(URL url) { super(url); supportedStrategies = new ArrayList<BBoshStrategy>(); supportedStrategies.add(new Polling(5, SECONDS));
supportedStrategies.add(new Streaming());
kaazing/netx
ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/PongTest.java
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTestUtil.java // public static byte[] fromHex(final String string) { // return fromHexByteArray(string.getBytes(UTF8_CHARSET)); // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.kaazing.netx.ws.internal.ext.flyweight.FrameTestUtil.fromHex; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.PONG; import java.nio.ByteBuffer; import org.junit.experimental.theories.Theory;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; public class PongTest extends FrameTest { @Theory public void shouldDecodeWithEmptyPayload(int offset) throws Exception { FrameRW pongFrame = new FrameRW().wrap(buffer, offset); pongFrame.fin(true); pongFrame.opcode(PONG); pongFrame.payloadPut((ByteBuffer) null, offset, 0); assertEquals(Opcode.PONG, pongFrame.opcode()); assertEquals(0, pongFrame.payloadLength()); assertEquals(true, pongFrame.fin()); } @Theory public void shouldDecodeWithPayload(int offset) throws Exception { FrameRW pongFrame = new FrameRW().wrap(buffer, offset);
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTestUtil.java // public static byte[] fromHex(final String string) { // return fromHexByteArray(string.getBytes(UTF8_CHARSET)); // } // Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/PongTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.kaazing.netx.ws.internal.ext.flyweight.FrameTestUtil.fromHex; import static org.kaazing.netx.ws.internal.ext.flyweight.Opcode.PONG; import java.nio.ByteBuffer; import org.junit.experimental.theories.Theory; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; public class PongTest extends FrameTest { @Theory public void shouldDecodeWithEmptyPayload(int offset) throws Exception { FrameRW pongFrame = new FrameRW().wrap(buffer, offset); pongFrame.fin(true); pongFrame.opcode(PONG); pongFrame.payloadPut((ByteBuffer) null, offset, 0); assertEquals(Opcode.PONG, pongFrame.opcode()); assertEquals(0, pongFrame.payloadLength()); assertEquals(true, pongFrame.fin()); } @Theory public void shouldDecodeWithPayload(int offset) throws Exception { FrameRW pongFrame = new FrameRW().wrap(buffer, offset);
byte[] inputBytes = fromHex("03e8ff01");
kaazing/netx
http/src/main/java/org/kaazing/netx/http/internal/auth/BasicChallengeResponseFactory.java
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeHandler.java // public abstract class ChallengeHandler { // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} using // * the {@link ServiceLoader} API with the implementation specified under // * META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz) { // return load0(clazz, ServiceLoader.load(clazz)); // } // // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} with // * specified {@link ClassLoader} using the {@link ServiceLoader} API with // * the implementation specified under META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @param classLoader ClassLoader to be used to instantiate // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz, // ClassLoader classLoader) { // return load0(clazz, ServiceLoader.load(clazz, classLoader)); // } // // /** // * Can the presented challenge be potentially handled by this challenge handler? // * // * @param challengeRequest a challenge request object containing a challenge // * @return true iff this challenge handler could potentially respond meaningfully to the challenge. // */ // public abstract boolean canHandle(ChallengeRequest challengeRequest); // // /** // * Handle the presented challenge by creating a challenge response or returning {@code null}. // * This responsibility is usually achieved // * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials // * into a {@link ChallengeResponse}. // * <p> // * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}. // * // * @param challengeRequest a challenge object // * @return a challenge response object or {@code null} if no response is possible. // */ // public abstract ChallengeResponse handle(ChallengeRequest challengeRequest); // // // ----------------------- Private Methods ------------------------------- // // private static <T extends ChallengeHandler> T load0(Class<T> clazz, // ServiceLoader<T> serviceLoader) { // for (ChallengeHandler challengeHandler: serviceLoader) { // Class<?> c = challengeHandler.getClass(); // if ((clazz != null) && clazz.isAssignableFrom(c)) { // try { // return clazz.cast(c.newInstance()); // } catch (InstantiationException e) { // String s = "Failed to instantiate class " + c; // throw new RuntimeException(s, e); // } catch (IllegalAccessException e) { // String s = "Failed to access and instantiate class " + c; // throw new RuntimeException(s, e); // } // } // } // return null; // } // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // }
import java.net.PasswordAuthentication; import java.nio.charset.Charset; import java.util.Arrays; import org.kaazing.netx.http.auth.ChallengeHandler; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.internal.Base64;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.internal.auth; public final class BasicChallengeResponseFactory { private static final Charset US_ASCII = Charset.forName("US-ASCII"); private BasicChallengeResponseFactory() { }
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeHandler.java // public abstract class ChallengeHandler { // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} using // * the {@link ServiceLoader} API with the implementation specified under // * META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz) { // return load0(clazz, ServiceLoader.load(clazz)); // } // // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} with // * specified {@link ClassLoader} using the {@link ServiceLoader} API with // * the implementation specified under META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @param classLoader ClassLoader to be used to instantiate // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz, // ClassLoader classLoader) { // return load0(clazz, ServiceLoader.load(clazz, classLoader)); // } // // /** // * Can the presented challenge be potentially handled by this challenge handler? // * // * @param challengeRequest a challenge request object containing a challenge // * @return true iff this challenge handler could potentially respond meaningfully to the challenge. // */ // public abstract boolean canHandle(ChallengeRequest challengeRequest); // // /** // * Handle the presented challenge by creating a challenge response or returning {@code null}. // * This responsibility is usually achieved // * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials // * into a {@link ChallengeResponse}. // * <p> // * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}. // * // * @param challengeRequest a challenge object // * @return a challenge response object or {@code null} if no response is possible. // */ // public abstract ChallengeResponse handle(ChallengeRequest challengeRequest); // // // ----------------------- Private Methods ------------------------------- // // private static <T extends ChallengeHandler> T load0(Class<T> clazz, // ServiceLoader<T> serviceLoader) { // for (ChallengeHandler challengeHandler: serviceLoader) { // Class<?> c = challengeHandler.getClass(); // if ((clazz != null) && clazz.isAssignableFrom(c)) { // try { // return clazz.cast(c.newInstance()); // } catch (InstantiationException e) { // String s = "Failed to instantiate class " + c; // throw new RuntimeException(s, e); // } catch (IllegalAccessException e) { // String s = "Failed to access and instantiate class " + c; // throw new RuntimeException(s, e); // } // } // } // return null; // } // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // } // Path: http/src/main/java/org/kaazing/netx/http/internal/auth/BasicChallengeResponseFactory.java import java.net.PasswordAuthentication; import java.nio.charset.Charset; import java.util.Arrays; import org.kaazing.netx.http.auth.ChallengeHandler; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.internal.Base64; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.internal.auth; public final class BasicChallengeResponseFactory { private static final Charset US_ASCII = Charset.forName("US-ASCII"); private BasicChallengeResponseFactory() { }
public static ChallengeResponse create(PasswordAuthentication creds, ChallengeHandler nextChallengeHandler) {
kaazing/netx
http/src/main/java/org/kaazing/netx/http/internal/auth/BasicChallengeResponseFactory.java
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeHandler.java // public abstract class ChallengeHandler { // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} using // * the {@link ServiceLoader} API with the implementation specified under // * META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz) { // return load0(clazz, ServiceLoader.load(clazz)); // } // // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} with // * specified {@link ClassLoader} using the {@link ServiceLoader} API with // * the implementation specified under META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @param classLoader ClassLoader to be used to instantiate // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz, // ClassLoader classLoader) { // return load0(clazz, ServiceLoader.load(clazz, classLoader)); // } // // /** // * Can the presented challenge be potentially handled by this challenge handler? // * // * @param challengeRequest a challenge request object containing a challenge // * @return true iff this challenge handler could potentially respond meaningfully to the challenge. // */ // public abstract boolean canHandle(ChallengeRequest challengeRequest); // // /** // * Handle the presented challenge by creating a challenge response or returning {@code null}. // * This responsibility is usually achieved // * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials // * into a {@link ChallengeResponse}. // * <p> // * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}. // * // * @param challengeRequest a challenge object // * @return a challenge response object or {@code null} if no response is possible. // */ // public abstract ChallengeResponse handle(ChallengeRequest challengeRequest); // // // ----------------------- Private Methods ------------------------------- // // private static <T extends ChallengeHandler> T load0(Class<T> clazz, // ServiceLoader<T> serviceLoader) { // for (ChallengeHandler challengeHandler: serviceLoader) { // Class<?> c = challengeHandler.getClass(); // if ((clazz != null) && clazz.isAssignableFrom(c)) { // try { // return clazz.cast(c.newInstance()); // } catch (InstantiationException e) { // String s = "Failed to instantiate class " + c; // throw new RuntimeException(s, e); // } catch (IllegalAccessException e) { // String s = "Failed to access and instantiate class " + c; // throw new RuntimeException(s, e); // } // } // } // return null; // } // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // }
import java.net.PasswordAuthentication; import java.nio.charset.Charset; import java.util.Arrays; import org.kaazing.netx.http.auth.ChallengeHandler; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.internal.Base64;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.internal.auth; public final class BasicChallengeResponseFactory { private static final Charset US_ASCII = Charset.forName("US-ASCII"); private BasicChallengeResponseFactory() { }
// Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeHandler.java // public abstract class ChallengeHandler { // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} using // * the {@link ServiceLoader} API with the implementation specified under // * META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz) { // return load0(clazz, ServiceLoader.load(clazz)); // } // // /** // * Creates a new instance of the sub-class of {@link ChallengeHandler} with // * specified {@link ClassLoader} using the {@link ServiceLoader} API with // * the implementation specified under META-INF/services. // * // * @param <T> subclass of ChallengeHandler // * @param clazz Class object of the sub-type // * @param classLoader ClassLoader to be used to instantiate // * @return ChallengeHandler // */ // protected static <T extends ChallengeHandler> T create(Class<T> clazz, // ClassLoader classLoader) { // return load0(clazz, ServiceLoader.load(clazz, classLoader)); // } // // /** // * Can the presented challenge be potentially handled by this challenge handler? // * // * @param challengeRequest a challenge request object containing a challenge // * @return true iff this challenge handler could potentially respond meaningfully to the challenge. // */ // public abstract boolean canHandle(ChallengeRequest challengeRequest); // // /** // * Handle the presented challenge by creating a challenge response or returning {@code null}. // * This responsibility is usually achieved // * by using the associated {@link LoginHandler} to obtain user credentials, and transforming those credentials // * into a {@link ChallengeResponse}. // * <p> // * When it is not possible to create a {@link ChallengeResponse}, this method MUST return {@code null}. // * // * @param challengeRequest a challenge object // * @return a challenge response object or {@code null} if no response is possible. // */ // public abstract ChallengeResponse handle(ChallengeRequest challengeRequest); // // // ----------------------- Private Methods ------------------------------- // // private static <T extends ChallengeHandler> T load0(Class<T> clazz, // ServiceLoader<T> serviceLoader) { // for (ChallengeHandler challengeHandler: serviceLoader) { // Class<?> c = challengeHandler.getClass(); // if ((clazz != null) && clazz.isAssignableFrom(c)) { // try { // return clazz.cast(c.newInstance()); // } catch (InstantiationException e) { // String s = "Failed to instantiate class " + c; // throw new RuntimeException(s, e); // } catch (IllegalAccessException e) { // String s = "Failed to access and instantiate class " + c; // throw new RuntimeException(s, e); // } // } // } // return null; // } // // } // // Path: http/src/main/java/org/kaazing/netx/http/auth/ChallengeResponse.java // public class ChallengeResponse { // // private char[] credentials; // private ChallengeHandler nextChallengeHandler; // // /** // * Constructor from a set of credentials to send to the server in an 'Authorization:' header // * and the next challenge handler responsible for handling any further challenges for the request. // * // * @param credentials a set of credentials to send to the server in an 'Authorization:' header // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeResponse(char[] credentials, ChallengeHandler nextChallengeHandler) { // this.credentials = credentials; // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Return the next challenge handler responsible for handling any further challenges for the request. // * // * @return the next challenge handler responsible for handling any further challenges for the request. // */ // public ChallengeHandler getNextChallengeHandler() { // return nextChallengeHandler; // } // // /** // * Return a set of credentials to send to the server in an 'Authorization:' header. // * // * @return a set of credentials to send to the server in an 'Authorization:' header. // */ // public char[] getCredentials() { // return credentials; // } // // /** // * Establish the credentials for this response. // * // * @param credentials the credentials to be used for this challenge response. // */ // public void setCredentials(char[] credentials) { // this.credentials = credentials; // } // // /** // * Establish the next challenge handler responsible for handling any further challenges for the request. // * // * @param nextChallengeHandler the next challenge handler responsible for handling any further challenges for the request. // */ // public void setNextChallengeHandler(ChallengeHandler nextChallengeHandler) { // this.nextChallengeHandler = nextChallengeHandler; // } // // /** // * Clear the credentials of this response. // * <p> // * Calling this method once the credentials have been communicated to the network layer // * protects credentials in memory. // */ // public void clearCredentials() { // if (getCredentials() != null) { // Arrays.fill(getCredentials(), (char) 0); // } // } // } // Path: http/src/main/java/org/kaazing/netx/http/internal/auth/BasicChallengeResponseFactory.java import java.net.PasswordAuthentication; import java.nio.charset.Charset; import java.util.Arrays; import org.kaazing.netx.http.auth.ChallengeHandler; import org.kaazing.netx.http.auth.ChallengeResponse; import org.kaazing.netx.http.internal.Base64; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.http.internal.auth; public final class BasicChallengeResponseFactory { private static final Charset US_ASCII = Charset.forName("US-ASCII"); private BasicChallengeResponseFactory() { }
public static ChallengeResponse create(PasswordAuthentication creds, ChallengeHandler nextChallengeHandler) {
kaazing/netx
ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/ContinuationTest.java
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTestUtil.java // public static byte[] fromHex(final String string) { // return fromHexByteArray(string.getBytes(UTF8_CHARSET)); // }
import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.kaazing.netx.ws.internal.ext.flyweight.FrameTestUtil.fromHex; import java.nio.ByteBuffer; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theory;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; public class ContinuationTest extends FrameTest { enum Fin { SET, UNSET; } @DataPoint public static final Fin FIN_SET = Fin.SET; @DataPoint public static final Fin FIN_UNSET = Fin.UNSET; @Theory public void shouldDecodeContinuationWithEmptyPayload(int offset, Fin fin) throws Exception { FrameRW continuationFrame = new FrameRW().wrap(buffer, offset); continuationFrame.fin((fin == Fin.SET) ? true : false); continuationFrame.opcode(Opcode.CONTINUATION); continuationFrame.payloadPut((ByteBuffer) null, offset, 0); assertEquals(Opcode.CONTINUATION, continuationFrame.opcode()); assertEquals(0, continuationFrame.payloadLength()); assertEquals(fin == Fin.SET, continuationFrame.fin()); } @Theory public void shouldDecodeContinuationWithUTF8Payload(int offset, Fin fin) throws Exception { FrameRW continuationFrame = new FrameRW().wrap(buffer, offset); ByteBuffer bytes = ByteBuffer.allocate(1000); bytes.put("e acute (0xE9 or 0x11101001): ".getBytes(UTF_8)); bytes.put((byte) 0xC3).put((byte) 0xA9); bytes.put(", Euro sign: ".getBytes(UTF_8));
// Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/FrameTestUtil.java // public static byte[] fromHex(final String string) { // return fromHexByteArray(string.getBytes(UTF8_CHARSET)); // } // Path: ws/src/test/java/org/kaazing/netx/ws/internal/ext/flyweight/ContinuationTest.java import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.kaazing.netx.ws.internal.ext.flyweight.FrameTestUtil.fromHex; import java.nio.ByteBuffer; import org.junit.experimental.theories.DataPoint; import org.junit.experimental.theories.Theory; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.ws.internal.ext.flyweight; public class ContinuationTest extends FrameTest { enum Fin { SET, UNSET; } @DataPoint public static final Fin FIN_SET = Fin.SET; @DataPoint public static final Fin FIN_UNSET = Fin.UNSET; @Theory public void shouldDecodeContinuationWithEmptyPayload(int offset, Fin fin) throws Exception { FrameRW continuationFrame = new FrameRW().wrap(buffer, offset); continuationFrame.fin((fin == Fin.SET) ? true : false); continuationFrame.opcode(Opcode.CONTINUATION); continuationFrame.payloadPut((ByteBuffer) null, offset, 0); assertEquals(Opcode.CONTINUATION, continuationFrame.opcode()); assertEquals(0, continuationFrame.payloadLength()); assertEquals(fin == Fin.SET, continuationFrame.fin()); } @Theory public void shouldDecodeContinuationWithUTF8Payload(int offset, Fin fin) throws Exception { FrameRW continuationFrame = new FrameRW().wrap(buffer, offset); ByteBuffer bytes = ByteBuffer.allocate(1000); bytes.put("e acute (0xE9 or 0x11101001): ".getBytes(UTF_8)); bytes.put((byte) 0xC3).put((byte) 0xA9); bytes.put(", Euro sign: ".getBytes(UTF_8));
bytes.put(fromHex("e282ac"));
kaazing/netx
bbosh/src/main/java/org/kaazing/netx/bbosh/internal/BBoshPollingSocket.java
// Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public abstract class BBoshStrategy { // // /** // * The BBOSH connection strategy kind. // */ // public static enum Kind { // // /** // * The polling BBOSH connection strategy kind. // */ // POLLING, // // /** // * The streaming BBOSH connection strategy kind. // */ // STREAMING // } // // /** // * Returns the BBOSH connection strategy kind. // * // * @return the BBOSH connection strategy kind // */ // public abstract Kind getKind(); // // /** // * Returns the maximum number of concurrent in-flight HTTP requests. // * // * @return the maximum number of concurrent in-flight HTTP requests // */ // public abstract int getRequests(); // // /** // * Returns the BBOSH connection strategy parsed from string format. // * // * @param strategy the string formatted BBOSH connection strategy // * // * @return the BBOSH connection strategy // * @throws IllegalArgumentException if the strategy cannot be parsed // */ // public static BBoshStrategy valueOf(String strategy) throws IllegalArgumentException { // // if (strategy != null && !strategy.isEmpty()) { // switch (strategy.charAt(0)) { // case 'p': // Matcher pollingMatcher = Polling.PATTERN.matcher(strategy); // if (pollingMatcher.matches()) { // int interval = parseInt(pollingMatcher.group(1)); // TimeUnit intervalUnit = SECONDS; // return new Polling(interval, intervalUnit); // } // break; // case 's': // Matcher streamingMatcher = Streaming.PATTERN.matcher(strategy); // if (streamingMatcher.matches()) { // return new Streaming(); // } // break; // default: // break; // } // } // // throw new IllegalArgumentException(strategy); // } // // /** // * The {@code Polling} BBOSH connection strategy. // * // * An HTTP request is repeatedly made to the server at a specific interval. When the client needs to send data to the // * server, then the HTTP request body is present. When the server needs to send data to the client, then the response // * body is present. // */ // public static final class Polling extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("polling;interval=([0-9]+)s"); // // private final int interval; // private final TimeUnit intervalUnit; // // /** // * Creates a new {@code Polling} BBOSH connection strategy. // * // * @param interval the time interval count // * @param intervalUnit the time interval unit // */ // public Polling(int interval, TimeUnit intervalUnit) { // this.interval = interval; // this.intervalUnit = intervalUnit; // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.POLLING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return a string representation such as {@code "polling;interval=30s"} // */ // public String toString() { // return format("polling;interval=%d%s", interval, toLowerCase(intervalUnit.name().charAt(0))); // } // } // // /** // * The {@code Streaming} BBOSH connection strategy. // * // * An HTTP request is streamed as chunks to the server and the HTTP response is streamed as chunks back to the client. // * When the client needs to send data to the server, then a new chunk is sent on the HTTP request body. // * When the server needs to send data to the client, then a new chunk is sent on the HTTP response body. // */ // public static final class Streaming extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("streaming;request=chunked"); // // /** // * Creates a new {@code Streaming} BBOSH connections strategy. // */ // public Streaming() { // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.STREAMING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return the string representation {@code "streaming;request=chunked"} // */ // public String toString() { // return "streaming;request=chunked"; // } // } // // }
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.kaazing.netx.bbosh.BBoshStrategy;
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.bbosh.internal; final class BBoshPollingSocket extends BBoshSocket { private static final int STATUS_OPEN = 0; private static final int STATUS_READ_CLOSED = 1 << 0; private static final int STATUS_WRITE_CLOSED = 1 << 1; private static final int STATUS_CLOSED = STATUS_READ_CLOSED | STATUS_WRITE_CLOSED; private final Object lock; private final URL location; private final HttpURLConnection[] connections; private final InputStream input; private final OutputStream output; private int sequenceNo; private int status;
// Path: bbosh/src/main/java/org/kaazing/netx/bbosh/BBoshStrategy.java // public abstract class BBoshStrategy { // // /** // * The BBOSH connection strategy kind. // */ // public static enum Kind { // // /** // * The polling BBOSH connection strategy kind. // */ // POLLING, // // /** // * The streaming BBOSH connection strategy kind. // */ // STREAMING // } // // /** // * Returns the BBOSH connection strategy kind. // * // * @return the BBOSH connection strategy kind // */ // public abstract Kind getKind(); // // /** // * Returns the maximum number of concurrent in-flight HTTP requests. // * // * @return the maximum number of concurrent in-flight HTTP requests // */ // public abstract int getRequests(); // // /** // * Returns the BBOSH connection strategy parsed from string format. // * // * @param strategy the string formatted BBOSH connection strategy // * // * @return the BBOSH connection strategy // * @throws IllegalArgumentException if the strategy cannot be parsed // */ // public static BBoshStrategy valueOf(String strategy) throws IllegalArgumentException { // // if (strategy != null && !strategy.isEmpty()) { // switch (strategy.charAt(0)) { // case 'p': // Matcher pollingMatcher = Polling.PATTERN.matcher(strategy); // if (pollingMatcher.matches()) { // int interval = parseInt(pollingMatcher.group(1)); // TimeUnit intervalUnit = SECONDS; // return new Polling(interval, intervalUnit); // } // break; // case 's': // Matcher streamingMatcher = Streaming.PATTERN.matcher(strategy); // if (streamingMatcher.matches()) { // return new Streaming(); // } // break; // default: // break; // } // } // // throw new IllegalArgumentException(strategy); // } // // /** // * The {@code Polling} BBOSH connection strategy. // * // * An HTTP request is repeatedly made to the server at a specific interval. When the client needs to send data to the // * server, then the HTTP request body is present. When the server needs to send data to the client, then the response // * body is present. // */ // public static final class Polling extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("polling;interval=([0-9]+)s"); // // private final int interval; // private final TimeUnit intervalUnit; // // /** // * Creates a new {@code Polling} BBOSH connection strategy. // * // * @param interval the time interval count // * @param intervalUnit the time interval unit // */ // public Polling(int interval, TimeUnit intervalUnit) { // this.interval = interval; // this.intervalUnit = intervalUnit; // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.POLLING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return a string representation such as {@code "polling;interval=30s"} // */ // public String toString() { // return format("polling;interval=%d%s", interval, toLowerCase(intervalUnit.name().charAt(0))); // } // } // // /** // * The {@code Streaming} BBOSH connection strategy. // * // * An HTTP request is streamed as chunks to the server and the HTTP response is streamed as chunks back to the client. // * When the client needs to send data to the server, then a new chunk is sent on the HTTP request body. // * When the server needs to send data to the client, then a new chunk is sent on the HTTP response body. // */ // public static final class Streaming extends BBoshStrategy { // // private static final Pattern PATTERN = Pattern.compile("streaming;request=chunked"); // // /** // * Creates a new {@code Streaming} BBOSH connections strategy. // */ // public Streaming() { // } // // /** // * {@inheritDoc} // */ // @Override // public Kind getKind() { // return Kind.STREAMING; // } // // /** // * {@inheritDoc} // */ // @Override // public int getRequests() { // return 1; // } // // /** // * Returns a string representation of this BBOSH connection strategy. // * // * @return the string representation {@code "streaming;request=chunked"} // */ // public String toString() { // return "streaming;request=chunked"; // } // } // // } // Path: bbosh/src/main/java/org/kaazing/netx/bbosh/internal/BBoshPollingSocket.java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import org.kaazing.netx.bbosh.BBoshStrategy; /** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaazing.netx.bbosh.internal; final class BBoshPollingSocket extends BBoshSocket { private static final int STATUS_OPEN = 0; private static final int STATUS_READ_CLOSED = 1 << 0; private static final int STATUS_WRITE_CLOSED = 1 << 1; private static final int STATUS_CLOSED = STATUS_READ_CLOSED | STATUS_WRITE_CLOSED; private final Object lock; private final URL location; private final HttpURLConnection[] connections; private final InputStream input; private final OutputStream output; private int sequenceNo; private int status;
BBoshPollingSocket(URL location, int initialSequenceNo, BBoshStrategy strategy) {
ralscha/eds-starter6-jpa
src/main/java/ch/rasc/eds/starter/schedule/DisableInactiveUser.java
// Path: src/main/java/ch/rasc/eds/starter/util/JPAQueryFactory.java // public class JPAQueryFactory extends com.querydsl.jpa.impl.JPAQueryFactory { // // private final EntityManager entityManager; // // public JPAQueryFactory(EntityManager entityManager) { // super(entityManager); // this.entityManager = entityManager; // } // // public EntityManager getEntityManager() { // return this.entityManager; // } // // }
import java.time.ZoneOffset; import java.time.ZonedDateTime; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ch.rasc.eds.starter.entity.QUser; import ch.rasc.eds.starter.util.JPAQueryFactory;
package ch.rasc.eds.starter.schedule; @Component public class DisableInactiveUser {
// Path: src/main/java/ch/rasc/eds/starter/util/JPAQueryFactory.java // public class JPAQueryFactory extends com.querydsl.jpa.impl.JPAQueryFactory { // // private final EntityManager entityManager; // // public JPAQueryFactory(EntityManager entityManager) { // super(entityManager); // this.entityManager = entityManager; // } // // public EntityManager getEntityManager() { // return this.entityManager; // } // // } // Path: src/main/java/ch/rasc/eds/starter/schedule/DisableInactiveUser.java import java.time.ZoneOffset; import java.time.ZonedDateTime; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ch.rasc.eds.starter.entity.QUser; import ch.rasc.eds.starter.util.JPAQueryFactory; package ch.rasc.eds.starter.schedule; @Component public class DisableInactiveUser {
private final JPAQueryFactory jpaQueryFactory;
ralscha/eds-starter6-jpa
src/main/java/ch/rasc/eds/starter/config/DataConfig.java
// Path: src/main/java/ch/rasc/eds/starter/util/JPAQueryFactory.java // public class JPAQueryFactory extends com.querydsl.jpa.impl.JPAQueryFactory { // // private final EntityManager entityManager; // // public JPAQueryFactory(EntityManager entityManager) { // super(entityManager); // this.entityManager = entityManager; // } // // public EntityManager getEntityManager() { // return this.entityManager; // } // // }
import javax.persistence.EntityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ch.rasc.eds.starter.util.JPAQueryFactory;
package ch.rasc.eds.starter.config; @Configuration public class DataConfig { @Bean
// Path: src/main/java/ch/rasc/eds/starter/util/JPAQueryFactory.java // public class JPAQueryFactory extends com.querydsl.jpa.impl.JPAQueryFactory { // // private final EntityManager entityManager; // // public JPAQueryFactory(EntityManager entityManager) { // super(entityManager); // this.entityManager = entityManager; // } // // public EntityManager getEntityManager() { // return this.entityManager; // } // // } // Path: src/main/java/ch/rasc/eds/starter/config/DataConfig.java import javax.persistence.EntityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ch.rasc.eds.starter.util.JPAQueryFactory; package ch.rasc.eds.starter.config; @Configuration public class DataConfig { @Bean
public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
ralscha/eds-starter6-jpa
src/main/java/ch/rasc/eds/starter/config/AppLocaleResolver.java
// Path: src/main/java/ch/rasc/eds/starter/config/security/JpaUserDetails.java // public class JpaUserDetails implements UserDetails { // // private static final long serialVersionUID = 1L; // // private Collection<GrantedAuthority> authorities; // // private final String userAuthorities; // // private final String password; // // private final String loginName; // // private final boolean enabled; // // private final Long userDbId; // // private final boolean locked; // // private final Locale locale; // // public JpaUserDetails(User user) { // this.userDbId = user.getId(); // // this.password = user.getPasswordHash(); // this.loginName = user.getLoginName(); // this.enabled = user.isEnabled(); // // if (StringUtils.hasText(user.getLocale())) { // this.locale = new Locale(user.getLocale()); // } // else { // this.locale = Locale.ENGLISH; // } // // this.locked = user.getLockedOutUntil() != null // && user.getLockedOutUntil().isAfter(ZonedDateTime.now(ZoneOffset.UTC)); // // this.userAuthorities = user.getAuthorities(); // // if (StringUtils.hasText(user.getSecret())) { // this.authorities = Collections.unmodifiableCollection( // AuthorityUtils.createAuthorityList("PRE_AUTH")); // } // else { // this.authorities = Collections.unmodifiableCollection(AuthorityUtils // .commaSeparatedStringToAuthorityList(user.getAuthorities())); // } // } // // public boolean isPreAuth() { // return hasAuthority("PRE_AUTH"); // } // // public void grantAuthorities() { // this.authorities = Collections.unmodifiableCollection( // AuthorityUtils.commaSeparatedStringToAuthorityList(this.userAuthorities)); // } // // @Override // public Collection<GrantedAuthority> getAuthorities() { // return this.authorities; // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.loginName; // } // // public User getUser(JPAQueryFactory jpaQueryFactory) { // User user = jpaQueryFactory.getEntityManager().find(User.class, getUserDbId()); // // if (user != null && !user.isDeleted()) { // return user; // } // // return null; // } // // public Long getUserDbId() { // return this.userDbId; // } // // public Locale getLocale() { // return this.locale; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return !this.locked; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return this.enabled; // } // // public boolean hasAuthority(String authority) { // return getAuthorities().stream() // .anyMatch(a -> authority.equals(a.getAuthority())); // } // // }
import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.servlet.i18n.AbstractLocaleResolver; import ch.rasc.eds.starter.config.security.JpaUserDetails;
package ch.rasc.eds.starter.config; public class AppLocaleResolver extends AbstractLocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { return request.getLocale(); }
// Path: src/main/java/ch/rasc/eds/starter/config/security/JpaUserDetails.java // public class JpaUserDetails implements UserDetails { // // private static final long serialVersionUID = 1L; // // private Collection<GrantedAuthority> authorities; // // private final String userAuthorities; // // private final String password; // // private final String loginName; // // private final boolean enabled; // // private final Long userDbId; // // private final boolean locked; // // private final Locale locale; // // public JpaUserDetails(User user) { // this.userDbId = user.getId(); // // this.password = user.getPasswordHash(); // this.loginName = user.getLoginName(); // this.enabled = user.isEnabled(); // // if (StringUtils.hasText(user.getLocale())) { // this.locale = new Locale(user.getLocale()); // } // else { // this.locale = Locale.ENGLISH; // } // // this.locked = user.getLockedOutUntil() != null // && user.getLockedOutUntil().isAfter(ZonedDateTime.now(ZoneOffset.UTC)); // // this.userAuthorities = user.getAuthorities(); // // if (StringUtils.hasText(user.getSecret())) { // this.authorities = Collections.unmodifiableCollection( // AuthorityUtils.createAuthorityList("PRE_AUTH")); // } // else { // this.authorities = Collections.unmodifiableCollection(AuthorityUtils // .commaSeparatedStringToAuthorityList(user.getAuthorities())); // } // } // // public boolean isPreAuth() { // return hasAuthority("PRE_AUTH"); // } // // public void grantAuthorities() { // this.authorities = Collections.unmodifiableCollection( // AuthorityUtils.commaSeparatedStringToAuthorityList(this.userAuthorities)); // } // // @Override // public Collection<GrantedAuthority> getAuthorities() { // return this.authorities; // } // // @Override // public String getPassword() { // return this.password; // } // // @Override // public String getUsername() { // return this.loginName; // } // // public User getUser(JPAQueryFactory jpaQueryFactory) { // User user = jpaQueryFactory.getEntityManager().find(User.class, getUserDbId()); // // if (user != null && !user.isDeleted()) { // return user; // } // // return null; // } // // public Long getUserDbId() { // return this.userDbId; // } // // public Locale getLocale() { // return this.locale; // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return !this.locked; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return this.enabled; // } // // public boolean hasAuthority(String authority) { // return getAuthorities().stream() // .anyMatch(a -> authority.equals(a.getAuthority())); // } // // } // Path: src/main/java/ch/rasc/eds/starter/config/AppLocaleResolver.java import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.servlet.i18n.AbstractLocaleResolver; import ch.rasc.eds.starter.config.security.JpaUserDetails; package ch.rasc.eds.starter.config; public class AppLocaleResolver extends AbstractLocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { return request.getLocale(); }
else if (authentication.getPrincipal() instanceof JpaUserDetails) {
ralscha/eds-starter6-jpa
src/main/java/ch/rasc/eds/starter/util/TotpAuthUtil.java
// Path: src/main/java/ch/rasc/eds/starter/Application.java // @Configuration // @ComponentScan(basePackageClasses = { ExtDirectSpring.class, Application.class }, // excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, // value = ApiController.class) }) // @EnableAutoConfiguration(exclude = { MustacheAutoConfiguration.class, // SpringDataWebAutoConfiguration.class }) // @EnableAsync // @EnableScheduling // @EntityScan(basePackageClasses = AbstractPersistable.class) // public class Application { // // public static final Logger logger = LoggerFactory // .getLogger(MethodHandles.lookup().lookupClass()); // // public static void main(String[] args) { // // -Dspring.profiles.active=development // SpringApplication.run(Application.class, args); // } // // }
import java.nio.ByteBuffer; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Random; import java.util.stream.Collectors; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.google.common.io.BaseEncoding; import ch.rasc.eds.starter.Application;
package ch.rasc.eds.starter.util; public class TotpAuthUtil { public static boolean verifyCode(String secret, int code, int variance) { long timeIndex = System.currentTimeMillis() / 1000 / 30; byte[] secretBytes = BaseEncoding.base32().decode(secret); for (int i = -variance; i <= variance; i++) { if (getCode(secretBytes, timeIndex + i) == code) { return true; } } return false; } public static long getCode(byte[] secret, long timeIndex) { try { SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1"); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(timeIndex); byte[] timeBytes = buffer.array(); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(timeBytes); int offset = hash[19] & 0xf; long truncatedHash = hash[offset] & 0x7f; for (int i = 1; i < 4; i++) { truncatedHash <<= 8; truncatedHash |= hash[offset + i] & 0xff; } return truncatedHash %= 1000000; } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e) {
// Path: src/main/java/ch/rasc/eds/starter/Application.java // @Configuration // @ComponentScan(basePackageClasses = { ExtDirectSpring.class, Application.class }, // excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, // value = ApiController.class) }) // @EnableAutoConfiguration(exclude = { MustacheAutoConfiguration.class, // SpringDataWebAutoConfiguration.class }) // @EnableAsync // @EnableScheduling // @EntityScan(basePackageClasses = AbstractPersistable.class) // public class Application { // // public static final Logger logger = LoggerFactory // .getLogger(MethodHandles.lookup().lookupClass()); // // public static void main(String[] args) { // // -Dspring.profiles.active=development // SpringApplication.run(Application.class, args); // } // // } // Path: src/main/java/ch/rasc/eds/starter/util/TotpAuthUtil.java import java.nio.ByteBuffer; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Random; import java.util.stream.Collectors; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.google.common.io.BaseEncoding; import ch.rasc.eds.starter.Application; package ch.rasc.eds.starter.util; public class TotpAuthUtil { public static boolean verifyCode(String secret, int code, int variance) { long timeIndex = System.currentTimeMillis() / 1000 / 30; byte[] secretBytes = BaseEncoding.base32().decode(secret); for (int i = -variance; i <= variance; i++) { if (getCode(secretBytes, timeIndex + i) == code) { return true; } } return false; } public static long getCode(byte[] secret, long timeIndex) { try { SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1"); ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(timeIndex); byte[] timeBytes = buffer.array(); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(timeBytes); int offset = hash[19] & 0xf; long truncatedHash = hash[offset] & 0x7f; for (int i = 1; i < 4; i++) { truncatedHash <<= 8; truncatedHash |= hash[offset + i] & 0xff; } return truncatedHash %= 1000000; } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException e) {
Application.logger.error("getCode", e);
ralscha/eds-starter6-jpa
src/main/java/ch/rasc/eds/starter/Application.java
// Path: src/main/java/ch/rasc/eds/starter/entity/AbstractPersistable.java // @MappedSuperclass // public abstract class AbstractPersistable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @ModelField(useNull = true, convert = "null") // private Long id; // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return String.format("Entity of type %s with id: %s", this.getClass().getName(), // getId()); // } // // @Override // public boolean equals(Object obj) { // // if (null == obj) { // return false; // } // // if (this == obj) { // return true; // } // // if (!getClass().equals(obj.getClass())) { // return false; // } // // AbstractPersistable that = (AbstractPersistable) obj; // // return null == this.getId() ? false : this.getId().equals(that.getId()); // } // // @Override // public int hashCode() { // int hashCode = 17; // hashCode += null == getId() ? 0 : getId().hashCode() * 31; // return hashCode; // } // }
import java.lang.invoke.MethodHandles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import ch.ralscha.extdirectspring.ExtDirectSpring; import ch.ralscha.extdirectspring.controller.ApiController; import ch.rasc.eds.starter.entity.AbstractPersistable;
package ch.rasc.eds.starter; @Configuration @ComponentScan(basePackageClasses = { ExtDirectSpring.class, Application.class }, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ApiController.class) }) @EnableAutoConfiguration(exclude = { MustacheAutoConfiguration.class, SpringDataWebAutoConfiguration.class }) @EnableAsync @EnableScheduling
// Path: src/main/java/ch/rasc/eds/starter/entity/AbstractPersistable.java // @MappedSuperclass // public abstract class AbstractPersistable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // @ModelField(useNull = true, convert = "null") // private Long id; // // public Long getId() { // return this.id; // } // // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return String.format("Entity of type %s with id: %s", this.getClass().getName(), // getId()); // } // // @Override // public boolean equals(Object obj) { // // if (null == obj) { // return false; // } // // if (this == obj) { // return true; // } // // if (!getClass().equals(obj.getClass())) { // return false; // } // // AbstractPersistable that = (AbstractPersistable) obj; // // return null == this.getId() ? false : this.getId().equals(that.getId()); // } // // @Override // public int hashCode() { // int hashCode = 17; // hashCode += null == getId() ? 0 : getId().hashCode() * 31; // return hashCode; // } // } // Path: src/main/java/ch/rasc/eds/starter/Application.java import java.lang.invoke.MethodHandles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import ch.ralscha.extdirectspring.ExtDirectSpring; import ch.ralscha.extdirectspring.controller.ApiController; import ch.rasc.eds.starter.entity.AbstractPersistable; package ch.rasc.eds.starter; @Configuration @ComponentScan(basePackageClasses = { ExtDirectSpring.class, Application.class }, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = ApiController.class) }) @EnableAutoConfiguration(exclude = { MustacheAutoConfiguration.class, SpringDataWebAutoConfiguration.class }) @EnableAsync @EnableScheduling
@EntityScan(basePackageClasses = AbstractPersistable.class)
ralscha/eds-starter6-jpa
src/main/java/ch/rasc/eds/starter/config/security/UserAuthSuccessfulHandler.java
// Path: src/main/java/ch/rasc/eds/starter/util/JPAQueryFactory.java // public class JPAQueryFactory extends com.querydsl.jpa.impl.JPAQueryFactory { // // private final EntityManager entityManager; // // public JPAQueryFactory(EntityManager entityManager) { // super(entityManager); // this.entityManager = entityManager; // } // // public EntityManager getEntityManager() { // return this.entityManager; // } // // }
import org.springframework.context.ApplicationListener; import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ch.rasc.eds.starter.entity.QUser; import ch.rasc.eds.starter.util.JPAQueryFactory;
package ch.rasc.eds.starter.config.security; @Component public class UserAuthSuccessfulHandler implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
// Path: src/main/java/ch/rasc/eds/starter/util/JPAQueryFactory.java // public class JPAQueryFactory extends com.querydsl.jpa.impl.JPAQueryFactory { // // private final EntityManager entityManager; // // public JPAQueryFactory(EntityManager entityManager) { // super(entityManager); // this.entityManager = entityManager; // } // // public EntityManager getEntityManager() { // return this.entityManager; // } // // } // Path: src/main/java/ch/rasc/eds/starter/config/security/UserAuthSuccessfulHandler.java import org.springframework.context.ApplicationListener; import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import ch.rasc.eds.starter.entity.QUser; import ch.rasc.eds.starter.util.JPAQueryFactory; package ch.rasc.eds.starter.config.security; @Component public class UserAuthSuccessfulHandler implements ApplicationListener<InteractiveAuthenticationSuccessEvent> {
private final JPAQueryFactory jpaQueryFactory;
deathmarine/Ultrabans
src/com/modcrafting/ultrabans/UltrabansAPI.java
// Path: src/com/modcrafting/ultrabans/util/InfoBan.java // public class InfoBan { // private String uuid; // private String[] aliases; // private String reason; // private String admin; // private long endTime; // private int type; // // public InfoBan(String uuid, String[] aliases, String reason, String admin, long endTime, int type) { // this.setUuid(uuid); // this.setAliases(aliases); // this.setReason(reason); // this.setAdmin(admin); // this.setEndTime(endTime); // this.setType(type); // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public String[] getAliases() { // return aliases; // } // // public void setAliases(String[] aliases) { // this.aliases = aliases; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getAdmin() { // return admin; // } // // public void setAdmin(String admin) { // this.admin = admin; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // } // // Path: src/com/modcrafting/ultrabans/util/BanType.java // public enum BanType { // BAN(0), IPBAN(1), WARN(2), KICK(3), UNBAN(5), JAIL(6), MUTE(7), INFO(8), PERMA( // 9), TEMPBAN(10), TEMPIPBAN(11), TEMPJAIL(12); // int id; // // private BanType(int i) { // id = i; // } // // public int getId() { // return id; // } // // public String toCode() { // return toCode(id); // } // // public static BanType fromID(int type) { // for (BanType tp : BanType.values()) // if (tp.getId() == type) // return tp; // return BAN; // } // // public static String toCode(int num) { // switch (num) { // case 0: // return "B"; // case 1: // return "IP"; // case 2: // return "W"; // case 3: // return "K"; // case 4: // return "F"; // case 5: // return "UN"; // case 6: // return "J"; // case 7: // return "M"; // case 9: // return "PB"; // default: // return "?"; // } // } // }
import java.util.ArrayList; import java.util.List; import com.modcrafting.ultrabans.util.InfoBan; import com.modcrafting.ultrabans.util.BanType;
/* COPYRIGHT (c) 2015 Deathmarine * This file is part of Ultrabans. * Ultrabans 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. * * Ultrabans 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. * * You should have received a copy of the GNU General Public License * along with Ultrabans. If not, see <http://www.gnu.org/licenses/>. */ package com.modcrafting.ultrabans; public class UltrabansAPI { Ultrabans plugin; public UltrabansAPI(Ultrabans instance){ plugin = instance; }
// Path: src/com/modcrafting/ultrabans/util/InfoBan.java // public class InfoBan { // private String uuid; // private String[] aliases; // private String reason; // private String admin; // private long endTime; // private int type; // // public InfoBan(String uuid, String[] aliases, String reason, String admin, long endTime, int type) { // this.setUuid(uuid); // this.setAliases(aliases); // this.setReason(reason); // this.setAdmin(admin); // this.setEndTime(endTime); // this.setType(type); // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public String[] getAliases() { // return aliases; // } // // public void setAliases(String[] aliases) { // this.aliases = aliases; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getAdmin() { // return admin; // } // // public void setAdmin(String admin) { // this.admin = admin; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // } // // Path: src/com/modcrafting/ultrabans/util/BanType.java // public enum BanType { // BAN(0), IPBAN(1), WARN(2), KICK(3), UNBAN(5), JAIL(6), MUTE(7), INFO(8), PERMA( // 9), TEMPBAN(10), TEMPIPBAN(11), TEMPJAIL(12); // int id; // // private BanType(int i) { // id = i; // } // // public int getId() { // return id; // } // // public String toCode() { // return toCode(id); // } // // public static BanType fromID(int type) { // for (BanType tp : BanType.values()) // if (tp.getId() == type) // return tp; // return BAN; // } // // public static String toCode(int num) { // switch (num) { // case 0: // return "B"; // case 1: // return "IP"; // case 2: // return "W"; // case 3: // return "K"; // case 4: // return "F"; // case 5: // return "UN"; // case 6: // return "J"; // case 7: // return "M"; // case 9: // return "PB"; // default: // return "?"; // } // } // } // Path: src/com/modcrafting/ultrabans/UltrabansAPI.java import java.util.ArrayList; import java.util.List; import com.modcrafting.ultrabans.util.InfoBan; import com.modcrafting.ultrabans.util.BanType; /* COPYRIGHT (c) 2015 Deathmarine * This file is part of Ultrabans. * Ultrabans 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. * * Ultrabans 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. * * You should have received a copy of the GNU General Public License * along with Ultrabans. If not, see <http://www.gnu.org/licenses/>. */ package com.modcrafting.ultrabans; public class UltrabansAPI { Ultrabans plugin; public UltrabansAPI(Ultrabans instance){ plugin = instance; }
public void addPlayer(final String uuid, final String reason, final String admin, final long time, final BanType type){
deathmarine/Ultrabans
src/com/modcrafting/ultrabans/UltrabansAPI.java
// Path: src/com/modcrafting/ultrabans/util/InfoBan.java // public class InfoBan { // private String uuid; // private String[] aliases; // private String reason; // private String admin; // private long endTime; // private int type; // // public InfoBan(String uuid, String[] aliases, String reason, String admin, long endTime, int type) { // this.setUuid(uuid); // this.setAliases(aliases); // this.setReason(reason); // this.setAdmin(admin); // this.setEndTime(endTime); // this.setType(type); // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public String[] getAliases() { // return aliases; // } // // public void setAliases(String[] aliases) { // this.aliases = aliases; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getAdmin() { // return admin; // } // // public void setAdmin(String admin) { // this.admin = admin; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // } // // Path: src/com/modcrafting/ultrabans/util/BanType.java // public enum BanType { // BAN(0), IPBAN(1), WARN(2), KICK(3), UNBAN(5), JAIL(6), MUTE(7), INFO(8), PERMA( // 9), TEMPBAN(10), TEMPIPBAN(11), TEMPJAIL(12); // int id; // // private BanType(int i) { // id = i; // } // // public int getId() { // return id; // } // // public String toCode() { // return toCode(id); // } // // public static BanType fromID(int type) { // for (BanType tp : BanType.values()) // if (tp.getId() == type) // return tp; // return BAN; // } // // public static String toCode(int num) { // switch (num) { // case 0: // return "B"; // case 1: // return "IP"; // case 2: // return "W"; // case 3: // return "K"; // case 4: // return "F"; // case 5: // return "UN"; // case 6: // return "J"; // case 7: // return "M"; // case 9: // return "PB"; // default: // return "?"; // } // } // }
import java.util.ArrayList; import java.util.List; import com.modcrafting.ultrabans.util.InfoBan; import com.modcrafting.ultrabans.util.BanType;
/* COPYRIGHT (c) 2015 Deathmarine * This file is part of Ultrabans. * Ultrabans 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. * * Ultrabans 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. * * You should have received a copy of the GNU General Public License * along with Ultrabans. If not, see <http://www.gnu.org/licenses/>. */ package com.modcrafting.ultrabans; public class UltrabansAPI { Ultrabans plugin; public UltrabansAPI(Ultrabans instance){ plugin = instance; } public void addPlayer(final String uuid, final String reason, final String admin, final long time, final BanType type){ plugin.getServer().getScheduler().runTaskAsynchronously(Ultrabans.getPlugin(),new Runnable(){ @Override public void run() { plugin.getUBDatabase().addPlayer(uuid, reason, admin, time, type.getId()); } }); } public void banPlayer(final String uuid, final String reason, final String admin){
// Path: src/com/modcrafting/ultrabans/util/InfoBan.java // public class InfoBan { // private String uuid; // private String[] aliases; // private String reason; // private String admin; // private long endTime; // private int type; // // public InfoBan(String uuid, String[] aliases, String reason, String admin, long endTime, int type) { // this.setUuid(uuid); // this.setAliases(aliases); // this.setReason(reason); // this.setAdmin(admin); // this.setEndTime(endTime); // this.setType(type); // } // // public String getUuid() { // return uuid; // } // // public void setUuid(String uuid) { // this.uuid = uuid; // } // // public String[] getAliases() { // return aliases; // } // // public void setAliases(String[] aliases) { // this.aliases = aliases; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getAdmin() { // return admin; // } // // public void setAdmin(String admin) { // this.admin = admin; // } // // public long getEndTime() { // return endTime; // } // // public void setEndTime(long endTime) { // this.endTime = endTime; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // } // // Path: src/com/modcrafting/ultrabans/util/BanType.java // public enum BanType { // BAN(0), IPBAN(1), WARN(2), KICK(3), UNBAN(5), JAIL(6), MUTE(7), INFO(8), PERMA( // 9), TEMPBAN(10), TEMPIPBAN(11), TEMPJAIL(12); // int id; // // private BanType(int i) { // id = i; // } // // public int getId() { // return id; // } // // public String toCode() { // return toCode(id); // } // // public static BanType fromID(int type) { // for (BanType tp : BanType.values()) // if (tp.getId() == type) // return tp; // return BAN; // } // // public static String toCode(int num) { // switch (num) { // case 0: // return "B"; // case 1: // return "IP"; // case 2: // return "W"; // case 3: // return "K"; // case 4: // return "F"; // case 5: // return "UN"; // case 6: // return "J"; // case 7: // return "M"; // case 9: // return "PB"; // default: // return "?"; // } // } // } // Path: src/com/modcrafting/ultrabans/UltrabansAPI.java import java.util.ArrayList; import java.util.List; import com.modcrafting.ultrabans.util.InfoBan; import com.modcrafting.ultrabans.util.BanType; /* COPYRIGHT (c) 2015 Deathmarine * This file is part of Ultrabans. * Ultrabans 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. * * Ultrabans 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. * * You should have received a copy of the GNU General Public License * along with Ultrabans. If not, see <http://www.gnu.org/licenses/>. */ package com.modcrafting.ultrabans; public class UltrabansAPI { Ultrabans plugin; public UltrabansAPI(Ultrabans instance){ plugin = instance; } public void addPlayer(final String uuid, final String reason, final String admin, final long time, final BanType type){ plugin.getServer().getScheduler().runTaskAsynchronously(Ultrabans.getPlugin(),new Runnable(){ @Override public void run() { plugin.getUBDatabase().addPlayer(uuid, reason, admin, time, type.getId()); } }); } public void banPlayer(final String uuid, final String reason, final String admin){
List<InfoBan> list = new ArrayList<InfoBan>();
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestFlowApi.java
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // }
import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result;
package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010");
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // Path: src/test/java/com/yunpian/sdk/api/TestFlowApi.java import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result; package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010");
Result<List<FlowPackage>> r = clnt.flow().get_package(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestFlowApi.java
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // }
import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result;
package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010");
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // Path: src/test/java/com/yunpian/sdk/api/TestFlowApi.java import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result; package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010");
Result<List<FlowPackage>> r = clnt.flow().get_package(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestFlowApi.java
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // }
import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result;
package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010"); Result<List<FlowPackage>> r = clnt.flow().get_package(param); System.out.println(r); // r = ((FlowApi) clnt.flow().version(VERSION_V1)).get_package(param); // System.out.println(r); } @Test public void rechargeTest() { Map<String, String> param = clnt.newParam(3); param.put(MOBILE, "11111111111"); param.put(SN, "1008601"); // param.put(CALLBACK_URL, "http://your_receive_url_address");
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // Path: src/test/java/com/yunpian/sdk/api/TestFlowApi.java import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result; package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010"); Result<List<FlowPackage>> r = clnt.flow().get_package(param); System.out.println(r); // r = ((FlowApi) clnt.flow().version(VERSION_V1)).get_package(param); // System.out.println(r); } @Test public void rechargeTest() { Map<String, String> param = clnt.newParam(3); param.put(MOBILE, "11111111111"); param.put(SN, "1008601"); // param.put(CALLBACK_URL, "http://your_receive_url_address");
Result<FlowSend> r = clnt.flow().recharge(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestFlowApi.java
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // }
import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result;
package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010"); Result<List<FlowPackage>> r = clnt.flow().get_package(param); System.out.println(r); // r = ((FlowApi) clnt.flow().version(VERSION_V1)).get_package(param); // System.out.println(r); } @Test public void rechargeTest() { Map<String, String> param = clnt.newParam(3); param.put(MOBILE, "11111111111"); param.put(SN, "1008601"); // param.put(CALLBACK_URL, "http://your_receive_url_address"); Result<FlowSend> r = clnt.flow().recharge(param); System.out.println(r); // r = ((FlowApi) clnt.flow().version(VERSION_V1)).recharge(param); // System.out.println(r); } @Test public void pull_statusTest() { Map<String, String> param = clnt.newParam(2); param.put(MOBILE, "11111111111"); // param.put(PAGE_SIZE, "20");
// Path: src/main/java/com/yunpian/sdk/model/FlowPackage.java // public class FlowPackage { // // private Long sn; // private double carrier_price; // private double discount; // private Integer capacity; // private Long carrier; // private String name; // // public Integer getCapacity() { // return capacity; // } // // public void setCapacity(Integer capacity) { // this.capacity = capacity; // } // // public Long getCarrier() { // return carrier; // } // // public void setCarrier(Long carrier) { // this.carrier = carrier; // } // // public double getCarrier_price() { // return carrier_price; // } // // public void setCarrier_price(double carrier_price) { // this.carrier_price = carrier_price; // } // // public double getDiscount() { // return discount; // } // // public void setDiscount(double discount) { // this.discount = discount; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Long getSn() { // return sn; // } // // public void setSn(Long sn) { // this.sn = sn; // } // // @Override // public String toString() { // return "FlowPackageInfo{" + "capacity=" + capacity + ", sn=" + sn + ", carrier_price=" + carrier_price // + ", discount=" + discount + ", carrier=" + carrier + ", name='" + name + '\'' + '}'; // } // } // // Path: src/main/java/com/yunpian/sdk/model/FlowSend.java // public class FlowSend extends BaseInfo { // } // // Path: src/main/java/com/yunpian/sdk/model/FlowStatus.java // public class FlowStatus extends BaseStatus { // } // // Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // Path: src/test/java/com/yunpian/sdk/api/TestFlowApi.java import java.util.List; import java.util.Map; import org.junit.Test; import com.yunpian.sdk.model.FlowPackage; import com.yunpian.sdk.model.FlowSend; import com.yunpian.sdk.model.FlowStatus; import com.yunpian.sdk.model.Result; package com.yunpian.sdk.api; /** * 手机流量API * * https://www.yunpian.com/api2.0/api-flow.html * * * @author dzh * @date Dec 4, 2016 8:48:08 PM * @since 1.2.0 */ public class TestFlowApi extends TestYunpianClient { @Test public void get_packageTest() { Map<String, String> param = clnt.newParam(1); // param.put(CARRIER, "10010"); Result<List<FlowPackage>> r = clnt.flow().get_package(param); System.out.println(r); // r = ((FlowApi) clnt.flow().version(VERSION_V1)).get_package(param); // System.out.println(r); } @Test public void rechargeTest() { Map<String, String> param = clnt.newParam(3); param.put(MOBILE, "11111111111"); param.put(SN, "1008601"); // param.put(CALLBACK_URL, "http://your_receive_url_address"); Result<FlowSend> r = clnt.flow().recharge(param); System.out.println(r); // r = ((FlowApi) clnt.flow().version(VERSION_V1)).recharge(param); // System.out.println(r); } @Test public void pull_statusTest() { Map<String, String> param = clnt.newParam(2); param.put(MOBILE, "11111111111"); // param.put(PAGE_SIZE, "20");
Result<List<FlowStatus>> r = clnt.flow().pull_status(param);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/SmsBatchSend.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import java.util.List; import com.yunpian.sdk.util.JsonUtil;
public void setData(List<SmsSingleSend> data) { this.data = data; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public Integer getTotal_count() { return total_count; } public void setTotal_count(Integer total_count) { this.total_count = total_count; } public Double getTotal_fee() { return total_fee; } public void setTotal_fee(Double total_fee) { this.total_fee = total_fee; } @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/SmsBatchSend.java import java.util.List; import com.yunpian.sdk.util.JsonUtil; public void setData(List<SmsSingleSend> data) { this.data = data; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public Integer getTotal_count() { return total_count; } public void setTotal_count(Integer total_count) { this.total_count = total_count; } public Double getTotal_fee() { return total_fee; } public void setTotal_fee(Double total_fee) { this.total_fee = total_fee; } @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestVoiceApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceSend.java // public class VoiceSend extends BaseInfo { // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java // public class VoiceStatus extends BaseStatus { // private String uid; // private String duration; // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public String getUid() { // return uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // }
import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.VoiceStatus;
package com.yunpian.sdk.api; /** * 语音验证码API * * https://www.yunpian.com/api2.0/api-voice.html * * @author dzh * @date Dec 4, 2016 8:24:07 PM * @since 1.2.0 */ public class TestVoiceApi extends TestYunpianClient { @Test @Ignore public void sendTest() { Map<String, String> param = clnt.newParam(4); param.put(MOBILE, "11111111111"); param.put(CODE, "123412"); // param.put(CALLBACK_URL, ""); // param.put(DISPLAY_NUM, "");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceSend.java // public class VoiceSend extends BaseInfo { // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java // public class VoiceStatus extends BaseStatus { // private String uid; // private String duration; // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public String getUid() { // return uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // } // Path: src/test/java/com/yunpian/sdk/api/TestVoiceApi.java import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.VoiceStatus; package com.yunpian.sdk.api; /** * 语音验证码API * * https://www.yunpian.com/api2.0/api-voice.html * * @author dzh * @date Dec 4, 2016 8:24:07 PM * @since 1.2.0 */ public class TestVoiceApi extends TestYunpianClient { @Test @Ignore public void sendTest() { Map<String, String> param = clnt.newParam(4); param.put(MOBILE, "11111111111"); param.put(CODE, "123412"); // param.put(CALLBACK_URL, ""); // param.put(DISPLAY_NUM, "");
Result<VoiceSend> r = clnt.voice().send(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestVoiceApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceSend.java // public class VoiceSend extends BaseInfo { // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java // public class VoiceStatus extends BaseStatus { // private String uid; // private String duration; // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public String getUid() { // return uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // }
import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.VoiceStatus;
package com.yunpian.sdk.api; /** * 语音验证码API * * https://www.yunpian.com/api2.0/api-voice.html * * @author dzh * @date Dec 4, 2016 8:24:07 PM * @since 1.2.0 */ public class TestVoiceApi extends TestYunpianClient { @Test @Ignore public void sendTest() { Map<String, String> param = clnt.newParam(4); param.put(MOBILE, "11111111111"); param.put(CODE, "123412"); // param.put(CALLBACK_URL, ""); // param.put(DISPLAY_NUM, "");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceSend.java // public class VoiceSend extends BaseInfo { // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java // public class VoiceStatus extends BaseStatus { // private String uid; // private String duration; // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public String getUid() { // return uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // } // Path: src/test/java/com/yunpian/sdk/api/TestVoiceApi.java import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.VoiceStatus; package com.yunpian.sdk.api; /** * 语音验证码API * * https://www.yunpian.com/api2.0/api-voice.html * * @author dzh * @date Dec 4, 2016 8:24:07 PM * @since 1.2.0 */ public class TestVoiceApi extends TestYunpianClient { @Test @Ignore public void sendTest() { Map<String, String> param = clnt.newParam(4); param.put(MOBILE, "11111111111"); param.put(CODE, "123412"); // param.put(CALLBACK_URL, ""); // param.put(DISPLAY_NUM, "");
Result<VoiceSend> r = clnt.voice().send(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestVoiceApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceSend.java // public class VoiceSend extends BaseInfo { // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java // public class VoiceStatus extends BaseStatus { // private String uid; // private String duration; // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public String getUid() { // return uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // }
import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.VoiceStatus;
package com.yunpian.sdk.api; /** * 语音验证码API * * https://www.yunpian.com/api2.0/api-voice.html * * @author dzh * @date Dec 4, 2016 8:24:07 PM * @since 1.2.0 */ public class TestVoiceApi extends TestYunpianClient { @Test @Ignore public void sendTest() { Map<String, String> param = clnt.newParam(4); param.put(MOBILE, "11111111111"); param.put(CODE, "123412"); // param.put(CALLBACK_URL, ""); // param.put(DISPLAY_NUM, ""); Result<VoiceSend> r = clnt.voice().send(param); System.out.println(r); // r = ((VoiceApi) clnt.voice().version(VERSION_V1)).send(param); // System.out.println(r); } @Test @Ignore public void pull_statusTest() { Map<String, String> param = clnt.newParam(1); // param.put(page_size, "20");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceSend.java // public class VoiceSend extends BaseInfo { // // } // // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java // public class VoiceStatus extends BaseStatus { // private String uid; // private String duration; // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public String getUid() { // return uid; // } // // public void setUid(String uid) { // this.uid = uid; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // } // Path: src/test/java/com/yunpian/sdk/api/TestVoiceApi.java import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.VoiceSend; import com.yunpian.sdk.model.VoiceStatus; package com.yunpian.sdk.api; /** * 语音验证码API * * https://www.yunpian.com/api2.0/api-voice.html * * @author dzh * @date Dec 4, 2016 8:24:07 PM * @since 1.2.0 */ public class TestVoiceApi extends TestYunpianClient { @Test @Ignore public void sendTest() { Map<String, String> param = clnt.newParam(4); param.put(MOBILE, "11111111111"); param.put(CODE, "123412"); // param.put(CALLBACK_URL, ""); // param.put(DISPLAY_NUM, ""); Result<VoiceSend> r = clnt.voice().send(param); System.out.println(r); // r = ((VoiceApi) clnt.voice().version(VERSION_V1)).send(param); // System.out.println(r); } @Test @Ignore public void pull_statusTest() { Map<String, String> param = clnt.newParam(1); // param.put(page_size, "20");
Result<List<VoiceStatus>> r = clnt.voice().pull_status(param);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/VideoLayout.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import java.util.List; import com.yunpian.sdk.util.JsonUtil;
this.attachments = attachments; return this; } } public static class FrameData { private int index = 1; private String fileName; // zip里的文件名,如file1.txt。模板创建后改为 文件id.后缀 根据这个字段获取文件 public int getIndex() { return index; } public FrameData setIndex(int index) { this.index = index; return this; } public String getFileName() { return fileName; } public FrameData setFileName(String fileName) { this.fileName = fileName; return this; } } public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/VideoLayout.java import java.util.List; import com.yunpian.sdk.util.JsonUtil; this.attachments = attachments; return this; } } public static class FrameData { private int index = 1; private String fileName; // zip里的文件名,如file1.txt。模板创建后改为 文件id.后缀 根据这个字段获取文件 public int getIndex() { return index; } public FrameData setIndex(int index) { this.index = index; return this; } public String getFileName() { return fileName; } public FrameData setFileName(String fileName) { this.fileName = fileName; return this; } } public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/SmsSingleSend.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import com.yunpian.sdk.util.JsonUtil;
public void setMobile(String mobile) { this.mobile = mobile; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Long getSid() { return sid; } public void setSid(Long sid) { this.sid = sid; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/SmsSingleSend.java import com.yunpian.sdk.util.JsonUtil; public void setMobile(String mobile) { this.mobile = mobile; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Long getSid() { return sid; } public void setSid(Long sid) { this.sid = sid; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/BaseStatus.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import com.yunpian.sdk.util.JsonUtil;
public void setMobile(String mobile) { this.mobile = mobile; } public String getReport_status() { return report_status; } public void setReport_status(String report_status) { this.report_status = report_status; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getUser_receive_time() { return user_receive_time; } public void setUser_receive_time(String user_receive_time) { this.user_receive_time = user_receive_time; } @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/BaseStatus.java import com.yunpian.sdk.util.JsonUtil; public void setMobile(String mobile) { this.mobile = mobile; } public String getReport_status() { return report_status; } public void setReport_status(String report_status) { this.report_status = report_status; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } public String getUser_receive_time() { return user_receive_time; } public void setUser_receive_time(String user_receive_time) { this.user_receive_time = user_receive_time; } @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestUserApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/User.java // public class User { // // private String nick; // // private Date gmt_created; // // private String mobile; // // private String email; // // private String ip_whitelist; // // private String api_version; // // private Long alarm_balance; // // private String emergency_contact; // // private String emergency_mobile; // // private Double balance; // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public Date getGmt_created() { // return gmt_created; // } // // public void setGmt_created(Date gmt_created) { // this.gmt_created = gmt_created; // } // // public String getMobile() { // return mobile; // } // // public void setMobile(String mobile) { // this.mobile = mobile; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getIp_whitelist() { // return ip_whitelist; // } // // public void setIp_whitelist(String ip_whitelist) { // this.ip_whitelist = ip_whitelist; // } // // public String getApi_version() { // return api_version; // } // // public void setApi_version(String api_version) { // this.api_version = api_version; // } // // public Long getAlarm_balance() { // return alarm_balance; // } // // public void setAlarm_balance(Long alarm_balance) { // this.alarm_balance = alarm_balance; // } // // public String getEmergency_contact() { // return emergency_contact; // } // // public void setEmergency_contact(String emergency_contact) { // this.emergency_contact = emergency_contact; // } // // public String getEmergency_mobile() { // return emergency_mobile; // } // // public void setEmergency_mobile(String emergency_mobile) { // this.emergency_mobile = emergency_mobile; // } // // public Double getBalance() { // return balance; // } // // public void setBalance(Double balance) { // this.balance = balance; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // }
import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.User; import java.util.Map; import org.junit.Test;
/** * */ package com.yunpian.sdk.api; /** * 账户API * * https://www.yunpian.com/api2.0/api-user.html * * @author dzh * @date Dec 3, 2016 12:09:10 AM * @since 1.2.0 */ public class TestUserApi extends TestYunpianClient { @Test public void getTest() {
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/User.java // public class User { // // private String nick; // // private Date gmt_created; // // private String mobile; // // private String email; // // private String ip_whitelist; // // private String api_version; // // private Long alarm_balance; // // private String emergency_contact; // // private String emergency_mobile; // // private Double balance; // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public Date getGmt_created() { // return gmt_created; // } // // public void setGmt_created(Date gmt_created) { // this.gmt_created = gmt_created; // } // // public String getMobile() { // return mobile; // } // // public void setMobile(String mobile) { // this.mobile = mobile; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getIp_whitelist() { // return ip_whitelist; // } // // public void setIp_whitelist(String ip_whitelist) { // this.ip_whitelist = ip_whitelist; // } // // public String getApi_version() { // return api_version; // } // // public void setApi_version(String api_version) { // this.api_version = api_version; // } // // public Long getAlarm_balance() { // return alarm_balance; // } // // public void setAlarm_balance(Long alarm_balance) { // this.alarm_balance = alarm_balance; // } // // public String getEmergency_contact() { // return emergency_contact; // } // // public void setEmergency_contact(String emergency_contact) { // this.emergency_contact = emergency_contact; // } // // public String getEmergency_mobile() { // return emergency_mobile; // } // // public void setEmergency_mobile(String emergency_mobile) { // this.emergency_mobile = emergency_mobile; // } // // public Double getBalance() { // return balance; // } // // public void setBalance(Double balance) { // this.balance = balance; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // } // Path: src/test/java/com/yunpian/sdk/api/TestUserApi.java import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.User; import java.util.Map; import org.junit.Test; /** * */ package com.yunpian.sdk.api; /** * 账户API * * https://www.yunpian.com/api2.0/api-user.html * * @author dzh * @date Dec 3, 2016 12:09:10 AM * @since 1.2.0 */ public class TestUserApi extends TestYunpianClient { @Test public void getTest() {
Result<User> r = clnt.user().get();
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestUserApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/User.java // public class User { // // private String nick; // // private Date gmt_created; // // private String mobile; // // private String email; // // private String ip_whitelist; // // private String api_version; // // private Long alarm_balance; // // private String emergency_contact; // // private String emergency_mobile; // // private Double balance; // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public Date getGmt_created() { // return gmt_created; // } // // public void setGmt_created(Date gmt_created) { // this.gmt_created = gmt_created; // } // // public String getMobile() { // return mobile; // } // // public void setMobile(String mobile) { // this.mobile = mobile; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getIp_whitelist() { // return ip_whitelist; // } // // public void setIp_whitelist(String ip_whitelist) { // this.ip_whitelist = ip_whitelist; // } // // public String getApi_version() { // return api_version; // } // // public void setApi_version(String api_version) { // this.api_version = api_version; // } // // public Long getAlarm_balance() { // return alarm_balance; // } // // public void setAlarm_balance(Long alarm_balance) { // this.alarm_balance = alarm_balance; // } // // public String getEmergency_contact() { // return emergency_contact; // } // // public void setEmergency_contact(String emergency_contact) { // this.emergency_contact = emergency_contact; // } // // public String getEmergency_mobile() { // return emergency_mobile; // } // // public void setEmergency_mobile(String emergency_mobile) { // this.emergency_mobile = emergency_mobile; // } // // public Double getBalance() { // return balance; // } // // public void setBalance(Double balance) { // this.balance = balance; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // }
import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.User; import java.util.Map; import org.junit.Test;
/** * */ package com.yunpian.sdk.api; /** * 账户API * * https://www.yunpian.com/api2.0/api-user.html * * @author dzh * @date Dec 3, 2016 12:09:10 AM * @since 1.2.0 */ public class TestUserApi extends TestYunpianClient { @Test public void getTest() {
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/User.java // public class User { // // private String nick; // // private Date gmt_created; // // private String mobile; // // private String email; // // private String ip_whitelist; // // private String api_version; // // private Long alarm_balance; // // private String emergency_contact; // // private String emergency_mobile; // // private Double balance; // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public Date getGmt_created() { // return gmt_created; // } // // public void setGmt_created(Date gmt_created) { // this.gmt_created = gmt_created; // } // // public String getMobile() { // return mobile; // } // // public void setMobile(String mobile) { // this.mobile = mobile; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getIp_whitelist() { // return ip_whitelist; // } // // public void setIp_whitelist(String ip_whitelist) { // this.ip_whitelist = ip_whitelist; // } // // public String getApi_version() { // return api_version; // } // // public void setApi_version(String api_version) { // this.api_version = api_version; // } // // public Long getAlarm_balance() { // return alarm_balance; // } // // public void setAlarm_balance(Long alarm_balance) { // this.alarm_balance = alarm_balance; // } // // public String getEmergency_contact() { // return emergency_contact; // } // // public void setEmergency_contact(String emergency_contact) { // this.emergency_contact = emergency_contact; // } // // public String getEmergency_mobile() { // return emergency_mobile; // } // // public void setEmergency_mobile(String emergency_mobile) { // this.emergency_mobile = emergency_mobile; // } // // public Double getBalance() { // return balance; // } // // public void setBalance(Double balance) { // this.balance = balance; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // } // Path: src/test/java/com/yunpian/sdk/api/TestUserApi.java import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.User; import java.util.Map; import org.junit.Test; /** * */ package com.yunpian.sdk.api; /** * 账户API * * https://www.yunpian.com/api2.0/api-user.html * * @author dzh * @date Dec 3, 2016 12:09:10 AM * @since 1.2.0 */ public class TestUserApi extends TestYunpianClient { @Test public void getTest() {
Result<User> r = clnt.user().get();
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestShortUrlApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/ShortUrl.java // public class ShortUrl { // // private String sid; // private String long_url; // private String short_url; // private String enter_url; // private String name; // private String stat_expire; // // public String getSid() { // return sid; // } // // public void setSid(String sid) { // this.sid = sid; // } // // public String getLong_url() { // return long_url; // } // // public void setLong_url(String long_url) { // this.long_url = long_url; // } // // public String getShort_url() { // return short_url; // } // // public void setShort_url(String short_url) { // this.short_url = short_url; // } // // public String getEnter_url() { // return enter_url; // } // // public void setEnter_url(String enter_url) { // this.enter_url = enter_url; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getStat_expire() { // return stat_expire; // } // // public void setStat_expire(String stat_expire) { // this.stat_expire = stat_expire; // } // }
import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.ShortUrl; import org.junit.Test; import java.util.Map;
package com.yunpian.sdk.api; /** * Created by liujie on 2017/9/29. */ public class TestShortUrlApi extends TestYunpianClient { @Test public void shortenTest() { Map<String, String> param = clnt.newParam(5); param.put(LONG_URL, "https://www.yunpian.com/"); param.put(NAME, "sdk-test1"); param.put(STAT_DURATION, "3"); param.put(PROVIDER, "1");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/ShortUrl.java // public class ShortUrl { // // private String sid; // private String long_url; // private String short_url; // private String enter_url; // private String name; // private String stat_expire; // // public String getSid() { // return sid; // } // // public void setSid(String sid) { // this.sid = sid; // } // // public String getLong_url() { // return long_url; // } // // public void setLong_url(String long_url) { // this.long_url = long_url; // } // // public String getShort_url() { // return short_url; // } // // public void setShort_url(String short_url) { // this.short_url = short_url; // } // // public String getEnter_url() { // return enter_url; // } // // public void setEnter_url(String enter_url) { // this.enter_url = enter_url; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getStat_expire() { // return stat_expire; // } // // public void setStat_expire(String stat_expire) { // this.stat_expire = stat_expire; // } // } // Path: src/test/java/com/yunpian/sdk/api/TestShortUrlApi.java import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.ShortUrl; import org.junit.Test; import java.util.Map; package com.yunpian.sdk.api; /** * Created by liujie on 2017/9/29. */ public class TestShortUrlApi extends TestYunpianClient { @Test public void shortenTest() { Map<String, String> param = clnt.newParam(5); param.put(LONG_URL, "https://www.yunpian.com/"); param.put(NAME, "sdk-test1"); param.put(STAT_DURATION, "3"); param.put(PROVIDER, "1");
Result<ShortUrl> r = clnt.shortUrl().shorten(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestShortUrlApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/ShortUrl.java // public class ShortUrl { // // private String sid; // private String long_url; // private String short_url; // private String enter_url; // private String name; // private String stat_expire; // // public String getSid() { // return sid; // } // // public void setSid(String sid) { // this.sid = sid; // } // // public String getLong_url() { // return long_url; // } // // public void setLong_url(String long_url) { // this.long_url = long_url; // } // // public String getShort_url() { // return short_url; // } // // public void setShort_url(String short_url) { // this.short_url = short_url; // } // // public String getEnter_url() { // return enter_url; // } // // public void setEnter_url(String enter_url) { // this.enter_url = enter_url; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getStat_expire() { // return stat_expire; // } // // public void setStat_expire(String stat_expire) { // this.stat_expire = stat_expire; // } // }
import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.ShortUrl; import org.junit.Test; import java.util.Map;
package com.yunpian.sdk.api; /** * Created by liujie on 2017/9/29. */ public class TestShortUrlApi extends TestYunpianClient { @Test public void shortenTest() { Map<String, String> param = clnt.newParam(5); param.put(LONG_URL, "https://www.yunpian.com/"); param.put(NAME, "sdk-test1"); param.put(STAT_DURATION, "3"); param.put(PROVIDER, "1");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/ShortUrl.java // public class ShortUrl { // // private String sid; // private String long_url; // private String short_url; // private String enter_url; // private String name; // private String stat_expire; // // public String getSid() { // return sid; // } // // public void setSid(String sid) { // this.sid = sid; // } // // public String getLong_url() { // return long_url; // } // // public void setLong_url(String long_url) { // this.long_url = long_url; // } // // public String getShort_url() { // return short_url; // } // // public void setShort_url(String short_url) { // this.short_url = short_url; // } // // public String getEnter_url() { // return enter_url; // } // // public void setEnter_url(String enter_url) { // this.enter_url = enter_url; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getStat_expire() { // return stat_expire; // } // // public void setStat_expire(String stat_expire) { // this.stat_expire = stat_expire; // } // } // Path: src/test/java/com/yunpian/sdk/api/TestShortUrlApi.java import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.ShortUrl; import org.junit.Test; import java.util.Map; package com.yunpian.sdk.api; /** * Created by liujie on 2017/9/29. */ public class TestShortUrlApi extends TestYunpianClient { @Test public void shortenTest() { Map<String, String> param = clnt.newParam(5); param.put(LONG_URL, "https://www.yunpian.com/"); param.put(NAME, "sdk-test1"); param.put(STAT_DURATION, "3"); param.put(PROVIDER, "1");
Result<ShortUrl> r = clnt.shortUrl().shorten(param);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/VoiceStatus.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import com.yunpian.sdk.util.JsonUtil;
package com.yunpian.sdk.model; /** * Created by bingone on 16/1/12. */ public class VoiceStatus extends BaseStatus { private String uid; private String duration; public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/VoiceStatus.java import com.yunpian.sdk.util.JsonUtil; package com.yunpian.sdk.model; /** * Created by bingone on 16/1/12. */ public class VoiceStatus extends BaseStatus { private String uid; private String duration; public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/SmsRecord.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import com.google.gson.annotations.SerializedName; import com.yunpian.sdk.util.JsonUtil;
package com.yunpian.sdk.model; /** * Created by bingone on 16/1/18. */ public class SmsRecord { private String sid; private String mobile; @SerializedName("send_time") private String sendTime; private String text; @SerializedName("report_status") private String reportStatus; private Double fee; @SerializedName("user_receive_time") private String userReceiveTime; @SerializedName("error_msg") private String errorMsg; private String uid; @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/SmsRecord.java import com.google.gson.annotations.SerializedName; import com.yunpian.sdk.util.JsonUtil; package com.yunpian.sdk.model; /** * Created by bingone on 16/1/18. */ public class SmsRecord { private String sid; private String mobile; @SerializedName("send_time") private String sendTime; private String text; @SerializedName("report_status") private String reportStatus; private Double fee; @SerializedName("user_receive_time") private String userReceiveTime; @SerializedName("error_msg") private String errorMsg; private String uid; @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/SmsReply.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import com.yunpian.sdk.util.JsonUtil;
package com.yunpian.sdk.model; /** * Created by bingone on 15/11/6. */ public class SmsReply { // 用户自定义id private String base_extend; private String extend; private String reply_time; private String mobile; private String text; private String id; private String _sign; public String getId() { return id; } public void setId(String id) { this.id = id; } public String get_sign() { return _sign; } public void set_sign(String _sign) { this._sign = _sign; } @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/SmsReply.java import com.yunpian.sdk.util.JsonUtil; package com.yunpian.sdk.model; /** * Created by bingone on 15/11/6. */ public class SmsReply { // 用户自定义id private String base_extend; private String extend; private String reply_time; private String mobile; private String text; private String id; private String _sign; public String getId() { return id; } public void setId(String id) { this.id = id; } public String get_sign() { return _sign; } public void set_sign(String _sign) { this._sign = _sign; } @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/service/JsonTest.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.yunpian.sdk.util.JsonUtil;
package com.yunpian.sdk.service; /** * Created by bingone on 16/1/19. */ @Deprecated public class JsonTest { String old = ""; @SuppressWarnings("unused") @Test public void test() { JsonParser jsonParser = new JsonParser(); JsonArray jsonArray = (JsonArray) jsonParser.parse(old); JsonObject ret = new JsonObject(); List<String> proList = new ArrayList<String>(); List<String> cityList = new ArrayList<String>(); for (int i = 0; i < jsonArray.size(); i++) { JsonObject jsonObject = jsonArray.get(i).getAsJsonObject(); proList.add(jsonObject.get("lable").getAsString()); cityList.clear(); JsonObject pro = new JsonObject(); JsonObject city = new JsonObject(); for (int j = 0; j < jsonObject.get("cities").getAsJsonArray().size(); j++) { JsonObject country = new JsonObject(); JsonObject jsonObject1 = jsonObject.get("cities").getAsJsonArray().get(j).getAsJsonObject(); cityList.add(jsonObject1.get("lable").getAsString()); JsonObject jsonObject2 = new JsonObject();
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/test/java/com/yunpian/sdk/service/JsonTest.java import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.yunpian.sdk.util.JsonUtil; package com.yunpian.sdk.service; /** * Created by bingone on 16/1/19. */ @Deprecated public class JsonTest { String old = ""; @SuppressWarnings("unused") @Test public void test() { JsonParser jsonParser = new JsonParser(); JsonArray jsonArray = (JsonArray) jsonParser.parse(old); JsonObject ret = new JsonObject(); List<String> proList = new ArrayList<String>(); List<String> cityList = new ArrayList<String>(); for (int i = 0; i < jsonArray.size(); i++) { JsonObject jsonObject = jsonArray.get(i).getAsJsonObject(); proList.add(jsonObject.get("lable").getAsString()); cityList.clear(); JsonObject pro = new JsonObject(); JsonObject city = new JsonObject(); for (int j = 0; j < jsonObject.get("cities").getAsJsonArray().size(); j++) { JsonObject country = new JsonObject(); JsonObject jsonObject1 = jsonObject.get("cities").getAsJsonArray().get(j).getAsJsonObject(); cityList.add(jsonObject1.get("lable").getAsString()); JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("countryList", JsonUtil.toJson(jsonObject1.get("counties")));
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestTplApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Template.java // public class Template { // private Long tpl_id; // private String tpl_content; // private String check_status; // private String reason; // private String lang; // private String country_code; // // public String getLang() { // return lang; // } // // public void setLang(String lang) { // this.lang = lang; // } // // public String getCountry_code() { // return country_code; // } // // public void setCountry_code(String country_code) { // this.country_code = country_code; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getTpl_content() { // return tpl_content; // } // // public void setTpl_content(String tpl_content) { // this.tpl_content = tpl_content; // } // // public Long getTpl_id() { // return tpl_id; // } // // public void setTpl_id(Long tpl_id) { // this.tpl_id = tpl_id; // } // // @Override // public String toString() { // return "TemplateInfo{" + "check_status='" + check_status + '\'' + ", tpl_id=" + tpl_id + ", tpl_content='" // + tpl_content + '\'' + ", reason='" + reason + '\'' + '}'; // } // }
import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Template;
package com.yunpian.sdk.api; /** * 模版 * * https://www.yunpian.com/api2.0/api-domestic/tpl_add.html * * @author dzh * @date Dec 5, 2016 12:33:43 PM * @since 1.2.0 */ public class TestTplApi extends TestYunpianClient { @Test @Ignore public void addTest() { Map<String, String> param = clnt.newParam(2); param.put(TPL_CONTENT, "【云片网】您的验证码是#code#"); // param.put(NOTIFY_TYPE, "true");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Template.java // public class Template { // private Long tpl_id; // private String tpl_content; // private String check_status; // private String reason; // private String lang; // private String country_code; // // public String getLang() { // return lang; // } // // public void setLang(String lang) { // this.lang = lang; // } // // public String getCountry_code() { // return country_code; // } // // public void setCountry_code(String country_code) { // this.country_code = country_code; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getTpl_content() { // return tpl_content; // } // // public void setTpl_content(String tpl_content) { // this.tpl_content = tpl_content; // } // // public Long getTpl_id() { // return tpl_id; // } // // public void setTpl_id(Long tpl_id) { // this.tpl_id = tpl_id; // } // // @Override // public String toString() { // return "TemplateInfo{" + "check_status='" + check_status + '\'' + ", tpl_id=" + tpl_id + ", tpl_content='" // + tpl_content + '\'' + ", reason='" + reason + '\'' + '}'; // } // } // Path: src/test/java/com/yunpian/sdk/api/TestTplApi.java import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Template; package com.yunpian.sdk.api; /** * 模版 * * https://www.yunpian.com/api2.0/api-domestic/tpl_add.html * * @author dzh * @date Dec 5, 2016 12:33:43 PM * @since 1.2.0 */ public class TestTplApi extends TestYunpianClient { @Test @Ignore public void addTest() { Map<String, String> param = clnt.newParam(2); param.put(TPL_CONTENT, "【云片网】您的验证码是#code#"); // param.put(NOTIFY_TYPE, "true");
Result<Template> r = clnt.tpl().add(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestTplApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Template.java // public class Template { // private Long tpl_id; // private String tpl_content; // private String check_status; // private String reason; // private String lang; // private String country_code; // // public String getLang() { // return lang; // } // // public void setLang(String lang) { // this.lang = lang; // } // // public String getCountry_code() { // return country_code; // } // // public void setCountry_code(String country_code) { // this.country_code = country_code; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getTpl_content() { // return tpl_content; // } // // public void setTpl_content(String tpl_content) { // this.tpl_content = tpl_content; // } // // public Long getTpl_id() { // return tpl_id; // } // // public void setTpl_id(Long tpl_id) { // this.tpl_id = tpl_id; // } // // @Override // public String toString() { // return "TemplateInfo{" + "check_status='" + check_status + '\'' + ", tpl_id=" + tpl_id + ", tpl_content='" // + tpl_content + '\'' + ", reason='" + reason + '\'' + '}'; // } // }
import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Template;
package com.yunpian.sdk.api; /** * 模版 * * https://www.yunpian.com/api2.0/api-domestic/tpl_add.html * * @author dzh * @date Dec 5, 2016 12:33:43 PM * @since 1.2.0 */ public class TestTplApi extends TestYunpianClient { @Test @Ignore public void addTest() { Map<String, String> param = clnt.newParam(2); param.put(TPL_CONTENT, "【云片网】您的验证码是#code#"); // param.put(NOTIFY_TYPE, "true");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Template.java // public class Template { // private Long tpl_id; // private String tpl_content; // private String check_status; // private String reason; // private String lang; // private String country_code; // // public String getLang() { // return lang; // } // // public void setLang(String lang) { // this.lang = lang; // } // // public String getCountry_code() { // return country_code; // } // // public void setCountry_code(String country_code) { // this.country_code = country_code; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public String getReason() { // return reason; // } // // public void setReason(String reason) { // this.reason = reason; // } // // public String getTpl_content() { // return tpl_content; // } // // public void setTpl_content(String tpl_content) { // this.tpl_content = tpl_content; // } // // public Long getTpl_id() { // return tpl_id; // } // // public void setTpl_id(Long tpl_id) { // this.tpl_id = tpl_id; // } // // @Override // public String toString() { // return "TemplateInfo{" + "check_status='" + check_status + '\'' + ", tpl_id=" + tpl_id + ", tpl_content='" // + tpl_content + '\'' + ", reason='" + reason + '\'' + '}'; // } // } // Path: src/test/java/com/yunpian/sdk/api/TestTplApi.java import java.util.List; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Template; package com.yunpian.sdk.api; /** * 模版 * * https://www.yunpian.com/api2.0/api-domestic/tpl_add.html * * @author dzh * @date Dec 5, 2016 12:33:43 PM * @since 1.2.0 */ public class TestTplApi extends TestYunpianClient { @Test @Ignore public void addTest() { Map<String, String> param = clnt.newParam(2); param.put(TPL_CONTENT, "【云片网】您的验证码是#code#"); // param.put(NOTIFY_TYPE, "true");
Result<Template> r = clnt.tpl().add(param);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/BaseInfo.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import com.yunpian.sdk.util.JsonUtil;
package com.yunpian.sdk.model; /** * Created by bingone on 16/1/12. */ class BaseInfo { protected String sid; protected String count; protected Double fee; @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/BaseInfo.java import com.yunpian.sdk.util.JsonUtil; package com.yunpian.sdk.model; /** * Created by bingone on 16/1/12. */ class BaseInfo { protected String sid; protected String count; protected Double fee; @Override public String toString() {
return JsonUtil.toJson(this);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestSignApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Sign.java // public class Sign { // // //申请签名时的申请信息 // private String apply_state; // private String sign; // private boolean is_apply_vip; // private boolean is_only_global; // private String industry_type; // // //获取签名时的返回参数(以及sign、industry_type),当前签名的信息 // private String chan; // private String check_status; // private boolean enabled; // private String extend; // private boolean only_global; // private String remark; // private boolean vip; // // // public String getApply_state() { // return apply_state; // } // // public void setApply_state(String apply_state) { // this.apply_state = apply_state; // } // // public String getSign() { // return sign; // } // // public void setSign(String sign) { // this.sign = sign; // } // // public boolean is_apply_vip() { // return is_apply_vip; // } // // public void setIs_apply_vip(boolean is_apply_vip) { // this.is_apply_vip = is_apply_vip; // } // // public boolean is_only_global() { // return is_only_global; // } // // public void setIs_only_global(boolean is_only_global) { // this.is_only_global = is_only_global; // } // // public String getIndustry_type() { // return industry_type; // } // // public void setIndustry_type(String industry_type) { // this.industry_type = industry_type; // } // // public String getChan() { // return chan; // } // // public void setChan(String chan) { // this.chan = chan; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public String getExtend() { // return extend; // } // // public void setExtend(String extend) { // this.extend = extend; // } // // public boolean isOnly_global() { // return only_global; // } // // public void setOnly_global(boolean only_global) { // this.only_global = only_global; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public boolean isVip() { // return vip; // } // // public void setVip(boolean vip) { // this.vip = vip; // } // } // // Path: src/main/java/com/yunpian/sdk/model/SignRecord.java // public class SignRecord { // // private int total; // private List<Sign> sign; // // public int getTotal() { // return total; // } // // public void setTotal(int total) { // this.total = total; // } // // public List<Sign> getSign() { // return sign; // } // // public void setSign(List<Sign> sign) { // this.sign = sign; // } // }
import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Sign; import com.yunpian.sdk.model.SignRecord; import org.junit.Test; import java.util.Map;
/** * */ package com.yunpian.sdk.api; /** * 短信签名功能 * <p> * https://www.yunpian.com/api2.0/api-domestic/sign_add.html * * @author dzh * @date Dec 5, 2016 10:27:25 AM * @since 1.2.0 */ public class TestSignApi extends TestYunpianClient { @Test public void addTest() { Map<String, String> param = clnt.newParam(5); param.put(SIGN, "你好吗"); param.put(NOTIFY, "true"); param.put(APPLYVIP, "false"); param.put(ISONLYGLOBAL, "false"); param.put(INDUSTRYTYPE, "其它"); param.put(LICENSE_URL, "https://www.yunpian.com/");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Sign.java // public class Sign { // // //申请签名时的申请信息 // private String apply_state; // private String sign; // private boolean is_apply_vip; // private boolean is_only_global; // private String industry_type; // // //获取签名时的返回参数(以及sign、industry_type),当前签名的信息 // private String chan; // private String check_status; // private boolean enabled; // private String extend; // private boolean only_global; // private String remark; // private boolean vip; // // // public String getApply_state() { // return apply_state; // } // // public void setApply_state(String apply_state) { // this.apply_state = apply_state; // } // // public String getSign() { // return sign; // } // // public void setSign(String sign) { // this.sign = sign; // } // // public boolean is_apply_vip() { // return is_apply_vip; // } // // public void setIs_apply_vip(boolean is_apply_vip) { // this.is_apply_vip = is_apply_vip; // } // // public boolean is_only_global() { // return is_only_global; // } // // public void setIs_only_global(boolean is_only_global) { // this.is_only_global = is_only_global; // } // // public String getIndustry_type() { // return industry_type; // } // // public void setIndustry_type(String industry_type) { // this.industry_type = industry_type; // } // // public String getChan() { // return chan; // } // // public void setChan(String chan) { // this.chan = chan; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public String getExtend() { // return extend; // } // // public void setExtend(String extend) { // this.extend = extend; // } // // public boolean isOnly_global() { // return only_global; // } // // public void setOnly_global(boolean only_global) { // this.only_global = only_global; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public boolean isVip() { // return vip; // } // // public void setVip(boolean vip) { // this.vip = vip; // } // } // // Path: src/main/java/com/yunpian/sdk/model/SignRecord.java // public class SignRecord { // // private int total; // private List<Sign> sign; // // public int getTotal() { // return total; // } // // public void setTotal(int total) { // this.total = total; // } // // public List<Sign> getSign() { // return sign; // } // // public void setSign(List<Sign> sign) { // this.sign = sign; // } // } // Path: src/test/java/com/yunpian/sdk/api/TestSignApi.java import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Sign; import com.yunpian.sdk.model.SignRecord; import org.junit.Test; import java.util.Map; /** * */ package com.yunpian.sdk.api; /** * 短信签名功能 * <p> * https://www.yunpian.com/api2.0/api-domestic/sign_add.html * * @author dzh * @date Dec 5, 2016 10:27:25 AM * @since 1.2.0 */ public class TestSignApi extends TestYunpianClient { @Test public void addTest() { Map<String, String> param = clnt.newParam(5); param.put(SIGN, "你好吗"); param.put(NOTIFY, "true"); param.put(APPLYVIP, "false"); param.put(ISONLYGLOBAL, "false"); param.put(INDUSTRYTYPE, "其它"); param.put(LICENSE_URL, "https://www.yunpian.com/");
Result<Sign> r = clnt.sign().add(param);
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/api/TestSignApi.java
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Sign.java // public class Sign { // // //申请签名时的申请信息 // private String apply_state; // private String sign; // private boolean is_apply_vip; // private boolean is_only_global; // private String industry_type; // // //获取签名时的返回参数(以及sign、industry_type),当前签名的信息 // private String chan; // private String check_status; // private boolean enabled; // private String extend; // private boolean only_global; // private String remark; // private boolean vip; // // // public String getApply_state() { // return apply_state; // } // // public void setApply_state(String apply_state) { // this.apply_state = apply_state; // } // // public String getSign() { // return sign; // } // // public void setSign(String sign) { // this.sign = sign; // } // // public boolean is_apply_vip() { // return is_apply_vip; // } // // public void setIs_apply_vip(boolean is_apply_vip) { // this.is_apply_vip = is_apply_vip; // } // // public boolean is_only_global() { // return is_only_global; // } // // public void setIs_only_global(boolean is_only_global) { // this.is_only_global = is_only_global; // } // // public String getIndustry_type() { // return industry_type; // } // // public void setIndustry_type(String industry_type) { // this.industry_type = industry_type; // } // // public String getChan() { // return chan; // } // // public void setChan(String chan) { // this.chan = chan; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public String getExtend() { // return extend; // } // // public void setExtend(String extend) { // this.extend = extend; // } // // public boolean isOnly_global() { // return only_global; // } // // public void setOnly_global(boolean only_global) { // this.only_global = only_global; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public boolean isVip() { // return vip; // } // // public void setVip(boolean vip) { // this.vip = vip; // } // } // // Path: src/main/java/com/yunpian/sdk/model/SignRecord.java // public class SignRecord { // // private int total; // private List<Sign> sign; // // public int getTotal() { // return total; // } // // public void setTotal(int total) { // this.total = total; // } // // public List<Sign> getSign() { // return sign; // } // // public void setSign(List<Sign> sign) { // this.sign = sign; // } // }
import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Sign; import com.yunpian.sdk.model.SignRecord; import org.junit.Test; import java.util.Map;
/** * */ package com.yunpian.sdk.api; /** * 短信签名功能 * <p> * https://www.yunpian.com/api2.0/api-domestic/sign_add.html * * @author dzh * @date Dec 5, 2016 10:27:25 AM * @since 1.2.0 */ public class TestSignApi extends TestYunpianClient { @Test public void addTest() { Map<String, String> param = clnt.newParam(5); param.put(SIGN, "你好吗"); param.put(NOTIFY, "true"); param.put(APPLYVIP, "false"); param.put(ISONLYGLOBAL, "false"); param.put(INDUSTRYTYPE, "其它"); param.put(LICENSE_URL, "https://www.yunpian.com/");
// Path: src/main/java/com/yunpian/sdk/model/Result.java // public class Result<T> { // // private Integer code = Code.OK; // private String msg; // private String detail; // // private Throwable e; // // private T data; // // public T getData() { // return data; // } // // public String getDetail() { // return detail; // } // // public Result<T> setDetail(String detail) { // this.detail = detail; // return this; // } // // public Result<T> setData(T data) { // this.data = data; // return this; // } // // public Integer getCode() { // return code; // } // // public Result<T> setCode(Integer code) { // this.code = code; // return this; // } // // public String getMsg() { // return msg; // } // // public Result<T> setMsg(String msg) { // this.msg = msg; // return this; // } // // public Throwable getThrowable() { // return e; // } // // public Result<T> setThrowable(Throwable e) { // this.e = e; // return this; // } // // public boolean isSucc() { // return code == Code.OK; // } // // @Override // public String toString() { // return JsonUtil.toJson(this); // } // // } // // Path: src/main/java/com/yunpian/sdk/model/Sign.java // public class Sign { // // //申请签名时的申请信息 // private String apply_state; // private String sign; // private boolean is_apply_vip; // private boolean is_only_global; // private String industry_type; // // //获取签名时的返回参数(以及sign、industry_type),当前签名的信息 // private String chan; // private String check_status; // private boolean enabled; // private String extend; // private boolean only_global; // private String remark; // private boolean vip; // // // public String getApply_state() { // return apply_state; // } // // public void setApply_state(String apply_state) { // this.apply_state = apply_state; // } // // public String getSign() { // return sign; // } // // public void setSign(String sign) { // this.sign = sign; // } // // public boolean is_apply_vip() { // return is_apply_vip; // } // // public void setIs_apply_vip(boolean is_apply_vip) { // this.is_apply_vip = is_apply_vip; // } // // public boolean is_only_global() { // return is_only_global; // } // // public void setIs_only_global(boolean is_only_global) { // this.is_only_global = is_only_global; // } // // public String getIndustry_type() { // return industry_type; // } // // public void setIndustry_type(String industry_type) { // this.industry_type = industry_type; // } // // public String getChan() { // return chan; // } // // public void setChan(String chan) { // this.chan = chan; // } // // public String getCheck_status() { // return check_status; // } // // public void setCheck_status(String check_status) { // this.check_status = check_status; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public String getExtend() { // return extend; // } // // public void setExtend(String extend) { // this.extend = extend; // } // // public boolean isOnly_global() { // return only_global; // } // // public void setOnly_global(boolean only_global) { // this.only_global = only_global; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public boolean isVip() { // return vip; // } // // public void setVip(boolean vip) { // this.vip = vip; // } // } // // Path: src/main/java/com/yunpian/sdk/model/SignRecord.java // public class SignRecord { // // private int total; // private List<Sign> sign; // // public int getTotal() { // return total; // } // // public void setTotal(int total) { // this.total = total; // } // // public List<Sign> getSign() { // return sign; // } // // public void setSign(List<Sign> sign) { // this.sign = sign; // } // } // Path: src/test/java/com/yunpian/sdk/api/TestSignApi.java import com.yunpian.sdk.model.Result; import com.yunpian.sdk.model.Sign; import com.yunpian.sdk.model.SignRecord; import org.junit.Test; import java.util.Map; /** * */ package com.yunpian.sdk.api; /** * 短信签名功能 * <p> * https://www.yunpian.com/api2.0/api-domestic/sign_add.html * * @author dzh * @date Dec 5, 2016 10:27:25 AM * @since 1.2.0 */ public class TestSignApi extends TestYunpianClient { @Test public void addTest() { Map<String, String> param = clnt.newParam(5); param.put(SIGN, "你好吗"); param.put(NOTIFY, "true"); param.put(APPLYVIP, "false"); param.put(ISONLYGLOBAL, "false"); param.put(INDUSTRYTYPE, "其它"); param.put(LICENSE_URL, "https://www.yunpian.com/");
Result<Sign> r = clnt.sign().add(param);
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/util/Convert.java
// Path: src/main/java/com/yunpian/sdk/YunpianException.java // public class YunpianException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public YunpianException(Throwable e) { // super(e); // } // // public YunpianException(String message, Throwable e) { // super(message, e); // } // // public YunpianException(String msg) { // super(msg); // } // // }
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import com.yunpian.sdk.YunpianException;
package com.yunpian.sdk.util; /** * Created by bingone on 15/11/8. */ @Deprecated public class Convert {
// Path: src/main/java/com/yunpian/sdk/YunpianException.java // public class YunpianException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 1L; // // public YunpianException(Throwable e) { // super(e); // } // // public YunpianException(String message, Throwable e) { // super(message, e); // } // // public YunpianException(String msg) { // super(msg); // } // // } // Path: src/main/java/com/yunpian/sdk/util/Convert.java import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import com.yunpian.sdk.YunpianException; package com.yunpian.sdk.util; /** * Created by bingone on 15/11/8. */ @Deprecated public class Convert {
public static Map<String, Object> ConvertObjToMap(Object obj) throws YunpianException {
yunpian/yunpian-java-sdk
src/test/java/com/yunpian/sdk/util/TestApiUtil.java
// Path: src/main/java/com/yunpian/sdk/util/ApiUtil.java // public class ApiUtil { // // static final Logger LOG = LoggerFactory.getLogger(ApiUtil.class); // // static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // public static final Date str2date(String date) { // if (date == null || "".equals(date)) // return null; // // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // try { // return format.parse(date); // } catch (ParseException e) { // LOG.error(date + "-" + e.getMessage(), e.fillInStackTrace()); // } // return null; // } // // public static final String urlEncode(String text, String charset) { // if (charset == null || "".equals(charset)) // charset = YunpianConstant.HTTP_CHARSET_DEFAULT; // try { // return URLEncoder.encode(text, charset); // } catch (UnsupportedEncodingException e) { // LOG.error(e.getMessage(), e.fillInStackTrace()); // } // return text; // } // // /** // * @since 1.2.2 // * @param charset // * @param seperator // * @param text // * @return encode(text[0],charset)+seperator+encode(text[1],charset)....seperator+encode(text[n],charset) // */ // public static final String urlEncodeAndLink(String charset, String seperator, String... text) { // if (text.length == 0) // return ""; // if (charset == null || "".equals(charset)) // charset = YunpianConstant.HTTP_CHARSET_DEFAULT; // if (seperator == null) { // seperator = YunpianConstant.SEPERATOR_COMMA; // } // // int len = 0; // for (String t : text) { // len += t.length(); // } // // StringBuilder buf = new StringBuilder(len + text.length - 1); // try { // buf.append(URLEncoder.encode(text[0], charset)); // for (int i = 1; i < text.length; i++) { // buf.append(seperator); // buf.append(URLEncoder.encode(text[i], charset)); // } // } catch (UnsupportedEncodingException e) { // LOG.error(e.getMessage(), e.fillInStackTrace()); // } // return buf.toString(); // } // // }
import com.yunpian.sdk.util.ApiUtil; import org.junit.Assert; import org.junit.Test;
/** * */ package com.yunpian.sdk.util; /** * @author dzh * @date Dec 21, 2016 3:37:53 PM * @since 1.2.0 */ public class TestApiUtil { @Test public void urlEncodeAndLinkTest() {
// Path: src/main/java/com/yunpian/sdk/util/ApiUtil.java // public class ApiUtil { // // static final Logger LOG = LoggerFactory.getLogger(ApiUtil.class); // // static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // public static final Date str2date(String date) { // if (date == null || "".equals(date)) // return null; // // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // try { // return format.parse(date); // } catch (ParseException e) { // LOG.error(date + "-" + e.getMessage(), e.fillInStackTrace()); // } // return null; // } // // public static final String urlEncode(String text, String charset) { // if (charset == null || "".equals(charset)) // charset = YunpianConstant.HTTP_CHARSET_DEFAULT; // try { // return URLEncoder.encode(text, charset); // } catch (UnsupportedEncodingException e) { // LOG.error(e.getMessage(), e.fillInStackTrace()); // } // return text; // } // // /** // * @since 1.2.2 // * @param charset // * @param seperator // * @param text // * @return encode(text[0],charset)+seperator+encode(text[1],charset)....seperator+encode(text[n],charset) // */ // public static final String urlEncodeAndLink(String charset, String seperator, String... text) { // if (text.length == 0) // return ""; // if (charset == null || "".equals(charset)) // charset = YunpianConstant.HTTP_CHARSET_DEFAULT; // if (seperator == null) { // seperator = YunpianConstant.SEPERATOR_COMMA; // } // // int len = 0; // for (String t : text) { // len += t.length(); // } // // StringBuilder buf = new StringBuilder(len + text.length - 1); // try { // buf.append(URLEncoder.encode(text[0], charset)); // for (int i = 1; i < text.length; i++) { // buf.append(seperator); // buf.append(URLEncoder.encode(text[i], charset)); // } // } catch (UnsupportedEncodingException e) { // LOG.error(e.getMessage(), e.fillInStackTrace()); // } // return buf.toString(); // } // // } // Path: src/test/java/com/yunpian/sdk/util/TestApiUtil.java import com.yunpian.sdk.util.ApiUtil; import org.junit.Assert; import org.junit.Test; /** * */ package com.yunpian.sdk.util; /** * @author dzh * @date Dec 21, 2016 3:37:53 PM * @since 1.2.0 */ public class TestApiUtil { @Test public void urlEncodeAndLinkTest() {
String text = ApiUtil.urlEncodeAndLink(null, ",", "【哈哈哈】您的验证码是1", "【哈哈哈】您的验证码是2", "【哈哈哈】您的验证码,是3");
yunpian/yunpian-java-sdk
src/main/java/com/yunpian/sdk/model/User.java
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // }
import java.util.Date; import com.yunpian.sdk.util.JsonUtil;
public void setAlarm_balance(Long alarm_balance) { this.alarm_balance = alarm_balance; } public String getEmergency_contact() { return emergency_contact; } public void setEmergency_contact(String emergency_contact) { this.emergency_contact = emergency_contact; } public String getEmergency_mobile() { return emergency_mobile; } public void setEmergency_mobile(String emergency_mobile) { this.emergency_mobile = emergency_mobile; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } @Override public String toString() {
// Path: src/main/java/com/yunpian/sdk/util/JsonUtil.java // public class JsonUtil { // private static final Gson Gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // // // private static final Type TypeMap = new TypeToken<Map<String, String>>() // // { // // }.getType(); // // public static <T> T fromJson(String json, Class<T> clazz) { // if (json == null || "".equals(json)) // return null; // return Gson.fromJson(json, clazz); // } // // public static String toJson(Object obj) { // return Gson.toJson(obj); // } // // /** // * TODO 优化 // * // * @param json // * @return // * @throws IOException // */ // public static Map<String, String> fromJsonToMap(String json) throws IOException { // return toMapStr(json); // } // // public static <T> T fromJsonToMap(Reader json, Type type) { // return Gson.<T>fromJson(json, type); // } // // public static <T> T fromJson(String json, Type t) { // return Gson.fromJson(json, t); // } // // public static <T> T fromJson(Reader json, Type t) { // return Gson.fromJson(json, t); // } // // private static Map<String, String> toMapStr(String json) throws IOException { // try (JsonReader in = new JsonReader(new StringReader(json))) { // JsonToken token = in.peek(); // if (token.equals(JsonToken.BEGIN_OBJECT)) { // Map<String, String> map = new LinkedHashMap<>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, true).toString()); // } // in.endObject(); // return map; // } // return Collections.emptyMap(); // } // } // // private static Object read2Str(JsonReader in, boolean str) throws IOException { // JsonToken token = in.peek(); // switch (token) { // case BEGIN_ARRAY: // List<Object> list = new LinkedList<Object>(); // in.beginArray(); // while (in.hasNext()) { // list.add(read2Str(in, false)); // } // in.endArray(); // return str ? JsonUtil.toJson(list) : list; // // case BEGIN_OBJECT: // Map<String, Object> map = new LinkedHashMap<String, Object>(); // in.beginObject(); // while (in.hasNext()) { // map.put(in.nextName(), read2Str(in, false)); // } // in.endObject(); // return str ? JsonUtil.toJson(map) : map; // // case STRING: // return in.nextString(); // // case NUMBER: // return in.nextString(); // case BOOLEAN: // return in.nextBoolean(); // // case NULL: // in.nextNull(); // return ""; // default: // return in.nextString(); // } // } // // } // Path: src/main/java/com/yunpian/sdk/model/User.java import java.util.Date; import com.yunpian.sdk.util.JsonUtil; public void setAlarm_balance(Long alarm_balance) { this.alarm_balance = alarm_balance; } public String getEmergency_contact() { return emergency_contact; } public void setEmergency_contact(String emergency_contact) { this.emergency_contact = emergency_contact; } public String getEmergency_mobile() { return emergency_mobile; } public void setEmergency_mobile(String emergency_mobile) { this.emergency_mobile = emergency_mobile; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } @Override public String toString() {
return JsonUtil.toJson(this);
codeborne/mobileid
test/com/codeborne/security/mobileid/HelloMobileID.java
// Path: src/com/codeborne/security/AuthenticationException.java // public class AuthenticationException extends RuntimeException { // public enum Code { // // Codes for mobileAuthenticate service: // SERVICE_ERROR(100, "Teenuse üldine veasituatsioon"), // INVALID_INPUT(101, "Sisendparameetrid mittekorrektsel kujul"), // MISSING_INPUT(102, "Mõni kohustuslik sisendparameeter on määramata"), // METHOD_NOT_ALLOWED(103, "Ligipääs antud meetodile antud parameetritega piiratud (näiteks kasutatav ServiceName ei ole teenuse pakkuja juures registreeritud)"), // AUTHENTICATION_ERROR(200, "Teenuse üldine viga"), // USER_CERTIFICATE_MISSING(201, "Kasutaja sertifikaat puudub"), // UNABLE_TO_TEST_USER_CERTIFICATE(202, "Kasutaja sertifikaadi kehtivus ei ole võimalik kontrollida"), // USER_PHONE_ERROR(300, "Kasutajaga telefoniga seotud üldine viga"), // NO_AGREEMENT(301, "Kasutajal pole Mobiil-ID lepingut"), // CERTIFICATE_REVOKED(302, "Kasutaja sertifikaat ei kehti (OCSP vastus REVOKED)."), // NOT_ACTIVATED(303, "Kasutajal pole Mobiil-ID aktiveeritud. Aktiveerimiseks tuleks minna aadressile http://mobiil.id.ee"), // NOT_VALID(304, "Toiming on lõppenud, kuid kasutaja poolt tekitatud signatuur ei ole kehtiv."), // Authentication failed: generated signature is not valid! // CERTIFICATE_EXPIRED(305, "Kasutaja sertifikaat on aegunud"), // // // Codes for GetMobileAuthenticateStatus service: // USER_AUTHENTICATED(0, "autentimine õnnestus"), // OUTSTANDING_TRANSACTION(200, "autentimine alles toimub"), // EXPIRED_TRANSACTION(0, "Sessioon on aegunud"), // USER_CANCEL(0, "Kasutaja katkestas"), // MID_NOT_READY(0, "Mobiil-ID funktsionaalsus ei ole veel kasutatav, proovida mõne aja pärast uuesti"), // PHONE_ABSENT(0, "Telefon ei ole levis"), // SENDING_ERROR(0, "Muu sõnumi saatmise viga (telefon ei suuda sõnumit vastu võtta, sõnumikeskus häiritud)"), // SIM_ERROR(0, "SIM rakenduse viga"), // INTERNAL_ERROR(0, "Teenuse tehniline viga"); // // private final int code; // private final String descriptionInEstonian; // // Code(int code, String descriptionInEstonian) { // this.code = code; // this.descriptionInEstonian = descriptionInEstonian; // } // // public int getCode() { // return code; // } // } // // private Code code; // // public AuthenticationException(Code code, String details, Throwable throwable) { // super(code + ": " + details, throwable); // this.code = code; // } // // public AuthenticationException(Code code) { // super(code.toString()); // this.code = code; // } // // public AuthenticationException(RemoteException e) { // this(findCode(e.getMessage()), e instanceof AxisFault ? ((AxisFault)e).getFaultDetails()[0].getTextContent() : null, e); // } // // private static Code findCode(String codeAsString) { // try { // int code = parseInt(codeAsString); // for (Code c : Code.values()) { // if (c.code == code) return c; // } // } // catch (NumberFormatException e) { // // just return below // } // return Code.SERVICE_ERROR; // } // // public Code getCode() { // return code; // } // }
import com.codeborne.security.AuthenticationException; import javax.swing.*; import java.awt.*; import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
package com.codeborne.security.mobileid; /** * You can use the following test phone numbers: * https://www.id.ee/?id=36373 */ public class HelloMobileID { private static final String TEST_DIGIDOC_SERVICE_URL = "https://tsp.demo.sk.ee/"; private MobileIDAuthenticator mid; private JFrame frame; private JTextField phone; private JLabel message; public static void main(String[] args) { System.setProperty("javax.net.ssl.trustStore", "test/keystore.jks"); HelloMobileID app = new HelloMobileID(); app.mid = new MobileIDAuthenticator(TEST_DIGIDOC_SERVICE_URL); app.create(); } private void login(String phoneNumber) { try { final MobileIDSession mobileIDSession = mid.startLogin(phoneNumber); showMessage("<br>Challenge: " + mobileIDSession.challenge + "<br>You will get SMS in few seconds.<br>Please accept it to login.<br>"); mid.waitForLogin(mobileIDSession); showMessage("You have logged in." + "<br>First name: " + mobileIDSession.firstName + "<br>Last name: " + mobileIDSession.lastName + "<br>Personal code: " + mobileIDSession.personalCode);
// Path: src/com/codeborne/security/AuthenticationException.java // public class AuthenticationException extends RuntimeException { // public enum Code { // // Codes for mobileAuthenticate service: // SERVICE_ERROR(100, "Teenuse üldine veasituatsioon"), // INVALID_INPUT(101, "Sisendparameetrid mittekorrektsel kujul"), // MISSING_INPUT(102, "Mõni kohustuslik sisendparameeter on määramata"), // METHOD_NOT_ALLOWED(103, "Ligipääs antud meetodile antud parameetritega piiratud (näiteks kasutatav ServiceName ei ole teenuse pakkuja juures registreeritud)"), // AUTHENTICATION_ERROR(200, "Teenuse üldine viga"), // USER_CERTIFICATE_MISSING(201, "Kasutaja sertifikaat puudub"), // UNABLE_TO_TEST_USER_CERTIFICATE(202, "Kasutaja sertifikaadi kehtivus ei ole võimalik kontrollida"), // USER_PHONE_ERROR(300, "Kasutajaga telefoniga seotud üldine viga"), // NO_AGREEMENT(301, "Kasutajal pole Mobiil-ID lepingut"), // CERTIFICATE_REVOKED(302, "Kasutaja sertifikaat ei kehti (OCSP vastus REVOKED)."), // NOT_ACTIVATED(303, "Kasutajal pole Mobiil-ID aktiveeritud. Aktiveerimiseks tuleks minna aadressile http://mobiil.id.ee"), // NOT_VALID(304, "Toiming on lõppenud, kuid kasutaja poolt tekitatud signatuur ei ole kehtiv."), // Authentication failed: generated signature is not valid! // CERTIFICATE_EXPIRED(305, "Kasutaja sertifikaat on aegunud"), // // // Codes for GetMobileAuthenticateStatus service: // USER_AUTHENTICATED(0, "autentimine õnnestus"), // OUTSTANDING_TRANSACTION(200, "autentimine alles toimub"), // EXPIRED_TRANSACTION(0, "Sessioon on aegunud"), // USER_CANCEL(0, "Kasutaja katkestas"), // MID_NOT_READY(0, "Mobiil-ID funktsionaalsus ei ole veel kasutatav, proovida mõne aja pärast uuesti"), // PHONE_ABSENT(0, "Telefon ei ole levis"), // SENDING_ERROR(0, "Muu sõnumi saatmise viga (telefon ei suuda sõnumit vastu võtta, sõnumikeskus häiritud)"), // SIM_ERROR(0, "SIM rakenduse viga"), // INTERNAL_ERROR(0, "Teenuse tehniline viga"); // // private final int code; // private final String descriptionInEstonian; // // Code(int code, String descriptionInEstonian) { // this.code = code; // this.descriptionInEstonian = descriptionInEstonian; // } // // public int getCode() { // return code; // } // } // // private Code code; // // public AuthenticationException(Code code, String details, Throwable throwable) { // super(code + ": " + details, throwable); // this.code = code; // } // // public AuthenticationException(Code code) { // super(code.toString()); // this.code = code; // } // // public AuthenticationException(RemoteException e) { // this(findCode(e.getMessage()), e instanceof AxisFault ? ((AxisFault)e).getFaultDetails()[0].getTextContent() : null, e); // } // // private static Code findCode(String codeAsString) { // try { // int code = parseInt(codeAsString); // for (Code c : Code.values()) { // if (c.code == code) return c; // } // } // catch (NumberFormatException e) { // // just return below // } // return Code.SERVICE_ERROR; // } // // public Code getCode() { // return code; // } // } // Path: test/com/codeborne/security/mobileid/HelloMobileID.java import com.codeborne.security.AuthenticationException; import javax.swing.*; import java.awt.*; import static javax.swing.WindowConstants.EXIT_ON_CLOSE; package com.codeborne.security.mobileid; /** * You can use the following test phone numbers: * https://www.id.ee/?id=36373 */ public class HelloMobileID { private static final String TEST_DIGIDOC_SERVICE_URL = "https://tsp.demo.sk.ee/"; private MobileIDAuthenticator mid; private JFrame frame; private JTextField phone; private JLabel message; public static void main(String[] args) { System.setProperty("javax.net.ssl.trustStore", "test/keystore.jks"); HelloMobileID app = new HelloMobileID(); app.mid = new MobileIDAuthenticator(TEST_DIGIDOC_SERVICE_URL); app.create(); } private void login(String phoneNumber) { try { final MobileIDSession mobileIDSession = mid.startLogin(phoneNumber); showMessage("<br>Challenge: " + mobileIDSession.challenge + "<br>You will get SMS in few seconds.<br>Please accept it to login.<br>"); mid.waitForLogin(mobileIDSession); showMessage("You have logged in." + "<br>First name: " + mobileIDSession.firstName + "<br>Last name: " + mobileIDSession.lastName + "<br>Personal code: " + mobileIDSession.personalCode);
} catch (AuthenticationException e) {
codeborne/mobileid
test/com/codeborne/security/mobileid/HelloMobileIDByPersonalCode.java
// Path: src/com/codeborne/security/AuthenticationException.java // public class AuthenticationException extends RuntimeException { // public enum Code { // // Codes for mobileAuthenticate service: // SERVICE_ERROR(100, "Teenuse üldine veasituatsioon"), // INVALID_INPUT(101, "Sisendparameetrid mittekorrektsel kujul"), // MISSING_INPUT(102, "Mõni kohustuslik sisendparameeter on määramata"), // METHOD_NOT_ALLOWED(103, "Ligipääs antud meetodile antud parameetritega piiratud (näiteks kasutatav ServiceName ei ole teenuse pakkuja juures registreeritud)"), // AUTHENTICATION_ERROR(200, "Teenuse üldine viga"), // USER_CERTIFICATE_MISSING(201, "Kasutaja sertifikaat puudub"), // UNABLE_TO_TEST_USER_CERTIFICATE(202, "Kasutaja sertifikaadi kehtivus ei ole võimalik kontrollida"), // USER_PHONE_ERROR(300, "Kasutajaga telefoniga seotud üldine viga"), // NO_AGREEMENT(301, "Kasutajal pole Mobiil-ID lepingut"), // CERTIFICATE_REVOKED(302, "Kasutaja sertifikaat ei kehti (OCSP vastus REVOKED)."), // NOT_ACTIVATED(303, "Kasutajal pole Mobiil-ID aktiveeritud. Aktiveerimiseks tuleks minna aadressile http://mobiil.id.ee"), // NOT_VALID(304, "Toiming on lõppenud, kuid kasutaja poolt tekitatud signatuur ei ole kehtiv."), // Authentication failed: generated signature is not valid! // CERTIFICATE_EXPIRED(305, "Kasutaja sertifikaat on aegunud"), // // // Codes for GetMobileAuthenticateStatus service: // USER_AUTHENTICATED(0, "autentimine õnnestus"), // OUTSTANDING_TRANSACTION(200, "autentimine alles toimub"), // EXPIRED_TRANSACTION(0, "Sessioon on aegunud"), // USER_CANCEL(0, "Kasutaja katkestas"), // MID_NOT_READY(0, "Mobiil-ID funktsionaalsus ei ole veel kasutatav, proovida mõne aja pärast uuesti"), // PHONE_ABSENT(0, "Telefon ei ole levis"), // SENDING_ERROR(0, "Muu sõnumi saatmise viga (telefon ei suuda sõnumit vastu võtta, sõnumikeskus häiritud)"), // SIM_ERROR(0, "SIM rakenduse viga"), // INTERNAL_ERROR(0, "Teenuse tehniline viga"); // // private final int code; // private final String descriptionInEstonian; // // Code(int code, String descriptionInEstonian) { // this.code = code; // this.descriptionInEstonian = descriptionInEstonian; // } // // public int getCode() { // return code; // } // } // // private Code code; // // public AuthenticationException(Code code, String details, Throwable throwable) { // super(code + ": " + details, throwable); // this.code = code; // } // // public AuthenticationException(Code code) { // super(code.toString()); // this.code = code; // } // // public AuthenticationException(RemoteException e) { // this(findCode(e.getMessage()), e instanceof AxisFault ? ((AxisFault)e).getFaultDetails()[0].getTextContent() : null, e); // } // // private static Code findCode(String codeAsString) { // try { // int code = parseInt(codeAsString); // for (Code c : Code.values()) { // if (c.code == code) return c; // } // } // catch (NumberFormatException e) { // // just return below // } // return Code.SERVICE_ERROR; // } // // public Code getCode() { // return code; // } // }
import com.codeborne.security.AuthenticationException; import javax.swing.*; import java.awt.*; import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
package com.codeborne.security.mobileid; /** * You can use the following test phone numbers: * https://www.id.ee/?id=36373 */ public class HelloMobileIDByPersonalCode { private static final String TEST_DIGIDOC_SERVICE_URL = "https://tsp.demo.sk.ee/"; private MobileIDAuthenticator mid; private JFrame frame; private JTextField personalCode; private JLabel message; public static void main(String[] args) { System.setProperty("javax.net.ssl.trustStore", "test/keystore.jks"); HelloMobileIDByPersonalCode app = new HelloMobileIDByPersonalCode(); app.mid = new MobileIDAuthenticator(TEST_DIGIDOC_SERVICE_URL); app.create(); } private void login(String personalCode) { try { final MobileIDSession mobileIDSession = mid.startLogin(personalCode, "EE"); showMessage("<br>Challenge: " + mobileIDSession.challenge + "<br>You will get SMS in few seconds.<br>Please accept it to login.<br>"); mid.waitForLogin(mobileIDSession); showMessage("You have logged in." + "<br>First name: " + mobileIDSession.firstName + "<br>Last name: " + mobileIDSession.lastName + "<br>Personal code: " + mobileIDSession.personalCode);
// Path: src/com/codeborne/security/AuthenticationException.java // public class AuthenticationException extends RuntimeException { // public enum Code { // // Codes for mobileAuthenticate service: // SERVICE_ERROR(100, "Teenuse üldine veasituatsioon"), // INVALID_INPUT(101, "Sisendparameetrid mittekorrektsel kujul"), // MISSING_INPUT(102, "Mõni kohustuslik sisendparameeter on määramata"), // METHOD_NOT_ALLOWED(103, "Ligipääs antud meetodile antud parameetritega piiratud (näiteks kasutatav ServiceName ei ole teenuse pakkuja juures registreeritud)"), // AUTHENTICATION_ERROR(200, "Teenuse üldine viga"), // USER_CERTIFICATE_MISSING(201, "Kasutaja sertifikaat puudub"), // UNABLE_TO_TEST_USER_CERTIFICATE(202, "Kasutaja sertifikaadi kehtivus ei ole võimalik kontrollida"), // USER_PHONE_ERROR(300, "Kasutajaga telefoniga seotud üldine viga"), // NO_AGREEMENT(301, "Kasutajal pole Mobiil-ID lepingut"), // CERTIFICATE_REVOKED(302, "Kasutaja sertifikaat ei kehti (OCSP vastus REVOKED)."), // NOT_ACTIVATED(303, "Kasutajal pole Mobiil-ID aktiveeritud. Aktiveerimiseks tuleks minna aadressile http://mobiil.id.ee"), // NOT_VALID(304, "Toiming on lõppenud, kuid kasutaja poolt tekitatud signatuur ei ole kehtiv."), // Authentication failed: generated signature is not valid! // CERTIFICATE_EXPIRED(305, "Kasutaja sertifikaat on aegunud"), // // // Codes for GetMobileAuthenticateStatus service: // USER_AUTHENTICATED(0, "autentimine õnnestus"), // OUTSTANDING_TRANSACTION(200, "autentimine alles toimub"), // EXPIRED_TRANSACTION(0, "Sessioon on aegunud"), // USER_CANCEL(0, "Kasutaja katkestas"), // MID_NOT_READY(0, "Mobiil-ID funktsionaalsus ei ole veel kasutatav, proovida mõne aja pärast uuesti"), // PHONE_ABSENT(0, "Telefon ei ole levis"), // SENDING_ERROR(0, "Muu sõnumi saatmise viga (telefon ei suuda sõnumit vastu võtta, sõnumikeskus häiritud)"), // SIM_ERROR(0, "SIM rakenduse viga"), // INTERNAL_ERROR(0, "Teenuse tehniline viga"); // // private final int code; // private final String descriptionInEstonian; // // Code(int code, String descriptionInEstonian) { // this.code = code; // this.descriptionInEstonian = descriptionInEstonian; // } // // public int getCode() { // return code; // } // } // // private Code code; // // public AuthenticationException(Code code, String details, Throwable throwable) { // super(code + ": " + details, throwable); // this.code = code; // } // // public AuthenticationException(Code code) { // super(code.toString()); // this.code = code; // } // // public AuthenticationException(RemoteException e) { // this(findCode(e.getMessage()), e instanceof AxisFault ? ((AxisFault)e).getFaultDetails()[0].getTextContent() : null, e); // } // // private static Code findCode(String codeAsString) { // try { // int code = parseInt(codeAsString); // for (Code c : Code.values()) { // if (c.code == code) return c; // } // } // catch (NumberFormatException e) { // // just return below // } // return Code.SERVICE_ERROR; // } // // public Code getCode() { // return code; // } // } // Path: test/com/codeborne/security/mobileid/HelloMobileIDByPersonalCode.java import com.codeborne.security.AuthenticationException; import javax.swing.*; import java.awt.*; import static javax.swing.WindowConstants.EXIT_ON_CLOSE; package com.codeborne.security.mobileid; /** * You can use the following test phone numbers: * https://www.id.ee/?id=36373 */ public class HelloMobileIDByPersonalCode { private static final String TEST_DIGIDOC_SERVICE_URL = "https://tsp.demo.sk.ee/"; private MobileIDAuthenticator mid; private JFrame frame; private JTextField personalCode; private JLabel message; public static void main(String[] args) { System.setProperty("javax.net.ssl.trustStore", "test/keystore.jks"); HelloMobileIDByPersonalCode app = new HelloMobileIDByPersonalCode(); app.mid = new MobileIDAuthenticator(TEST_DIGIDOC_SERVICE_URL); app.create(); } private void login(String personalCode) { try { final MobileIDSession mobileIDSession = mid.startLogin(personalCode, "EE"); showMessage("<br>Challenge: " + mobileIDSession.challenge + "<br>You will get SMS in few seconds.<br>Please accept it to login.<br>"); mid.waitForLogin(mobileIDSession); showMessage("You have logged in." + "<br>First name: " + mobileIDSession.firstName + "<br>Last name: " + mobileIDSession.lastName + "<br>Personal code: " + mobileIDSession.personalCode);
} catch (AuthenticationException e) {
codeborne/mobileid
test/com/codeborne/security/mobileid/test/MobileIDAuthenticatorStubTest.java
// Path: src/com/codeborne/security/mobileid/MobileIDSession.java // public class MobileIDSession implements Serializable { // public final String firstName; // public final String lastName; // public final String personalCode; // public final String challenge; // public final int sessCode; // // public MobileIDSession(int sessCode, String challenge, String firstName, String lastName, String personalCode) { // this.firstName = firstName; // this.lastName = lastName; // this.personalCode = personalCode; // this.challenge = challenge; // this.sessCode = sessCode; // } // // public String getFullName() { // return firstName + "\u00A0" + lastName; // } // // @Override // public String toString() { // return sessCode + ":::" + challenge + ":::" + firstName + ":::" + lastName + ":::" + personalCode; // } // // public static MobileIDSession fromString(String serializedMobileIDSession) { // String[] tokens = serializedMobileIDSession.split(":::"); // return new MobileIDSession(parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4]); // } // }
import com.codeborne.security.mobileid.MobileIDSession; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat;
package com.codeborne.security.mobileid.test; public class MobileIDAuthenticatorStubTest { private MobileIDAuthenticatorStub stub = new MobileIDAuthenticatorStub(); @Test public void emulatesMobileIdSession_withConstantUserData_and_givenPhoneNumber() {
// Path: src/com/codeborne/security/mobileid/MobileIDSession.java // public class MobileIDSession implements Serializable { // public final String firstName; // public final String lastName; // public final String personalCode; // public final String challenge; // public final int sessCode; // // public MobileIDSession(int sessCode, String challenge, String firstName, String lastName, String personalCode) { // this.firstName = firstName; // this.lastName = lastName; // this.personalCode = personalCode; // this.challenge = challenge; // this.sessCode = sessCode; // } // // public String getFullName() { // return firstName + "\u00A0" + lastName; // } // // @Override // public String toString() { // return sessCode + ":::" + challenge + ":::" + firstName + ":::" + lastName + ":::" + personalCode; // } // // public static MobileIDSession fromString(String serializedMobileIDSession) { // String[] tokens = serializedMobileIDSession.split(":::"); // return new MobileIDSession(parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4]); // } // } // Path: test/com/codeborne/security/mobileid/test/MobileIDAuthenticatorStubTest.java import com.codeborne.security.mobileid.MobileIDSession; import org.hamcrest.CoreMatchers; import org.junit.Test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; package com.codeborne.security.mobileid.test; public class MobileIDAuthenticatorStubTest { private MobileIDAuthenticatorStub stub = new MobileIDAuthenticatorStub(); @Test public void emulatesMobileIdSession_withConstantUserData_and_givenPhoneNumber() {
MobileIDSession mobileIDSession = stub.startLogin(null, null, "+372516273849");
superzanti/ServerSync
src/main/java/com/superzanti/serversync/GUIJavaFX/Gui_JavaFX.java
// Path: src/main/java/com/superzanti/serversync/RefStrings.java // public class RefStrings { // public static final String MODID = "com.superzanti.serversync"; // public static final String NAME = "ServerSync"; // public static final String VERSION = "v4.2.0"; // // public static final String ERROR_TOKEN = "<E>"; // public static final String DELETE_TOKEN = "<D>"; // public static final String UPDATE_TOKEN = "<U>"; // public static final String CLEANUP_TOKEN = "<C>"; // public static final String IGNORE_TOKEN = "<I>"; // } // // Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // }
import com.superzanti.serversync.RefStrings; import com.superzanti.serversync.config.SyncConfig; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.stage.Stage;
package com.superzanti.serversync.GUIJavaFX; // Main class of the GUI, launch the window public class Gui_JavaFX extends Application { private static StackMainMenu root = new StackMainMenu(); public static StackMainMenu getStackMainPane() { if (root == null) { root = new StackMainMenu(); } return root; } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception {
// Path: src/main/java/com/superzanti/serversync/RefStrings.java // public class RefStrings { // public static final String MODID = "com.superzanti.serversync"; // public static final String NAME = "ServerSync"; // public static final String VERSION = "v4.2.0"; // // public static final String ERROR_TOKEN = "<E>"; // public static final String DELETE_TOKEN = "<D>"; // public static final String UPDATE_TOKEN = "<U>"; // public static final String CLEANUP_TOKEN = "<C>"; // public static final String IGNORE_TOKEN = "<I>"; // } // // Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // } // Path: src/main/java/com/superzanti/serversync/GUIJavaFX/Gui_JavaFX.java import com.superzanti.serversync.RefStrings; import com.superzanti.serversync.config.SyncConfig; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.stage.Stage; package com.superzanti.serversync.GUIJavaFX; // Main class of the GUI, launch the window public class Gui_JavaFX extends Application { private static StackMainMenu root = new StackMainMenu(); public static StackMainMenu getStackMainPane() { if (root == null) { root = new StackMainMenu(); } return root; } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception {
root.setStyle(SyncConfig.getConfig().THEME.toString());
superzanti/ServerSync
src/main/java/com/superzanti/serversync/GUIJavaFX/Gui_JavaFX.java
// Path: src/main/java/com/superzanti/serversync/RefStrings.java // public class RefStrings { // public static final String MODID = "com.superzanti.serversync"; // public static final String NAME = "ServerSync"; // public static final String VERSION = "v4.2.0"; // // public static final String ERROR_TOKEN = "<E>"; // public static final String DELETE_TOKEN = "<D>"; // public static final String UPDATE_TOKEN = "<U>"; // public static final String CLEANUP_TOKEN = "<C>"; // public static final String IGNORE_TOKEN = "<I>"; // } // // Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // }
import com.superzanti.serversync.RefStrings; import com.superzanti.serversync.config.SyncConfig; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.stage.Stage;
package com.superzanti.serversync.GUIJavaFX; // Main class of the GUI, launch the window public class Gui_JavaFX extends Application { private static StackMainMenu root = new StackMainMenu(); public static StackMainMenu getStackMainPane() { if (root == null) { root = new StackMainMenu(); } return root; } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { root.setStyle(SyncConfig.getConfig().THEME.toString()); Scene scene = new Scene(root, 1024, 576); scene.getStylesheets().add(this.getClass().getResource("/css/application.bss").toExternalForm()); primaryStage.setScene(scene);
// Path: src/main/java/com/superzanti/serversync/RefStrings.java // public class RefStrings { // public static final String MODID = "com.superzanti.serversync"; // public static final String NAME = "ServerSync"; // public static final String VERSION = "v4.2.0"; // // public static final String ERROR_TOKEN = "<E>"; // public static final String DELETE_TOKEN = "<D>"; // public static final String UPDATE_TOKEN = "<U>"; // public static final String CLEANUP_TOKEN = "<C>"; // public static final String IGNORE_TOKEN = "<I>"; // } // // Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // } // Path: src/main/java/com/superzanti/serversync/GUIJavaFX/Gui_JavaFX.java import com.superzanti.serversync.RefStrings; import com.superzanti.serversync.config.SyncConfig; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.stage.Stage; package com.superzanti.serversync.GUIJavaFX; // Main class of the GUI, launch the window public class Gui_JavaFX extends Application { private static StackMainMenu root = new StackMainMenu(); public static StackMainMenu getStackMainPane() { if (root == null) { root = new StackMainMenu(); } return root; } public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { root.setStyle(SyncConfig.getConfig().THEME.toString()); Scene scene = new Scene(root, 1024, 576); scene.getStylesheets().add(this.getClass().getResource("/css/application.bss").toExternalForm()); primaryStage.setScene(scene);
primaryStage.setTitle(RefStrings.NAME + " - " + RefStrings.VERSION);
superzanti/ServerSync
src/main/java/com/superzanti/serversync/client/ClientWorker.java
// Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/PrettyCollection.java // public class PrettyCollection { // public static String get(Map<?, ?> map) { // String body = map.entrySet().stream() // .map(entry -> String.format("%s -> %s", entry.getKey(), entry.getValue())) // .collect(Collectors.joining("\n ")); // return build(body); // } // // public static String get(List<?> list) { // String body = list.stream() // .map(Object::toString) // .collect(Collectors.joining("\n ")); // return build(body); // } // // private static void appendHeader(StringBuilder builder) { // builder.append("{"); // builder.append("\n "); // } // // private static void appendFooter(StringBuilder builder) { // builder.append("\n"); // builder.append("}"); // } // // private static String build(String body) { // StringBuilder builder = new StringBuilder(); // appendHeader(builder); // builder.append(body); // appendFooter(builder); // return builder.toString(); // } // }
import com.superzanti.serversync.files.FileManifest; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.PrettyCollection; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer;
package com.superzanti.serversync.client; /** * The sync process for clients. * * @author Rheimus */ public class ClientWorker implements Runnable, Closeable { private String address; private int port = -1; private Server server; private Mode2Sync sync; public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } /** * Generate a list of actions required to synchronize with the server. * <p> * This method requires an address and port to be configured via setAddress & setPort. * * @return A list of actions */ public Callable<List<ActionEntry>> fetchActions() { return () -> {
// Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/PrettyCollection.java // public class PrettyCollection { // public static String get(Map<?, ?> map) { // String body = map.entrySet().stream() // .map(entry -> String.format("%s -> %s", entry.getKey(), entry.getValue())) // .collect(Collectors.joining("\n ")); // return build(body); // } // // public static String get(List<?> list) { // String body = list.stream() // .map(Object::toString) // .collect(Collectors.joining("\n ")); // return build(body); // } // // private static void appendHeader(StringBuilder builder) { // builder.append("{"); // builder.append("\n "); // } // // private static void appendFooter(StringBuilder builder) { // builder.append("\n"); // builder.append("}"); // } // // private static String build(String body) { // StringBuilder builder = new StringBuilder(); // appendHeader(builder); // builder.append(body); // appendFooter(builder); // return builder.toString(); // } // } // Path: src/main/java/com/superzanti/serversync/client/ClientWorker.java import com.superzanti.serversync.files.FileManifest; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.PrettyCollection; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer; package com.superzanti.serversync.client; /** * The sync process for clients. * * @author Rheimus */ public class ClientWorker implements Runnable, Closeable { private String address; private int port = -1; private Server server; private Mode2Sync sync; public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } /** * Generate a list of actions required to synchronize with the server. * <p> * This method requires an address and port to be configured via setAddress & setPort. * * @return A list of actions */ public Callable<List<ActionEntry>> fetchActions() { return () -> {
FileManifest manifest = sync.fetchManifest();
superzanti/ServerSync
src/main/java/com/superzanti/serversync/client/ClientWorker.java
// Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/PrettyCollection.java // public class PrettyCollection { // public static String get(Map<?, ?> map) { // String body = map.entrySet().stream() // .map(entry -> String.format("%s -> %s", entry.getKey(), entry.getValue())) // .collect(Collectors.joining("\n ")); // return build(body); // } // // public static String get(List<?> list) { // String body = list.stream() // .map(Object::toString) // .collect(Collectors.joining("\n ")); // return build(body); // } // // private static void appendHeader(StringBuilder builder) { // builder.append("{"); // builder.append("\n "); // } // // private static void appendFooter(StringBuilder builder) { // builder.append("\n"); // builder.append("}"); // } // // private static String build(String body) { // StringBuilder builder = new StringBuilder(); // appendHeader(builder); // builder.append(body); // appendFooter(builder); // return builder.toString(); // } // }
import com.superzanti.serversync.files.FileManifest; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.PrettyCollection; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer;
package com.superzanti.serversync.client; /** * The sync process for clients. * * @author Rheimus */ public class ClientWorker implements Runnable, Closeable { private String address; private int port = -1; private Server server; private Mode2Sync sync; public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } /** * Generate a list of actions required to synchronize with the server. * <p> * This method requires an address and port to be configured via setAddress & setPort. * * @return A list of actions */ public Callable<List<ActionEntry>> fetchActions() { return () -> { FileManifest manifest = sync.fetchManifest();
// Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/PrettyCollection.java // public class PrettyCollection { // public static String get(Map<?, ?> map) { // String body = map.entrySet().stream() // .map(entry -> String.format("%s -> %s", entry.getKey(), entry.getValue())) // .collect(Collectors.joining("\n ")); // return build(body); // } // // public static String get(List<?> list) { // String body = list.stream() // .map(Object::toString) // .collect(Collectors.joining("\n ")); // return build(body); // } // // private static void appendHeader(StringBuilder builder) { // builder.append("{"); // builder.append("\n "); // } // // private static void appendFooter(StringBuilder builder) { // builder.append("\n"); // builder.append("}"); // } // // private static String build(String body) { // StringBuilder builder = new StringBuilder(); // appendHeader(builder); // builder.append(body); // appendFooter(builder); // return builder.toString(); // } // } // Path: src/main/java/com/superzanti/serversync/client/ClientWorker.java import com.superzanti.serversync.files.FileManifest; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.PrettyCollection; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer; package com.superzanti.serversync.client; /** * The sync process for clients. * * @author Rheimus */ public class ClientWorker implements Runnable, Closeable { private String address; private int port = -1; private Server server; private Mode2Sync sync; public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } /** * Generate a list of actions required to synchronize with the server. * <p> * This method requires an address and port to be configured via setAddress & setPort. * * @return A list of actions */ public Callable<List<ActionEntry>> fetchActions() { return () -> { FileManifest manifest = sync.fetchManifest();
Logger.log("Determining actions for manifest");
superzanti/ServerSync
src/main/java/com/superzanti/serversync/client/ClientWorker.java
// Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/PrettyCollection.java // public class PrettyCollection { // public static String get(Map<?, ?> map) { // String body = map.entrySet().stream() // .map(entry -> String.format("%s -> %s", entry.getKey(), entry.getValue())) // .collect(Collectors.joining("\n ")); // return build(body); // } // // public static String get(List<?> list) { // String body = list.stream() // .map(Object::toString) // .collect(Collectors.joining("\n ")); // return build(body); // } // // private static void appendHeader(StringBuilder builder) { // builder.append("{"); // builder.append("\n "); // } // // private static void appendFooter(StringBuilder builder) { // builder.append("\n"); // builder.append("}"); // } // // private static String build(String body) { // StringBuilder builder = new StringBuilder(); // appendHeader(builder); // builder.append(body); // appendFooter(builder); // return builder.toString(); // } // }
import com.superzanti.serversync.files.FileManifest; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.PrettyCollection; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer;
package com.superzanti.serversync.client; /** * The sync process for clients. * * @author Rheimus */ public class ClientWorker implements Runnable, Closeable { private String address; private int port = -1; private Server server; private Mode2Sync sync; public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } /** * Generate a list of actions required to synchronize with the server. * <p> * This method requires an address and port to be configured via setAddress & setPort. * * @return A list of actions */ public Callable<List<ActionEntry>> fetchActions() { return () -> { FileManifest manifest = sync.fetchManifest(); Logger.log("Determining actions for manifest");
// Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/PrettyCollection.java // public class PrettyCollection { // public static String get(Map<?, ?> map) { // String body = map.entrySet().stream() // .map(entry -> String.format("%s -> %s", entry.getKey(), entry.getValue())) // .collect(Collectors.joining("\n ")); // return build(body); // } // // public static String get(List<?> list) { // String body = list.stream() // .map(Object::toString) // .collect(Collectors.joining("\n ")); // return build(body); // } // // private static void appendHeader(StringBuilder builder) { // builder.append("{"); // builder.append("\n "); // } // // private static void appendFooter(StringBuilder builder) { // builder.append("\n"); // builder.append("}"); // } // // private static String build(String body) { // StringBuilder builder = new StringBuilder(); // appendHeader(builder); // builder.append(body); // appendFooter(builder); // return builder.toString(); // } // } // Path: src/main/java/com/superzanti/serversync/client/ClientWorker.java import com.superzanti.serversync.files.FileManifest; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.PrettyCollection; import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer; package com.superzanti.serversync.client; /** * The sync process for clients. * * @author Rheimus */ public class ClientWorker implements Runnable, Closeable { private String address; private int port = -1; private Server server; private Mode2Sync sync; public void setAddress(String address) { this.address = address; } public void setPort(int port) { this.port = port; } /** * Generate a list of actions required to synchronize with the server. * <p> * This method requires an address and port to be configured via setAddress & setPort. * * @return A list of actions */ public Callable<List<ActionEntry>> fetchActions() { return () -> { FileManifest manifest = sync.fetchManifest(); Logger.log("Determining actions for manifest");
Logger.log(PrettyCollection.get(manifest.directories));
superzanti/ServerSync
src/main/java/com/superzanti/serversync/GUIJavaFX/PaneUpdate.java
// Path: src/main/java/com/superzanti/serversync/RefStrings.java // public class RefStrings { // public static final String MODID = "com.superzanti.serversync"; // public static final String NAME = "ServerSync"; // public static final String VERSION = "v4.2.0"; // // public static final String ERROR_TOKEN = "<E>"; // public static final String DELETE_TOKEN = "<D>"; // public static final String UPDATE_TOKEN = "<U>"; // public static final String CLEANUP_TOKEN = "<C>"; // public static final String IGNORE_TOKEN = "<I>"; // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // }
import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import com.superzanti.serversync.RefStrings; import com.superzanti.serversync.util.Logger; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import java.awt.Desktop; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*;
// Now it's "open", we can set the request method, headers etc. connection.setRequestProperty("accept", "application/json"); // This line makes the request InputStream responseStream = connection.getInputStream(); BufferedReader bR = new BufferedReader( new InputStreamReader(responseStream)); String line = ""; StringBuilder responseStrBuilder = new StringBuilder(); while((line = bR.readLine()) != null){ responseStrBuilder.append(line); } responseStream.close(); JsonObject release = Json.parse(responseStrBuilder.toString()).asObject(); String lastVersion = release.get("tag_name").toString(); this.labelVersion2.setText(lastVersion); String releaseVersion = release.get("update_url").toString(); String urlRelease = "https://github.com" + releaseVersion.substring(1, releaseVersion.length() - 1); this.hyperUpdatedUrl.setText(urlRelease); System.out.println(responseStrBuilder.toString()); if(!this.curVersion.equals(lastVersion)){ Gui_JavaFX.getStackMainPane().getPaneSideBar().updateIconUpdate("notUpdate"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { //e.printStackTrace();
// Path: src/main/java/com/superzanti/serversync/RefStrings.java // public class RefStrings { // public static final String MODID = "com.superzanti.serversync"; // public static final String NAME = "ServerSync"; // public static final String VERSION = "v4.2.0"; // // public static final String ERROR_TOKEN = "<E>"; // public static final String DELETE_TOKEN = "<D>"; // public static final String UPDATE_TOKEN = "<U>"; // public static final String CLEANUP_TOKEN = "<C>"; // public static final String IGNORE_TOKEN = "<I>"; // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // Path: src/main/java/com/superzanti/serversync/GUIJavaFX/PaneUpdate.java import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import com.superzanti.serversync.RefStrings; import com.superzanti.serversync.util.Logger; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Hyperlink; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import java.awt.Desktop; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; // Now it's "open", we can set the request method, headers etc. connection.setRequestProperty("accept", "application/json"); // This line makes the request InputStream responseStream = connection.getInputStream(); BufferedReader bR = new BufferedReader( new InputStreamReader(responseStream)); String line = ""; StringBuilder responseStrBuilder = new StringBuilder(); while((line = bR.readLine()) != null){ responseStrBuilder.append(line); } responseStream.close(); JsonObject release = Json.parse(responseStrBuilder.toString()).asObject(); String lastVersion = release.get("tag_name").toString(); this.labelVersion2.setText(lastVersion); String releaseVersion = release.get("update_url").toString(); String urlRelease = "https://github.com" + releaseVersion.substring(1, releaseVersion.length() - 1); this.hyperUpdatedUrl.setText(urlRelease); System.out.println(responseStrBuilder.toString()); if(!this.curVersion.equals(lastVersion)){ Gui_JavaFX.getStackMainPane().getPaneSideBar().updateIconUpdate("notUpdate"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { //e.printStackTrace();
Logger.debug("Can't check the last version from Github");
superzanti/ServerSync
src/main/java/com/superzanti/serversync/GUIJavaFX/PaneLogs.java
// Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // }
import com.superzanti.serversync.util.Logger; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.geometry.Insets; import javafx.scene.control.TextArea; import javafx.scene.layout.BorderPane; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.SimpleFormatter;
package com.superzanti.serversync.GUIJavaFX; // GUI for showing the logs public class PaneLogs extends BorderPane { private final TextArea textArea = new TextArea(); public PaneLogs() { textArea.setEditable(false); setMargin(textArea, new Insets(10, 10, 10, 10)); this.setCenter(textArea); final StringProperty records = new SimpleStringProperty(); getText().textProperty().bind(records); Handler handler = new Handler() { final SimpleFormatter fmt = new SimpleFormatter(); final StringBuilder r = new StringBuilder(); @Override public void publish(LogRecord record) { if (record.getLevel().equals(Level.INFO)) { r.append(fmt.format(record));
// Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // Path: src/main/java/com/superzanti/serversync/GUIJavaFX/PaneLogs.java import com.superzanti.serversync.util.Logger; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.geometry.Insets; import javafx.scene.control.TextArea; import javafx.scene.layout.BorderPane; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.SimpleFormatter; package com.superzanti.serversync.GUIJavaFX; // GUI for showing the logs public class PaneLogs extends BorderPane { private final TextArea textArea = new TextArea(); public PaneLogs() { textArea.setEditable(false); setMargin(textArea, new Insets(10, 10, 10, 10)); this.setCenter(textArea); final StringProperty records = new SimpleStringProperty(); getText().textProperty().bind(records); Handler handler = new Handler() { final SimpleFormatter fmt = new SimpleFormatter(); final StringBuilder r = new StringBuilder(); @Override public void publish(LogRecord record) { if (record.getLevel().equals(Level.INFO)) { r.append(fmt.format(record));
Logger.flush();
superzanti/ServerSync
src/main/java/com/superzanti/serversync/util/errors/UnknownMessageError.java
// Path: src/main/java/com/superzanti/serversync/util/enums/EErrorType.java // public enum EErrorType { // FILE_ACCESS, // STREAM_ACCESS, // MESSAGE_UNKNOWN // }
import com.superzanti.serversync.util.enums.EErrorType;
package com.superzanti.serversync.util.errors; public class UnknownMessageError extends MessageError { /** * */ private static final long serialVersionUID = 5925745070127909014L; public UnknownMessageError() {
// Path: src/main/java/com/superzanti/serversync/util/enums/EErrorType.java // public enum EErrorType { // FILE_ACCESS, // STREAM_ACCESS, // MESSAGE_UNKNOWN // } // Path: src/main/java/com/superzanti/serversync/util/errors/UnknownMessageError.java import com.superzanti.serversync.util.enums.EErrorType; package com.superzanti.serversync.util.errors; public class UnknownMessageError extends MessageError { /** * */ private static final long serialVersionUID = 5925745070127909014L; public UnknownMessageError() {
super("", EErrorType.MESSAGE_UNKNOWN);
superzanti/ServerSync
src/main/java/com/superzanti/serversync/config/IgnoredFilesMatcher.java
// Path: src/main/java/com/superzanti/serversync/util/Glob.java // public class Glob { // private static String sanitizePattern(String pattern) { // if (File.separator.equals("\\")) { // return pattern.replaceAll("[/\\\\]", "\\\\\\\\"); // Gross // } else { // return pattern.replaceAll("[/\\\\]", File.separator); // } // } // // private static PathMatcher globMatcher(String pattern) { // return FileSystems.getDefault().getPathMatcher("glob:" + pattern); // } // // public static Optional<String> getPattern(Path path, List<String> patterns) { // return patterns.stream().filter(p -> globMatcher(sanitizePattern(p)).matches(path)).findFirst(); // } // // public static boolean matches(Path path, String pattern) { // return globMatcher(sanitizePattern(pattern)).matches(path); // } // // public static boolean matches(Path path, List<String> patterns) { // return patterns.stream().anyMatch(pattern -> globMatcher(sanitizePattern(pattern)).matches(path)); // } // }
import com.superzanti.serversync.util.Glob; import java.nio.file.Path;
package com.superzanti.serversync.config; /** * A wrapper for: {@link Glob}. * * Matches against the user configured list of ignored files. * * @author Rheimus */ public class IgnoredFilesMatcher { private static final SyncConfig config = SyncConfig.getConfig(); public static boolean matches(Path file) {
// Path: src/main/java/com/superzanti/serversync/util/Glob.java // public class Glob { // private static String sanitizePattern(String pattern) { // if (File.separator.equals("\\")) { // return pattern.replaceAll("[/\\\\]", "\\\\\\\\"); // Gross // } else { // return pattern.replaceAll("[/\\\\]", File.separator); // } // } // // private static PathMatcher globMatcher(String pattern) { // return FileSystems.getDefault().getPathMatcher("glob:" + pattern); // } // // public static Optional<String> getPattern(Path path, List<String> patterns) { // return patterns.stream().filter(p -> globMatcher(sanitizePattern(p)).matches(path)).findFirst(); // } // // public static boolean matches(Path path, String pattern) { // return globMatcher(sanitizePattern(pattern)).matches(path); // } // // public static boolean matches(Path path, List<String> patterns) { // return patterns.stream().anyMatch(pattern -> globMatcher(sanitizePattern(pattern)).matches(path)); // } // } // Path: src/main/java/com/superzanti/serversync/config/IgnoredFilesMatcher.java import com.superzanti.serversync.util.Glob; import java.nio.file.Path; package com.superzanti.serversync.config; /** * A wrapper for: {@link Glob}. * * Matches against the user configured list of ignored files. * * @author Rheimus */ public class IgnoredFilesMatcher { private static final SyncConfig config = SyncConfig.getConfig(); public static boolean matches(Path file) {
return Glob.matches(file, config.FILE_IGNORE_LIST);
superzanti/ServerSync
src/test/java/com/superzanti/serversync/SyncConfigTests.java
// Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/enums/EConfigType.java // public enum EConfigType { // SERVER, // CLIENT, // COMMON // }
import com.superzanti.serversync.config.SyncConfig; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.enums.EConfigType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.superzanti.serversync; public class SyncConfigTests { private SyncConfig config; @BeforeEach void init() {
// Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/enums/EConfigType.java // public enum EConfigType { // SERVER, // CLIENT, // COMMON // } // Path: src/test/java/com/superzanti/serversync/SyncConfigTests.java import com.superzanti.serversync.config.SyncConfig; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.enums.EConfigType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; package com.superzanti.serversync; public class SyncConfigTests { private SyncConfig config; @BeforeEach void init() {
Logger.instantiate("testing");
superzanti/ServerSync
src/test/java/com/superzanti/serversync/SyncConfigTests.java
// Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/enums/EConfigType.java // public enum EConfigType { // SERVER, // CLIENT, // COMMON // }
import com.superzanti.serversync.config.SyncConfig; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.enums.EConfigType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue;
package com.superzanti.serversync; public class SyncConfigTests { private SyncConfig config; @BeforeEach void init() { Logger.instantiate("testing");
// Path: src/main/java/com/superzanti/serversync/config/SyncConfig.java // public class SyncConfig { // public final EConfigType configType; // // // COMMON ////////////////////////////// // public String SERVER_IP = "127.0.0.1"; // public List<String> FILE_IGNORE_LIST = Arrays.asList("**/serversync-*.jar", "**/serversync-*.cfg"); // public List<String> CONFIG_INCLUDE_LIST = new ArrayList<>(); // public Locale LOCALE = Locale.getDefault(); // public ETheme THEME = ETheme.BLUE_YELLOW; // public int BUFFER_SIZE = 1024 * 64; // //////////////////////////////////////// // // // SERVER ////////////////////////////// // public int SERVER_PORT = 38067; // public Boolean PUSH_CLIENT_MODS = false; // public List<String> FILE_INCLUDE_LIST = Collections.singletonList("mods/**"); // public List<DirectoryEntry> DIRECTORY_INCLUDE_LIST = Collections.singletonList(new DirectoryEntry( // "mods", // EDirectoryMode.mirror // )); // public List<FileRedirect> REDIRECT_FILES_LIST = new ArrayList<>(); // public int SYNC_MODE = 2; // //////////////////////////////////////// // // // CLIENT ////////////////////////////// // public Boolean REFUSE_CLIENT_MODS = false; // //////////////////////////////////////// // // private static SyncConfig singleton; // // public SyncConfig() { // this.configType = EConfigType.COMMON; // } // // public SyncConfig(EConfigType type) { // configType = type; // } // // public static SyncConfig getConfig() { // if (SyncConfig.singleton == null) { // if (ServerSync.MODE == EServerMode.SERVER) { // SyncConfig.singleton = new SyncConfig(EConfigType.SERVER); // } // if (ServerSync.MODE == EServerMode.CLIENT) { // SyncConfig.singleton = new SyncConfig(EConfigType.CLIENT); // } // } // return SyncConfig.singleton; // } // // public void save() throws IOException { // ConfigLoader.save(configType); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // // Path: src/main/java/com/superzanti/serversync/util/enums/EConfigType.java // public enum EConfigType { // SERVER, // CLIENT, // COMMON // } // Path: src/test/java/com/superzanti/serversync/SyncConfigTests.java import com.superzanti.serversync.config.SyncConfig; import com.superzanti.serversync.util.Logger; import com.superzanti.serversync.util.enums.EConfigType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; package com.superzanti.serversync; public class SyncConfigTests { private SyncConfig config; @BeforeEach void init() { Logger.instantiate("testing");
config = new SyncConfig(EConfigType.COMMON);
superzanti/ServerSync
src/main/java/com/superzanti/serversync/files/FileHash.java
// Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // }
import com.superzanti.serversync.util.Logger; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.DigestInputStream; import java.security.MessageDigest; import java.util.Arrays;
package com.superzanti.serversync.files; public class FileHash { public static String hashFile(Path file) { try { InputStream stream = null; if( FileHash.isBinaryFile(file) ){ stream = Files.newInputStream(file); }else{ stream = new ByteArrayInputStream(String.join("", Files.readAllLines(file, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); } DigestInputStream in = new DigestInputStream( new BufferedInputStream(stream), MessageDigest.getInstance("SHA-256") ); byte[] buffer = new byte[8192]; while (in.read(buffer) > -1) { } return String.format("%064x", new BigInteger(1, in.getMessageDigest().digest())); } catch (Exception e) {
// Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // Path: src/main/java/com/superzanti/serversync/files/FileHash.java import com.superzanti.serversync.util.Logger; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.DigestInputStream; import java.security.MessageDigest; import java.util.Arrays; package com.superzanti.serversync.files; public class FileHash { public static String hashFile(Path file) { try { InputStream stream = null; if( FileHash.isBinaryFile(file) ){ stream = Files.newInputStream(file); }else{ stream = new ByteArrayInputStream(String.join("", Files.readAllLines(file, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); } DigestInputStream in = new DigestInputStream( new BufferedInputStream(stream), MessageDigest.getInstance("SHA-256") ); byte[] buffer = new byte[8192]; while (in.read(buffer) > -1) { } return String.format("%064x", new BigInteger(1, in.getMessageDigest().digest())); } catch (Exception e) {
Logger.debug(String.format("Failed to hash file: %s", file));
superzanti/ServerSync
src/main/java/com/superzanti/serversync/util/errors/MessageError.java
// Path: src/main/java/com/superzanti/serversync/util/enums/EErrorType.java // public enum EErrorType { // FILE_ACCESS, // STREAM_ACCESS, // MESSAGE_UNKNOWN // }
import com.superzanti.serversync.util.enums.EErrorType; import java.io.Serializable;
package com.superzanti.serversync.util.errors; public class MessageError implements Serializable { /** * */ private static final long serialVersionUID = -4141407496772125650L; public String message;
// Path: src/main/java/com/superzanti/serversync/util/enums/EErrorType.java // public enum EErrorType { // FILE_ACCESS, // STREAM_ACCESS, // MESSAGE_UNKNOWN // } // Path: src/main/java/com/superzanti/serversync/util/errors/MessageError.java import com.superzanti.serversync.util.enums.EErrorType; import java.io.Serializable; package com.superzanti.serversync.util.errors; public class MessageError implements Serializable { /** * */ private static final long serialVersionUID = -4141407496772125650L; public String message;
public final EErrorType type;
superzanti/ServerSync
src/test/java/com/superzanti/serversync/LineFeedTest.java
// Path: src/main/java/com/superzanti/serversync/files/FileHash.java // public class FileHash { // public static String hashFile(Path file) { // try { // InputStream stream = null; // if( FileHash.isBinaryFile(file) ){ // stream = Files.newInputStream(file); // }else{ // stream = new ByteArrayInputStream(String.join("", Files.readAllLines(file, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); // } // // DigestInputStream in = new DigestInputStream( // new BufferedInputStream(stream), // MessageDigest.getInstance("SHA-256") // ); // // byte[] buffer = new byte[8192]; // while (in.read(buffer) > -1) { } // return String.format("%064x", new BigInteger(1, in.getMessageDigest().digest())); // } catch (Exception e) { // Logger.debug(String.format("Failed to hash file: %s", file)); // Logger.debug(e); // } // return ""; // } // // private static boolean isBinaryFile(Path f) throws IOException { // String[] textMime = {"text", "application/xml", "application/json", "application/javascript", "application/vnd.ms-excel"}; // // String type = Files.probeContentType(f); // //type isn't text // if (type == null) { // //type couldn't be determined, guess via first 8192 bytes // try (InputStream stream = new BufferedInputStream(Files.newInputStream(f))) { // byte[] buffer = new byte[8192]; // int read = stream.read(buffer); // for( int i = 0; i < read; i++ ){ // if(buffer[i] == 0x00) return true; // } // return false; // } // } else return Arrays.stream(textMime).noneMatch(type::startsWith); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // }
import com.superzanti.serversync.files.FileHash; import com.superzanti.serversync.util.Logger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.nio.file.Paths;
package com.superzanti.serversync; class LineFeedTest { public LineFeedTest() {
// Path: src/main/java/com/superzanti/serversync/files/FileHash.java // public class FileHash { // public static String hashFile(Path file) { // try { // InputStream stream = null; // if( FileHash.isBinaryFile(file) ){ // stream = Files.newInputStream(file); // }else{ // stream = new ByteArrayInputStream(String.join("", Files.readAllLines(file, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); // } // // DigestInputStream in = new DigestInputStream( // new BufferedInputStream(stream), // MessageDigest.getInstance("SHA-256") // ); // // byte[] buffer = new byte[8192]; // while (in.read(buffer) > -1) { } // return String.format("%064x", new BigInteger(1, in.getMessageDigest().digest())); // } catch (Exception e) { // Logger.debug(String.format("Failed to hash file: %s", file)); // Logger.debug(e); // } // return ""; // } // // private static boolean isBinaryFile(Path f) throws IOException { // String[] textMime = {"text", "application/xml", "application/json", "application/javascript", "application/vnd.ms-excel"}; // // String type = Files.probeContentType(f); // //type isn't text // if (type == null) { // //type couldn't be determined, guess via first 8192 bytes // try (InputStream stream = new BufferedInputStream(Files.newInputStream(f))) { // byte[] buffer = new byte[8192]; // int read = stream.read(buffer); // for( int i = 0; i < read; i++ ){ // if(buffer[i] == 0x00) return true; // } // return false; // } // } else return Arrays.stream(textMime).noneMatch(type::startsWith); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // Path: src/test/java/com/superzanti/serversync/LineFeedTest.java import com.superzanti.serversync.files.FileHash; import com.superzanti.serversync.util.Logger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.nio.file.Paths; package com.superzanti.serversync; class LineFeedTest { public LineFeedTest() {
Logger.instantiate("test");
superzanti/ServerSync
src/test/java/com/superzanti/serversync/LineFeedTest.java
// Path: src/main/java/com/superzanti/serversync/files/FileHash.java // public class FileHash { // public static String hashFile(Path file) { // try { // InputStream stream = null; // if( FileHash.isBinaryFile(file) ){ // stream = Files.newInputStream(file); // }else{ // stream = new ByteArrayInputStream(String.join("", Files.readAllLines(file, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); // } // // DigestInputStream in = new DigestInputStream( // new BufferedInputStream(stream), // MessageDigest.getInstance("SHA-256") // ); // // byte[] buffer = new byte[8192]; // while (in.read(buffer) > -1) { } // return String.format("%064x", new BigInteger(1, in.getMessageDigest().digest())); // } catch (Exception e) { // Logger.debug(String.format("Failed to hash file: %s", file)); // Logger.debug(e); // } // return ""; // } // // private static boolean isBinaryFile(Path f) throws IOException { // String[] textMime = {"text", "application/xml", "application/json", "application/javascript", "application/vnd.ms-excel"}; // // String type = Files.probeContentType(f); // //type isn't text // if (type == null) { // //type couldn't be determined, guess via first 8192 bytes // try (InputStream stream = new BufferedInputStream(Files.newInputStream(f))) { // byte[] buffer = new byte[8192]; // int read = stream.read(buffer); // for( int i = 0; i < read; i++ ){ // if(buffer[i] == 0x00) return true; // } // return false; // } // } else return Arrays.stream(textMime).noneMatch(type::startsWith); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // }
import com.superzanti.serversync.files.FileHash; import com.superzanti.serversync.util.Logger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.nio.file.Paths;
package com.superzanti.serversync; class LineFeedTest { public LineFeedTest() { Logger.instantiate("test"); } @Test @DisplayName("Should hash text files ignoring line feeds") void textHash() { // We know these resource files will not be null Path crlf = Paths.get(getClass().getResource("/hash_crlf.txt").getPath().substring(1)); Path lf = Paths.get(getClass().getResource("/hash_lf.txt").getPath().substring(1));
// Path: src/main/java/com/superzanti/serversync/files/FileHash.java // public class FileHash { // public static String hashFile(Path file) { // try { // InputStream stream = null; // if( FileHash.isBinaryFile(file) ){ // stream = Files.newInputStream(file); // }else{ // stream = new ByteArrayInputStream(String.join("", Files.readAllLines(file, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8)); // } // // DigestInputStream in = new DigestInputStream( // new BufferedInputStream(stream), // MessageDigest.getInstance("SHA-256") // ); // // byte[] buffer = new byte[8192]; // while (in.read(buffer) > -1) { } // return String.format("%064x", new BigInteger(1, in.getMessageDigest().digest())); // } catch (Exception e) { // Logger.debug(String.format("Failed to hash file: %s", file)); // Logger.debug(e); // } // return ""; // } // // private static boolean isBinaryFile(Path f) throws IOException { // String[] textMime = {"text", "application/xml", "application/json", "application/javascript", "application/vnd.ms-excel"}; // // String type = Files.probeContentType(f); // //type isn't text // if (type == null) { // //type couldn't be determined, guess via first 8192 bytes // try (InputStream stream = new BufferedInputStream(Files.newInputStream(f))) { // byte[] buffer = new byte[8192]; // int read = stream.read(buffer); // for( int i = 0; i < read; i++ ){ // if(buffer[i] == 0x00) return true; // } // return false; // } // } else return Arrays.stream(textMime).noneMatch(type::startsWith); // } // } // // Path: src/main/java/com/superzanti/serversync/util/Logger.java // public class Logger { // public static LoggerInstance instance = null; // private static final Object mutex = new Object(); // private static Handler uiHandler; // // // Probably a heinous implementation of debounce but whatever // private static final long dbTimeMS = 2000L; // private static final ScheduledExecutorService dbRunner = Executors.newSingleThreadScheduledExecutor(); // private static ScheduledFuture<?> waitingFlush; // // public static String getContext() { // return ServerSync.MODE == null ? "undefined" : ServerSync.MODE.toString(); // } // // public static LoggerInstance getInstance() { // LoggerInstance result = instance; // if (result == null) { // //synchronized block to remove overhead // synchronized (mutex) { // result = instance; // if (result == null) { // // if instance is null, initialize // instance = result = new LoggerInstance(getContext()); // } // } // } // return result; // } // // public static void instantiate(String context) { // instance = new LoggerInstance(context); // } // // public static synchronized void setSystemOutput(boolean output) { // // enable/disable System.out logging // getInstance().javaLogger.setUseParentHandlers(output); // } // // public static synchronized void log(String s) { // getInstance().log(s); // } // // public static synchronized void error(String s) { // getInstance().error(s); // } // // public static synchronized void debug(String s) { // getInstance().debug(s); // } // // public static synchronized void debug(Exception e) { // getInstance().debug(Arrays.toString(e.getStackTrace())); // } // // public static synchronized void outputError(Object object) { // getInstance().debug("Failed to write object (" + object + ") to output stream"); // } // // public static synchronized void attachUIHandler(Handler handler) { // if (uiHandler != null) { // uiHandler.close(); // getInstance().javaLogger.removeHandler(uiHandler); // } // uiHandler = handler; // getInstance().javaLogger.addHandler(uiHandler); // } // // public static synchronized void flush() { // if (uiHandler != null) { // if (waitingFlush == null || waitingFlush.isDone()) { // waitingFlush = dbRunner.schedule(() -> { // uiHandler.flush(); // }, dbTimeMS, TimeUnit.MILLISECONDS); // } // } // } // } // Path: src/test/java/com/superzanti/serversync/LineFeedTest.java import com.superzanti.serversync.files.FileHash; import com.superzanti.serversync.util.Logger; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.nio.file.Paths; package com.superzanti.serversync; class LineFeedTest { public LineFeedTest() { Logger.instantiate("test"); } @Test @DisplayName("Should hash text files ignoring line feeds") void textHash() { // We know these resource files will not be null Path crlf = Paths.get(getClass().getResource("/hash_crlf.txt").getPath().substring(1)); Path lf = Paths.get(getClass().getResource("/hash_lf.txt").getPath().substring(1));
String hashLF = FileHash.hashFile(lf);
superzanti/ServerSync
src/main/java/com/superzanti/serversync/client/ManifestServer.java
// Path: src/main/java/com/superzanti/serversync/communication/Requests.java // public class Requests { // private final Server server; // private final ServerInfo info; // private final ObjectInputStream input; // private final ObjectOutputStream output; // // private Requests(Server server) { // this.server = server; // this.info = server.info; // this.input = server.input; // this.output = server.output; // } // // public static Requests forServer(Server server) { // return new Requests(server); // } // // /** // * The manifest of files present on the server. // * // * @return The file manifest or null if an error occurs // */ // public FileManifest getManifest() { // Logger.debug("Requesting file manifest"); // try { // writeMessage(EServerMessage.GET_MANIFEST); // } catch (IOException e) { // return null; // } // // try { // return (FileManifest) input.readObject(); // } catch (ClassNotFoundException | IOException e) { // Logger.debug("Failed to read from server stream"); // Logger.debug(e); // return null; // } // } // // public List<String> getManagedDirectories() { // Logger.debug("Requesting managed directories"); // try { // writeMessage(EServerMessage.GET_MANAGED_DIRECTORIES); // } catch (IOException e) { // Logger.debug("Failed to write message to server"); // Logger.debug(e); // return Collections.emptyList(); // } // // try { // @SuppressWarnings("unchecked") // List<String> directories = (List<String>) input.readObject(); // return directories; // } catch (ClassNotFoundException e) { // Logger.debug("Received unknown object in server response"); // Logger.debug(e); // return Collections.emptyList(); // } catch (IOException e) { // Logger.debug("Failed to read from server stream"); // Logger.debug(e); // return Collections.emptyList(); // } // } // // /** // * The number of files being managed by the server. // * // * @return int number of files or -1 if failure occurs // */ // public int getNumberOfManagedFiles() { // Logger.debug("Requesting number of managed files"); // try { // writeMessage(EServerMessage.GET_NUMBER_OF_MANAGED_FILES); // } catch (IOException e) { // Logger.debug("Failed to write to server stream"); // Logger.debug(e); // return -1; // } // // try { // return input.readInt(); // } catch (IOException e) { // Logger.debug("Failed to read from server stream"); // Logger.debug(e); // return -1; // } // } // // public boolean updateFile(ActionEntry entry, Consumer<ActionProgress> progressConsumer) { // try { // writeMessage(EServerMessage.UPDATE_FILE); // writeObject(entry.target); // } catch (IOException e) { // return false; // } // // try { // boolean serverHasFile = input.readBoolean(); // // if (!serverHasFile) { // Logger.error(String.format("File does not exist on the server: %s", entry.target)); // return false; // } // } catch (IOException e) { // Logger.error("Failed to read file status from stream"); // Logger.debug(e); // return false; // } // // try { // long fileSize = input.readLong(); // ActionProgress progress = new ActionProgress(-1d, entry.target.path, false, entry); // progressConsumer.accept(progress);// Init the updates with baseline // // SyncFileOutputStream out = new SyncFileOutputStream(server, fileSize, entry.target.resolvePath()); // out.write((pc) -> { // progress.setProgress(pc); // progressConsumer.accept(progress); // }); // progress.setComplete(true); // progressConsumer.accept(progress); // return true; // } catch (IOException e) { // return false; // } // } // // private void writeMessage(EServerMessage message) throws IOException { // String m = message.toString(); // try { // output.writeUTF(m); // output.flush(); // } catch (IOException e) { // Logger.debug(String.format("Failed to write message %s to server stream", message)); // Logger.debug(e); // throw e; // } // } // // private void writeObject(Object o) throws IOException { // try { // output.writeObject(o); // output.flush(); // } catch (IOException e) { // Logger.debug("Failed to write to server stream"); // Logger.debug(e); // throw e; // } // } // } // // Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // }
import com.superzanti.serversync.communication.Requests; import com.superzanti.serversync.files.FileManifest; import java.util.function.Consumer;
package com.superzanti.serversync.client; public class ManifestServer { private final Requests requests; public ManifestServer(Server server) { this.requests = Requests.forServer(server); }
// Path: src/main/java/com/superzanti/serversync/communication/Requests.java // public class Requests { // private final Server server; // private final ServerInfo info; // private final ObjectInputStream input; // private final ObjectOutputStream output; // // private Requests(Server server) { // this.server = server; // this.info = server.info; // this.input = server.input; // this.output = server.output; // } // // public static Requests forServer(Server server) { // return new Requests(server); // } // // /** // * The manifest of files present on the server. // * // * @return The file manifest or null if an error occurs // */ // public FileManifest getManifest() { // Logger.debug("Requesting file manifest"); // try { // writeMessage(EServerMessage.GET_MANIFEST); // } catch (IOException e) { // return null; // } // // try { // return (FileManifest) input.readObject(); // } catch (ClassNotFoundException | IOException e) { // Logger.debug("Failed to read from server stream"); // Logger.debug(e); // return null; // } // } // // public List<String> getManagedDirectories() { // Logger.debug("Requesting managed directories"); // try { // writeMessage(EServerMessage.GET_MANAGED_DIRECTORIES); // } catch (IOException e) { // Logger.debug("Failed to write message to server"); // Logger.debug(e); // return Collections.emptyList(); // } // // try { // @SuppressWarnings("unchecked") // List<String> directories = (List<String>) input.readObject(); // return directories; // } catch (ClassNotFoundException e) { // Logger.debug("Received unknown object in server response"); // Logger.debug(e); // return Collections.emptyList(); // } catch (IOException e) { // Logger.debug("Failed to read from server stream"); // Logger.debug(e); // return Collections.emptyList(); // } // } // // /** // * The number of files being managed by the server. // * // * @return int number of files or -1 if failure occurs // */ // public int getNumberOfManagedFiles() { // Logger.debug("Requesting number of managed files"); // try { // writeMessage(EServerMessage.GET_NUMBER_OF_MANAGED_FILES); // } catch (IOException e) { // Logger.debug("Failed to write to server stream"); // Logger.debug(e); // return -1; // } // // try { // return input.readInt(); // } catch (IOException e) { // Logger.debug("Failed to read from server stream"); // Logger.debug(e); // return -1; // } // } // // public boolean updateFile(ActionEntry entry, Consumer<ActionProgress> progressConsumer) { // try { // writeMessage(EServerMessage.UPDATE_FILE); // writeObject(entry.target); // } catch (IOException e) { // return false; // } // // try { // boolean serverHasFile = input.readBoolean(); // // if (!serverHasFile) { // Logger.error(String.format("File does not exist on the server: %s", entry.target)); // return false; // } // } catch (IOException e) { // Logger.error("Failed to read file status from stream"); // Logger.debug(e); // return false; // } // // try { // long fileSize = input.readLong(); // ActionProgress progress = new ActionProgress(-1d, entry.target.path, false, entry); // progressConsumer.accept(progress);// Init the updates with baseline // // SyncFileOutputStream out = new SyncFileOutputStream(server, fileSize, entry.target.resolvePath()); // out.write((pc) -> { // progress.setProgress(pc); // progressConsumer.accept(progress); // }); // progress.setComplete(true); // progressConsumer.accept(progress); // return true; // } catch (IOException e) { // return false; // } // } // // private void writeMessage(EServerMessage message) throws IOException { // String m = message.toString(); // try { // output.writeUTF(m); // output.flush(); // } catch (IOException e) { // Logger.debug(String.format("Failed to write message %s to server stream", message)); // Logger.debug(e); // throw e; // } // } // // private void writeObject(Object o) throws IOException { // try { // output.writeObject(o); // output.flush(); // } catch (IOException e) { // Logger.debug("Failed to write to server stream"); // Logger.debug(e); // throw e; // } // } // } // // Path: src/main/java/com/superzanti/serversync/files/FileManifest.java // public class FileManifest implements Serializable { // public List<DirectoryEntry> directories = new ArrayList<>(); // /** // * The files that the server wants to manage. // */ // public List<FileEntry> files = new ArrayList<>(); // } // Path: src/main/java/com/superzanti/serversync/client/ManifestServer.java import com.superzanti.serversync.communication.Requests; import com.superzanti.serversync.files.FileManifest; import java.util.function.Consumer; package com.superzanti.serversync.client; public class ManifestServer { private final Requests requests; public ManifestServer(Server server) { this.requests = Requests.forServer(server); }
public FileManifest fetchManifest() {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessor.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // }
import com.ning.http.client.AsyncHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; import java.io.IOException;
package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class AsynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessor.class); @Autowired
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessor.java import com.ning.http.client.AsyncHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; import java.io.IOException; package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class AsynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessor.class); @Autowired
private StateMachine stateMachine;
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessor.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // }
import com.ning.http.client.AsyncHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; import java.io.IOException;
package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class AsynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessor.class); @Autowired private StateMachine stateMachine; private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); @Value("${sp.non_blocking.url}") private String SP_NON_BLOCKING_URL; @Override
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessor.java import com.ning.http.client.AsyncHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; import java.io.IOException; package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class AsynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessor.class); @Autowired private StateMachine stateMachine; private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); @Value("${sp.non_blocking.url}") private String SP_NON_BLOCKING_URL; @Override
public void process(State state) {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/deferredresult/DeferredResultStateMachineCallback.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachineCallback.java // public interface StateMachineCallback { // void onCompleted(State state); // void onFailure(State state, Throwable t); // }
import org.springframework.web.context.request.async.DeferredResult; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachineCallback;
package se.callista.springmvc.asynch.common.deferredresult; /** * Created by magnus on 08/06/14. */ public class DeferredResultStateMachineCallback implements StateMachineCallback { private DeferredResult deferredResult; public DeferredResultStateMachineCallback(DeferredResult deferredResult) { this.deferredResult = deferredResult; } @Override
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachineCallback.java // public interface StateMachineCallback { // void onCompleted(State state); // void onFailure(State state, Throwable t); // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/deferredresult/DeferredResultStateMachineCallback.java import org.springframework.web.context.request.async.DeferredResult; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachineCallback; package se.callista.springmvc.asynch.common.deferredresult; /** * Created by magnus on 08/06/14. */ public class DeferredResultStateMachineCallback implements StateMachineCallback { private DeferredResult deferredResult; public DeferredResultStateMachineCallback(DeferredResult deferredResult) { this.deferredResult = deferredResult; } @Override
public void onCompleted(State state) {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/RoutingSlipNonBlockingConfiguration.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; /** * Created by magnus on 08/06/14. */ @Component public class RoutingSlipNonBlockingConfiguration { @Autowired private AsynchProcessor asynchProcessor; /** * Simulates setting up a number of processing steps from some kind of configuration... * * @return */
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/RoutingSlipNonBlockingConfiguration.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; /** * Created by magnus on 08/06/14. */ @Component public class RoutingSlipNonBlockingConfiguration { @Autowired private AsynchProcessor asynchProcessor; /** * Simulates setting up a number of processing steps from some kind of configuration... * * @return */
public Iterator<Processor> getProcessingSteps() {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/aggregator/nonblocking/callback/AggregatorEventHandler.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/log/LogHelper.java // public class LogHelper { // // private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); // private static final AtomicLong lastRequestId = new AtomicLong(0); // private static final AtomicLong concurrentRequests = new AtomicLong(0); // private static long maxConcurrentRequests = 0; // // private final String name; // private final Logger log; // private final int requestsPerLog; // private final long reqId; // // public LogHelper(Class clz, String name, int requestsPerLog) { // this.log = LoggerFactory.getLogger(clz); // this.name = name; // this.requestsPerLog = requestsPerLog; // this.reqId = lastRequestId.getAndIncrement(); // } // // public void logStartBlocking() { // logStart("blocking"); // } // // public void logStartNonBlocking() { // logStart("non-blocking"); // } // // public void logStartProcessingStepBlocking(int processingStepNo) { // logStartProcessingStep("blocking", processingStepNo); // } // public void logStartProcessingStepNonBlocking(int processingStepNo) { // logStartProcessingStep("non-blocking", processingStepNo); // } // // public void logAsynchProcessingStepComplete() { // // long concReqs = concurrentRequests.get(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Asynch call complete för request #{}, hand over to the state machine for the next action", concReqs, reqId); // } // // public void logMessage(String message) { // long concReqs = concurrentRequests.get(); // // log.debug("{}: Request #{} - {}", concReqs, reqId, message); // } // // public void logEndProcessingStepBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("blocking", processingStepNo, httpStatus); // } // // public void logEndProcessingStepNonBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("non-blocking", processingStepNo, httpStatus); // } // // public void logEndBlocking(int httpStatus) { // logEnd("blocking", httpStatus, null); // } // // public void logEndNonBlocking(int httpStatus, boolean deferredStatus) { // logEnd("non-blocking", httpStatus, deferredStatus); // } // // public void logExceptionBlocking(Throwable t) { // logException("blocking", t); // } // // public void logExceptionNonBlocking(Throwable t) { // logException("non-blocking", t); // } // // public void logLeaveThreadNonBlocking() { // // long concReqs = concurrentRequests.get(); // // log.debug("{}: Processing of non-blocking {} request #{}, leave the request thread", concReqs, name, reqId); // } // // public void logAlreadyExpiredNonBlocking() { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of non-blocking {} request #{} already expired", concReqs, name, reqId); // } // // /* // * PRIVATE PARTS :-) // */ // // protected void logStart(String type) { // // long concReqs = concurrentRequests.getAndIncrement(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Start of {} {} request #{}.", concReqs, type, name, reqId); // } // // protected void logEnd(String type, int httpStatus, Boolean deferredStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // if (deferredStatus == null) { // log.debug("{}: End of {} {} request #{}, http-status: {}", concReqs, type, name, reqId, httpStatus); // } else { // log.debug("{}: End of {} {} request #{}, http-status: {}, deferred-status: {}", concReqs, type, name, reqId, httpStatus, deferredStatus); // } // } // // protected void logStartProcessingStep(String type, int processingStepNo) { // // long concReqs = concurrentRequests.getAndIncrement(); // // log.debug("{}: Start processing of {} call #{} in request #{}", concReqs, type, processingStepNo, reqId); // } // // protected void logEndProcessingStep(String type, int processingStepNo, int httpStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.debug("{}: End of processing of {} call #{} in request #{}, http-status: {}", concReqs, type, processingStepNo, reqId, httpStatus); // } // // protected void logException(String type, Throwable t) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of {} {} request #{} caused an exception: {}", concReqs, type, name, reqId, t); // } // protected void updateStatistics(long reqId, long concReqs) { // if (concReqs > maxConcurrentRequests) { // maxConcurrentRequests = concReqs; // } // // if (reqId % requestsPerLog == 0 && reqId > 0) { // Object openFiles = "UNKNOWN"; // if (os instanceof UnixOperatingSystemMXBean) { // openFiles = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount(); // } // log.info("Statistics: noOfReqs: {}, maxConcReqs: {}, openFiles: {}", reqId, maxConcurrentRequests, openFiles); // } // } // // }
import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.ListenableFuture; import com.ning.http.client.Response; import org.springframework.web.context.request.async.DeferredResult; import se.callista.springmvc.asynch.common.log.LogHelper; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicInteger;
package se.callista.springmvc.asynch.pattern.aggregator.nonblocking.callback; /** * Created by magnus on 22/04/14. */ public class AggregatorEventHandler { private Timer timer = new Timer();
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/log/LogHelper.java // public class LogHelper { // // private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); // private static final AtomicLong lastRequestId = new AtomicLong(0); // private static final AtomicLong concurrentRequests = new AtomicLong(0); // private static long maxConcurrentRequests = 0; // // private final String name; // private final Logger log; // private final int requestsPerLog; // private final long reqId; // // public LogHelper(Class clz, String name, int requestsPerLog) { // this.log = LoggerFactory.getLogger(clz); // this.name = name; // this.requestsPerLog = requestsPerLog; // this.reqId = lastRequestId.getAndIncrement(); // } // // public void logStartBlocking() { // logStart("blocking"); // } // // public void logStartNonBlocking() { // logStart("non-blocking"); // } // // public void logStartProcessingStepBlocking(int processingStepNo) { // logStartProcessingStep("blocking", processingStepNo); // } // public void logStartProcessingStepNonBlocking(int processingStepNo) { // logStartProcessingStep("non-blocking", processingStepNo); // } // // public void logAsynchProcessingStepComplete() { // // long concReqs = concurrentRequests.get(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Asynch call complete för request #{}, hand over to the state machine for the next action", concReqs, reqId); // } // // public void logMessage(String message) { // long concReqs = concurrentRequests.get(); // // log.debug("{}: Request #{} - {}", concReqs, reqId, message); // } // // public void logEndProcessingStepBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("blocking", processingStepNo, httpStatus); // } // // public void logEndProcessingStepNonBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("non-blocking", processingStepNo, httpStatus); // } // // public void logEndBlocking(int httpStatus) { // logEnd("blocking", httpStatus, null); // } // // public void logEndNonBlocking(int httpStatus, boolean deferredStatus) { // logEnd("non-blocking", httpStatus, deferredStatus); // } // // public void logExceptionBlocking(Throwable t) { // logException("blocking", t); // } // // public void logExceptionNonBlocking(Throwable t) { // logException("non-blocking", t); // } // // public void logLeaveThreadNonBlocking() { // // long concReqs = concurrentRequests.get(); // // log.debug("{}: Processing of non-blocking {} request #{}, leave the request thread", concReqs, name, reqId); // } // // public void logAlreadyExpiredNonBlocking() { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of non-blocking {} request #{} already expired", concReqs, name, reqId); // } // // /* // * PRIVATE PARTS :-) // */ // // protected void logStart(String type) { // // long concReqs = concurrentRequests.getAndIncrement(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Start of {} {} request #{}.", concReqs, type, name, reqId); // } // // protected void logEnd(String type, int httpStatus, Boolean deferredStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // if (deferredStatus == null) { // log.debug("{}: End of {} {} request #{}, http-status: {}", concReqs, type, name, reqId, httpStatus); // } else { // log.debug("{}: End of {} {} request #{}, http-status: {}, deferred-status: {}", concReqs, type, name, reqId, httpStatus, deferredStatus); // } // } // // protected void logStartProcessingStep(String type, int processingStepNo) { // // long concReqs = concurrentRequests.getAndIncrement(); // // log.debug("{}: Start processing of {} call #{} in request #{}", concReqs, type, processingStepNo, reqId); // } // // protected void logEndProcessingStep(String type, int processingStepNo, int httpStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.debug("{}: End of processing of {} call #{} in request #{}, http-status: {}", concReqs, type, processingStepNo, reqId, httpStatus); // } // // protected void logException(String type, Throwable t) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of {} {} request #{} caused an exception: {}", concReqs, type, name, reqId, t); // } // protected void updateStatistics(long reqId, long concReqs) { // if (concReqs > maxConcurrentRequests) { // maxConcurrentRequests = concReqs; // } // // if (reqId % requestsPerLog == 0 && reqId > 0) { // Object openFiles = "UNKNOWN"; // if (os instanceof UnixOperatingSystemMXBean) { // openFiles = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount(); // } // log.info("Statistics: noOfReqs: {}, maxConcReqs: {}, openFiles: {}", reqId, maxConcurrentRequests, openFiles); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/aggregator/nonblocking/callback/AggregatorEventHandler.java import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.ListenableFuture; import com.ning.http.client.Response; import org.springframework.web.context.request.async.DeferredResult; import se.callista.springmvc.asynch.common.log.LogHelper; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicInteger; package se.callista.springmvc.asynch.pattern.aggregator.nonblocking.callback; /** * Created by magnus on 22/04/14. */ public class AggregatorEventHandler { private Timer timer = new Timer();
private final LogHelper log;
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/pattern/router/RouterControllerTest.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java // @ComponentScan() // @EnableAutoConfiguration // public class Application { // // @SuppressWarnings("unused") // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // @Bean // public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ // return new MyEmbeddedServletContainerCustomizer(); // } // // @Value("${threadPool.db.init_size}") // private int THREAD_POOL_DB_INIT_SIZE; // // @Value("${threadPool.db.max_size}") // private int THREAD_POOL_DB_MAX_SIZE; // // @Value("${threadPool.db.queue_size}") // private int THREAD_POOL_DB_QUEUE_SIZE; // // @Bean(name="dbThreadPoolExecutor") // public TaskExecutor getTaskExecutor() { // ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); // tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); // tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); // tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); // tpte.initialize(); // return tpte; // } // // @Bean // public AsyncHttpClientLambdaAware getAsyncHttpClient() { // LOG.info("### Creates a new AsyncHttpClientLambdaAware-object"); // return new AsyncHttpClientLambdaAware(); // } // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/AsynchTestBase.java // abstract public class AsynchTestBase extends EmbeddedHttpServerTestBase { // // private static final Logger LOG = LoggerFactory.getLogger(AsynchTestBase.class); // // protected void createResponse(HttpServletRequest request, String requestBody, HttpServletResponse response) throws IOException, URISyntaxException { // // Map<String, String> parMap = new HashMap<>(); // parMap.put("minMs", "0"); // parMap.put("maxMs", "0"); // getQueryParameters(request, parMap); // // int minMs = Integer.parseInt(parMap.get("minMs")); // int maxMs = Integer.parseInt(parMap.get("maxMs")); // int processingTimeMs = calculateProcessingTime(minMs, maxMs); // // LOG.debug("Start blocking request, processing time: {} ms (" + minMs + " - " + maxMs + ").", processingTimeMs); // try { // Thread.sleep(processingTimeMs); // } // catch (InterruptedException e) {} // // String responseBody = "{\"status\":\"Ok\",\"processingTimeMs\":" + processingTimeMs + "}"; // response.setStatus(SC_OK); // response.setContentType("text/plain;charset=ISO-8859-1"); // write(responseBody, response.getOutputStream()); // } // // private int calculateProcessingTime(int minMs, int maxMs) { // if (maxMs < minMs) maxMs = minMs; // int processingTimeMs = minMs + (int) (Math.random() * (maxMs - minMs)); // return processingTimeMs; // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import se.callista.springmvc.asynch.Application; import se.callista.springmvc.asynch.common.AsynchTestBase; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package se.callista.springmvc.asynch.pattern.router; /** * Created by magnus on 29/05/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java // @ComponentScan() // @EnableAutoConfiguration // public class Application { // // @SuppressWarnings("unused") // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // @Bean // public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ // return new MyEmbeddedServletContainerCustomizer(); // } // // @Value("${threadPool.db.init_size}") // private int THREAD_POOL_DB_INIT_SIZE; // // @Value("${threadPool.db.max_size}") // private int THREAD_POOL_DB_MAX_SIZE; // // @Value("${threadPool.db.queue_size}") // private int THREAD_POOL_DB_QUEUE_SIZE; // // @Bean(name="dbThreadPoolExecutor") // public TaskExecutor getTaskExecutor() { // ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); // tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); // tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); // tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); // tpte.initialize(); // return tpte; // } // // @Bean // public AsyncHttpClientLambdaAware getAsyncHttpClient() { // LOG.info("### Creates a new AsyncHttpClientLambdaAware-object"); // return new AsyncHttpClientLambdaAware(); // } // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/AsynchTestBase.java // abstract public class AsynchTestBase extends EmbeddedHttpServerTestBase { // // private static final Logger LOG = LoggerFactory.getLogger(AsynchTestBase.class); // // protected void createResponse(HttpServletRequest request, String requestBody, HttpServletResponse response) throws IOException, URISyntaxException { // // Map<String, String> parMap = new HashMap<>(); // parMap.put("minMs", "0"); // parMap.put("maxMs", "0"); // getQueryParameters(request, parMap); // // int minMs = Integer.parseInt(parMap.get("minMs")); // int maxMs = Integer.parseInt(parMap.get("maxMs")); // int processingTimeMs = calculateProcessingTime(minMs, maxMs); // // LOG.debug("Start blocking request, processing time: {} ms (" + minMs + " - " + maxMs + ").", processingTimeMs); // try { // Thread.sleep(processingTimeMs); // } // catch (InterruptedException e) {} // // String responseBody = "{\"status\":\"Ok\",\"processingTimeMs\":" + processingTimeMs + "}"; // response.setStatus(SC_OK); // response.setContentType("text/plain;charset=ISO-8859-1"); // write(responseBody, response.getOutputStream()); // } // // private int calculateProcessingTime(int minMs, int maxMs) { // if (maxMs < minMs) maxMs = minMs; // int processingTimeMs = minMs + (int) (Math.random() * (maxMs - minMs)); // return processingTimeMs; // } // } // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/pattern/router/RouterControllerTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import se.callista.springmvc.asynch.Application; import se.callista.springmvc.asynch.common.AsynchTestBase; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package se.callista.springmvc.asynch.pattern.router; /** * Created by magnus on 29/05/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration
public class RouterControllerTest extends AsynchTestBase {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/log/LogHelper.java // public class LogHelper { // // private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); // private static final AtomicLong lastRequestId = new AtomicLong(0); // private static final AtomicLong concurrentRequests = new AtomicLong(0); // private static long maxConcurrentRequests = 0; // // private final String name; // private final Logger log; // private final int requestsPerLog; // private final long reqId; // // public LogHelper(Class clz, String name, int requestsPerLog) { // this.log = LoggerFactory.getLogger(clz); // this.name = name; // this.requestsPerLog = requestsPerLog; // this.reqId = lastRequestId.getAndIncrement(); // } // // public void logStartBlocking() { // logStart("blocking"); // } // // public void logStartNonBlocking() { // logStart("non-blocking"); // } // // public void logStartProcessingStepBlocking(int processingStepNo) { // logStartProcessingStep("blocking", processingStepNo); // } // public void logStartProcessingStepNonBlocking(int processingStepNo) { // logStartProcessingStep("non-blocking", processingStepNo); // } // // public void logAsynchProcessingStepComplete() { // // long concReqs = concurrentRequests.get(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Asynch call complete för request #{}, hand over to the state machine for the next action", concReqs, reqId); // } // // public void logMessage(String message) { // long concReqs = concurrentRequests.get(); // // log.debug("{}: Request #{} - {}", concReqs, reqId, message); // } // // public void logEndProcessingStepBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("blocking", processingStepNo, httpStatus); // } // // public void logEndProcessingStepNonBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("non-blocking", processingStepNo, httpStatus); // } // // public void logEndBlocking(int httpStatus) { // logEnd("blocking", httpStatus, null); // } // // public void logEndNonBlocking(int httpStatus, boolean deferredStatus) { // logEnd("non-blocking", httpStatus, deferredStatus); // } // // public void logExceptionBlocking(Throwable t) { // logException("blocking", t); // } // // public void logExceptionNonBlocking(Throwable t) { // logException("non-blocking", t); // } // // public void logLeaveThreadNonBlocking() { // // long concReqs = concurrentRequests.get(); // // log.debug("{}: Processing of non-blocking {} request #{}, leave the request thread", concReqs, name, reqId); // } // // public void logAlreadyExpiredNonBlocking() { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of non-blocking {} request #{} already expired", concReqs, name, reqId); // } // // /* // * PRIVATE PARTS :-) // */ // // protected void logStart(String type) { // // long concReqs = concurrentRequests.getAndIncrement(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Start of {} {} request #{}.", concReqs, type, name, reqId); // } // // protected void logEnd(String type, int httpStatus, Boolean deferredStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // if (deferredStatus == null) { // log.debug("{}: End of {} {} request #{}, http-status: {}", concReqs, type, name, reqId, httpStatus); // } else { // log.debug("{}: End of {} {} request #{}, http-status: {}, deferred-status: {}", concReqs, type, name, reqId, httpStatus, deferredStatus); // } // } // // protected void logStartProcessingStep(String type, int processingStepNo) { // // long concReqs = concurrentRequests.getAndIncrement(); // // log.debug("{}: Start processing of {} call #{} in request #{}", concReqs, type, processingStepNo, reqId); // } // // protected void logEndProcessingStep(String type, int processingStepNo, int httpStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.debug("{}: End of processing of {} call #{} in request #{}, http-status: {}", concReqs, type, processingStepNo, reqId, httpStatus); // } // // protected void logException(String type, Throwable t) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of {} {} request #{} caused an exception: {}", concReqs, type, name, reqId, t); // } // protected void updateStatistics(long reqId, long concReqs) { // if (concReqs > maxConcurrentRequests) { // maxConcurrentRequests = concReqs; // } // // if (reqId % requestsPerLog == 0 && reqId > 0) { // Object openFiles = "UNKNOWN"; // if (os instanceof UnixOperatingSystemMXBean) { // openFiles = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount(); // } // log.info("Statistics: noOfReqs: {}, maxConcReqs: {}, openFiles: {}", reqId, maxConcurrentRequests, openFiles); // } // } // // }
import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.log.LogHelper; import java.util.Iterator;
package se.callista.springmvc.asynch.common.statemachine; /** * A stateless minimal state machine */ @Component public class StateMachine {
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/log/LogHelper.java // public class LogHelper { // // private static OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean(); // private static final AtomicLong lastRequestId = new AtomicLong(0); // private static final AtomicLong concurrentRequests = new AtomicLong(0); // private static long maxConcurrentRequests = 0; // // private final String name; // private final Logger log; // private final int requestsPerLog; // private final long reqId; // // public LogHelper(Class clz, String name, int requestsPerLog) { // this.log = LoggerFactory.getLogger(clz); // this.name = name; // this.requestsPerLog = requestsPerLog; // this.reqId = lastRequestId.getAndIncrement(); // } // // public void logStartBlocking() { // logStart("blocking"); // } // // public void logStartNonBlocking() { // logStart("non-blocking"); // } // // public void logStartProcessingStepBlocking(int processingStepNo) { // logStartProcessingStep("blocking", processingStepNo); // } // public void logStartProcessingStepNonBlocking(int processingStepNo) { // logStartProcessingStep("non-blocking", processingStepNo); // } // // public void logAsynchProcessingStepComplete() { // // long concReqs = concurrentRequests.get(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Asynch call complete för request #{}, hand over to the state machine for the next action", concReqs, reqId); // } // // public void logMessage(String message) { // long concReqs = concurrentRequests.get(); // // log.debug("{}: Request #{} - {}", concReqs, reqId, message); // } // // public void logEndProcessingStepBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("blocking", processingStepNo, httpStatus); // } // // public void logEndProcessingStepNonBlocking(int processingStepNo, int httpStatus) { // logEndProcessingStep("non-blocking", processingStepNo, httpStatus); // } // // public void logEndBlocking(int httpStatus) { // logEnd("blocking", httpStatus, null); // } // // public void logEndNonBlocking(int httpStatus, boolean deferredStatus) { // logEnd("non-blocking", httpStatus, deferredStatus); // } // // public void logExceptionBlocking(Throwable t) { // logException("blocking", t); // } // // public void logExceptionNonBlocking(Throwable t) { // logException("non-blocking", t); // } // // public void logLeaveThreadNonBlocking() { // // long concReqs = concurrentRequests.get(); // // log.debug("{}: Processing of non-blocking {} request #{}, leave the request thread", concReqs, name, reqId); // } // // public void logAlreadyExpiredNonBlocking() { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of non-blocking {} request #{} already expired", concReqs, name, reqId); // } // // /* // * PRIVATE PARTS :-) // */ // // protected void logStart(String type) { // // long concReqs = concurrentRequests.getAndIncrement(); // // updateStatistics(reqId, concReqs); // // log.debug("{}: Start of {} {} request #{}.", concReqs, type, name, reqId); // } // // protected void logEnd(String type, int httpStatus, Boolean deferredStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // if (deferredStatus == null) { // log.debug("{}: End of {} {} request #{}, http-status: {}", concReqs, type, name, reqId, httpStatus); // } else { // log.debug("{}: End of {} {} request #{}, http-status: {}, deferred-status: {}", concReqs, type, name, reqId, httpStatus, deferredStatus); // } // } // // protected void logStartProcessingStep(String type, int processingStepNo) { // // long concReqs = concurrentRequests.getAndIncrement(); // // log.debug("{}: Start processing of {} call #{} in request #{}", concReqs, type, processingStepNo, reqId); // } // // protected void logEndProcessingStep(String type, int processingStepNo, int httpStatus) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.debug("{}: End of processing of {} call #{} in request #{}, http-status: {}", concReqs, type, processingStepNo, reqId, httpStatus); // } // // protected void logException(String type, Throwable t) { // // long concReqs = concurrentRequests.getAndDecrement(); // // log.warn("{}: Processing of {} {} request #{} caused an exception: {}", concReqs, type, name, reqId, t); // } // protected void updateStatistics(long reqId, long concReqs) { // if (concReqs > maxConcurrentRequests) { // maxConcurrentRequests = concReqs; // } // // if (reqId % requestsPerLog == 0 && reqId > 0) { // Object openFiles = "UNKNOWN"; // if (os instanceof UnixOperatingSystemMXBean) { // openFiles = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount(); // } // log.info("Statistics: noOfReqs: {}, maxConcReqs: {}, openFiles: {}", reqId, maxConcurrentRequests, openFiles); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.log.LogHelper; import java.util.Iterator; package se.callista.springmvc.asynch.common.statemachine; /** * A stateless minimal state machine */ @Component public class StateMachine {
public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/blocking/statemachine/SynchProcessor.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine;
package se.callista.springmvc.asynch.pattern.routingslip.blocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class SynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(SynchProcessor.class); @Autowired
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/blocking/statemachine/SynchProcessor.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; package se.callista.springmvc.asynch.pattern.routingslip.blocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class SynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(SynchProcessor.class); @Autowired
private StateMachine stateMachine;
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/blocking/statemachine/SynchProcessor.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine;
package se.callista.springmvc.asynch.pattern.routingslip.blocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class SynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(SynchProcessor.class); @Autowired private StateMachine stateMachine; private RestTemplate restTemplate = new RestTemplate(); @Value("${sp.non_blocking.url}") private String SP_NON_BLOCKING_URL; @Override
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/blocking/statemachine/SynchProcessor.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import se.callista.springmvc.asynch.common.statemachine.Processor; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; package se.callista.springmvc.asynch.pattern.routingslip.blocking.statemachine; /** * Created by magnus on 15/05/14. */ @Component public class SynchProcessor implements Processor { private static final Logger LOG = LoggerFactory.getLogger(SynchProcessor.class); @Autowired private StateMachine stateMachine; private RestTemplate restTemplate = new RestTemplate(); @Value("${sp.non_blocking.url}") private String SP_NON_BLOCKING_URL; @Override
public void process(State state) {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/pattern/routingslip/RoutingSlipControllerTest.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java // @ComponentScan() // @EnableAutoConfiguration // public class Application { // // @SuppressWarnings("unused") // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // @Bean // public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ // return new MyEmbeddedServletContainerCustomizer(); // } // // @Value("${threadPool.db.init_size}") // private int THREAD_POOL_DB_INIT_SIZE; // // @Value("${threadPool.db.max_size}") // private int THREAD_POOL_DB_MAX_SIZE; // // @Value("${threadPool.db.queue_size}") // private int THREAD_POOL_DB_QUEUE_SIZE; // // @Bean(name="dbThreadPoolExecutor") // public TaskExecutor getTaskExecutor() { // ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); // tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); // tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); // tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); // tpte.initialize(); // return tpte; // } // // @Bean // public AsyncHttpClientLambdaAware getAsyncHttpClient() { // LOG.info("### Creates a new AsyncHttpClientLambdaAware-object"); // return new AsyncHttpClientLambdaAware(); // } // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/AsynchTestBase.java // abstract public class AsynchTestBase extends EmbeddedHttpServerTestBase { // // private static final Logger LOG = LoggerFactory.getLogger(AsynchTestBase.class); // // protected void createResponse(HttpServletRequest request, String requestBody, HttpServletResponse response) throws IOException, URISyntaxException { // // Map<String, String> parMap = new HashMap<>(); // parMap.put("minMs", "0"); // parMap.put("maxMs", "0"); // getQueryParameters(request, parMap); // // int minMs = Integer.parseInt(parMap.get("minMs")); // int maxMs = Integer.parseInt(parMap.get("maxMs")); // int processingTimeMs = calculateProcessingTime(minMs, maxMs); // // LOG.debug("Start blocking request, processing time: {} ms (" + minMs + " - " + maxMs + ").", processingTimeMs); // try { // Thread.sleep(processingTimeMs); // } // catch (InterruptedException e) {} // // String responseBody = "{\"status\":\"Ok\",\"processingTimeMs\":" + processingTimeMs + "}"; // response.setStatus(SC_OK); // response.setContentType("text/plain;charset=ISO-8859-1"); // write(responseBody, response.getOutputStream()); // } // // private int calculateProcessingTime(int minMs, int maxMs) { // if (maxMs < minMs) maxMs = minMs; // int processingTimeMs = minMs + (int) (Math.random() * (maxMs - minMs)); // return processingTimeMs; // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import se.callista.springmvc.asynch.Application; import se.callista.springmvc.asynch.common.AsynchTestBase; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package se.callista.springmvc.asynch.pattern.routingslip; /** * Created by magnus on 29/05/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java // @ComponentScan() // @EnableAutoConfiguration // public class Application { // // @SuppressWarnings("unused") // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // @Bean // public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ // return new MyEmbeddedServletContainerCustomizer(); // } // // @Value("${threadPool.db.init_size}") // private int THREAD_POOL_DB_INIT_SIZE; // // @Value("${threadPool.db.max_size}") // private int THREAD_POOL_DB_MAX_SIZE; // // @Value("${threadPool.db.queue_size}") // private int THREAD_POOL_DB_QUEUE_SIZE; // // @Bean(name="dbThreadPoolExecutor") // public TaskExecutor getTaskExecutor() { // ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); // tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); // tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); // tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); // tpte.initialize(); // return tpte; // } // // @Bean // public AsyncHttpClientLambdaAware getAsyncHttpClient() { // LOG.info("### Creates a new AsyncHttpClientLambdaAware-object"); // return new AsyncHttpClientLambdaAware(); // } // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/AsynchTestBase.java // abstract public class AsynchTestBase extends EmbeddedHttpServerTestBase { // // private static final Logger LOG = LoggerFactory.getLogger(AsynchTestBase.class); // // protected void createResponse(HttpServletRequest request, String requestBody, HttpServletResponse response) throws IOException, URISyntaxException { // // Map<String, String> parMap = new HashMap<>(); // parMap.put("minMs", "0"); // parMap.put("maxMs", "0"); // getQueryParameters(request, parMap); // // int minMs = Integer.parseInt(parMap.get("minMs")); // int maxMs = Integer.parseInt(parMap.get("maxMs")); // int processingTimeMs = calculateProcessingTime(minMs, maxMs); // // LOG.debug("Start blocking request, processing time: {} ms (" + minMs + " - " + maxMs + ").", processingTimeMs); // try { // Thread.sleep(processingTimeMs); // } // catch (InterruptedException e) {} // // String responseBody = "{\"status\":\"Ok\",\"processingTimeMs\":" + processingTimeMs + "}"; // response.setStatus(SC_OK); // response.setContentType("text/plain;charset=ISO-8859-1"); // write(responseBody, response.getOutputStream()); // } // // private int calculateProcessingTime(int minMs, int maxMs) { // if (maxMs < minMs) maxMs = minMs; // int processingTimeMs = minMs + (int) (Math.random() * (maxMs - minMs)); // return processingTimeMs; // } // } // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/pattern/routingslip/RoutingSlipControllerTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import se.callista.springmvc.asynch.Application; import se.callista.springmvc.asynch.common.AsynchTestBase; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package se.callista.springmvc.asynch.pattern.routingslip; /** * Created by magnus on 29/05/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration
public class RoutingSlipControllerTest extends AsynchTestBase {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/pattern/aggregator/AggregatorControllerTest.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java // @ComponentScan() // @EnableAutoConfiguration // public class Application { // // @SuppressWarnings("unused") // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // @Bean // public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ // return new MyEmbeddedServletContainerCustomizer(); // } // // @Value("${threadPool.db.init_size}") // private int THREAD_POOL_DB_INIT_SIZE; // // @Value("${threadPool.db.max_size}") // private int THREAD_POOL_DB_MAX_SIZE; // // @Value("${threadPool.db.queue_size}") // private int THREAD_POOL_DB_QUEUE_SIZE; // // @Bean(name="dbThreadPoolExecutor") // public TaskExecutor getTaskExecutor() { // ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); // tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); // tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); // tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); // tpte.initialize(); // return tpte; // } // // @Bean // public AsyncHttpClientLambdaAware getAsyncHttpClient() { // LOG.info("### Creates a new AsyncHttpClientLambdaAware-object"); // return new AsyncHttpClientLambdaAware(); // } // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/AsynchTestBase.java // abstract public class AsynchTestBase extends EmbeddedHttpServerTestBase { // // private static final Logger LOG = LoggerFactory.getLogger(AsynchTestBase.class); // // protected void createResponse(HttpServletRequest request, String requestBody, HttpServletResponse response) throws IOException, URISyntaxException { // // Map<String, String> parMap = new HashMap<>(); // parMap.put("minMs", "0"); // parMap.put("maxMs", "0"); // getQueryParameters(request, parMap); // // int minMs = Integer.parseInt(parMap.get("minMs")); // int maxMs = Integer.parseInt(parMap.get("maxMs")); // int processingTimeMs = calculateProcessingTime(minMs, maxMs); // // LOG.debug("Start blocking request, processing time: {} ms (" + minMs + " - " + maxMs + ").", processingTimeMs); // try { // Thread.sleep(processingTimeMs); // } // catch (InterruptedException e) {} // // String responseBody = "{\"status\":\"Ok\",\"processingTimeMs\":" + processingTimeMs + "}"; // response.setStatus(SC_OK); // response.setContentType("text/plain;charset=ISO-8859-1"); // write(responseBody, response.getOutputStream()); // } // // private int calculateProcessingTime(int minMs, int maxMs) { // if (maxMs < minMs) maxMs = minMs; // int processingTimeMs = minMs + (int) (Math.random() * (maxMs - minMs)); // return processingTimeMs; // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/ProcessingStatus.java // @XmlRootElement // public class ProcessingStatus { // // @XmlElement // private final String status; // // @XmlElement // private final int processingTimeMs; // // public ProcessingStatus() { // status = "UNKNOWN"; // processingTimeMs = -1; // } // // public ProcessingStatus(String status, int processingTimeMs) { // this.status = status; // this.processingTimeMs = processingTimeMs; // } // // public String getStatus() { // return status; // } // // public int getProcessingTimeMs() { // return processingTimeMs; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import se.callista.springmvc.asynch.Application; import se.callista.springmvc.asynch.common.AsynchTestBase; import se.callista.springmvc.asynch.common.ProcessingStatus; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package se.callista.springmvc.asynch.pattern.aggregator; /** * Created by magnus on 29/05/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java // @ComponentScan() // @EnableAutoConfiguration // public class Application { // // @SuppressWarnings("unused") // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // @Bean // public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ // return new MyEmbeddedServletContainerCustomizer(); // } // // @Value("${threadPool.db.init_size}") // private int THREAD_POOL_DB_INIT_SIZE; // // @Value("${threadPool.db.max_size}") // private int THREAD_POOL_DB_MAX_SIZE; // // @Value("${threadPool.db.queue_size}") // private int THREAD_POOL_DB_QUEUE_SIZE; // // @Bean(name="dbThreadPoolExecutor") // public TaskExecutor getTaskExecutor() { // ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); // tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); // tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); // tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); // tpte.initialize(); // return tpte; // } // // @Bean // public AsyncHttpClientLambdaAware getAsyncHttpClient() { // LOG.info("### Creates a new AsyncHttpClientLambdaAware-object"); // return new AsyncHttpClientLambdaAware(); // } // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/AsynchTestBase.java // abstract public class AsynchTestBase extends EmbeddedHttpServerTestBase { // // private static final Logger LOG = LoggerFactory.getLogger(AsynchTestBase.class); // // protected void createResponse(HttpServletRequest request, String requestBody, HttpServletResponse response) throws IOException, URISyntaxException { // // Map<String, String> parMap = new HashMap<>(); // parMap.put("minMs", "0"); // parMap.put("maxMs", "0"); // getQueryParameters(request, parMap); // // int minMs = Integer.parseInt(parMap.get("minMs")); // int maxMs = Integer.parseInt(parMap.get("maxMs")); // int processingTimeMs = calculateProcessingTime(minMs, maxMs); // // LOG.debug("Start blocking request, processing time: {} ms (" + minMs + " - " + maxMs + ").", processingTimeMs); // try { // Thread.sleep(processingTimeMs); // } // catch (InterruptedException e) {} // // String responseBody = "{\"status\":\"Ok\",\"processingTimeMs\":" + processingTimeMs + "}"; // response.setStatus(SC_OK); // response.setContentType("text/plain;charset=ISO-8859-1"); // write(responseBody, response.getOutputStream()); // } // // private int calculateProcessingTime(int minMs, int maxMs) { // if (maxMs < minMs) maxMs = minMs; // int processingTimeMs = minMs + (int) (Math.random() * (maxMs - minMs)); // return processingTimeMs; // } // } // // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/common/ProcessingStatus.java // @XmlRootElement // public class ProcessingStatus { // // @XmlElement // private final String status; // // @XmlElement // private final int processingTimeMs; // // public ProcessingStatus() { // status = "UNKNOWN"; // processingTimeMs = -1; // } // // public ProcessingStatus(String status, int processingTimeMs) { // this.status = status; // this.processingTimeMs = processingTimeMs; // } // // public String getStatus() { // return status; // } // // public int getProcessingTimeMs() { // return processingTimeMs; // } // } // Path: spring-mvc-asynch/src/test/java/se/callista/springmvc/asynch/pattern/aggregator/AggregatorControllerTest.java import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import se.callista.springmvc.asynch.Application; import se.callista.springmvc.asynch.common.AsynchTestBase; import se.callista.springmvc.asynch.common.ProcessingStatus; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package se.callista.springmvc.asynch.pattern.aggregator; /** * Created by magnus on 29/05/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebAppConfiguration
public class AggregatorControllerTest extends AsynchTestBase {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessorCallback.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // }
import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine;
package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; public class AsynchProcessorCallback extends AsyncCompletionHandler<Response> { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessorCallback.class);
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessorCallback.java import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; public class AsynchProcessorCallback extends AsyncCompletionHandler<Response> { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessorCallback.class);
private final StateMachine stateMachine;
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessorCallback.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // }
import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine;
package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; public class AsynchProcessorCallback extends AsyncCompletionHandler<Response> { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessorCallback.class); private final StateMachine stateMachine;
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/State.java // public class State { // // private static final AtomicLong lastProcessId = new AtomicLong(0); // // private StateProcessingStepIterator processingSteps; // private long processId; // private LogHelper log; // private StateMachineCallback completionCallback; // private String result = ""; // // public State(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // this.processingSteps = new StateProcessingStepIterator(processingSteps); // this.log = log; // this.completionCallback = completionCallback; // this.processId = lastProcessId.incrementAndGet(); // } // // public LogHelper getLog() { // return log; // } // public long getProcessId() { // return processId; // } // // public Iterator<Processor> getProcessingSteps() { // return processingSteps; // } // public int getProcessingStepNo() { return processingSteps.getProcessingStepNo(); } // // public StateMachineCallback getCompletionCallback() { // return completionCallback; // } // // public String appendResult(String newResult) { // return result += newResult; // } // public String getResult() { // return result; // } // } // // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/StateMachine.java // @Component // public class StateMachine { // // public void initProcessing(Iterator<Processor> processingSteps, LogHelper log, StateMachineCallback completionCallback) { // executeNextStep(new State(processingSteps, log, completionCallback)); // } // // public void executeNextStep(State state) { // // if (state.getProcessingSteps().hasNext()) { // // Initiate next processing step... // state.getProcessingSteps().next().process(state); // // } else { // // We are done... // state.getCompletionCallback().onCompleted(state); // } // } // // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/nonblocking/statemachine/AsynchProcessorCallback.java import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.callista.springmvc.asynch.common.statemachine.State; import se.callista.springmvc.asynch.common.statemachine.StateMachine; package se.callista.springmvc.asynch.pattern.routingslip.nonblocking.statemachine; public class AsynchProcessorCallback extends AsyncCompletionHandler<Response> { private static final Logger LOG = LoggerFactory.getLogger(AsynchProcessorCallback.class); private final StateMachine stateMachine;
private final State state;
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/lambdasupport/AsyncHttpClientLambdaAware.java // public class AsyncHttpClientLambdaAware { // // private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); // // public ListenableFuture<Response> execute(String url, final Completed c, final Error e) throws IOException { // return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() { // // @Override // public Response onCompleted(Response response) throws Exception { // return c.onCompleted(response); // } // // @Override // public void onThrowable(Throwable t) { // e.onThrowable(t); // } // // }); // }; // // public ListenableFuture<Response> execute(String url, final Completed c) throws IOException { // return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() { // // @Override // public Response onCompleted(Response response) throws Exception { // return c.onCompleted(response); // } // }); // }; // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import se.callista.springmvc.asynch.common.lambdasupport.AsyncHttpClientLambdaAware; import se.callista.springmvc.asynch.config.MyEmbeddedServletContainerCustomizer;
package se.callista.springmvc.asynch; @ComponentScan() @EnableAutoConfiguration public class Application { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(Application.class); @Bean public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ return new MyEmbeddedServletContainerCustomizer(); } @Value("${threadPool.db.init_size}") private int THREAD_POOL_DB_INIT_SIZE; @Value("${threadPool.db.max_size}") private int THREAD_POOL_DB_MAX_SIZE; @Value("${threadPool.db.queue_size}") private int THREAD_POOL_DB_QUEUE_SIZE; @Bean(name="dbThreadPoolExecutor") public TaskExecutor getTaskExecutor() { ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); tpte.initialize(); return tpte; } @Bean
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/lambdasupport/AsyncHttpClientLambdaAware.java // public class AsyncHttpClientLambdaAware { // // private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); // // public ListenableFuture<Response> execute(String url, final Completed c, final Error e) throws IOException { // return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() { // // @Override // public Response onCompleted(Response response) throws Exception { // return c.onCompleted(response); // } // // @Override // public void onThrowable(Throwable t) { // e.onThrowable(t); // } // // }); // }; // // public ListenableFuture<Response> execute(String url, final Completed c) throws IOException { // return asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() { // // @Override // public Response onCompleted(Response response) throws Exception { // return c.onCompleted(response); // } // }); // }; // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/Application.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import se.callista.springmvc.asynch.common.lambdasupport.AsyncHttpClientLambdaAware; import se.callista.springmvc.asynch.config.MyEmbeddedServletContainerCustomizer; package se.callista.springmvc.asynch; @ComponentScan() @EnableAutoConfiguration public class Application { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(Application.class); @Bean public EmbeddedServletContainerCustomizer embeddedServletCustomizer(){ return new MyEmbeddedServletContainerCustomizer(); } @Value("${threadPool.db.init_size}") private int THREAD_POOL_DB_INIT_SIZE; @Value("${threadPool.db.max_size}") private int THREAD_POOL_DB_MAX_SIZE; @Value("${threadPool.db.queue_size}") private int THREAD_POOL_DB_QUEUE_SIZE; @Bean(name="dbThreadPoolExecutor") public TaskExecutor getTaskExecutor() { ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor(); tpte.setCorePoolSize(THREAD_POOL_DB_INIT_SIZE); tpte.setMaxPoolSize(THREAD_POOL_DB_MAX_SIZE); tpte.setQueueCapacity(THREAD_POOL_DB_QUEUE_SIZE); tpte.initialize(); return tpte; } @Bean
public AsyncHttpClientLambdaAware getAsyncHttpClient() {
callistaenterprise/blog-non-blocking-rest-service-with-spring-mvc
spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/blocking/statemachine/RoutingSlipBlockingConfiguration.java
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
package se.callista.springmvc.asynch.pattern.routingslip.blocking.statemachine; /** * Created by magnus on 08/06/14. */ @Component public class RoutingSlipBlockingConfiguration { @Autowired private SynchProcessor synchProcessor; /** * Simulates setting up a number of processing steps from some kind of configuration... * * @return */
// Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/common/statemachine/Processor.java // public interface Processor { // public void process(State state); // } // Path: spring-mvc-asynch/src/main/java/se/callista/springmvc/asynch/pattern/routingslip/blocking/statemachine/RoutingSlipBlockingConfiguration.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import se.callista.springmvc.asynch.common.statemachine.Processor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; package se.callista.springmvc.asynch.pattern.routingslip.blocking.statemachine; /** * Created by magnus on 08/06/14. */ @Component public class RoutingSlipBlockingConfiguration { @Autowired private SynchProcessor synchProcessor; /** * Simulates setting up a number of processing steps from some kind of configuration... * * @return */
public Iterator<Processor> getProcessingSteps() {
hexabeast/HexBox
core/src/com/hexabeast/sandbox/ModifyTerrain.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NBlockModification.java // public class NBlockModification { // public int x; // public int y; // // public int id; // // // public boolean layer; // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.hexabeast.hexboxserver.NBlockModification;
newCellType = AllBlocTypes.instance.getType(newCell); if(!isThereObstacle(newCellType.collide) || (layer == Map.instance.backLayer))// && !isThereObstacleHouse()) ) { //IS OBSIDIAN = NO ACTION if(!getCell(layer,decalaX+0,decalaY+0).unbreakable && (!AllBlocTypes.instance.getType(newCell).needBack || getCell(Map.instance.backLayer,decalaX+0,decalaY+0).collide)) { float ratePose2 = ratePose; if(Parameters.i.ultrarate)ratePose2/=100; //IS PLACING TILE if(time>lastTimePose+ratePose2 && getCell(layer,decalaX+0,decalaY+0).air && !newCellType.air)// && (true || layer != oldLayer || decalaX != oldclicPos.x || decalaY != oldclicPos.y)) { lastTimePose = time; setBlock(decalaX, decalaY, newCell, layer); if(normalWay)GameScreen.inventory.invItemsArray[selectorId][0].number--; Tools.checkItems(); success = true; } } oldnewCell = newCell; } return success; } public void setBlock(int x, int y, int id, MapLayer layer) { if(NetworkManager.instance.online) {
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NBlockModification.java // public class NBlockModification { // public int x; // public int y; // // public int id; // // // public boolean layer; // } // Path: core/src/com/hexabeast/sandbox/ModifyTerrain.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.hexabeast.hexboxserver.NBlockModification; newCellType = AllBlocTypes.instance.getType(newCell); if(!isThereObstacle(newCellType.collide) || (layer == Map.instance.backLayer))// && !isThereObstacleHouse()) ) { //IS OBSIDIAN = NO ACTION if(!getCell(layer,decalaX+0,decalaY+0).unbreakable && (!AllBlocTypes.instance.getType(newCell).needBack || getCell(Map.instance.backLayer,decalaX+0,decalaY+0).collide)) { float ratePose2 = ratePose; if(Parameters.i.ultrarate)ratePose2/=100; //IS PLACING TILE if(time>lastTimePose+ratePose2 && getCell(layer,decalaX+0,decalaY+0).air && !newCellType.air)// && (true || layer != oldLayer || decalaX != oldclicPos.x || decalaY != oldclicPos.y)) { lastTimePose = time; setBlock(decalaX, decalaY, newCell, layer); if(normalWay)GameScreen.inventory.invItemsArray[selectorId][0].number--; Tools.checkItems(); success = true; } } oldnewCell = newCell; } return success; } public void setBlock(int x, int y, int id, MapLayer layer) { if(NetworkManager.instance.online) {
NBlockModification nn = new NBlockModification();
hexabeast/HexBox
core/src/com/hexabeast/sandbox/LoadingScreen.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NCompressedLayer.java // public class NCompressedLayer // { // public boolean isMain; // public String layer; // // public NCompressedLayer() // { // } // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.hexabeast.hexboxserver.NCompressedLayer;
package com.hexabeast.sandbox; public class LoadingScreen implements Screen { public OrthographicCamera camera; Texture loadingJ; TextureRegion loadingV; Texture backGround; TextureRegion loadingShadow; boolean passed = false; Texture[] loadingCadre = new Texture[7]; SpriteBatch batch; int state = 0; int checkState = 2; float progress = 0f; float progresspeed = 0.3f; float progressSmooth = 0f; float width = Gdx.graphics.getWidth(); float height = Gdx.graphics.getHeight(); boolean mapLoaded = false; public boolean NmainLoaded; public boolean NbackLoaded;
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NCompressedLayer.java // public class NCompressedLayer // { // public boolean isMain; // public String layer; // // public NCompressedLayer() // { // } // } // Path: core/src/com/hexabeast/sandbox/LoadingScreen.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.hexabeast.hexboxserver.NCompressedLayer; package com.hexabeast.sandbox; public class LoadingScreen implements Screen { public OrthographicCamera camera; Texture loadingJ; TextureRegion loadingV; Texture backGround; TextureRegion loadingShadow; boolean passed = false; Texture[] loadingCadre = new Texture[7]; SpriteBatch batch; int state = 0; int checkState = 2; float progress = 0f; float progresspeed = 0.3f; float progressSmooth = 0f; float width = Gdx.graphics.getWidth(); float height = Gdx.graphics.getHeight(); boolean mapLoaded = false; public boolean NmainLoaded; public boolean NbackLoaded;
public NCompressedLayer NmainLayer;
hexabeast/HexBox
core/src/com/hexabeast/sandbox/IntegratedServerMap.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NBlockModification.java // public class NBlockModification { // public int x; // public int y; // // public int id; // // // public boolean layer; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NCompressedLayer.java // public class NCompressedLayer // { // public boolean isMain; // public String layer; // // public NCompressedLayer() // { // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/VirtualMap.java // public class VirtualMap { // public VirtualMap() // { // } // // public synchronized void setBlock(NBlockModification conf) // { // // } // // public void setChanged(int x, int y, int layer) // { // // } // // public synchronized void sendCompressedMap(boolean isMain, Connection c) // { // // } // // public void sendLayer(boolean isMain, Connection c) throws IOException // { // // } // // public void loadMap(byte[][] layer, FileHandle[][] mapFile) throws IOException // { // // } // // public void saveMap() // { // // } // // public void SaveLayers(int m, boolean saveAll) throws IOException // { // // } // }
import com.hexabeast.hexboxserver.NBlockModification; import com.hexabeast.hexboxserver.NCompressedLayer; import com.hexabeast.hexboxserver.VirtualMap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.StreamUtils; import com.esotericsoftware.kryonet.Connection;
package com.hexabeast.sandbox; public class IntegratedServerMap extends VirtualMap{ String fileName; public IntegratedServerMap() { } @Override
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NBlockModification.java // public class NBlockModification { // public int x; // public int y; // // public int id; // // // public boolean layer; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NCompressedLayer.java // public class NCompressedLayer // { // public boolean isMain; // public String layer; // // public NCompressedLayer() // { // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/VirtualMap.java // public class VirtualMap { // public VirtualMap() // { // } // // public synchronized void setBlock(NBlockModification conf) // { // // } // // public void setChanged(int x, int y, int layer) // { // // } // // public synchronized void sendCompressedMap(boolean isMain, Connection c) // { // // } // // public void sendLayer(boolean isMain, Connection c) throws IOException // { // // } // // public void loadMap(byte[][] layer, FileHandle[][] mapFile) throws IOException // { // // } // // public void saveMap() // { // // } // // public void SaveLayers(int m, boolean saveAll) throws IOException // { // // } // } // Path: core/src/com/hexabeast/sandbox/IntegratedServerMap.java import com.hexabeast.hexboxserver.NBlockModification; import com.hexabeast.hexboxserver.NCompressedLayer; import com.hexabeast.hexboxserver.VirtualMap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.StreamUtils; import com.esotericsoftware.kryonet.Connection; package com.hexabeast.sandbox; public class IntegratedServerMap extends VirtualMap{ String fileName; public IntegratedServerMap() { } @Override
public synchronized void setBlock(NBlockModification conf)
hexabeast/HexBox
core/src/com/hexabeast/sandbox/IntegratedServerMap.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NBlockModification.java // public class NBlockModification { // public int x; // public int y; // // public int id; // // // public boolean layer; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NCompressedLayer.java // public class NCompressedLayer // { // public boolean isMain; // public String layer; // // public NCompressedLayer() // { // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/VirtualMap.java // public class VirtualMap { // public VirtualMap() // { // } // // public synchronized void setBlock(NBlockModification conf) // { // // } // // public void setChanged(int x, int y, int layer) // { // // } // // public synchronized void sendCompressedMap(boolean isMain, Connection c) // { // // } // // public void sendLayer(boolean isMain, Connection c) throws IOException // { // // } // // public void loadMap(byte[][] layer, FileHandle[][] mapFile) throws IOException // { // // } // // public void saveMap() // { // // } // // public void SaveLayers(int m, boolean saveAll) throws IOException // { // // } // }
import com.hexabeast.hexboxserver.NBlockModification; import com.hexabeast.hexboxserver.NCompressedLayer; import com.hexabeast.hexboxserver.VirtualMap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.StreamUtils; import com.esotericsoftware.kryonet.Connection;
public synchronized void sendCompressedMap(boolean isMain, Connection c) { try { sendLayer(isMain,c); } catch (IOException e) { e.printStackTrace(); } } @Override public void sendLayer(boolean isMain, Connection c) throws IOException { MapLayer m = Map.instance.mainLayer; if(!isMain)m = Map.instance.backLayer; ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); DeflaterOutputStream dos; baos2 = new ByteArrayOutputStream(); dos = new DeflaterOutputStream(baos2); for(int k = 0; k<Map.instance.width; k++) { for(int l = 0; l<Map.instance.height; l++) { dos.write(m.getBloc(k, l).Id & 0x000000FF); } } if(dos != null) { dos.finish(); }
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NBlockModification.java // public class NBlockModification { // public int x; // public int y; // // public int id; // // // public boolean layer; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NCompressedLayer.java // public class NCompressedLayer // { // public boolean isMain; // public String layer; // // public NCompressedLayer() // { // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/VirtualMap.java // public class VirtualMap { // public VirtualMap() // { // } // // public synchronized void setBlock(NBlockModification conf) // { // // } // // public void setChanged(int x, int y, int layer) // { // // } // // public synchronized void sendCompressedMap(boolean isMain, Connection c) // { // // } // // public void sendLayer(boolean isMain, Connection c) throws IOException // { // // } // // public void loadMap(byte[][] layer, FileHandle[][] mapFile) throws IOException // { // // } // // public void saveMap() // { // // } // // public void SaveLayers(int m, boolean saveAll) throws IOException // { // // } // } // Path: core/src/com/hexabeast/sandbox/IntegratedServerMap.java import com.hexabeast.hexboxserver.NBlockModification; import com.hexabeast.hexboxserver.NCompressedLayer; import com.hexabeast.hexboxserver.VirtualMap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.StreamUtils; import com.esotericsoftware.kryonet.Connection; public synchronized void sendCompressedMap(boolean isMain, Connection c) { try { sendLayer(isMain,c); } catch (IOException e) { e.printStackTrace(); } } @Override public void sendLayer(boolean isMain, Connection c) throws IOException { MapLayer m = Map.instance.mainLayer; if(!isMain)m = Map.instance.backLayer; ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); DeflaterOutputStream dos; baos2 = new ByteArrayOutputStream(); dos = new DeflaterOutputStream(baos2); for(int k = 0; k<Map.instance.width; k++) { for(int l = 0; l<Map.instance.height; l++) { dos.write(m.getBloc(k, l).Id & 0x000000FF); } } if(dos != null) { dos.finish(); }
NCompressedLayer l = new NCompressedLayer();
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Map.java
// Path: core/src/com/hexabeast/sandbox/mobs/MobSave.java // public class MobSave { // public int[] type; // public float[] x; // public float[] y; // // public MobSave() {} // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.StreamUtils; import com.hexabeast.sandbox.mobs.MobSave;
mapFile2[i][j].file().createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } backLayer = new MapLayer(false); random = true; } lights = new LightManager(); } public void Save() throws IOException { SaveLayer(mapFile1, mainLayer,false); SaveLayer(mapFile2, backLayer,false); //SaveVillage(mapFileVillage1,mainLayer); //SaveVillage(mapFileVillage2,backLayer); SaveEntities(); } public void SaveEntities() { TreeSave treesav = new TreeSave(); FurnitureSave fursav = new FurnitureSave();
// Path: core/src/com/hexabeast/sandbox/mobs/MobSave.java // public class MobSave { // public int[] type; // public float[] x; // public float[] y; // // public MobSave() {} // } // Path: core/src/com/hexabeast/sandbox/Map.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.StreamUtils; import com.hexabeast.sandbox.mobs.MobSave; mapFile2[i][j].file().createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } backLayer = new MapLayer(false); random = true; } lights = new LightManager(); } public void Save() throws IOException { SaveLayer(mapFile1, mainLayer,false); SaveLayer(mapFile2, backLayer,false); //SaveVillage(mapFileVillage1,mainLayer); //SaveVillage(mapFileVillage2,backLayer); SaveEntities(); } public void SaveEntities() { TreeSave treesav = new TreeSave(); FurnitureSave fursav = new FurnitureSave();
MobSave mobsav = new MobSave();
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Chat.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/HMessage.java // public class HMessage { // // public int id; // public String str; // public String owner; // // public HMessage() // { // // } // // public HMessage(String str, String owner) // { // this.str = str; // this.owner = owner; // } // }
import java.util.ArrayList; import java.util.Random; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.badlogic.gdx.utils.Align; import com.hexabeast.hexboxserver.HMessage;
package com.hexabeast.sandbox; public class Chat { TextField inputField; Stage scene; ArrayList<Message> messages = new ArrayList<Message>(); BitmapFont font; Random ran; public Chat() { ran = new Random(); font = FontManager.instance.fontsmall; this.scene = new Stage(); TextFieldStyle tfs = new TextFieldStyle(); tfs.font = font; tfs.fontColor = Color.WHITE; tfs.selection = new TextureRegionDrawable(TextureManager.instance.textBoxSurline); tfs.cursor = new TextureRegionDrawable(TextureManager.instance.textBoxCursor); //tfs.background = new TextureRegionDrawable(TextureManager.instance.ipButton); inputField = new TextField("", tfs); inputField.setWidth(400); inputField.setPosition(10,60); scene.addActor(inputField); }
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/HMessage.java // public class HMessage { // // public int id; // public String str; // public String owner; // // public HMessage() // { // // } // // public HMessage(String str, String owner) // { // this.str = str; // this.owner = owner; // } // } // Path: core/src/com/hexabeast/sandbox/Chat.java import java.util.ArrayList; import java.util.Random; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.badlogic.gdx.utils.Align; import com.hexabeast.hexboxserver.HMessage; package com.hexabeast.sandbox; public class Chat { TextField inputField; Stage scene; ArrayList<Message> messages = new ArrayList<Message>(); BitmapFont font; Random ran; public Chat() { ran = new Random(); font = FontManager.instance.fontsmall; this.scene = new Stage(); TextFieldStyle tfs = new TextFieldStyle(); tfs.font = font; tfs.fontColor = Color.WHITE; tfs.selection = new TextureRegionDrawable(TextureManager.instance.textBoxSurline); tfs.cursor = new TextureRegionDrawable(TextureManager.instance.textBoxCursor); //tfs.background = new TextureRegionDrawable(TextureManager.instance.ipButton); inputField = new TextField("", tfs); inputField.setWidth(400); inputField.setPosition(10,60); scene.addActor(inputField); }
public void addMessageN(HMessage msg)
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Main.java
// Path: core/src/com/hexabeast/sandbox/Parameters.java // public class Parameters { // public static Parameters i; // // public boolean fullBright = false; // public boolean noShadow = false; // public boolean shader = true; // public int HQ = 5; // public boolean RGB = true; // public float daylight = 1.0f; // public boolean cheatMagic = false; // public int lightSpeed = 120; // public int resolution = 2; // public boolean fullscreen = false; // public boolean superman = false; // public boolean ultrarate = false; // public boolean multithread = false;//TODO // public float deltaMultiplier = 1; // public boolean vsync = false; // public boolean details = true; // public boolean drawhitbox = false; // public boolean ultrarange = false; // public boolean godmode = false; // public boolean rain = false; // public boolean background = true; // public boolean oldtransition = false; // public int currentTransform = 0; // public boolean goodmagic = true; // public int lightDistance = 2; // public boolean FBORender = false; // public boolean zoomLock = false; // public boolean ratio = true; // public String name = "John"; // // public int head = 0; // public int body = 0; // public int arms = 0; // public int legs = 0; // public int eyes = 0; // public int hair = 0; // // public int volume = 10; // public int volumeMusic = 10; // public int volumeFX = 10; // // public int keyboard = HKeys.QWERTY; // // Parameters() // { // // } // // public void disableCheats() // { // drawhitbox = false; // deltaMultiplier = 1; // cheatMagic = false; // rain = false; // godmode = false; // ultrarange = false; // ultrarate = false; // noShadow = false; // superman = false; // fullBright = false; // cheatMagic = false; // } // // public void SwitchQuality() // { // HQ++; // if(HQ>=Constants.qualities.length)HQ = 1; // } // // }
import java.io.IOException; import java.util.Random; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Matrix4; import com.hexabeast.sandbox.Parameters;
public static FrameBuffer fbo; public static Random random; public static Mesh mesh; public static InputMultiplexer inputMultiplexer; static Joystick joy; public static boolean allLoaded; public static void sCreate() { allLoaded = false; noUI = false; multiplayer = false; host = false; ingame = false; time = 0; pause = false; loaded = false; zoom = 1; backtom = false; inputMultiplexer = new InputMultiplexer(); if(NetworkManager.instance != null && NetworkManager.instance.server != null)NetworkManager.instance.server.stop(); network= new NetworkManager(); //if(multiplayer)network.connectLocal();
// Path: core/src/com/hexabeast/sandbox/Parameters.java // public class Parameters { // public static Parameters i; // // public boolean fullBright = false; // public boolean noShadow = false; // public boolean shader = true; // public int HQ = 5; // public boolean RGB = true; // public float daylight = 1.0f; // public boolean cheatMagic = false; // public int lightSpeed = 120; // public int resolution = 2; // public boolean fullscreen = false; // public boolean superman = false; // public boolean ultrarate = false; // public boolean multithread = false;//TODO // public float deltaMultiplier = 1; // public boolean vsync = false; // public boolean details = true; // public boolean drawhitbox = false; // public boolean ultrarange = false; // public boolean godmode = false; // public boolean rain = false; // public boolean background = true; // public boolean oldtransition = false; // public int currentTransform = 0; // public boolean goodmagic = true; // public int lightDistance = 2; // public boolean FBORender = false; // public boolean zoomLock = false; // public boolean ratio = true; // public String name = "John"; // // public int head = 0; // public int body = 0; // public int arms = 0; // public int legs = 0; // public int eyes = 0; // public int hair = 0; // // public int volume = 10; // public int volumeMusic = 10; // public int volumeFX = 10; // // public int keyboard = HKeys.QWERTY; // // Parameters() // { // // } // // public void disableCheats() // { // drawhitbox = false; // deltaMultiplier = 1; // cheatMagic = false; // rain = false; // godmode = false; // ultrarange = false; // ultrarate = false; // noShadow = false; // superman = false; // fullBright = false; // cheatMagic = false; // } // // public void SwitchQuality() // { // HQ++; // if(HQ>=Constants.qualities.length)HQ = 1; // } // // } // Path: core/src/com/hexabeast/sandbox/Main.java import java.io.IOException; import java.util.Random; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Matrix4; import com.hexabeast.sandbox.Parameters; public static FrameBuffer fbo; public static Random random; public static Mesh mesh; public static InputMultiplexer inputMultiplexer; static Joystick joy; public static boolean allLoaded; public static void sCreate() { allLoaded = false; noUI = false; multiplayer = false; host = false; ingame = false; time = 0; pause = false; loaded = false; zoom = 1; backtom = false; inputMultiplexer = new InputMultiplexer(); if(NetworkManager.instance != null && NetworkManager.instance.server != null)NetworkManager.instance.server.stop(); network= new NetworkManager(); //if(multiplayer)network.connectLocal();
Parameters.i = new Parameters();
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Inputs.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick;
package com.hexabeast.sandbox; public class Inputs implements InputProcessor{ public static Inputs instance; public boolean mouseup; private boolean tomouseup; public boolean mousedown; private boolean tomousedown; public boolean leftmousedown; private boolean toleftmousedown; public boolean rightmousedown; private boolean torightmousedown; public boolean leftmouseup; private boolean toleftmouseup; public boolean rightmouseup; private boolean torightmouseup; public boolean middleOrAPressed; public boolean tomiddleOrAPressed; public boolean CTRL = false; public boolean Q = false; public boolean Z = false; public boolean S = false; public boolean D = false; public boolean shift = false; public boolean space = false; public boolean spacePressed = false; public boolean leftpress = false; public boolean rightpress = false;
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // } // Path: core/src/com/hexabeast/sandbox/Inputs.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick; package com.hexabeast.sandbox; public class Inputs implements InputProcessor{ public static Inputs instance; public boolean mouseup; private boolean tomouseup; public boolean mousedown; private boolean tomousedown; public boolean leftmousedown; private boolean toleftmousedown; public boolean rightmousedown; private boolean torightmousedown; public boolean leftmouseup; private boolean toleftmouseup; public boolean rightmouseup; private boolean torightmouseup; public boolean middleOrAPressed; public boolean tomiddleOrAPressed; public boolean CTRL = false; public boolean Q = false; public boolean Z = false; public boolean S = false; public boolean D = false; public boolean shift = false; public boolean space = false; public boolean spacePressed = false; public boolean leftpress = false; public boolean rightpress = false;
public NInputUpdate Ninput = new NInputUpdate();
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Inputs.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick;
public boolean S = false; public boolean D = false; public boolean shift = false; public boolean space = false; public boolean spacePressed = false; public boolean leftpress = false; public boolean rightpress = false; public NInputUpdate Ninput = new NInputUpdate(); public Inputs() { } @Override public boolean keyTyped(char character) {return false;} @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { tomousedown = true; if (button == Input.Buttons.RIGHT)torightmousedown = true; if (button == Input.Buttons.LEFT)toleftmousedown = true; if(button == Input.Buttons.MIDDLE)tomiddleOrAPressed = true; if(Main.ingame)GameScreen.updatePauseClick(); if(Main.ingame && !Main.pause) {
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // } // Path: core/src/com/hexabeast/sandbox/Inputs.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick; public boolean S = false; public boolean D = false; public boolean shift = false; public boolean space = false; public boolean spacePressed = false; public boolean leftpress = false; public boolean rightpress = false; public NInputUpdate Ninput = new NInputUpdate(); public Inputs() { } @Override public boolean keyTyped(char character) {return false;} @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { tomousedown = true; if (button == Input.Buttons.RIGHT)torightmousedown = true; if (button == Input.Buttons.LEFT)toleftmousedown = true; if(button == Input.Buttons.MIDDLE)tomiddleOrAPressed = true; if(Main.ingame)GameScreen.updatePauseClick(); if(Main.ingame && !Main.pause) {
Nclick iu = new Nclick();
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Inputs.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick;
if(tid>=0 && ModifyTerrain.instance.UseAbsolute(GameScreen.player.PNJ.middle.x, GameScreen.player.PNJ.middle.y, tid, GameScreen.player.currentCellState, Map.instance.mainLayer,Main.time,false)) GameScreen.inventory.remove(tid, 1); } } @Override public boolean keyDown(int keycode) { boolean CHEAT = false; if(Main.ingame) { if(Main.game.chatEnabled) { if(keycode == Keys.ENTER && !Main.pause) { Main.game.chat.addMessage(Main.game.chat.inputField.getText()); Main.game.chatEnabled = false; } } else { if(!Main.pause) { if(keycode == HKeys.Q) { tomiddleOrAPressed = true; } else if(keycode == HKeys.A) {
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // } // Path: core/src/com/hexabeast/sandbox/Inputs.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick; if(tid>=0 && ModifyTerrain.instance.UseAbsolute(GameScreen.player.PNJ.middle.x, GameScreen.player.PNJ.middle.y, tid, GameScreen.player.currentCellState, Map.instance.mainLayer,Main.time,false)) GameScreen.inventory.remove(tid, 1); } } @Override public boolean keyDown(int keycode) { boolean CHEAT = false; if(Main.ingame) { if(Main.game.chatEnabled) { if(keycode == Keys.ENTER && !Main.pause) { Main.game.chat.addMessage(Main.game.chat.inputField.getText()); Main.game.chatEnabled = false; } } else { if(!Main.pause) { if(keycode == HKeys.Q) { tomiddleOrAPressed = true; } else if(keycode == HKeys.A) {
if(NetworkManager.instance.online)NetworkManager.instance.sendTCP(new NInputRightLeft(false,true));
hexabeast/HexBox
core/src/com/hexabeast/sandbox/Inputs.java
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick;
@Override public boolean keyDown(int keycode) { boolean CHEAT = false; if(Main.ingame) { if(Main.game.chatEnabled) { if(keycode == Keys.ENTER && !Main.pause) { Main.game.chat.addMessage(Main.game.chat.inputField.getText()); Main.game.chatEnabled = false; } } else { if(!Main.pause) { if(keycode == HKeys.Q) { tomiddleOrAPressed = true; } else if(keycode == HKeys.A) { if(NetworkManager.instance.online)NetworkManager.instance.sendTCP(new NInputRightLeft(false,true)); Q = true; } else if(keycode == HKeys.W) {
// Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputRightLeft.java // public class NInputRightLeft { // public boolean right; // public boolean pressed; // public int id; // // public NInputRightLeft(){} // // public NInputRightLeft(boolean direction, boolean press) // { // right = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpDown.java // public class NInputUpDown { // public boolean up; // public boolean pressed; // public int id; // // public NInputUpDown(){} // // public NInputUpDown(boolean direction, boolean press) // { // up = direction; // pressed = press; // } // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/NInputUpdate.java // public class NInputUpdate { // // public NInputUpdate() // { // // } // // public int id; // // public boolean Q; // public boolean S; // public boolean D; // public boolean Z; // // //public boolean A; // // public boolean Left; // public boolean Right; // // public boolean Space; // // public Vector2 mousePos; // } // // Path: HexBoxServer/src/com/hexabeast/hexboxserver/Nclick.java // public class Nclick { // public int id; // public boolean right; // public boolean left; // public boolean jump; // public boolean hook; // } // Path: core/src/com/hexabeast/sandbox/Inputs.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.hexabeast.hexboxserver.NInputRightLeft; import com.hexabeast.hexboxserver.NInputUpDown; import com.hexabeast.hexboxserver.NInputUpdate; import com.hexabeast.hexboxserver.Nclick; @Override public boolean keyDown(int keycode) { boolean CHEAT = false; if(Main.ingame) { if(Main.game.chatEnabled) { if(keycode == Keys.ENTER && !Main.pause) { Main.game.chat.addMessage(Main.game.chat.inputField.getText()); Main.game.chatEnabled = false; } } else { if(!Main.pause) { if(keycode == HKeys.Q) { tomiddleOrAPressed = true; } else if(keycode == HKeys.A) { if(NetworkManager.instance.online)NetworkManager.instance.sendTCP(new NInputRightLeft(false,true)); Q = true; } else if(keycode == HKeys.W) {
if(NetworkManager.instance.online)NetworkManager.instance.sendTCP(new NInputUpDown(true,true));
hexabeast/HexBox
core/src/com/hexabeast/sandbox/MapGenerator.java
// Path: core/src/com/hexabeast/sandbox/mobs/MobSave.java // public class MobSave { // public int[] type; // public float[] x; // public float[] y; // // public MobSave() {} // }
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.StreamUtils; import com.hexabeast.sandbox.mobs.MobSave;
if(treeList!= null) { for(int i = 0; i<treeList.x.length; i++) { GameScreen.entities.trees.PlaceTree(treeList.x[i], treeList.y[i], treeList.seed[i],treeList.ecloseTime[i]); } } } } public void LoadFurs(FileHandle mapFile) throws IOException { if(mapFile.exists()) { String loadFurs = mapFile.readString(); FurnitureSave furList = new Json().fromJson(FurnitureSave.class, loadFurs); if(furList!= null) { for(int i = 0; i<furList.x.length; i++) { GameScreen.entities.furnitures.addFurniture(furList.x[i], furList.y[i], furList.type[i],furList.chestids[i],furList.chestnumbers[i], furList.isTurned[i]); } } } } public void LoadMobs(FileHandle mapFile) throws IOException { if(mapFile.exists()) { String loadMobs = mapFile.readString();
// Path: core/src/com/hexabeast/sandbox/mobs/MobSave.java // public class MobSave { // public int[] type; // public float[] x; // public float[] y; // // public MobSave() {} // } // Path: core/src/com/hexabeast/sandbox/MapGenerator.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.StreamUtils; import com.hexabeast.sandbox.mobs.MobSave; if(treeList!= null) { for(int i = 0; i<treeList.x.length; i++) { GameScreen.entities.trees.PlaceTree(treeList.x[i], treeList.y[i], treeList.seed[i],treeList.ecloseTime[i]); } } } } public void LoadFurs(FileHandle mapFile) throws IOException { if(mapFile.exists()) { String loadFurs = mapFile.readString(); FurnitureSave furList = new Json().fromJson(FurnitureSave.class, loadFurs); if(furList!= null) { for(int i = 0; i<furList.x.length; i++) { GameScreen.entities.furnitures.addFurniture(furList.x[i], furList.y[i], furList.type[i],furList.chestids[i],furList.chestnumbers[i], furList.isTurned[i]); } } } } public void LoadMobs(FileHandle mapFile) throws IOException { if(mapFile.exists()) { String loadMobs = mapFile.readString();
MobSave mobList = new Json().fromJson(MobSave.class, loadMobs);
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Command.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/Delegate.java // public interface Delegate { // // void validate() throws ParameterException; // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/properties/InternalProperties.java // public abstract class InternalProperties extends CompositeConfiguration { // // public InternalProperties(List<String> propertyFiles) throws IOException, ConfigurationException { // // if (propertyFiles == null || propertyFiles.isEmpty()) { // // throw new IllegalArgumentException("Property files not specified."); // } // // for (String file : propertyFiles) { // // try (InputStream is = getClass().getClassLoader().getResourceAsStream(file)) { // // PropertiesConfiguration configuration = new PropertiesConfiguration(); // configuration.load(is); // // addConfiguration(configuration); // } // } // } // }
import com.documaster.validator.config.delegates.Delegate; import com.documaster.validator.config.properties.InternalProperties; import org.apache.commons.lang.StringUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterDescription; import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParametersDelegate;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.config.commands; public abstract class Command<T extends InternalProperties> { private JCommander argParser; public Command() { } public Command(JCommander argParser) { this.argParser = argParser; } /** * Validates all {@link ParametersDelegate}s in this {@link Command}. * * @throws ParameterException * if the validation fails */ public void validate() throws ParameterException { for (Field field : getClass().getDeclaredFields()) {
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/Delegate.java // public interface Delegate { // // void validate() throws ParameterException; // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/properties/InternalProperties.java // public abstract class InternalProperties extends CompositeConfiguration { // // public InternalProperties(List<String> propertyFiles) throws IOException, ConfigurationException { // // if (propertyFiles == null || propertyFiles.isEmpty()) { // // throw new IllegalArgumentException("Property files not specified."); // } // // for (String file : propertyFiles) { // // try (InputStream is = getClass().getClassLoader().getResourceAsStream(file)) { // // PropertiesConfiguration configuration = new PropertiesConfiguration(); // configuration.load(is); // // addConfiguration(configuration); // } // } // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Command.java import com.documaster.validator.config.delegates.Delegate; import com.documaster.validator.config.properties.InternalProperties; import org.apache.commons.lang.StringUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterDescription; import com.beust.jcommander.ParameterException; import com.beust.jcommander.ParametersDelegate; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.config.commands; public abstract class Command<T extends InternalProperties> { private JCommander argParser; public Command() { } public Command(JCommander argParser) { this.argParser = argParser; } /** * Validates all {@link ParametersDelegate}s in this {@link Command}. * * @throws ParameterException * if the validation fails */ public void validate() throws ParameterException { for (Field field : getClass().getDeclaredFields()) {
if (field.getAnnotation(ParametersDelegate.class) != null && Delegate.class
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/converters/xsd/ConversionErrorListener.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/converters/Converter.java // public interface Converter { // // /** // * Returns the model that was generated as a result of the conversion. // * <p/> // * // * @return < object name , object > // */ // Map<String, ItemDef> getItemDefs() throws Exception; // // /** // * Returns the entries that were generated as a result of the conversion. // * // * @return A list of {@link Item}. // */ // List<Item> getItems() throws Exception; // // void convert(List<File> files) throws Exception; // }
import com.documaster.validator.converters.Converter; import com.sun.tools.xjc.AbortException; import com.sun.tools.xjc.api.ErrorListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXParseException;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.converters.xsd; class ConversionErrorListener implements ErrorListener { private Logger logger;
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/converters/Converter.java // public interface Converter { // // /** // * Returns the model that was generated as a result of the conversion. // * <p/> // * // * @return < object name , object > // */ // Map<String, ItemDef> getItemDefs() throws Exception; // // /** // * Returns the entries that were generated as a result of the conversion. // * // * @return A list of {@link Item}. // */ // List<Item> getItems() throws Exception; // // void convert(List<File> files) throws Exception; // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/converters/xsd/ConversionErrorListener.java import com.documaster.validator.converters.Converter; import com.sun.tools.xjc.AbortException; import com.sun.tools.xjc.api.ErrorListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXParseException; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.converters.xsd; class ConversionErrorListener implements ErrorListener { private Logger logger;
ConversionErrorListener(Class<? extends Converter> reportingClass) {
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationGroup.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/collector/ValidationCollector.java // public class ValidationCollector { // // private Map<String, List<ValidationResult>> results; // // private int totalSummaryCount = 0; // private int totalInformationCount = 0; // private int totalWarningCount = 0; // private int totalErrorCount = 0; // // private Map<String, Integer> summaryCount; // private Map<String, Integer> informationCount; // private Map<String, Integer> warningCount; // private Map<String, Integer> errorCount; // // private Map<String, ValidationStatus> statuses; // // public ValidationCollector() { // // results = new LinkedHashMap<>(); // // summaryCount = new HashMap<>(); // informationCount = new HashMap<>(); // warningCount = new HashMap<>(); // errorCount = new HashMap<>(); // statuses = new HashMap<>(); // } // // public Map<String, List<ValidationResult>> getAllResults() { // // return results; // } // // public int getTotalSummaryCount() { // // return totalSummaryCount; // } // // public int getTotalInformationCount() { // // return totalInformationCount; // } // // public int getTotalWarningCount() { // // return totalWarningCount; // } // // public int getTotalErrorCount() { // // return totalErrorCount; // } // // public int getSummaryCountIn(String groupName) { // // return summaryCount.containsKey(groupName) ? summaryCount.get(groupName) : 0; // } // // public int getInformationCountIn(String groupName) { // // return informationCount.getOrDefault(groupName, 0); // } // // public int getWarningCountIn(String groupName) { // // return warningCount.getOrDefault(groupName, 0); // } // // public int getErrorCountIn(String groupName) { // // return errorCount.getOrDefault(groupName, 0); // } // // public int getTotalResultCountIn(String groupName) { // // return results.get(groupName) != null ? results.get(groupName).size() : 0; // } // // public ValidationStatus getGroupStatus(String groupName) { // // return statuses.get(groupName); // } // // public void collect(ValidationResult result) { // // String groupName = result.getGroupName(); // // if (results.containsKey(groupName)) { // // results.get(groupName).add(result); // // } else { // // results.put(groupName, new ArrayList<>(Collections.singletonList(result))); // } // // putOrIncrementMapCounter(summaryCount, groupName, result.getSummary().size()); // putOrIncrementMapCounter(informationCount, groupName, result.getInformation().size()); // putOrIncrementMapCounter(warningCount, groupName, result.getWarnings().size()); // putOrIncrementMapCounter(errorCount, groupName, result.getErrors().size()); // // totalSummaryCount += result.getSummary().size(); // totalInformationCount += result.getInformation().size(); // totalWarningCount += result.getWarnings().size(); // totalErrorCount += result.getErrors().size(); // // if (!statuses.containsKey(groupName) || result.getStatus().isMoreSevereThan(statuses.get(groupName))) { // statuses.put(groupName, result.getStatus()); // } // } // // private static void putOrIncrementMapCounter(Map<String, Integer> map, String key, int size) { // // if (map.containsKey(key)) { // map.put(key, map.get(key) + size); // } else { // map.put(key, size); // } // } // }
import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; import com.documaster.validator.validation.collector.ValidationCollector;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider; @XmlType(name = "group") @XmlEnum public enum ValidationGroup { @XmlEnumValue("arkivstruktur") ARCHIVE_STRUCTURE("arkivstruktur", "AS"), @XmlEnumValue("loependejournal") RUNNING_JOURNAL("loependejournal", "LJ"), @XmlEnumValue("offentligjournal") PUBLIC_JOURNAL("offentligjournal", "OJ"), @XmlEnumValue("arkivuttrekk") TRANSFER_EXPORTS("addml", "AU"), @XmlEnumValue("endringslogg") CHANGE_LOG("endringslogg", "EL"), @XmlEnumValue("package") PACKAGE("package", "P"), @XmlEnumValue("exceptions") EXCEPTIONS("exceptions", "E"); private final String name; private final String prefix; ValidationGroup(String name, String prefix) { this.name = name; this.prefix = prefix; } public String getName() { return name; } public String getGroupPrefix() { return prefix; }
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/collector/ValidationCollector.java // public class ValidationCollector { // // private Map<String, List<ValidationResult>> results; // // private int totalSummaryCount = 0; // private int totalInformationCount = 0; // private int totalWarningCount = 0; // private int totalErrorCount = 0; // // private Map<String, Integer> summaryCount; // private Map<String, Integer> informationCount; // private Map<String, Integer> warningCount; // private Map<String, Integer> errorCount; // // private Map<String, ValidationStatus> statuses; // // public ValidationCollector() { // // results = new LinkedHashMap<>(); // // summaryCount = new HashMap<>(); // informationCount = new HashMap<>(); // warningCount = new HashMap<>(); // errorCount = new HashMap<>(); // statuses = new HashMap<>(); // } // // public Map<String, List<ValidationResult>> getAllResults() { // // return results; // } // // public int getTotalSummaryCount() { // // return totalSummaryCount; // } // // public int getTotalInformationCount() { // // return totalInformationCount; // } // // public int getTotalWarningCount() { // // return totalWarningCount; // } // // public int getTotalErrorCount() { // // return totalErrorCount; // } // // public int getSummaryCountIn(String groupName) { // // return summaryCount.containsKey(groupName) ? summaryCount.get(groupName) : 0; // } // // public int getInformationCountIn(String groupName) { // // return informationCount.getOrDefault(groupName, 0); // } // // public int getWarningCountIn(String groupName) { // // return warningCount.getOrDefault(groupName, 0); // } // // public int getErrorCountIn(String groupName) { // // return errorCount.getOrDefault(groupName, 0); // } // // public int getTotalResultCountIn(String groupName) { // // return results.get(groupName) != null ? results.get(groupName).size() : 0; // } // // public ValidationStatus getGroupStatus(String groupName) { // // return statuses.get(groupName); // } // // public void collect(ValidationResult result) { // // String groupName = result.getGroupName(); // // if (results.containsKey(groupName)) { // // results.get(groupName).add(result); // // } else { // // results.put(groupName, new ArrayList<>(Collections.singletonList(result))); // } // // putOrIncrementMapCounter(summaryCount, groupName, result.getSummary().size()); // putOrIncrementMapCounter(informationCount, groupName, result.getInformation().size()); // putOrIncrementMapCounter(warningCount, groupName, result.getWarnings().size()); // putOrIncrementMapCounter(errorCount, groupName, result.getErrors().size()); // // totalSummaryCount += result.getSummary().size(); // totalInformationCount += result.getInformation().size(); // totalWarningCount += result.getWarnings().size(); // totalErrorCount += result.getErrors().size(); // // if (!statuses.containsKey(groupName) || result.getStatus().isMoreSevereThan(statuses.get(groupName))) { // statuses.put(groupName, result.getStatus()); // } // } // // private static void putOrIncrementMapCounter(Map<String, Integer> map, String key, int size) { // // if (map.containsKey(key)) { // map.put(key, map.get(key) + size); // } else { // map.put(key, size); // } // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationGroup.java import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; import com.documaster.validator.validation.collector.ValidationCollector; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider; @XmlType(name = "group") @XmlEnum public enum ValidationGroup { @XmlEnumValue("arkivstruktur") ARCHIVE_STRUCTURE("arkivstruktur", "AS"), @XmlEnumValue("loependejournal") RUNNING_JOURNAL("loependejournal", "LJ"), @XmlEnumValue("offentligjournal") PUBLIC_JOURNAL("offentligjournal", "OJ"), @XmlEnumValue("arkivuttrekk") TRANSFER_EXPORTS("addml", "AU"), @XmlEnumValue("endringslogg") CHANGE_LOG("endringslogg", "EL"), @XmlEnumValue("package") PACKAGE("package", "P"), @XmlEnumValue("exceptions") EXCEPTIONS("exceptions", "E"); private final String name; private final String prefix; ValidationGroup(String name, String prefix) { this.name = name; this.prefix = prefix; } public String getName() { return name; } public String getGroupPrefix() { return prefix; }
public String getNextGroupId(ValidationCollector collector) {