hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
bc14e0d13195b923f2a11d50e9b8fcf5cbac6177
710
package eas.com.Exception; import eas.com.entity.ErrorMessage; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Created by eduardo on 12/7/2016. * * This is a best way to management the exception in JAX-RS * * */ @Provider public class AuthorExceptionMapper implements ExceptionMapper<AuthorExceptionNoFound> { @Override public Response toResponse(AuthorExceptionNoFound authorExceptionNoFound) { ErrorMessage errorMessage = new ErrorMessage(Response.Status.NOT_FOUND.getStatusCode(), authorExceptionNoFound.getMessage()); return Response.status(Response.Status.NOT_FOUND).entity(errorMessage).build(); } }
27.307692
133
0.766197
ef3224e4ade7de9dc9da8066c10e91b110b263e3
2,480
/* * Copyright (c) Joachim Ansorg, mail@ansorg-it.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.antego.bashmock.psi.impl.heredoc; import com.github.antego.bashmock.psi.api.heredoc.BashHereDocMarker; import com.github.antego.bashmock.psi.impl.BashBaseElement; import com.github.antego.bashmock.util.HeredocSharedImpl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.ResolveState; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; /** * Abstract base class for heredoc markers. * <br> * @author jansorg */ abstract class AbstractHeredocMarker extends BashBaseElement implements BashHereDocMarker { private HeredocMarkerReference reference; AbstractHeredocMarker(ASTNode astNode, String name) { super(astNode, name); } @Override public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) { return processor.execute(this, state); } @Override public String getName() { return getMarkerText(); } @Override public String getMarkerText() { return HeredocSharedImpl.cleanMarker(getText(), isIgnoringTabs()); } @Override public PsiElement setName(@NotNull String newElementName) throws IncorrectOperationException { PsiReference reference = getReference(); return reference != null ? reference.handleElementRename(newElementName) : null; } @Override public PsiReference getReference() { if (reference == null) { reference = createReference(); } return reference; } public abstract HeredocMarkerReference createReference(); @NotNull public String getCanonicalText() { return getText(); } }
31.794872
157
0.734274
d697f0c38486c6929c47d9d323da692ecde0b80c
2,191
/* * Copyright 2015 Adaptris Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.adaptris.core.runtime; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import com.adaptris.core.CoreException; import com.adaptris.core.Workflow; /** * Interface specifying controls for a single channel. */ public interface ChannelManagerMBean extends AdapterComponentMBean, ParentRuntimeInfoComponentMBean, ChildRuntimeInfoComponentMBean, HierarchicalMBean, ParentComponentMBean { /** * Add a {@link Workflow} to this channel. * * @param xmlString the string representation of the workflow. * @return the ObjectName reference to the newly created ChannelManagerMBean. * @throws CoreException wrapping any exception * @throws IllegalStateException if the state of the adapter is not "Closed" * @throws MalformedObjectNameException upon ObjectName errors. */ ObjectName addWorkflow(String xmlString) throws CoreException, IllegalStateException, MalformedObjectNameException; /** * Remove a {@link Workflow} from this channel. * * <p> * This also removes the associated {@link WorkflowManager} and calls {@link #unregisterMBean()}. * </p> * * @param id the id of the channel to remove. * @throws CoreException wrapping any exception * @throws IllegalStateException if the state of the adapter is not "Closed" * @return true if the channel existed and was removed, false otherwise. * @throws MalformedObjectNameException upon ObjectName errors. */ boolean removeWorkflow(String id) throws CoreException, IllegalStateException, MalformedObjectNameException; }
37.135593
117
0.759471
ffd16304df0fcf1dcc80d68853e85270f067f502
38,604
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package rdpclient.ntlmssp; import java.nio.charset.Charset; import rdpclient.ntlmssp.asn1.NegoItem; import rdpclient.ntlmssp.asn1.SubjectPublicKeyInfo; import rdpclient.ntlmssp.asn1.TSRequest; import rdpclient.rdp.RdpConstants; import streamer.ByteBuffer; import streamer.Element; import streamer.Link; import streamer.OneTimeSwitch; import streamer.Pipeline; import streamer.PipelineImpl; import streamer.debug.Dumper; import streamer.debug.MockSink; import streamer.debug.MockSource; import streamer.ssl.SSLState; import common.asn1.Tag; /** * @see http://msdn.microsoft.com/en-us/library/cc236643.aspx */ public class ClientNtlmsspPubKeyAuth extends OneTimeSwitch implements NtlmConstants, Dumper { /** * Offset of first byte of allocated block after NTLMSSP header and block * descriptors. */ private static final int BLOCKS_OFFSET = 88; protected NtlmState ntlmState; protected SSLState sslState; protected String targetDomain; protected String user; protected String password; protected String workstation; protected String serverHostName; public ClientNtlmsspPubKeyAuth(String id, NtlmState ntlmState, SSLState sslState, String serverHostName, String targetDomain, String workstation, String user, String password) { super(id); this.ntlmState = ntlmState; this.sslState = sslState; this.serverHostName = serverHostName; this.targetDomain = targetDomain; this.workstation = workstation; this.user = user; this.password = password; } @Override protected void handleOneTimeData(ByteBuffer buf, Link link) { if (buf == null) return; throw new RuntimeException("Unexpected packet: " + buf + "."); } @Override protected void onStart() { super.onStart(); /* * @see * http://blogs.msdn.com/b/openspecification/archive/2010/04/20/ntlm-keys * -and-sundry-stuff.aspx */ ntlmState.domain = targetDomain; ntlmState.user = user; ntlmState.password = password; ntlmState.workstation = workstation; ntlmState.generateServicePrincipalName(serverHostName); ntlmState.ntlm_construct_authenticate_target_info(); ntlmState.ntlm_generate_timestamp(); ntlmState.ntlm_generate_client_challenge(); ntlmState.ntlm_compute_lm_v2_response(); ntlmState.ntlm_compute_ntlm_v2_response(); ntlmState.ntlm_generate_key_exchange_key(); ntlmState.ntlm_generate_random_session_key(); ntlmState.ntlm_generate_exported_session_key(); ntlmState.ntlm_encrypt_random_session_key(); ntlmState.ntlm_init_rc4_seal_states(); ByteBuffer authenticateMessage = generateAuthenticateMessage(ntlmState); ByteBuffer messageSignatureAndEncryptedServerPublicKey = generateMessageSignatureAndEncryptedServerPublicKey(ntlmState); // Length of packet ByteBuffer buf = new ByteBuffer(4096, true); TSRequest tsRequest = new TSRequest("TSRequest"); tsRequest.version.value = 2L; NegoItem negoItem = new NegoItem("NegoItem"); negoItem.negoToken.value = authenticateMessage; tsRequest.negoTokens.tags = new Tag[] {negoItem}; tsRequest.pubKeyAuth.value = messageSignatureAndEncryptedServerPublicKey; tsRequest.writeTag(buf); // Trim buffer to actual length of data written buf.trimAtCursor(); pushDataToOTOut(buf); switchOff(); } private byte[] getServerPublicKey() { // SSL certificate public key with algorithm ByteBuffer subjectPublicKeyInfo = new ByteBuffer(sslState.serverCertificateSubjectPublicKeyInfo); // Parse subjectPublicKeyInfo SubjectPublicKeyInfo parser = new SubjectPublicKeyInfo("SubjectPublicKeyInfo"); parser.readTag(subjectPublicKeyInfo); // Copy subjectPublicKey subfield to separate byte buffer ByteBuffer subjectPublicKey = new ByteBuffer(subjectPublicKeyInfo.length); parser.subjectPublicKey.writeTag(subjectPublicKey); subjectPublicKeyInfo.unref(); subjectPublicKey.trimAtCursor(); // Skip tag: // 03 82 01 0f (tag) 00 (padding byte) subjectPublicKey.trimHeader(5);// FIXME: parse it properly // * DEBUG */System.out.println("DEBUG: subjectPublicKey:\n" + // subjectPublicKey.dump()); ntlmState.subjectPublicKey = subjectPublicKey.toByteArray(); return ntlmState.subjectPublicKey; } /** * The client encrypts the public key it received from the server (contained * in the X.509 certificate) in the TLS handshake from step 1, by using the * confidentiality support of SPNEGO. * * The public key that is encrypted is the ASN.1-encoded SubjectPublicKey * sub-field of SubjectPublicKeyInfo from the X.509 certificate, as specified * in [RFC3280] section 4.1. The encrypted key is encapsulated in the * pubKeyAuth field of the TSRequest structure and is sent over the TLS * channel to the server. */ private ByteBuffer generateMessageSignatureAndEncryptedServerPublicKey(NtlmState ntlmState) { return new ByteBuffer(ntlmState.ntlm_EncryptMessage(getServerPublicKey())); } public static ByteBuffer generateAuthenticateMessage(NtlmState ntlmState) { // Allocate memory for blocks from given fixed offset int blocksCursor = BLOCKS_OFFSET; ByteBuffer buf = new ByteBuffer(4096); // Signature: "NTLMSSP\0" buf.writeString(NTLMSSP, RdpConstants.CHARSET_8); buf.writeByte(0); // NTLM Message Type: NTLMSSP_AUTH (0x00000003) buf.writeIntLE(NtlmConstants.NTLMSSP_AUTH); // Although the protocol allows authentication to succeed if the client // provides either LmChallengeResponse or NtChallengeResponse, Windows // implementations provide both. // LM V2 response blocksCursor = writeBlock(buf, ntlmState.lmChallengeResponse, blocksCursor); // NT v2 response blocksCursor = writeBlock(buf, ntlmState.ntChallengeResponse, blocksCursor); // DomainName blocksCursor = writeStringBlock(buf, ntlmState.domain, blocksCursor, RdpConstants.CHARSET_16); // UserName blocksCursor = writeStringBlock(buf, ntlmState.user, blocksCursor, RdpConstants.CHARSET_16); // Workstation blocksCursor = writeStringBlock(buf, ntlmState.workstation, blocksCursor, RdpConstants.CHARSET_16); // EncryptedRandomSessionKey, 16 bytes blocksCursor = writeBlock(buf, ntlmState.encryptedRandomSessionKey, blocksCursor); // NegotiateFlags (4 bytes): In connection-oriented mode, a NEGOTIATE // structure that contains the set of bit flags (section 2.2.2.5) negotiated // in the previous messages. buf.writeIntLE(/*ntlmState.negotiatedFlags.value*/0xe288b235); // FIXME: remove hardcoded value buf.writeBytes(generateVersion()); // If the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an // MsvAvTimestamp present, the client SHOULD provide a MIC(Message Integrity // Check) int savedCursorForMIC = buf.cursor; // Save cursor position to write MIC // later buf.writeBytes(new byte[16]); // Write 16 zeroes if (BLOCKS_OFFSET != buf.cursor) throw new RuntimeException("BUG: Actual offset of first byte of allocated blocks is not equal hardcoded offset. Hardcoded offset: " + BLOCKS_OFFSET + ", actual offset: " + buf.cursor + ". Update hardcoded offset to match actual offset."); buf.cursor = blocksCursor; buf.trimAtCursor(); ntlmState.authenticateMessage = buf.toByteArray(); // Calculate and write MIC to reserved position ntlmState.ntlm_compute_message_integrity_check(); buf.cursor = savedCursorForMIC; buf.writeBytes(ntlmState.messageIntegrityCheck); buf.rewindCursor(); return buf; } /** * Write string as security buffer, using given charset, without trailing '\0' * character. */ private static int writeStringBlock(ByteBuffer buf, String string, int blocksCursor, Charset charset) { return writeBlock(buf, string.getBytes(charset), blocksCursor); } /** * Write block to blocks buffer and block descriptor to main buffer. */ private static int writeBlock(ByteBuffer buf, byte[] block, int blocksCursor) { // Write block descriptor // Length buf.writeShortLE(block.length); // Allocated buf.writeShortLE(block.length); // Offset buf.writeIntLE(blocksCursor); // Write block to position pointed by blocksCursor instead of buf.cursor int savedCursor = buf.cursor; buf.cursor = blocksCursor; buf.writeBytes(block); blocksCursor = buf.cursor; buf.cursor = savedCursor; return blocksCursor; } /** * Version (8 bytes): A VERSION structure (section 2.2.2.10) that is present * only when the NTLMSSP_NEGOTIATE_VERSION flag is set in the NegotiateFlags * field. This structure is used for debugging purposes only. In normal * protocol messages, it is ignored and does not affect the NTLM message * processing. */ private static byte[] generateVersion() { // Version (6.1, Build 7601), NTLM current revision: 15 return new byte[] {0x06, 0x01, (byte)0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f}; } /** * Example. */ public static void main(String args[]) { System.setProperty("streamer.Element.debug", "true"); /* @formatter:off */ // // Client NEGOTIATE // byte[] clientNegotiatePacket = new byte[] { (byte)0x30, (byte)0x37, (byte)0xa0, (byte)0x03, (byte)0x02, (byte)0x01, (byte)0x02, (byte)0xa1, (byte)0x30, (byte)0x30, (byte)0x2e, (byte)0x30, (byte)0x2c, (byte)0xa0, (byte)0x2a, (byte)0x04, (byte)0x28, (byte)0x4e, (byte)0x54, (byte)0x4c, (byte)0x4d, (byte)0x53, (byte)0x53, (byte)0x50, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xb7, (byte)0x82, (byte)0x08, (byte)0xe2, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x06, (byte)0x01, (byte)0xb1, (byte)0x1d, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0f, }; // // Server CHALLENGE // byte[] serverChallengePacket = new byte[] { 0x30, (byte) 0x82, 0x01, 0x02, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 258 bytes (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes 0x02, 0x01, 0x03, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes, Version: 0x3 (byte) 0xa1, (byte) 0x81, (byte) 0xfa, // TAG: [1] (constructed) LEN: 250 bytes 0x30, (byte) 0x81, (byte) 0xf7, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 247 bytes 0x30, (byte) 0x81, (byte) 0xf4, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 244 bytes (byte) 0xa0, (byte) 0x81, (byte) 0xf1, // TAG: [0] (constructed) LEN: 241 bytes 0x04, (byte) 0x81, (byte) 0xee, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 238 bytes 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, // "NTLMSSP\0" 0x02, 0x00, 0x00, 0x00, // MessageType (CHALLENGE) 0x1e, 0x00, 0x1e, 0x00, 0x38, 0x00, 0x00, 0x00, // TargetName (length: 30, allocated space: 30, offset: 56) 0x35, (byte) 0x82, (byte) 0x8a, (byte) 0xe2, // NegotiateFlags: NEGOTIATE_56 NEGOTIATE_KEY_EXCH NEGOTIATE_128 NEGOTIATE_VERSION NEGOTIATE_TARGET_INFO NEGOTIATE_EXTENDED_SESSION_SECURITY TARGET_TYPE_SERVER NEGOTIATE_ALWAYS_SIGN NEGOTIATE_NTLM NEGOTIATE_SEAL NEGOTIATE_SIGN REQUEST_TARGET NEGOTIATE_UNICODE (byte)0xc1, (byte)0x4a, (byte)0xc8, (byte)0x98, (byte)0x2f, (byte)0xd1, (byte)0x93, (byte)0xd4, // ServerChallenge 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved (byte) 0x98, 0x00, (byte) 0x98, 0x00, 0x56, 0x00, 0x00, 0x00, // TargetInfo (length: 152, allocated space: 152, offset: 86) 0x06, 0x03, (byte) 0xd7, 0x24, 0x00, 0x00, 0x00, 0x0f, // Version (6.3, build 9431) , NTLM current revision: 15 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // Target name value: "WIN-LO419B2LSR0" // Target Info value: // Attribute list 0x02, 0x00, // Item Type: NetBIOS domain name (0x0002, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" 0x01, 0x00, // Item Type: NetBIOS computer name (0x0001, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" 0x04, 0x00, // Item Type: DNS domain name (0x0004, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" 0x03, 0x00, // Item Type: DNS computer name (0x0003, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0" 0x07, 0x00, // Item Type: Timestamp (0x0007, LE) 0x08, 0x00, // Item Length: 8 (LE) (byte)0x1d, (byte)0xea, (byte)0x6b, (byte)0x60, (byte)0xf8, (byte)0xc5, (byte)0xce, (byte)0x01, // Time: Oct 10, 2013 23:36:20.056937300 EEST // Attribute: End of list 0x00, 0x00, 0x00, 0x00, }; // // Client NTLMSSP_AUTH // byte[] clientAuthPacket = new byte[] { 0x30, (byte) 0x82, 0x03, 0x13, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 787 bytes // // TSRequest.version // (byte) 0xa0, 0x03, // TAG: [0] (constructed) LEN: 3 bytes 0x02, 0x01, 0x02, // TAG: [UNIVERSAL 2] (primitive) "INTEGER" LEN: 1 bytes // // TSRequest.negoData // (byte) 0xa1, (byte) 0x82, 0x01, (byte) 0xe4, // TAG: [1] (constructed) LEN: 484 bytes 0x30, (byte) 0x82, 0x01, (byte) 0xe0, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 480 bytes 0x30, (byte) 0x82, 0x01, (byte) 0xdc, // TAG: [UNIVERSAL 16] (constructed) "SEQUENCE" LEN: 476 bytes // // NegoItem.negoToken // (byte) 0xa0, (byte) 0x82, 0x01, (byte) 0xd8, // TAG: [0] (constructed) LEN: 472 bytes 0x04, (byte) 0x82, 0x01, (byte) 0xd4, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 468 bytes // NTLMSSP 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, // "NTLMSSP\0" 0x03, 0x00, 0x00, 0x00, // NTLM Message Type: NTLMSSP_AUTH (0x00000003) 0x18, 0x00, 0x18, 0x00, (byte) 0x92, 0x00, 0x00, 0x00, // LmChallengeResponse (length 24, allocated: 24, offset 146) 0x1a, 0x01, 0x1a, 0x01, (byte) 0xaa, 0x00, 0x00, 0x00, // NtChallengeResponse (length 282, allocated: 282, offset 170) 0x12, 0x00, 0x12, 0x00, 0x58, 0x00, 0x00, 0x00, // DomainName (length 18, allocated: 88, offset 88) 0x1a, 0x00, 0x1a, 0x00, 0x6a, 0x00, 0x00, 0x00, // UserName (length 26, allocated:26, offset 106) 0x0e, 0x00, 0x0e, 0x00, (byte) 0x84, 0x00, 0x00, 0x00, // Workstation (length 14, offset 132) 0x10, 0x00, 0x10, 0x00, (byte) 0xc4, 0x01, 0x00, 0x00, // EncryptedRandomSessionKey (length 16, offset 452) 0x35, (byte) 0xb2, (byte) 0x88, (byte) 0xe2, // NegotiateFlags 0x06, 0x01, (byte) 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f, // Version (6.1, Build 7601), NTLM current revision: 15 (byte)0x8c, (byte)0x69, (byte)0x53, (byte)0x1c, (byte)0xbb, (byte)0x6f, (byte)0xfb, (byte)0x9a, (byte)0x5d, (byte)0x2c, (byte)0x63, (byte)0xf2, (byte)0xc9, (byte)0x51, (byte)0xc5, (byte)0x11, // Message integrity check 0x77, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6b, 0x00, 0x67, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x70, 0x00, // Domain name value: "Workgroup" 0x41, 0x00, 0x64, 0x00, 0x6d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x69, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x61, 0x00, 0x74, 0x00, 0x6f, 0x00, 0x72, 0x00, // User name value: "Administrator" 0x61, 0x00, 0x70, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x33, 0x00, // Workstation host name value: "apollo3" // Lan manager challenge response value // Response: HMAC_MD(ResponseKeyLM, concatenate(ServerChallenge, ClientChallenge), where ResponseKeyLM=ntlmv2Hash(target, user, password) (byte)0x17, (byte)0x9b, (byte)0x7d, (byte)0x7b, (byte)0x2f, (byte)0x79, (byte)0x9f, (byte)0x19, (byte)0xa0, (byte)0x4b, (byte)0x00, (byte)0xed, (byte)0x2b, (byte)0x39, (byte)0xbb, (byte)0x23, // Client challenge (fixed for debugging) (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, // // NTLM challenge response value: // (byte)0x49, (byte)0xea, (byte)0x27, (byte)0x4f, (byte)0xcc, (byte)0x05, (byte)0x8b, (byte)0x79, (byte)0x20, (byte)0x0b, (byte)0x08, (byte)0x42, (byte)0xa9, (byte)0xc8, (byte)0x0e, (byte)0xc7, // HMAC 0x01, 0x01, 0x00, 0x00, // Header: 0x00000101 (LE) 0x00, 0x00, 0x00, 0x00, // Reserved: 0x00000000 (byte)0x1d, (byte)0xea, (byte)0x6b, (byte)0x60, (byte)0xf8, (byte)0xc5, (byte)0xce, (byte)0x01, // Time: Oct 10, 2013 23:36:20.056937300 EEST (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, // Client challenge (fixed) 0x00, 0x00, 0x00, 0x00, // Reserved // Target Info value: // Attribute list 0x02, 0x00, // Item Type: NetBIOS domain name (0x0002, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " 0x01, 0x00, // Item Type: NetBIOS computer name (0x0001, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " 0x04, 0x00, // Item Type: DNS domain name (0x0004, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " 0x03, 0x00, // Item Type: DNS computer name (0x0003, LE) 0x1e, 0x00, // Item Length: 30 (LE) 0x57, 0x00, 0x49, 0x00, 0x4e, 0x00, 0x2d, 0x00, 0x4c, 0x00, 0x4f, 0x00, 0x34, 0x00, 0x31, 0x00, 0x39, 0x00, 0x42, 0x00, 0x32, 0x00, 0x4c, 0x00, 0x53, 0x00, 0x52, 0x00, 0x30, 0x00, // "WIN-LO419B2LSR0 " 0x07, 0x00, // Item Type: Timestamp (0x0007, LE) 0x08, 0x00, // Item Length: 8 (LE) (byte)0x1d, (byte)0xea, (byte)0x6b, (byte)0x60, (byte)0xf8, (byte)0xc5, (byte)0xce, (byte)0x01, // Timestamp: Oct 10, 2013 23:36:20.056937300 EEST 0x06, 0x00, // Item Type: Flags (0x0006, LE) 0x04, 0x00, // Item Length: 4 (LE) 0x02, 0x00, 0x00, 0x00, // Flags: 0x00000002 0x0a, 0x00, // Item Type: Channel Bindings (0x000a, LE) 0x10, 0x00, // Item Length: 16 (LE) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Channel Bindings: 00000000000000000000000000000000 0x09, 0x00, // Item Type: Target Name (0x0009, LE) 0x2a, 0x00, // Item Length: 42 (LE) 0x54, 0x00, 0x45, 0x00, 0x52, 0x00, 0x4d, 0x00, 0x53, 0x00, 0x52, 0x00, 0x56, 0x00, 0x2f, 0x00, 0x31, 0x00, 0x39, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x31, 0x00, 0x36, 0x00, 0x38, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x2e, 0x00, 0x31, 0x00, 0x30, 0x00, 0x31, 0x00, // Target Name: "TERMSRV/192.168.0.101" (UTF-16) // Attribute: End of list 0x00, 0x00, // 0x00, 0x00, // // Attribute: End of list 0x00, 0x00, // 0x00, 0x00, // // Attribute: End of list 0x00, 0x00, // 0x00, 0x00, // // Attribute: End of list 0x00, 0x00, // 0x00, 0x00, // // Session Key // RC4 key (Server KeyExchangeKey or SessionBaseKey): // 6e bd e3 da 83 c2 fd f1 38 a2 78 be 8c e6 75 d6 // // RC4 data (Client nonce): // 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 // // RC4 encrypted: // 2c 24 da 10 17 cf 40 69 35 49 6f 58 e1 29 9e 79 (byte)0x2c, (byte)0x24, (byte)0xda, (byte)0x10, (byte)0x17, (byte)0xcf, (byte)0x40, (byte)0x69, (byte)0x35, (byte)0x49, (byte)0x6f, (byte)0x58, (byte)0xe1, (byte)0x29, (byte)0x9e, (byte)0x79, // // TSRequest.publicKey // (byte) 0xa3, (byte) 0x82, 0x01, 0x22, // TAG: [3] (constructed) LEN: 290 bytes 0x04, (byte) 0x82, 0x01, 0x1e, // TAG: [UNIVERSAL 4] (primitive) "OCTET STRING" LEN: 286 bytes // NTLMSSP_MESSAGE_SIGNATURE, @see http://msdn.microsoft.com/en-us/library/cc422952.aspx // Version: 0x00000001 (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, // Checksum (8 bytes): An 8-byte array that contains the checksum for the message. (byte)0x72, (byte)0x76, (byte)0x1e, (byte)0x57, (byte)0x49, (byte)0xb5, (byte)0x0f, (byte)0xad, // seqNum of the message: 0 (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // Encrypted public key (byte)0x15, (byte)0xf7, (byte)0xf2, (byte)0x54, (byte)0xda, (byte)0xa9, (byte)0xe5, (byte)0xad, (byte)0x85, (byte)0x04, (byte)0x67, (byte)0x4d, (byte)0x0b, (byte)0xcb, (byte)0xf9, (byte)0xb1, (byte)0xf8, (byte)0x02, (byte)0x8a, (byte)0x77, (byte)0xc2, (byte)0x63, (byte)0xab, (byte)0xd5, (byte)0x74, (byte)0x23, (byte)0x9f, (byte)0x9d, (byte)0x5d, (byte)0x1f, (byte)0xd3, (byte)0xb3, (byte)0xa0, (byte)0xac, (byte)0x16, (byte)0x8a, (byte)0x4b, (byte)0x08, (byte)0xf5, (byte)0x47, (byte)0x70, (byte)0x58, (byte)0x10, (byte)0xb4, (byte)0xe7, (byte)0x87, (byte)0xb3, (byte)0x4b, (byte)0xc9, (byte)0xa2, (byte)0xd5, (byte)0xd1, (byte)0xca, (byte)0x0f, (byte)0xd4, (byte)0xe3, (byte)0x8d, (byte)0x76, (byte)0x5a, (byte)0x60, (byte)0x28, (byte)0xf8, (byte)0x06, (byte)0x5d, (byte)0xe4, (byte)0x7e, (byte)0x21, (byte)0xc8, (byte)0xbb, (byte)0xac, (byte)0xe5, (byte)0x79, (byte)0x85, (byte)0x30, (byte)0x9b, (byte)0x88, (byte)0x13, (byte)0x2f, (byte)0x8f, (byte)0xfc, (byte)0x04, (byte)0x52, (byte)0xfe, (byte)0x87, (byte)0x94, (byte)0xcf, (byte)0xcb, (byte)0x49, (byte)0x4a, (byte)0xda, (byte)0x6f, (byte)0xdd, (byte)0xee, (byte)0x57, (byte)0xa5, (byte)0xe4, (byte)0x4d, (byte)0x0e, (byte)0x5c, (byte)0x3d, (byte)0x0b, (byte)0x63, (byte)0x1f, (byte)0xf6, (byte)0x3d, (byte)0x1b, (byte)0xae, (byte)0x5a, (byte)0xf6, (byte)0x42, (byte)0x2a, (byte)0x46, (byte)0xfa, (byte)0x42, (byte)0x71, (byte)0x67, (byte)0x46, (byte)0x02, (byte)0x71, (byte)0xea, (byte)0x51, (byte)0x98, (byte)0xf7, (byte)0xd4, (byte)0x43, (byte)0xbf, (byte)0x8e, (byte)0xe8, (byte)0x3c, (byte)0xc8, (byte)0xfa, (byte)0x79, (byte)0x9d, (byte)0x8c, (byte)0xfc, (byte)0xc2, (byte)0x42, (byte)0xc9, (byte)0xbb, (byte)0xd0, (byte)0xab, (byte)0x81, (byte)0xc4, (byte)0x53, (byte)0xfd, (byte)0x41, (byte)0xda, (byte)0xab, (byte)0x0f, (byte)0x25, (byte)0x79, (byte)0x5f, (byte)0xbd, (byte)0xa3, (byte)0x8c, (byte)0xd3, (byte)0xf5, (byte)0x1b, (byte)0xab, (byte)0x20, (byte)0xd1, (byte)0xf4, (byte)0xd8, (byte)0x81, (byte)0x9c, (byte)0x18, (byte)0x4a, (byte)0xa4, (byte)0x77, (byte)0xee, (byte)0xe1, (byte)0x51, (byte)0xee, (byte)0x2a, (byte)0xc1, (byte)0x94, (byte)0x37, (byte)0xc5, (byte)0x06, (byte)0x7a, (byte)0x3f, (byte)0x0f, (byte)0x25, (byte)0x5b, (byte)0x4e, (byte)0x6a, (byte)0xdc, (byte)0x0b, (byte)0x62, (byte)0x6f, (byte)0x12, (byte)0x83, (byte)0x03, (byte)0xae, (byte)0x4e, (byte)0xce, (byte)0x2b, (byte)0x6e, (byte)0xd4, (byte)0xd5, (byte)0x23, (byte)0x27, (byte)0xf6, (byte)0xa6, (byte)0x38, (byte)0x67, (byte)0xec, (byte)0x95, (byte)0x82, (byte)0xc6, (byte)0xba, (byte)0xd4, (byte)0xf6, (byte)0xe6, (byte)0x22, (byte)0x7d, (byte)0xb9, (byte)0xe4, (byte)0x81, (byte)0x97, (byte)0x24, (byte)0xff, (byte)0x40, (byte)0xb2, (byte)0x42, (byte)0x3c, (byte)0x11, (byte)0x24, (byte)0xd0, (byte)0x3a, (byte)0x96, (byte)0xd9, (byte)0xc1, (byte)0x13, (byte)0xd6, (byte)0x62, (byte)0x45, (byte)0x21, (byte)0x60, (byte)0x5b, (byte)0x7b, (byte)0x2b, (byte)0x62, (byte)0x44, (byte)0xf7, (byte)0x40, (byte)0x93, (byte)0x29, (byte)0x5b, (byte)0x44, (byte)0xb7, (byte)0xda, (byte)0x9c, (byte)0xa6, (byte)0xa9, (byte)0x3b, (byte)0xe1, (byte)0x3b, (byte)0x9d, (byte)0x31, (byte)0xf2, (byte)0x21, (byte)0x53, (byte)0x0f, (byte)0xb3, (byte)0x70, (byte)0x55, (byte)0x84, (byte)0x2c, (byte)0xb4, }; SSLState sslState = new SSLState(); sslState.serverCertificateSubjectPublicKeyInfo = new byte[] { 0x30, (byte) 0x82, 0x01, 0x22, // Sequence, length: 290 bytes 0x30, 0x0d, // Sequence, length: 13 bytes { 0x06, 0x09, // Object ID, length: 9 bytes 0x2a, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, // NULL, length: 0 bytes (byte)0x03, (byte)0x82, (byte)0x01, (byte)0x0f, // Bit string, length: 271 bytes (byte)0x00, // Pading (byte)0x30, (byte)0x82, (byte)0x01, (byte)0x0a, // Sequence (byte)0x02, (byte)0x82, (byte)0x01, (byte)0x01, // Integer, length: 257 bytes (byte)0x00, (byte)0xa8, (byte)0x56, (byte)0x65, (byte)0xd3, (byte)0xce, (byte)0x8a, (byte)0x54, (byte)0x4d, (byte)0x9d, (byte)0xb0, (byte)0x84, (byte)0x31, (byte)0x19, (byte)0x71, (byte)0x7f, (byte)0xdd, (byte)0x42, (byte)0xfb, (byte)0x2a, (byte)0x7a, (byte)0x72, (byte)0x13, (byte)0xa1, (byte)0xb9, (byte)0x72, (byte)0xbb, (byte)0xd3, (byte)0x08, (byte)0xad, (byte)0x7d, (byte)0x6c, (byte)0x15, (byte)0x65, (byte)0x03, (byte)0xd1, (byte)0xc4, (byte)0x54, (byte)0xc5, (byte)0x33, (byte)0x6b, (byte)0x7d, (byte)0x69, (byte)0x89, (byte)0x5e, (byte)0xfe, (byte)0xe0, (byte)0x01, (byte)0xc0, (byte)0x7e, (byte)0x9b, (byte)0xcb, (byte)0x5d, (byte)0x65, (byte)0x36, (byte)0xcd, (byte)0x77, (byte)0x5d, (byte)0xf3, (byte)0x7a, (byte)0x5b, (byte)0x29, (byte)0x44, (byte)0x72, (byte)0xd5, (byte)0x38, (byte)0xe2, (byte)0xcf, (byte)0xb1, (byte)0xc7, (byte)0x78, (byte)0x9b, (byte)0x58, (byte)0xb9, (byte)0x17, (byte)0x7c, (byte)0xb7, (byte)0xd6, (byte)0xc7, (byte)0xc7, (byte)0xbf, (byte)0x90, (byte)0x4e, (byte)0x7c, (byte)0x39, (byte)0x93, (byte)0xcb, (byte)0x2e, (byte)0xe0, (byte)0xc2, (byte)0x33, (byte)0x2d, (byte)0xa5, (byte)0x7e, (byte)0xe0, (byte)0x7b, (byte)0xb6, (byte)0xf9, (byte)0x91, (byte)0x32, (byte)0xb7, (byte)0xd4, (byte)0x85, (byte)0xb7, (byte)0x35, (byte)0x2d, (byte)0x2b, (byte)0x00, (byte)0x6d, (byte)0xf8, (byte)0xea, (byte)0x8c, (byte)0x97, (byte)0x5f, (byte)0x51, (byte)0x1d, (byte)0x68, (byte)0x04, (byte)0x3c, (byte)0x79, (byte)0x14, (byte)0x71, (byte)0xa7, (byte)0xc7, (byte)0xd7, (byte)0x70, (byte)0x7a, (byte)0xe0, (byte)0xba, (byte)0x12, (byte)0x69, (byte)0xc8, (byte)0xd3, (byte)0xd9, (byte)0x4e, (byte)0xab, (byte)0x51, (byte)0x47, (byte)0xa3, (byte)0xec, (byte)0x99, (byte)0xd4, (byte)0x88, (byte)0xca, (byte)0xda, (byte)0xc2, (byte)0x7f, (byte)0x79, (byte)0x4b, (byte)0x66, (byte)0xed, (byte)0x87, (byte)0xbe, (byte)0xc2, (byte)0x5f, (byte)0xea, (byte)0xcf, (byte)0xe1, (byte)0xb5, (byte)0xf0, (byte)0x3d, (byte)0x9b, (byte)0xf2, (byte)0x19, (byte)0xc3, (byte)0xe0, (byte)0xe1, (byte)0x7a, (byte)0x45, (byte)0x71, (byte)0x12, (byte)0x3d, (byte)0x72, (byte)0x1d, (byte)0x6f, (byte)0x2b, (byte)0x1c, (byte)0x46, (byte)0x68, (byte)0xc0, (byte)0x8f, (byte)0x4f, (byte)0xce, (byte)0x3a, (byte)0xc5, (byte)0xcd, (byte)0x22, (byte)0x65, (byte)0x2d, (byte)0x43, (byte)0xb0, (byte)0x5c, (byte)0xdd, (byte)0x89, (byte)0xae, (byte)0xbe, (byte)0x70, (byte)0x59, (byte)0x5e, (byte)0x0c, (byte)0xbd, (byte)0xf5, (byte)0x46, (byte)0x82, (byte)0x1e, (byte)0xe4, (byte)0x86, (byte)0x95, (byte)0x7b, (byte)0x60, (byte)0xae, (byte)0x45, (byte)0x50, (byte)0xc2, (byte)0x54, (byte)0x08, (byte)0x49, (byte)0x9a, (byte)0x9e, (byte)0xfb, (byte)0xb2, (byte)0xb6, (byte)0x78, (byte)0xe5, (byte)0x2f, (byte)0x9c, (byte)0x5a, (byte)0xd0, (byte)0x8a, (byte)0x03, (byte)0x77, (byte)0x68, (byte)0x30, (byte)0x93, (byte)0x78, (byte)0x6d, (byte)0x90, (byte)0x6d, (byte)0x50, (byte)0xfa, (byte)0xa7, (byte)0x65, (byte)0xfe, (byte)0x59, (byte)0x33, (byte)0x27, (byte)0x4e, (byte)0x4b, (byte)0xf8, (byte)0x38, (byte)0x44, (byte)0x3a, (byte)0x12, (byte)0xf4, (byte)0x07, (byte)0xa0, (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01, (byte)0x00, (byte)0x01, }; /* @formatter:on */ NtlmState ntlmState = new NtlmState(); MockSource source = new MockSource("source", ByteBuffer.convertByteArraysToByteBuffers(serverChallengePacket, new byte[] {1, 2, 3})); Element ntlmssp_negotiate = new ClientNtlmsspNegotiate("ntlmssp_negotiate", ntlmState); Element ntlmssp_challenge = new ServerNtlmsspChallenge("ntlmssp_challenge", ntlmState); Element ntlmssp_auth = new ClientNtlmsspPubKeyAuth("ntlmssp_auth", ntlmState, sslState, "192.168.0.101", "workgroup", "apollo3", "Administrator", "R2Preview!"); Element sink = new MockSink("sink", ByteBuffer.convertByteArraysToByteBuffers(clientNegotiatePacket, clientAuthPacket), (Dumper)ntlmssp_auth); Element mainSink = new MockSink("mainSink", ByteBuffer.convertByteArraysToByteBuffers(new byte[] {1, 2, 3})); Pipeline pipeline = new PipelineImpl("test"); pipeline.add(source, ntlmssp_negotiate, ntlmssp_challenge, ntlmssp_auth, sink, mainSink); pipeline.link("source", "ntlmssp_negotiate", "ntlmssp_challenge", "ntlmssp_auth", "mainSink"); pipeline.link("ntlmssp_negotiate >" + OTOUT, "ntlmssp_negotiate< sink"); pipeline.link("ntlmssp_challenge >" + OTOUT, "ntlmssp_challenge< sink"); pipeline.link("ntlmssp_auth >" + OTOUT, "ntlmssp_auth< sink"); pipeline.runMainLoop("source", STDOUT, false, false); } @Override public void dump(ByteBuffer buf) { buf.rewindCursor(); TSRequest request = new TSRequest("TSRequest"); request.readTag(buf); System.out.println("TSRequest version: " + request.version.value); System.out.println("TSRequest pubKey: " + request.pubKeyAuth.value.toPlainHexString()); ByteBuffer negoToken = ((NegoItem)request.negoTokens.tags[0]).negoToken.value; System.out.println("TSRequest negotoken: " + negoToken.toPlainHexString()); dumpNegoToken(negoToken); negoToken.unref(); } private void dumpNegoToken(ByteBuffer buf) { String signature = buf.readVariableString(RdpConstants.CHARSET_8); if (!signature.equals(NTLMSSP)) throw new RuntimeException("Unexpected NTLM message singature: \"" + signature + "\". Expected signature: \"" + NTLMSSP + "\". Data: " + buf + "."); // MessageType (CHALLENGE) int messageType = buf.readSignedIntLE(); if (messageType != NtlmConstants.NTLMSSP_AUTH) throw new RuntimeException("Unexpected NTLM message type: " + messageType + ". Expected type: CHALLENGE (" + NtlmConstants.CHALLENGE + "). Data: " + buf + "."); System.out.println("lmChallengeResponseFields: " + ServerNtlmsspChallenge.readBlockByDescription(buf).toPlainHexString()); ByteBuffer ntChallengeResponseBuf = ServerNtlmsspChallenge.readBlockByDescription(buf); System.out.println("NtChallengeResponse: " + ntChallengeResponseBuf.toPlainHexString()); System.out.println("DomainName: " + ServerNtlmsspChallenge.readStringByDescription(buf)); System.out.println("UserName: " + ServerNtlmsspChallenge.readStringByDescription(buf)); System.out.println("Workstation: " + ServerNtlmsspChallenge.readStringByDescription(buf)); System.out.println("EncryptedRandomSessionKey: " + ServerNtlmsspChallenge.readBlockByDescription(buf).toPlainHexString()); System.out.println("NegotiateFlags: " + new NegoFlags(buf.readSignedIntLE())); System.out.println("Version: " + buf.readBytes(8).toPlainHexString()); dumpNtChallengeResponse(ntChallengeResponseBuf); } private void dumpNtChallengeResponse(ByteBuffer buf) { System.out.println("HMAC: " + buf.readBytes(16).toPlainHexString()); System.out.format("Header: 0x%08x\n", buf.readUnsignedIntLE()); System.out.format("Reserved: 0x%08x\n", buf.readUnsignedIntLE()); System.out.println("Time: " + buf.readBytes(8).toPlainHexString()); System.out.println("Client challenge: " + buf.readBytes(8).toPlainHexString()); System.out.format("Reserved: 0x%08x\n", buf.readUnsignedIntLE()); // Parse attribute list while (buf.remainderLength() > 0) { int type = buf.readUnsignedShortLE(); int length = buf.readUnsignedShortLE(); if (type == MSV_AV_EOL) // End of list break; ByteBuffer data = buf.readBytes(length); switch (type) { case MSV_AV_NETBIOS_DOMAIN_NAME: System.out.println("AV Netbios Domain name: " + data.readString(length, RdpConstants.CHARSET_16)); break; case MSV_AV_NETBIOS_COMPUTER_NAME: System.out.println("AV Netbios Computer name: " + data.readString(length, RdpConstants.CHARSET_16)); break; case MSV_AV_DNS_DOMAIN_NAME: System.out.println("AV DNS Domain name: " + data.readString(length, RdpConstants.CHARSET_16)); break; case MSV_AV_DNS_COMPUTER_NAME: System.out.println("AV DNS Computer name: " + data.readString(length, RdpConstants.CHARSET_16)); break; case MSV_AV_CHANNEL_BINDINGS: System.out.println("AV Channel Bindings: " + data.readBytes(length).toPlainHexString()); break; case MSV_AV_TIMESTAMP: System.out.println("AV Timestamp: " + data.readBytes(length).toPlainHexString()); break; case MSV_AV_FLAGS: System.out.println("AV Flags: " + data.readBytes(length).toPlainHexString()); break; case MSV_AV_TARGET_NAME: System.out.println("AV Target Name: " + data.readString(length, RdpConstants.CHARSET_16)); break; default: System.out.println("Unknown NTLM target info attribute: " + type + ". Data: " + data + "."); } data.unref(); } } }
56.687225
320
0.613304
0807eb337b137888d2ad40d810864c1f2dc953e4
1,674
package org.prebid.server.util; import org.apache.commons.compress.utils.IOUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.stream.Collectors; /** * This class consists of {@code static} utility methods for operating application resources. */ public class ResourceUtil { private ResourceUtil() { } /** * Reads files from classpath. Throws {@link IllegalArgumentException} if file was not found. */ public static String readFromClasspath(String path) throws IOException { final InputStream resourceAsStream = ResourceUtil.class.getClassLoader().getResourceAsStream(path); if (resourceAsStream == null) { throw new IllegalArgumentException(String.format("Could not find file at path: %s", path)); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8))) { return reader.lines().collect(Collectors.joining("\n")); } } /** * Reads files from classpath as array of bytes. Throws {@link IllegalArgumentException} if file was not found. */ public static byte[] readByteArrayFromClassPath(String path) throws IOException { final InputStream resourceAsStream = ResourceUtil.class.getClassLoader().getResourceAsStream(path); if (resourceAsStream == null) { throw new IllegalArgumentException(String.format("Could not find file at path: %s", path)); } return IOUtils.toByteArray(resourceAsStream); } }
35.617021
115
0.706093
7fa32aa3cbb38b736ba50dc183e88ace43656771
985
/** * @(#)CRTFlags.java 1.4 03/01/23 * * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.tools.javac.v8.code; /** * The CharacterRangeTable flags indicating type of an entry. */ public interface CRTFlags { /** * CRTEntry flags. */ public static final int CRT_STATEMENT = 1; public static final int CRT_BLOCK = 2; public static final int CRT_ASSIGNMENT = 4; public static final int CRT_FLOW_CONTROLLER = 8; public static final int CRT_FLOW_TARGET = 16; public static final int CRT_INVOKE = 32; public static final int CRT_CREATE = 64; public static final int CRT_BRANCH_TRUE = 128; public static final int CRT_BRANCH_FALSE = 256; /** * The mask for valid flags */ public static final int CRT_VALID_FLAGS = CRT_STATEMENT | CRT_BLOCK | CRT_ASSIGNMENT | CRT_FLOW_CONTROLLER | CRT_FLOW_TARGET | CRT_INVOKE | CRT_CREATE | CRT_BRANCH_TRUE | CRT_BRANCH_FALSE; }
28.970588
68
0.739086
19defc5d70d8b7d17baf93973173d7fc538af6a9
3,453
package com.elementary.tasks.notes.editor.layers; import android.graphics.Canvas; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.ItemTouchHelper; /** * Copyright 2017 Nazar Suhovich * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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. */ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback { public static final float ALPHA_FULL = 1.0f; private final LayersRecyclerAdapter mAdapter; public SimpleItemTouchHelperCallback(LayersRecyclerAdapter adapter) { mAdapter = adapter; } @Override public boolean isLongPressDragEnabled() { return false; } @Override public boolean isItemViewSwipeEnabled() { return true; } @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (recyclerView.getLayoutManager() instanceof GridLayoutManager) { final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; final int swipeFlags = 0; return makeMovementFlags(dragFlags, swipeFlags); } else { final int dragFlags = ItemTouchHelper.START | ItemTouchHelper.END; final int swipeFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; return makeMovementFlags(dragFlags, swipeFlags); } } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) { if (source.getItemViewType() != target.getItemViewType()) { return false; } mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition()); return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) { mAdapter.onItemDismiss(viewHolder.getAdapterPosition()); } @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { final float alpha = ALPHA_FULL - Math.abs(dY) / (float) viewHolder.itemView.getWidth(); viewHolder.itemView.setAlpha(alpha); viewHolder.itemView.setTranslationY(dY); } else { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { super.onSelectedChanged(viewHolder, actionState); } @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); viewHolder.itemView.setAlpha(ALPHA_FULL); } }
37.129032
166
0.713293
4bbd238db2e4641746a0f449cf40b2cc9057bf07
413
package com.blade.ioc.annotation; import java.lang.annotation.*; /** * Bean annotations can be injected * * @author <a href="mailto:biezhi.me@gmail.com" target="_blank">biezhi</a> * @since 1.5 */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Bean { String value() default ""; @Deprecated boolean singleton() default true; }
19.666667
74
0.707022
fca682d1f9338953f8e4513de822c6a71544f3c1
2,740
/******************************************************************************* * * This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim> * for the latest version of iBioSim. * * Copyright (C) 2017 University of Utah * * This library is free software; you can redistribute it and/or modify it * under the terms of the Apache License. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online at <http://www.async.ece.utah.edu/ibiosim/License>. * *******************************************************************************/ package edu.utah.ece.async.ibiosim.gui.modelEditor.comp; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import edu.utah.ece.async.ibiosim.gui.modelEditor.schematic.ModelEditor; import edu.utah.ece.async.ibiosim.gui.modelEditor.schematic.Schematic; /** * grid actions * these come from the right-click menu * * @author Chris Myers * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a> * @version %I% */ public class GridAction extends AbstractAction { private static final long serialVersionUID = 1L; Schematic schematic; Grid grid; public GridAction(String name, Schematic schematic) { super(name); //we need the gcm to do deletion/addition of nodes through these actions this.schematic = schematic; this.grid = schematic.getGrid(); } @Override public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals("Clear Selected Location(s)")) { grid.eraseSelectedNodes(schematic.getGCM()); schematic.getGCM2SBML().getSpeciesPanel().refreshSpeciesPanel(schematic.getGCM()); schematic.getGCM2SBML().makeUndoPoint(); } else if (event.getActionCommand().equals("Add Module(s) to (Non-Occupied) Selected Location(s)")) { //bring up a panel so the component/gcm can be chosen to add to the selected locations boolean added = DropComponentPanel.dropSelectedComponents( schematic.getGCM2SBML(), schematic.getGCM()); if (added) { ModelEditor gcm2sbml = schematic.getGCM2SBML(); gcm2sbml.setDirty(true); gcm2sbml.refresh(); schematic.getGraph().buildGraph(); schematic.repaint(); schematic.getGCM2SBML().getSpeciesPanel().refreshSpeciesPanel(schematic.getGCM()); schematic.getGCM2SBML().makeUndoPoint(); return; } } else if (event.getActionCommand().equals("Select All Locations")) grid.selectAllNodes(); else if (event.getActionCommand().equals("De-select All Locations")) grid.deselectAllNodes(); schematic.getGraph().buildGraph(); schematic.repaint(); } }
31.860465
101
0.684307
90943ecdd5032d8d01df7dca2609006f9e0e7111
762
package leetcode; import java.util.Arrays; public class leetcode31 { class Solution { public void nextPermutation(int[] nums) { for (int i= nums.length-1;i>0;i--) { if (nums[i]>nums[i-1]){ Arrays.sort(nums,i,nums.length); for (int j=i;j< nums.length;j++){ if (nums[j]>nums[i-1]){ swap(nums,i-1,j); return; } } } } Arrays.sort(nums); return; } public void swap(int[] nums,int i,int j){ int temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } }
26.275862
53
0.380577
a65303832e9a52b5453ca7f5985c8f5da5f20bb8
7,033
/* * Copyright 2019 ukuz90 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ukuz.piccolo.config.properties; import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.Reader; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.commons.configuration2.PropertiesConfiguration.PropertiesReader; /** * @author ukuz90 */ public class ComplexPropertiesReader extends PropertiesReader { /** Constant for the supported comment characters.*/ static final String COMMENT_CHARS = "#!"; /** Constant for the default properties separator.*/ static final char DEFAULT_SEPARATOR = '='; final Stack<Character> bracketStack = new Stack(); /** Stores the name of the last read property.*/ private String propertyName; /** isComplex of the last read propery.*/ private boolean complex; /** The list of possible key/value separators */ private static final char[] SEPARATORS = new char[] {'=', ':'}; /** The regular expression to parse the key and the value of a property. */ private static final Pattern PROPERTY_PATTERN = Pattern .compile("(([\\S&&[^\\\\" + new String(SEPARATORS) + "]]|\\\\.)*)(\\s*(\\s+|[" + new String(SEPARATORS) + "])\\s*)?(.*)"); private static final String COMPLEX_VALUE_SEPARATOR = "\n"; // private static final Pattern COMPLEX_KEY_PATTERN = Pattern.compile(""); public ComplexPropertiesReader(Reader in) { super(in); } @Override public String readProperty() throws IOException { propertyName = null; complex = false; StringBuilder sb = new StringBuilder(); while (true) { mark(getLineNumber()); String line = readLine(); if (line == null) { //EOF return sb.length() > 0 ? sb.toString() : null; } if (isCommentLine(line)) { continue; } line = line.trim(); if (checkBracketLines(line)) { //parse array complex = true; sb.append(line).append(COMPLEX_VALUE_SEPARATOR); String currentPropertyName = fetchLeftBracketName(line); if (StringUtils.isNotEmpty(propertyName) && !currentPropertyName.equals(propertyName)) { reset(); break; } propertyName = currentPropertyName; } else if (!complex && checkCombineLines(line)) { line = line.substring(0, line.length() - 1); sb.append(line); } else if (!complex) { sb.append(line); break; } else { reset(); break; } } return sb.toString(); } @Override protected void parseProperty(String line) { if (!complex) { super.parseProperty(line); } else { String[] property = doParseComplexProperty(line); initPropertyName(property[0]); initPropertyValue(property[1]); initPropertySeparator(property[2]); } } String[] doParseComplexProperty(String line) { String[] result = new String[]{"", "", ""}; String[] lineArr = line.split(COMPLEX_VALUE_SEPARATOR); StringBuilder jsonValueString = new StringBuilder(); LinkedHashMap<Integer, Map<String, String>> tmpPropertyValue = new LinkedHashMap<>(); for (String singleLine : lineArr) { final Matcher matcher = PROPERTY_PATTERN.matcher(singleLine); if (matcher.matches()) { String pName = matcher.group(1).trim(); String pValue = matcher.group(5); result[2] = matcher.group(3); //TODO regex parse String subName = fetchRightBracketName(pName); int index = fetchMiddleBracketIndex(pName); if (StringUtils.isNotEmpty(subName) && index >= 0) { tmpPropertyValue.computeIfAbsent(index, (k) -> new HashMap<>()); tmpPropertyValue.get(index).put(subName, pValue); } } } jsonValueString.append("["); tmpPropertyValue.forEach((i, map) -> { jsonValueString.append(JSON.toJSON(map)); if (i != tmpPropertyValue.size() - 1) { jsonValueString.append(","); } }); jsonValueString.append("]"); result[0] = propertyName; result[1] = jsonValueString.toString(); return result; } static boolean isCommentLine(final String line) { final String s = line.trim(); // blank lines are also treated as comment lines return s.length() < 1 || COMMENT_CHARS.indexOf(s.charAt(0)) >= 0; } static boolean checkCombineLines(final String line) { return countTrailingBS(line) % 2 != 0; } boolean checkBracketLines(final String line) { bracketStack.clear(); final String s = line.trim(); for (int idx = 0; idx < s.length() && line.charAt(idx) != DEFAULT_SEPARATOR; idx++) { if (line.charAt(idx) == ']' && bracketStack.peek().equals('[')) { bracketStack.push(line.charAt(idx)); } if (line.charAt(idx) == '[' && bracketStack.isEmpty()) { bracketStack.push(line.charAt(idx)); } } return bracketStack.size() > 0 && bracketStack.size() % 2 == 0; } String fetchLeftBracketName(final String line) { final String s = line.trim(); return s.substring(0, s.indexOf('[')); } String fetchRightBracketName(final String line) { final String s = line.trim(); int idx = s.indexOf("]."); return idx > 0 ? s.substring(idx + 2) : ""; } int fetchMiddleBracketIndex(final String line) { final String s = line.trim(); int lIdx = s.indexOf("["); int rIdx = s.indexOf("]"); return Integer.parseInt(s.substring(lIdx + 1, rIdx)); } private static int countTrailingBS(final String line) { int bsCount = 0; for (int idx = line.length() - 1; idx >= 0 && line.charAt(idx) == '\\'; idx--){ bsCount++; } return bsCount; } }
33.975845
104
0.573155
8cfa3482c2a3dac70afd10456758102fc39f65f7
507
package cn.rui97.ruigou.service.impl; import cn.rui97.ruigou.domain.CommodityExt; import cn.rui97.ruigou.mapper.CommodityExtMapper; import cn.rui97.ruigou.service.ICommodityExtService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 商品扩展 服务实现类 * </p> * * @author lurui * @since 2019-01-18 */ @Service public class CommodityExtServiceImpl extends ServiceImpl<CommodityExtMapper, CommodityExt> implements ICommodityExtService { }
24.142857
124
0.792899
f7ac78c55fe2d6c6af8f6febb278e201bf0d3a39
1,384
package com.pubmedknowledgegraph.worker.pubmedknowledgegraph_worker.model.compositekeys; import com.pubmedknowledgegraph.worker.pubmedknowledgegraph_worker.model.db.Article; import javax.persistence.Embeddable; import javax.persistence.ManyToOne; import java.io.Serializable; @Embeddable public class ArticleHistoryKey implements Serializable { private String status; private String date; @ManyToOne private Article article; public ArticleHistoryKey() { } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArticleHistoryKey that = (ArticleHistoryKey) o; if (!status.equals(that.status)) return false; return date.equals(that.date); } @Override public int hashCode() { int result = status.hashCode(); result = 31 * result + date.hashCode(); return result; } }
21.968254
88
0.649566
2ecb1e98de1757e3c6e3eacdc86f37202bba4a93
211
package com.lanking.uxb.service.sys.api; import java.util.List; import com.lanking.cloud.domain.yoo.common.Banner; public interface BannerService { List<Banner> listEnable(BannerQuery query); }
17.583333
51
0.744076
d70534e29f69fa8779aa90bfca36a88ac5d9dbaf
11,338
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Fensterbank.ultiMinePlugin.Objects; import org.bukkit.Server; import org.bukkit.plugin.Plugin; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import Fensterbank.ultiMinePlugin.ultiMinePlugin; import Fensterbank.ultiMinePlugin.HelpClasses.Convert; import Fensterbank.ultiMinePlugin.HelpClasses.Methoden; import Fensterbank.ultiMinePlugin.Manager.PlayerManager; import Fensterbank.ultiMinePlugin.Objects.ultiMinePlayer; import Fensterbank.ultiMinePlugin.HelpClasses.sendDelayedMessageTask; import java.util.logging.Logger; import java.util.ArrayList; import java.util.Random; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; // Imports für PermissionsEx import ru.tehkode.permissions.PermissionManager; import ru.tehkode.permissions.PermissionUser; /** * * @author vncuser */ public class UltiBot { private static final Logger log = Logger.getLogger("Minecraft"); private Server currServer; private ultiMinePlugin currPlugin; private PlayerManager currPlayerManager; private Random rnd; private UltiBotMemory memory; private PermissionManager permissionManager; private ArrayList<String> warningLevel4; private ArrayList<String> warningLevel3; private ArrayList<String> warningLevel2; private ArrayList<String> warningLevel1; public UltiBot(Server server, Plugin plugin, PlayerManager playerManager, PermissionManager permissionManager) { this.currServer = server; this.currPlugin = (ultiMinePlugin) plugin; this.currPlayerManager = playerManager; this.permissionManager = permissionManager; this.rnd = new Random(); this.memory = this.loadStoredMemory(); if (this.memory == null) { this.memory = new UltiBotMemory(); } warningLevel4 = new ArrayList<String>(); warningLevel3 = new ArrayList<String>(); warningLevel2 = new ArrayList<String>(); warningLevel1 = new ArrayList<String>(); if (this.permissionManager!=null) { log.info("[ultiMinePlugin] Lade Mitglieder, die Speicherplatzwarnungen erhalten..."); this.InitializeWarningReceiver(); log.info("[ultiMinePlugin] Fertig. Warnstufe 1 (" + warningLevel1.size() + "), Wanrstufe 2 (" + warningLevel2.size() + "), Warnstufe 3 (" + warningLevel3.size() + "), Warnstufe 4 (" + warningLevel4.size() + ")"); } else { log.warning("[ultiMinePlugin] ultiBot kann nicht auf ein modernes Permissionsystem zugreifen. Wurde das Permissionsystem geändert oder deaktiviert?"); log.warning("[ultiMinePlugin] Speicherplatzwarnungen von ultiBot sind daher deaktiviert!"); } log.info("[ultiMinePlugin] ultiBot initialisiert."); } private void InitializeWarningReceiver() { for (PermissionUser user : permissionManager.getUsers()) { if (user.has("ultimineplugin.ultibot.warning.level4")) { warningLevel4.add(user.getName()); } if (user.has("ultimineplugin.ultibot.warning.level3")) { warningLevel3.add(user.getName()); } if (user.has("ultimineplugin.ultibot.warning.level2")) { warningLevel2.add(user.getName()); } if (user.has("ultimineplugin.ultibot.warning.level1")) { warningLevel1.add(user.getName()); } } } public void sendMessage(String message, int delaySeconds) { long delay = Convert.toServerticks(delaySeconds); this.currServer.getScheduler().scheduleSyncDelayedTask(currPlugin, new sendDelayedMessageTask(currServer, ChatColor.WHITE + "<" + ChatColor.DARK_GREEN + "[B] ultiBot" + ChatColor.WHITE + "> " + message), delay); } public void sendMessage(String message) { sendMessage(message, 1); } public void sendPM(Player target, String message, int delaySeconds) { long delay = Convert.toServerticks(delaySeconds); this.currServer.getScheduler().scheduleSyncDelayedTask(currPlugin, new sendDelayedMessageTask(currServer, ChatColor.GRAY + "[" + ChatColor.DARK_GREEN + "[B] ultiBot" + ChatColor.GRAY + " -> mir] " + ChatColor.WHITE + message, target), delay); } public void sendPM(Player target, String message) { sendPM(target, message, 1); } public void welcomePlayer(String playerName) { ultiMinePlayer player = this.currPlayerManager.getPlayerFromCache(playerName); if (player != null) { if (player.getLastSeen() == null) { log.info("[ultiMinePlugin] Spieler ist dem ultiMinePlugin noch unbekannt, ultiBot begruesst ihn."); this.sendMessage(getRandomWelcomeSentence(playerName), 4); } else { if (!Methoden.isToday(player.getLastSeen())) { log.info("[ultiMinePlugin] Spieler war heute noch nicht online, ultiBot begruesst ihn."); this.sendMessage(getRandomWelcomeSentence(playerName), 4); } else { log.info("[ultiMinePlugin] Spieler war heute bereits online."); } } } else { log.info("[ultiMinePlugin] Spieler nicht gefunden."); } } private String getRandomWelcomeSentence(String var) { switch (rnd.nextInt(10)) { case 0: return "Hi"; case 1: return "Hallo " + var; case 2: return "Hi " + var; case 3: return "Moin!"; case 4: return "Tach " + var; case 5: return "Heyho " + var; case 6: return "Hey " + var + "!"; case 7: return "Moin Moin"; case 8: return "Servus " + var + "!"; case 9: return "Tach auch!"; default: return "Hi"; } } public void storeMemory() { try { FileOutputStream f_out = new FileOutputStream("plugins/ultiMinePlugin/data/ultiBotMemory.dat"); ObjectOutputStream obj_out = new ObjectOutputStream(f_out); obj_out.writeObject(this.memory); obj_out.close(); } catch (Exception ex) { ex.printStackTrace(); } } private UltiBotMemory loadStoredMemory() { ObjectInputStream ois = null; FileInputStream fis = null; try { fis = new FileInputStream("plugins/ultiMinePlugin/data/ultiBotMemory.dat"); ois = new ObjectInputStream(fis); Object obj = ois.readObject(); if (obj instanceof UltiBotMemory) { return (UltiBotMemory) obj; } } catch (IOException e) { } catch (ClassNotFoundException e) { } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { } } if (fis != null) { try { fis.close(); } catch (IOException e) { } } } return null; } public final void checkWarningForDiskSpace(final int freeSpace) { if (currPlugin.getWbbManager().isActive()) { ArrayList<String> recipients = new ArrayList<String>(); String subject; String message; if (freeSpace <= 6) { if (this.memory.getDiskSpaceWarningLevel() < 4) { this.memory.setDiskSpaceWarningLevel(4); this.storeMemory(); recipients.addAll(this.warningLevel4); subject = "Speicherplatz-Warnung, ALARMSTUFE 4"; message = "Hallo Leute<br /><br />meine Nachricht musste hiermit aufgrund der dringenden Sachlage eskaliert werden.<br />" + "Der verfügbare Speicherplatz beträgt derzeit nur noch " + freeSpace + " GB.<br /><br />" + "Wenn niemand etwas tut, wird der Server schon in <b>wenigen Stunden</b> nicht mehr erreichbar sein.<br>" + "Bitte kontaktiert die entsprechenden Personen, da diese ja wohl nicht auf meine Warnungen reagieren, es ist äußerst dringend!<br /><br />Viele Grüße,<br />ultiBot"; currPlugin.getWbbManager().sendPM("ultiBot", recipients, subject, message); } } else if (freeSpace <= 20) { if (this.memory.getDiskSpaceWarningLevel() < 3) { this.memory.setDiskSpaceWarningLevel(3); this.storeMemory(); recipients.addAll(this.warningLevel3); subject = "Speicherplatz-Warnung, Stufe 3"; message = "Hallo Leute<br /><br />der verfügbare Speicherplatz beträgt derzeit nur noch " + freeSpace + " GB.<br /><br />Ich empfehle <b>dringenst</b>, wieder etwas Speicherplatz freizugeben!!<br />" + "Bitte kontaktiert die entsprechenden Personen, da diese ja wohl nicht auf meine Warnungen reagieren.<br /><br />Viele Grüße,<br />ultiBot"; currPlugin.getWbbManager().sendPM("ultiBot", recipients, subject, message); } } else if (freeSpace <= 40) { if (this.memory.getDiskSpaceWarningLevel() < 2) { this.memory.setDiskSpaceWarningLevel(2); this.storeMemory(); recipients.addAll(this.warningLevel2); subject = "Speicherplatz-Warnung, Stufe 2"; message = "Hallo <br /><br />der verfügbare Speicherplatz beträgt derzeit nur noch " + freeSpace + " GB.<br /><br />Ich empfehle erneut, wieder etwas Speicherplatz freizugeben.<br /><br />Viele Grüße,<br />ultiBot"; currPlugin.getWbbManager().sendPM("ultiBot", recipients, subject, message); } } else if (freeSpace <= 60) { if (this.memory.getDiskSpaceWarningLevel() < 1) { this.memory.setDiskSpaceWarningLevel(1); this.storeMemory(); recipients.addAll(this.warningLevel1); subject = "Speicherplatz-Warnung, Stufe 1"; message = "Hallo <br /><br />der verfügbare Speicherplatz beträgt derzeit nur noch " + freeSpace + " GB.<br /><br />Ich empfehle hiermit, wieder etwas Speicherplatz freizugeben.<br /><br />Viele Grüße,<br />ultiBot"; currPlugin.getWbbManager().sendPM("ultiBot", recipients, subject, message); } } else { if (this.memory.getDiskSpaceWarningLevel() != 0) { this.memory.setDiskSpaceWarningLevel(0); this.storeMemory(); } } } } }
42.148699
250
0.587141
e56d502300ceffcd8b64dfcd8253ab771c38a7bf
109
package ch05; public class Car { public static void main(String[] args) { System.out.println("Car"); } }
15.571429
41
0.678899
018e10f2a7d49ff74337c75b88007895b871bfdf
1,912
/* * Copyright 2018-present, Nike, Inc. * All rights reserved. * * This source code is licensed under the Apache-2.0 license found in * the LICENSE file in the root directory of this source tree. * */ package com.nike.epc.model.gid; import static com.nike.epc.util.Validation.notNullOrEmpty; /** * From the standard: The General Identifier EPC scheme is independent of any specifications or * identity scheme outsdie the EPCglobal Tag Data Standard. * * <p>The generalManagerNumber dentifies an organisational entity responsible for maintaining the * numbers in the other fields as unique. */ public class Gid { private final String generalManagerNumber, objectClass, serialNumber; private Gid(String generalManagerNumber, String objectClass, String serialNumber) { this.generalManagerNumber = generalManagerNumber; this.objectClass = objectClass; this.serialNumber = serialNumber; } public String generalManagerNumber() { return generalManagerNumber; } public String objectClass() { return objectClass; } public String serialNumber() { return serialNumber; } public static final class Builder { private String generalManagerNumber, objectClass, serialNumber; private Builder() {} public Builder withGeneralManagerNumber(String generalManagerNumber) { this.generalManagerNumber = generalManagerNumber; return this; } public Builder withObjectClass(String objectClass) { this.objectClass = objectClass; return this; } public Builder withSerialNumber(String serialNumber) { this.serialNumber = serialNumber; return this; } public Gid build() { return new Gid( notNullOrEmpty(generalManagerNumber), notNullOrEmpty(objectClass), notNullOrEmpty(serialNumber)); } } public static Builder builder() { return new Builder(); } }
26.191781
97
0.721757
f3e85bfde9236c206ba87a59c5a04012b38bba42
3,771
/*- * #%L * BigDataViewer-Playground * %% * Copyright (C) 2019 - 2021 Nicolas Chiaruttini, EPFL - Robert Haase, MPI CBG - Christian Tischer, EMBL * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package sc.fiji.bdvpg.io; import bdv.util.BdvHandle; import bdv.viewer.SourceAndConverter; import net.imagej.ImageJ; import org.junit.After; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.scijava.Context; import sc.fiji.bdvpg.TestHelper; import sc.fiji.bdvpg.scijava.services.SourceAndConverterBdvDisplayService; import sc.fiji.bdvpg.scijava.services.SourceAndConverterService; import sc.fiji.bdvpg.services.SourceAndConverterServices; import sc.fiji.bdvpg.spimdata.importer.SpimDataFromXmlImporter; import java.time.Duration; import java.time.Instant; /** * Test of opening multiple datasets * * The limiting performance factor is the construction of the tree UI which scales * very badly. For now, its speed it user-ok for a number of sources below ~600 * * 300 datasets ~ 3 secs * * 3000 sources takes ~ 120 secs * * TODO : fix performance issue if several thousands of sources are necessary (could be coming sooner than expected) * */ public class PerfOpenMultipleSpimDataTest { static ImageJ ij; public static void main( String[] args ) { // Create the ImageJ application context with all available services; necessary for SourceAndConverterServices creation ij = new ImageJ(); ij.ui().showUI(); // Gets an active BdvHandle instance // SourceAndConverterServices.getSourceAndConverterDisplayService().getActiveBdv(); tic(); for (int i=0;i<100;i++) { // Import SpimData new SpimDataFromXmlImporter( "src/test/resources/mri-stack.xml" ).run(); new SpimDataFromXmlImporter("src/test/resources/mri-stack-shiftedX.xml").run(); new SpimDataFromXmlImporter( "src/test/resources/mri-stack-shiftedY.xml" ).run(); System.out.println(i); } toc(); } static Instant start; public static void tic() { start = Instant.now(); } static long timeElapsedInS; public static void toc() { Instant finish = Instant.now(); timeElapsedInS = Duration.between(start, finish).toMillis()/1000; System.out.println("It took "+timeElapsedInS+" s to open 300 datasets"); } @Test // Takes too much memory when all tests run at the same time public void demoRunOk() { main(new String[]{""}); Assert.assertTrue(timeElapsedInS<10); } @After public void closeFiji() { TestHelper.closeFijiAndBdvs(ij); } }
33.371681
121
0.750729
4ade33b243221dbeb80ac9ef1e2859adbecd8aa2
3,453
package com.vmware.spring.workshop.services.facade.impl; import java.util.Collection; import javax.inject.Inject; import org.apache.commons.collections.CollectionUtils; import org.junit.Assert; import org.junit.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import com.vmware.spring.workshop.dto.user.UserDTO; import com.vmware.spring.workshop.dto.user.UserRoleTypeDTO; import com.vmware.spring.workshop.services.AbstractServicesTestSupport; import com.vmware.spring.workshop.services.facade.AbstractFacadeTestSupport; import com.vmware.spring.workshop.services.facade.FacadeValueFinder; import com.vmware.spring.workshop.services.facade.UsersFacade; /** * @author lgoldstein */ @ContextConfiguration(locations={ AbstractServicesTestSupport.DEFAULT_TEST_CONTEXT }) @ActiveProfiles("hibernate") public class UsersFacadeImplTest extends AbstractFacadeTestSupport { @Inject private UsersFacade _usrFacade; public UsersFacadeImplTest() { super(); } @Test public void testFindByLoginName () { runFacadeValueFinderTest(new FacadeValueFinder<UsersFacade,UserDTO>() { @Override public UserDTO findDtoValue(UsersFacade facade, UserDTO dto) { return facade.findByLoginName(dto.getLoginName()); } }); } @Test public void testFindById () { runFacadeValueFinderTest(new FacadeValueFinder<UsersFacade,UserDTO>() { @Override public UserDTO findDtoValue(UsersFacade facade, UserDTO dto) { return facade.findById(dto.getId()); } }); } @Test public void testInternalUserAuthentication () { final Collection<? extends UserDTO> dtoList=_usrFacade.findAll(); Assert.assertFalse("No current users", CollectionUtils.isEmpty(dtoList)); for (final UserDTO dto : dtoList) { final Authentication authData=new UsernamePasswordAuthenticationToken(dto.getLoginName(), dto.getPassword()), authResult=_usrFacade.authenticate(authData); Assert.assertNotNull("No authentication result for " + dto, authResult); final Object principal=authResult.getPrincipal(); Assert.assertTrue("Principal not UserDTO for " + dto, principal instanceof UserDTO); Assert.assertEquals("Mismatched principal values", dto, principal); final Collection<? extends GrantedAuthority> gaList=authResult.getAuthorities(); Assert.assertFalse("No authorities for " + dto, CollectionUtils.isEmpty(gaList)); Assert.assertEquals("Mismatched size of authorities for " + dto, 1, gaList.size()); final GrantedAuthority ga=gaList.iterator().next(); final UserRoleTypeDTO role=dto.getRole(); Assert.assertEquals("Mismatched granted authority for " + dto, role.name(), ga.getAuthority()); } } private void runFacadeValueFinderTest (final FacadeValueFinder<UsersFacade,UserDTO> finder) { runFacadeValueFinderTest(_usrFacade, _usrFacade.findAll(), finder); } }
41.60241
124
0.706053
bca89b2146659cfa42acb9ae2c9b70ab64190c8f
3,803
/* * Copyright 2021 Whilein * * 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 te4j.filter.impl; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.NonNull; import org.jetbrains.annotations.NotNull; import te4j.filter.Filter; import te4j.util.TypeUtils; import java.lang.reflect.Type; /** * @author whilein */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class Sum implements Filter { public static @NonNull Filter create() { return new Sum(); } @Override public @NotNull String getName() { return "sum"; } @Override public Type getWrappedType(@NonNull Type type) { Type component = TypeUtils.getComponentType(type); if (component instanceof Class<?>) { boolean isArray = type instanceof Class<?> && ((Class<?>) type).isArray(); Class<?> componentClass = (Class<?>) component; if (!componentClass.isArray()) { if (componentClass == byte.class || componentClass == short.class || componentClass == int.class || componentClass == boolean.class || (componentClass == Boolean.class && isArray)) { return int.class; } return double.class; } } return null; } public static int process(byte[] value) { int res = 0; for (byte i : value) { res += i; } return res; } public static int process(short[] value) { int res = 0; for (short i : value) { res += i; } return res; } public static int process(int[] value) { int res = 0; for (int i : value) { res += i; } return res; } public static int process(Boolean[] value) { int res = 0; for (boolean i : value) { res += i ? 1 : 0; } return res; } public static int process(boolean[] value) { int res = 0; for (boolean i : value) { res += i ? 1 : 0; } return res; } public static long process(long[] value) { long res = 0; for (long i : value) { res += i; } return res; } public static double process(float[] value) { double res = 0; for (float i : value) { res += i; } return res; } public static double process(double[] value) { double res = 0; for (double i : value) { res += i; } return res; } public static double process(Iterable<?> value) { double res = 0; for (Object object : value) { res += object instanceof Number ? ((Number) object).doubleValue() : object == Boolean.TRUE ? 1 : 0; } return res; } public static double process(Object[] value) { double res = 0; for (Object object : value) { res += object instanceof Number ? ((Number) object).doubleValue() : object == Boolean.TRUE ? 1 : 0; } return res; } }
22.502959
111
0.534841
6443f9dde7276f4fa96622aab83ccbd50913d759
497
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.search.models; import com.azure.core.annotation.Fluent; /** * Describes an API key for a given Azure Cognitive Search service that has permissions * for query operations only. */ @Fluent public interface QueryKey { /** * @return the name of the query API key */ String name(); /** * @return the key value */ String key(); }
20.708333
87
0.676056
a8c535b6ff95a7906c84fee2bc55d5b8ee9434c8
3,468
package pl.kania.warehousemanager.services.security.jwt; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import pl.kania.warehousemanager.model.db.ClientDetails; import pl.kania.warehousemanager.model.db.User; import java.time.LocalDate; import java.util.Date; import java.util.List; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; class TokenCreatorTest { @ParameterizedTest @MethodSource(value = "pl.kania.warehousemanager.services.security.jwt.TestTokenFactory#getTestDataRequiredToCreateToken") void createNewTokenThenCheckIfAllValuesAreValidAndClaimsArePresent(User user, ClientDetails client, String issuer, String audience) { String token = TokenCreator.createJWT(user, client, issuer, audience); DecodedJWT decodedToken = JWT.decode(token); assertAll( () -> assertEquals(decodedToken.getSubject(), user.getId().toString(), "Different subject"), () -> assertEquals(decodedToken.getIssuer(), issuer, "Different issuer"), () -> { List<String> audienceFromToken = decodedToken.getAudience(); assertTrue(audienceFromToken.contains(audience), "Lack of audience: " + audience); assertTrue(audienceFromToken.contains(client.getClientId()), "Lack of audience: " + client.getClientId()); }, () -> { Claim login = decodedToken.getClaim("login"); assertNotNull(login, "Lack of login claim"); assertEquals(login.asString(), user.getLogin(), "Different login claim"); }, () -> { Claim role = decodedToken.getClaim("role"); assertNotNull(role, "Lack of role claim"); assertEquals(role.asString(), user.getRole().name(), "Different role"); }, () -> { Claim clientId = decodedToken.getClaim("clientId"); assertNotNull(clientId, "Lack of clientId claim"); assertEquals(clientId.asString(), client.getClientId(), "Different clientId"); }, () -> assertEquals(decodedToken.getAlgorithm(), Algorithm.HMAC256("").getName()), () -> { LocalDate now = LocalDate.now(); LocalDate nowPlus6days = now.plusDays(6); LocalDate nowPlus8days = now.plusDays(8); Date expiresAtDate = decodedToken.getExpiresAt(); assertNotNull(expiresAtDate, "Lack of expiresAt date"); LocalDate expiresAt = new java.sql.Date(expiresAtDate.getTime()).toLocalDate(); assertFalse(nowPlus6days.isAfter(expiresAt), "Token expires too soon - after 6 days should be still valid"); assertTrue(nowPlus8days.isAfter(expiresAt), "Token expires too late - after 8 days should be expired"); } ); } }
51
137
0.634948
8fe910fe0dce3716296a3385ef6c5c9315257646
38,180
package com.example.tyl.timer.util; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.LinkedList; /**数据库工具 * Created by TYL on 2017/6/11. * */ public class MyDatabaseHelper extends SQLiteOpenHelper { //info 状态 static final int NOTHING = -1; static final int PLAN= 0; static final int WORKING = 1; static final int FINISHED = 2; static final int UNFINISHED = 3; static final int WARING = 6; // day 状态 static final int PAST = 0; static final int NOW = 1; static final int FUTURE = 2; public static MyDatabaseHelper sMyDatabaseHelper = new MyDatabaseHelper(MyApplication.getContex(), "Timer.db", null, 1); public static SQLiteDatabase mSQLiteDatabase = sMyDatabaseHelper.getWritableDatabase(); //创建每天的数据数据 库表 infromain信息 TABLE_INFO information; TABLE_DAY days public static final String CREATE_TABLE1= "create table if not exists TABLE_INFO (" +"id integer primary key autoincrement," +"dayID integer," + "year integer," + "month integer," + "day integer," + "hour integer," + "minute integer," +"lastTime integer," + "completed integer,"//完成状态 0:还为到指定时间;1:正在进行中;2:已完成;3:未完成 + "information text )"; //创建天单位数据库表 day信息 public static final String CREATE_TABLE2= "create table if not exists TABLE_DAY (" +"id integer primary key autoincrement," + "year integer," + "month integer," + "day integer," + "allThing integer," + "done integer," + "losed integer," + "theRest integer," + "status integer )"; //status 0:昨日 1:今日 2:明日 //创建触发器 //对information表进行插入操作室,day表会更新 public static final String CREATE_TRIGGER1 = "CREATE TRIGGER if not exists INFO_INSERT " + "AFTER INSERT ON TABLE_INFO " + "FOR EACH ROW " + "BEGIN " + "UPDATE TABLE_DAY SET allThing=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID)," + "done=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID AND completed=2)," + "losed=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID AND completed=3),"+ "theRest=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID AND completed=0) "+ " WHERE TABLE_DAY.id=new.dayID ;" + "END;"; // public static final String CREATE_TRIGGER2 = "CREATE TRIGGER if not exists INFO_UPDATE " + "AFTER UPDATE ON TABLE_INFO " +"FOR EACH ROW " +"BEGIN " + "UPDATE TABLE_DAY SET allThing=(select count(*)from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID), " + " done=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID AND completed=2), " + " losed=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID AND completed=3), " + " theRest=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=new.dayID AND completed=0) " + " WHERE TABLE_DAY.id=new.dayID; " +"END;"; public static final String CREATE_TRIGGER3= "CREATE TRIGGER if not exists INFO_DELETE " + "AFTER DELETE ON TABLE_INFO " +"FOR EACH ROW " +"BEGIN " + "UPDATE TABLE_DAY SET allThing=(select count(*)from TABLE_INFO WHERE TABLE_INFO.dayID=old.dayID)," + "done=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=old.dayID AND completed=2)," + "losed=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=old.dayID AND completed=3)," + "theRest=(select count(*) from TABLE_INFO WHERE TABLE_INFO.dayID=old.dayID AND completed=0) " + " WHERE TABLE_DAY.id=old.dayID;" +"END;"; //构造方法 public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } //拿到数据库 @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE1); db.execSQL(CREATE_TABLE2); db.execSQL(CREATE_TRIGGER1); // Log.d("trigger1", "trigger1创建成功"); db.execSQL(CREATE_TRIGGER2); // Log.d("trigger2", "trigger2创建成功"); db.execSQL(CREATE_TRIGGER3); // Log.d("trigger2", "trigger2创建成功"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } // /** // * 根据年月日获的某一天的数据 // * // * @param year // * @param month // * @param day // * @return // */ // // public static LinkedList<Information> getListByYMD(int year, int month, int day) { // // LinkedList<Information> mInformationsList = new LinkedList<Information>(); // Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? AND month=? AND day=?",new String[]{year+"",month+"",day+""},null,null,null); // if(cursor.moveToFirst()){ // do { // Information information = new Information(); // //遍历cusor对象,取出数据变放存 // information.setId(cursor.getInt(cursor.getColumnIndex("id"))); // information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); // information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); // information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); // information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); // information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); // information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); // information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); // information.setInformation(cursor.getString(cursor.getColumnIndex("information"))); // information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); // mInformationsList.add(information); // } while (cursor.moveToNext()); // cursor.close(); // return mInformationsList; // } // cursor.close(); // return new LinkedList<Information>(); // } /** * 根据 dayID拿到对应day的status值 * @param dayID * @return */ public static int getStatusByDayID(int dayID) { Cursor cursor= mSQLiteDatabase.query("TABLE_DAY", null, "id=?", new String[]{dayID + ""}, null, null, null); if (cursor.moveToFirst()) { return cursor.getInt(cursor.getColumnIndex("status")); } return -1; } /** * 根据year、month、day、information查看数据库中是否有满足条件的数据 * @param year * @param month * @param day * @param information * @return */ public static boolean havesearchData(String year, String month, String day, String information) { String yearUtil; String monthUtil; String dayUtil; if (year==null) { yearUtil = "year like ?"; year = "%"; }else { yearUtil = "year = ?"; } if (month==null) { monthUtil = " AND month like ?"; month = "%"; }else { monthUtil = " AND month = ?"; } if (day==null) { dayUtil = " AND day like ?"; day = "%"; }else { dayUtil = " AND day = ?"; } if(information!=null) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, yearUtil+monthUtil+dayUtil+" AND information like ?", new String[]{year,month,day,"%"+information+"%"}, null, null,null); if (cursor.moveToFirst()) { return true; }else { return false;} }else { Cursor cursor= mSQLiteDatabase.query("TABLE_DAY", null, yearUtil+monthUtil+dayUtil, new String[]{year, month, day}, null, null, null); if (cursor.moveToFirst()) { return true; }else { return false; } } } /*** *根据year,month,day,information查找day(information==null) 或infromation(information!=null)数据 * @param year * @param month * @param day * @param information * @return */ public static ArrayList searchData(String year,String month,String day,String information) { String yearUtil; String monthUtil; String dayUtil; if (year==null) { yearUtil = "year like ?"; year = "%"; }else { yearUtil = "year = ?"; } if (month==null) { monthUtil = " AND month like ?"; month = "%"; }else { monthUtil = " AND month = ?"; } if (day==null) { dayUtil = " AND day like ?"; day = "%"; }else { dayUtil = " AND day = ?"; } ArrayList<Information> ArrayList = new ArrayList<Information>(); ArrayList<Day> ArrayList1=new ArrayList<Day>(); if (information != null) { //information有值,返回infolist Cursor cursor=mSQLiteDatabase.query("TABLE_INFO", null, yearUtil+monthUtil+dayUtil+" AND information like ?", new String[]{year,month,day,"%"+information+"%"}, null, null, "year DESC,month DESC,day DESC ,hour DESC, minute DESC,lastTime DESC"); if (cursor.moveToFirst()) { do { Information informationNew = new Information(); informationNew.setId(cursor.getInt(cursor.getColumnIndex("id"))); informationNew.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); informationNew.setYear(cursor.getInt(cursor.getColumnIndex("year"))); informationNew.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); informationNew.setDay(cursor.getInt(cursor.getColumnIndex("day"))); informationNew.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); informationNew.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); informationNew.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); informationNew.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); informationNew.setInformation(cursor.getString(cursor.getColumnIndex("information"))); ArrayList.add(informationNew); } while (cursor.moveToNext()); } cursor.close(); return ArrayList; }else { //此时information没有值,返回daylist Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, yearUtil+monthUtil+dayUtil, new String[]{year, month, day}, null, null, "year DESC, month DESC,day DESC"); if (cursor.moveToFirst()) { do { Day day1 = new Day(); day1.setId(cursor.getInt(cursor.getColumnIndex("id"))); day1.setYear(cursor.getInt(cursor.getColumnIndex("year"))); day1.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); day1.setDay(cursor.getInt(cursor.getColumnIndex("day"))); day1.setAll(cursor.getInt(cursor.getColumnIndex("allThing"))); day1.setDone(cursor.getInt(cursor.getColumnIndex("done"))); day1.setLosed(cursor.getInt(cursor.getColumnIndex("losed"))); day1.setTheRest(cursor.getInt(cursor.getColumnIndex("theRest"))); day1.setStatus(cursor.getInt(cursor.getColumnIndex("status"))); ArrayList1.add(day1); } while (cursor.moveToNext()); } cursor.close(); return ArrayList1; } } /** * 根据提供的day查看数据库中是否存在相应的day数据 * @param dayUsed * @return */ public static boolean havaList(Day dayUsed) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "dayID=?", new String[]{dayUsed.getId() + ""}, null, null, null); if (cursor.moveToFirst()) { cursor.close(); return true; } cursor.close(); return false; } public static LinkedList<Information> getListByDayID(int ID) { LinkedList<Information> mInformationsList = new LinkedList<Information>(); Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "dayID=?",new String[]{ID+""},null,null,null); if(cursor.moveToFirst()){ do { Information information = new Information(); //遍历cusor对象,取出数据变放存 information.setId(cursor.getInt(cursor.getColumnIndex("id"))); information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); information.setInformation(cursor.getString(cursor.getColumnIndex("information"))); information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); mInformationsList.add(information); } while (cursor.moveToNext()); cursor.close(); return mInformationsList; } cursor.close(); return mInformationsList; } // /** // * 根据年月日时分删除某一条具体的数据 // * // * @param year // * @param month // * @param day // * @param hour // * @param minute // */ //// public void deletInformation(int year, int month, int day, int hour, int minute) { // mSQLiteDatabase.delete("TABLE_INFO","year=? AND month=? AND day=? AND hour=? AND minute=?",new String[]{year+"",month+"",day+"",hour+"",minute+""}); // // } public static void deletInformation(Information infoUsed) { int id = infoUsed.getId(); mSQLiteDatabase.delete("TABLE_INFO", "id=?", new String[]{id + ""}); } public static void deletDay(Day dayUsed) { int id = dayUsed.getId(); mSQLiteDatabase.delete("TABLE_DAY", "id=?", new String[]{id + ""}); } // /** // * 根据年月日时分增加某一条具体数据 // * // * @param year // * @param month // * @param day // * @param hour // * @param minute // */ // public void addInformation(int year, int month, int day, int hour, int minute,int lastTime,int completed,String information) { // ContentValues values = new ContentValues(); // values.put("year", year); // values.put("month", month); // values.put("day", day); // values.put("hour", hour); // values.put("minute", minute); // values.put("lastTime",lastTime); // values.put("completed", completed); // values.put("information", information); // mSQLiteDatabase.insert("TABLE_INFO", null, values); // } public static int addInfoByinfomation(Information infoUsed) { ContentValues values = new ContentValues(); values.put("dayID", infoUsed.getDayID()); values.put("year", infoUsed.getYear()); values.put("month", infoUsed.getMonth()); values.put("day", infoUsed.getDay()); values.put("hour", infoUsed.getHour()); values.put("minute", infoUsed.getMinute()); values.put("lastTime", infoUsed.getLastTime()); values.put("completed", infoUsed.getCompleted()); values.put("information", infoUsed.getInformation()); long i= mSQLiteDatabase.insert("TABLE_INFO", null, values); int id = (int) i; return id; } // /** // * // * @param id // * @param completed // */ // public static void updateInformation(int id, int completed) { // ContentValues values = new ContentValues(); // values.put("completed",completed); // mSQLiteDatabase.update("TABLE_INFO",values,"id=?",new String[]{id+"" }); // } public static void updateInformationById(int id, int completed) { ContentValues values = new ContentValues(); values.put("completed", completed); mSQLiteDatabase.update("TABLE_INFO", values, "id=?", new String[]{id + ""}); } /** * 获取每天的概况 * * @return */ public LinkedList<Day> getDays() { LinkedList<Day> mDayInfoList = new LinkedList<Day>(); Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, null, null, null, null, null); if(cursor.moveToFirst()){ do { Day date = new Day(); date.setId(cursor.getInt(cursor.getColumnIndex("id"))); date.setYear(cursor.getInt(cursor.getColumnIndex("year"))); date.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); date.setDay(cursor.getInt(cursor.getColumnIndex("day"))); date.setAll(cursor.getInt(cursor.getColumnIndex("allThing"))); date.setLosed(cursor.getInt(cursor.getColumnIndex("losed"))); date.setDone(cursor.getInt(cursor.getColumnIndex("done"))); date.setTheRest(cursor.getInt(cursor.getColumnIndex("theRest"))); date.setStatus(cursor.getInt(cursor.getColumnIndex("status"))); mDayInfoList.add(date); } while (cursor.moveToNext()); cursor.close(); return mDayInfoList; } cursor.close(); return new LinkedList<Day>(); } // public static Day getDayByDate(Day day_year_month_day) { // Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, "year=? AND month=? AND day=?", new String[]{day_year_month_day.getYear() + "", day_year_month_day.getMonth() + "", day_year_month_day.getDay() + ""}, null, null, null, null); // Day date = new Day(); // if (cursor.moveToFirst()) { // date.setYear(cursor.getInt(cursor.getColumnIndex("year"))); // date.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); // date.setDay(cursor.getInt(cursor.getColumnIndex("day"))); // date.setAll(cursor.getInt(cursor.getColumnIndex("allThing"))); // date.setLosed(cursor.getInt(cursor.getColumnIndex("losed"))); // date.setDone(cursor.getInt(cursor.getColumnIndex("done"))); // date.setTheRest(cursor.getInt(cursor.getColumnIndex("theRest"))); // date.setStatus(cursor.getInt(cursor.getColumnIndex("status"))); // cursor.close(); // return date; // } // return null; // } public static Day getDayByID(int dayID) { Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, "id=?", new String[]{dayID + ""}, null, null, null, null); Day date = new Day(); if( cursor.moveToFirst()){ date.setId(cursor.getInt(cursor.getColumnIndex("id"))); date.setYear(cursor.getInt(cursor.getColumnIndex("year"))); date.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); date.setDay(cursor.getInt(cursor.getColumnIndex("day"))); date.setAll(cursor.getInt(cursor.getColumnIndex("allThing"))); date.setLosed(cursor.getInt(cursor.getColumnIndex("losed"))); date.setDone(cursor.getInt(cursor.getColumnIndex("done"))); date.setTheRest(cursor.getInt(cursor.getColumnIndex("theRest"))); date.setStatus(cursor.getInt(cursor.getColumnIndex("status"))); cursor.close(); return date; } return null; } /** * * @param day * @return 返回id key */ public static int addDay(Day day) { ContentValues values = new ContentValues(); values.put("year", day.getYear()); values.put("month", day.getMonth()); values.put("day", day.getDay()); values.put("allThing",day.getAll()); values.put("done",day.getDone()); values.put("theRest",day.getTheRest()); values.put("losed",day.getLosed()); values.put("status",day.getStatus()); return (int)mSQLiteDatabase.insert("TABLE_DAY", null, values); } /**用来更新status状态: 0昨日 1现在 2未来 * * @param date * @param status */ public static void updateDay(Day date,int status) { int year = date.getYear(); int month = date.getMonth(); int day = date.getDay(); ContentValues values = new ContentValues(); values.put("status", status); mSQLiteDatabase.update("TABLE_DAY", values, "year=? AND month=? AND day=?", new String[]{year + "", month + "", day + ""}); } /** * 根据提供的day(有day,month,year)判断数据里是否存在该day * @param day * @return 若存在,返回day的id key ,不存在返回-1 */ public static int haveDay(Day day) { Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, "year=? AND month=? AND day=?", new String[]{day.getYear() + "", day.getMonth()+ "", day.getDay() + ""}, null, null, null); if(cursor.moveToFirst()){ int id = cursor.getInt(cursor.getColumnIndex("id")); cursor.close(); return id; } cursor.close(); return -1; } /** * 根据提供的info(该info有dayID)判断数据里是否存在该info * @param information *@return ture 有;false 无 */ public static boolean haveInfo(Information information) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "dayID=? AND hour=? AND minute=?",new String[]{information.getDayID()+"",information.getHour()+"",information.getMinute()+""}, null, null, null, null); if (cursor.moveToFirst()) { return true; } cursor.close(); return false; } // public static ArrayList<Information> getTrableMaker() { // Cursor cursor=mSQLiteDatabase.query("TABLE_INFO",null,"completed=? OR ? OR ?") // // // } // /** // * 获得状态为0,1,6 information // * @return // */ // public static ArrayList<Information> getTargetInfo016() { // Cursor cursor=mSQLiteDatabase.query("TABLE_INFO",null,"completed=? OR ? OR ?",new String[]{0+"",1+"",6+""},null,null,null); // ArrayList<Information> informationsList = new ArrayList<>(); // if(cursor.moveToFirst()){ // do { // Information information = new Information(); // //遍历cusor对象,取出数据变放存 // information.setId(cursor.getInt(cursor.getColumnIndex("id"))); // information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); // information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); // information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); // information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); // information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); // information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); // information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); // information.setInformation(cursor.getString(cursor.getColumnIndex("information"))); // information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); // informationsList.add(information); // } while (cursor.moveToNext()); // cursor.close(); // return informationsList; // } // cursor.close(); // return informationsList; // } /** * 获状态为PLAN(0) information * @return */ public static LinkedList<Information> getTargetInfoPlan() { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "completed=?", new String[]{PLAN + ""}, null, null, null); LinkedList<Information> informationsList = new LinkedList<>(); if (cursor.moveToFirst()) { do { Information information = new Information(); //遍历cusor对象,取出数据变放存 information.setId(cursor.getInt(cursor.getColumnIndex("id"))); information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); information.setInformation(cursor.getString(cursor.getColumnIndex("information"))); informationsList.add(information); } while (cursor.moveToNext()); cursor.close(); return informationsList; } cursor.close(); return null; } /** * 获得状态为WORKING(0) information * @return */ public static LinkedList<Information> getTargetInfoWorking() { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "completed=?", new String[]{WORKING + ""}, null, null, null); LinkedList<Information> informationsList = new LinkedList<>(); if (cursor.moveToFirst()) { do { Information information = new Information(); //遍历cusor对象,取出数据变放存 information.setId(cursor.getInt(cursor.getColumnIndex("id"))); information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); information.setInformation(cursor.getString(cursor.getColumnIndex("information"))); informationsList.add(information); } while (cursor.moveToNext()); cursor.close(); return informationsList; } cursor.close(); return null; } /** * 获得状态为WORNING(0) information * @return */ public static LinkedList<Information> getTargetInfoWaring() { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "completed=?", new String[]{WARING + ""}, null, null, null); LinkedList<Information> informationsList = new LinkedList<>(); if (cursor.moveToFirst()) { do { Information information = new Information(); //遍历cusor对象,取出数据变放存 information.setId(cursor.getInt(cursor.getColumnIndex("id"))); information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); information.setInformation(cursor.getString(cursor.getColumnIndex("information"))); informationsList.add(information); } while (cursor.moveToNext()); cursor.close(); return informationsList; } cursor.close(); return null; } /** * 获得状态为0、1的信息 * @return */ public static ArrayList<Information> getTargetInfoPlanOrWoring() { Cursor cursor=mSQLiteDatabase.query("TABLE_INFO",null,"completed=? OR ? ",new String[]{PLAN+"",WORKING+""},null,null,null); ArrayList<Information> informationsList = new ArrayList<>(); if(cursor.moveToFirst()){ do { Information information = new Information(); //遍历cusor对象,取出数据变放存 information.setId(cursor.getInt(cursor.getColumnIndex("id"))); information.setYear(cursor.getInt(cursor.getColumnIndex("year"))); information.setMonth(cursor.getInt(cursor.getColumnIndex("month"))); information.setDay(cursor.getInt(cursor.getColumnIndex("day"))); information.setHour(cursor.getInt(cursor.getColumnIndex("hour"))); information.setMinute(cursor.getInt(cursor.getColumnIndex("minute"))); information.setLastTime(cursor.getInt(cursor.getColumnIndex("lastTime"))); information.setCompleted(cursor.getInt(cursor.getColumnIndex("completed"))); information.setDayID(cursor.getInt(cursor.getColumnIndex("dayID"))); informationsList.add(information); } while (cursor.moveToNext()); cursor.close(); return informationsList; } cursor.close(); return null; } /** * 开机初始化day * 检查状态为NOW(1),FUTURE(2)的day信息是否过期,过期则改状态 * */ public static int initialDate() { int year = TimeUtil.getYear(); int month = TimeUtil.getMonth(); int day = TimeUtil.getDay(); int dayID=-7; //随便写的一个负数,因为最后dayID都会是一个正整数 int newDAY=0; Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, "status=? OR ?", new String[]{ NOW+"",FUTURE+""}, null, null, null); if (cursor.moveToFirst()) { do { ContentValues values = new ContentValues(); int year1 = cursor.getInt(cursor.getColumnIndex("year")); int month1 = cursor.getInt(cursor.getColumnIndex("month")); int day1 = cursor.getInt(cursor.getColumnIndex("day")); int id = cursor.getInt(cursor.getColumnIndex("id")); int i = 500 * (year - year1) + 35 * (month - month1) + (day - day1); if ( i> 0) { //在今天之前的日子全部更新为PAST values.put("status",PAST); mSQLiteDatabase.update("TABLE_DAY", values, "id=?", new String[]{id + ""}); } else if (i == 0) { //今天 values.put("status", NOW); mSQLiteDatabase.update("TABLE_DAY", values, "id=?", new String[]{id + ""}); newDAY = newDAY + 1; dayID = id; } } while (cursor.moveToNext()); cursor.close(); if (newDAY == 0) { //不存在今天数据,插入新的一天 ContentValues values = new ContentValues(); values.put("year", year); values.put("month", month); values.put("day", day); values.put("allThing", 0); values.put("done", 0); values.put("losed", 0); values.put("theRest", 0); values.put("status", NOW); dayID=(int)MyDatabaseHelper.mSQLiteDatabase.insert("TABLE_DAY", null, values); } }else { //不存在数据,第一次启动app ContentValues values = new ContentValues(); values.put("year", year); values.put("month", month); values.put("day", day); values.put("allThing", 0); values.put("done", 0); values.put("losed", 0); values.put("theRest", 0); values.put("status", NOW); dayID= (int)MyDatabaseHelper.mSQLiteDatabase.insert("TABLE_DAY", null, values); } return dayID; } /** * 开机初始化info */ public static void initialInfo() { ArrayList<Information> informationsList = sMyDatabaseHelper.getTargetInfoPlanOrWoring(); //查找数据库中状态为PLAN(0),WORKING(1) if (informationsList!=null) { for(Information information:informationsList) { int id = information.getId(); int year = information.getYear(); int month = information.getMonth(); int day = information.getDay(); int hour = information.getHour(); int minute = information.getMinute(); int lastTime = information.getLastTime(); int completed = information.getCompleted(); long begin = TimeUtil.getMillis(year, month, day, hour, minute); switch (completed) { case PLAN://状态是未来的,检查是否有漏过的计划 if (begin + lastTime * 60000 - TimeUtil.getNowMillis() >= 0) { //如果结束时间在当前时间之后 if (begin - TimeUtil.getNowMillis() <= 0) { //开始时间在当前时间之前 sMyDatabaseHelper.updateInformationById(id, 1); } } else { //结束时间在当前时间之前 sMyDatabaseHelper.updateInformationById(id, 6); } break; case WORKING: //已经开始的计划 if (begin + lastTime * 60000 - TimeUtil.getNowMillis() < 0) { //已经开始并且结束的任务 sMyDatabaseHelper.updateInformationById(id, 6); } break; default: break; } } } } /** * 获取当月信息的数量 * @param month * @return */ public static int getInfoNumMaxInMonth(int year,int month) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? AND month=?", new String[]{year+"",month + ""}, null, null, null); return cursor.getCount(); } /** * 获取当月已经结束信息的数量 * * @return */ public static int getInfoNumDoneInMonth(int year, int month) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? AND month=? AND completed IN (2,3)", new String[]{year + "", month + ""}, null, null, null); return cursor.getCount(); } /** * 获取当月已经结束信息的数量 * @param year * @param month * @return */ public static int getInfoNumLosedInMonth(int year, int month) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? AND month=? AND completed=?", new String[]{year + "", month + "", UNFINISHED + ""}, null, null, null); return cursor.getCount(); } /** * 获取当月信息的数量 * @param * @return */ public static int getInfoNumMaxInYear(int year) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? ", new String[]{year+""}, null, null, null); return cursor.getCount(); } /** * 获取今年已经结束信息的数量 * * @return */ public static int getInfoNumDoneInYear(int year) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? AND completed in (2,3)", new String[]{year + ""}, null, null, null); return cursor.getCount(); } /** * 获取今年失败信息的数量 * @param year * @param * @return */ public static int getInfoNumLosedInYear(int year) { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "year=? AND completed=?", new String[]{year + "", UNFINISHED + ""}, null, null, null); return cursor.getCount(); } /** * 获取从安装开始 当天全部完成 天数和 * @return */ public static int getDayAllFinishNumFromBegin() { Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, " allThing!=? AND losed=? AND status=?", new String[]{0+"",0+"" , 0+ ""}, null, null, null); return cursor.getCount(); } /** * 获取数据库中到目前为止所有的有安排的天数 */ public static int getDayMarkNumFromBegin() { Cursor cursor = mSQLiteDatabase.query("TABLE_DAY", null, " allThing!=? AND status=?", new String[]{0+"",PAST+"" }, null, null, null); return cursor.getCount(); } /** * 查询所有完成的info * @return */ public static int getInfoFininshNumFromBegin() { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "completed = ?", new String[]{FINISHED+""}, null, null, null); return cursor.getCount(); } /** * 查询所有没有完成的info * @return */ public static int getInfoLosedNumFromBegin() { Cursor cursor = mSQLiteDatabase.query("TABLE_INFO", null, "completed = ?", new String[]{UNFINISHED+""}, null, null, null); return cursor.getCount(); } }
39.605809
244
0.571922
0dec752102b8524692de8d0d781902e7f233cdfd
615
package com.fasterxml.jackson.databind.node; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public abstract class BaseJsonNode extends JsonNode implements JsonSerializable { public abstract void serialize(JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException; protected BaseJsonNode() { } }
38.4375
147
0.842276
b60da2266d8af03b3123eb8811b8beb97877189e
1,203
package org.folio.marccat.resources; import org.folio.marccat.ModMarccat; import org.folio.marccat.config.Global; import org.folio.marccat.resources.domain.HeadingTypeCollection; import org.springframework.web.bind.annotation.*; import static java.util.Optional.ofNullable; import static org.folio.marccat.integration.MarccatHelper.doGet; import static org.folio.marccat.resources.shared.MappingUtils.mapToHeading; /** * Header type code RESTful APIs. * * @author cchiama * @since 1.0 */ @RestController @RequestMapping(value = ModMarccat.BASE_URI, produces = "application/json") public class HeaderTypeAPI extends BaseResource { @GetMapping("/header-types") public HeadingTypeCollection getHeadingTypes( @RequestParam final String code, @RequestParam final String lang, @RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) { return doGet((storageService, configuration) -> { final int category = Global.HEADER_CATEGORY; if (ofNullable(storageService.getFirstCorrelation(lang, category)).isPresent()) return mapToHeading(storageService.getFirstCorrelation(lang, category), code); return null; }, tenant, configurator); } }
31.657895
86
0.771405
e2e49beea95e967dd6abbd81cbf3753920af7dd1
484
package it.smartcommunitylab.innoweee.engine.repository; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.stereotype.Repository; import it.smartcommunitylab.innoweee.engine.model.Catalog; @Repository public interface CatalogRepository extends MongoRepository<Catalog, String> { @Query(value="{tenantId:?0, gameId:?1}") Catalog findByGameId(String tenantId, String gameId); }
34.571429
77
0.832645
8f2e1609104298d8faafe693e79d5b757ecc6897
6,678
package com.rajpriya.home.utils; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.provider.Settings; import android.support.v4.app.Fragment; import android.widget.Toast; import com.rajpriya.home.InstalledAppsFragment; import com.rajpriya.home.R; import java.io.File; import java.util.List; /** * Created by rajkumar on 3/8/14. */ public class Utils { public interface AppUninstall { public void onAppDeleted(); } public static void launchAppDetails(final Context context, final String packageName) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", packageName, null); intent.setData(uri); context.startActivity(intent); } public static void launchApp(final Context context, final String packageName) { PackageManager pm = context.getPackageManager(); Intent intent = pm.getLaunchIntentForPackage(packageName); if (intent != null) { context.startActivity(intent); } } public static void deleteApp(final Context context, final String packageName, InstalledAppsFragment caller) { Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package:"+packageName)); ((Activity)context).startActivityForResult(intent, 200); } public static void showActionDialog(final Context context, final String packageName, final InstalledAppsFragment caller) { final AlertDialog levelDialog; // Strings to Show In Dialog with Radio Buttons final CharSequence[] items = { " Share this App ", " Launch ", " View in Google Play ", " View Details "," Uninstall from Device ",}; // Creating and Building the Dialog AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Choose Action"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch(item) { case 1: // Your code when first option seletced Utils.launchApp(context, packageName); break; case 3: // Your code when 2nd option seletced Utils.launchAppDetails(context, packageName); break; case 4: // Your code when 3rd option seletced Utils.deleteApp(context, packageName, caller); break; case 0: // Your code when 4th option seletced BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter == null) { // Device does not support Bluetooth // Inform user that we're done. Toast.makeText(context, "Your device does not support Bluetooth!", Toast.LENGTH_LONG).show(); break; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("application/zip"); //list of apps that can handle our intent PackageManager pm = context.getPackageManager(); List<ResolveInfo> appsList = pm.queryIntentActivities( intent, 0); /* if(appsList.size() > 0) { // proceed //select bluetooth String packageName = null; String className = null; boolean found = false; for(ResolveInfo info: appsList){ packageName = info.activityInfo.packageName; if( packageName.equals("com.android.bluetooth")){ className = info.activityInfo.name; found = true; break;// found } } if(! found){ Toast.makeText(context, "Bluetooth package not found", Toast.LENGTH_SHORT).show(); //break; } intent.setClassName(packageName, className); }*/ ApplicationInfo app = null; try { app = (context.getPackageManager()).getApplicationInfo(packageName, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (app != null ) { intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(app.publicSourceDir)) ); context.startActivity(intent); } break; case 2: final String appPackageName = packageName; // getPackageName() from Context or Activity object try { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName))); } break; } dialog.dismiss(); } }); levelDialog = builder.create(); levelDialog.show(); } /** Check if the application is uninstalled from System */ public static boolean isAppPresent(String packageName,Context context) { try{ ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0 ); return true; } catch( PackageManager.NameNotFoundException e ){ return false; } } }
41.7375
159
0.54103
2582ab8acb29d9b23dc677de003567f9f3d2d538
202
package org.omg.zx.globaldefs; /** * Automatically generated from IDL const definition * @author JacORB IDL compiler */ public interface interfaceVersion { java.lang.String value = "V2.02.02"; }
18.363636
53
0.732673
6b485e2382f134df3f9649398c6b5e73a440d4df
146
/* * Copyright (c) 2007, tamacat.org * All rights reserved. */ package org.tamacat.core; public interface Core { String getCoreName(); }
13.272727
34
0.671233
4784d46cc2220ce4a9b8ddbff22f14b7dc49be2d
4,967
package vb.obama; import java.io.File; import java.io.IOException; import org.antlr.runtime.*; import org.antlr.runtime.tree.CommonTreeNodeStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.rules.TemporaryFolder; import vb.obama.antlr.ObamaChecker; import vb.obama.antlr.ObamaCodegen; import vb.obama.antlr.ObamaLexer; import vb.obama.antlr.ObamaParser; import vb.obama.antlr.tree.TypedNode; import vb.obama.antlr.tree.TypedNodeAdapter; import vb.obama.compiler.SymbolTable; import vb.obama.util.DebugAppender; import vb.obama.util.LoggerSetup; import vb.obama.util.ProcessRunner; import org.junit.After; import org.junit.Before; /** * Abstract class for the tests of the code samples. Contains a helper methods * which allows us to easily execute a test. * * @version 1.0 */ abstract class AbstractTest { /** * Reference to logger (used to output information to stdout/stderr). */ private static final Logger logger = LogManager.getLogger(AbstractTest.class); /** * Reference to appender. */ private static final DebugAppender appender = new DebugAppender(); /** * Placeholder to temporary working directory. */ public TemporaryFolder tempFolder = new TemporaryFolder(); /** * Debug the parser if true. */ protected boolean debugParser = false; protected boolean debugChecker = false; protected boolean debugCodegen = false; public AbstractTest() { appender.start(); LoggerSetup.setup(appender); } /** * Handle creation of temporary test output folder. */ @Before public void before() { try { this.tempFolder.create(); } catch (IOException exception) { logger.error("Unable to create temporary folder for test output", exception); } } /** * Handle cleanup of temporary test output folder. */ @After public void after() { this.tempFolder.delete(); } /** * Execute one test from file. * * @param file Path to file * @return Number of syntax errors, or -1 if an RecognitionException occurred * @throws IOException */ private int executeFile(String file, boolean doChecker, boolean doCodegen, String path) throws RecognitionException, IOException { int errors = 0; appender.setTable(null); logger.info(String.format("*** Testing file '%s' ***", file)); try { // Symbol table SymbolTable table = new SymbolTable(); appender.setTable(table); // Lexer ObamaLexer lexer = new ObamaLexer(new ANTLRInputStream(this.getClass().getResourceAsStream(file))); CommonTokenStream tokens = new CommonTokenStream(lexer); // Parser ObamaParser parser = this.debugParser ? new ObamaParser(tokens) : new ObamaParser(tokens); parser.setTreeAdaptor(new TypedNodeAdapter()); ObamaParser.program_return parserResult = parser.program(); TypedNode tree = parserResult.getTree(); errors = errors + parser.getNumberOfSyntaxErrors(); // Checker if (doChecker) { CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree); ObamaChecker checker = this.debugChecker ? new ObamaChecker(nodes) : new ObamaChecker(nodes); checker.setSymbolTable(table); checker.setInputFile(file); checker.setTreeAdaptor(new TypedNodeAdapter()); checker.program(); // Codegen if (doCodegen) { CommonTreeNodeStream codegenNodes = new CommonTreeNodeStream(tree); ObamaCodegen codegen = this.debugCodegen ? new ObamaCodegen(codegenNodes) : new ObamaCodegen(codegenNodes); codegen.setTreeAdaptor(new TypedNodeAdapter()); codegen.program(); // Generate code codegen.getHelper().toClasses(path); } } } catch (IOException exception) { appender.setTable(null); logger.info(String.format("*** Test failed: test not found ***")); throw exception; } catch (RecognitionException exception) { appender.setTable(null); logger.info(String.format("*** Test finished: exception: %s ***", exception)); throw exception; } appender.setTable(null); logger.info(String.format("*** Test finished: %d errors ***", errors)); return errors; } protected int executeFileParser(String file) throws RecognitionException, IOException { return this.executeFile(file, false, false, null); } protected int executeFileChecker(String file) throws RecognitionException, IOException { return this.executeFile(file, true, false, null); } protected int executeFileCodegen(String file) throws RecognitionException, IOException { return this.executeFile(file, true, true, this.tempFolder.getRoot().getAbsolutePath()); } /** * Execute a Java application and return its stdin. Requires java to be on the * execution path. * * @param className Name of class to execute * @return Console stdout output * @throws IOException */ public String runJavaFile(String className) throws IOException { String[] arguments = {"java", className}; return ProcessRunner.runProcess(arguments, this.tempFolder.getRoot()); } }
29.217647
131
0.729011
e2534160397c4d3079fc47de8d13114f0677e8dd
2,712
package org.blockchainnative.quorum.transactions; import org.blockchainnative.ethereum.transactions.EthereumBaseTransactionRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.web3j.protocol.exceptions.TransactionException; import org.web3j.quorum.Quorum; import org.web3j.quorum.tx.ClientTransactionManager; import org.web3j.tx.TransactionManager; import java.io.IOException; import java.math.BigInteger; import java.util.List; import java.util.stream.Collectors; /** * * @author Matthias Veit * @since 1.1 */ public class QuorumTransactionRequest extends EthereumBaseTransactionRequest { private static final Logger LOGGER = LoggerFactory.getLogger(QuorumTransactionRequest.class); private List<String> privateFor; public QuorumTransactionRequest(Quorum quorum, TransactionManager transactionManager) { super(quorum, transactionManager); } public List<String> getPrivateFor() { return privateFor; } public void setPrivateFor(List<String> privateFor) { this.privateFor = privateFor; } @Override public String sendInternal() { List<String> previousPrivateFor = null; try { // set the transaction's privateFor list while preserving the previous state if (transactionManager instanceof ClientTransactionManager) { previousPrivateFor = ((ClientTransactionManager) transactionManager).getPrivateFor(); ((ClientTransactionManager) transactionManager).setPrivateFor(getPrivateFor()); } var transactionReceipt = super.send(recipient, encodeData(data), value, BigInteger.ZERO, gasLimit); return transactionReceipt.getTransactionHash(); } catch (IOException | TransactionException e) { throw new org.blockchainnative.transactions.exceptions.TransactionException( String.format("Failed to execute transaction with recipient '%s'", recipient), e); } finally { // reset the transactionManager's privateFor list if required if (transactionManager instanceof ClientTransactionManager && previousPrivateFor != null) { ((ClientTransactionManager) transactionManager).setPrivateFor(previousPrivateFor); } } } @Override protected void validateProperties() { validateRecipient(); validateGasLimit(); validateValue(); validateData(); validatePrivateFor(); } protected void validatePrivateFor(){ LOGGER.debug("Private for: {}", privateFor != null ? privateFor.stream().collect(Collectors.joining(", ")) : "<null>"); } }
35.220779
127
0.696903
13fbdf129f37d17c3ed89e5bbd0f974d0978cec8
1,969
package com.elderresearch.commons.rjava.util; import org.apache.commons.lang3.ArrayUtils; import org.rosuda.REngine.REXPMismatchException; import org.rosuda.REngine.REngineException; import com.elderresearch.commons.jri.PackageScope; import com.elderresearch.commons.jri.PackageType; import com.elderresearch.commons.jri.util.RPath; import com.elderresearch.commons.rjava.RSession; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.val; import lombok.experimental.Accessors; import lombok.extern.log4j.Log4j2; @Log4j2 @Setter @Accessors(chain = true, fluent = true) @RequiredArgsConstructor(staticName = "ofPackage") public class InstallDependencies { private static final String DEF_CRAN_URL = "https://cloud.r-project.org"; private final RPath packagePath; private String cranUrl = DEF_CRAN_URL; private PackageScope[] scopes = PackageScope.getDefaultScopes(); private PackageType type = PackageType.getDefaultType(); private RSession session = new RSession(); public InstallDependencies setScopes(PackageScope... scopes) { this.scopes = scopes; return this; } public void install() { // Create an R engine val re = session.start(false); try { // Use cloud CDN CRAN to download dependencies re.assign("url", cranUrl); // Binaries aren't available on *Nix, having the right toolchain to compile is hard on Mac/Win re.assign("type", type.toString()); // Set the type of dependencies to install re.assign("deps", ArrayUtils.toStringArray(scopes)); // Install the package to the specified local directory, which installs any transitive dependencies re.parseAndEval(String.format("remotes::install_local('%s', " + "upgrade='never', " + "dependencies=deps, " + "lib='%s', " + "type=type, " + "repos=url)", packagePath, session.libraryPath())); } catch (REngineException | REXPMismatchException e) { log.warn("Error installing {}", packagePath, e); } re.close(); } }
33.948276
102
0.74708
7c3216c38e4539c9ffbf3fca55cbb56abdaa2a51
9,511
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.RunVmParams; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmDynamic; import org.ovirt.engine.core.common.businessentities.VmExitStatus; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.compat.DateTime; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.dao.VmDAO; import org.ovirt.engine.core.dao.VmDynamicDAO; import org.ovirt.engine.core.utils.lock.EngineLock; import org.ovirt.engine.core.utils.lock.LockManagerFactory; import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class represent a job which is responsible for running HA VMs */ public class AutoStartVmsRunner { private static final Logger log = LoggerFactory.getLogger(AutoStartVmsRunner.class); /** How long to wait before rerun HA VM that failed to start (not because of lock acquisition) */ private static final int RETRY_TO_RUN_HA_VM_INTERVAL = Config.<Integer> getValue(ConfigValues.RetryToRunAutoStartVmIntervalInSeconds); private static AutoStartVmsRunner instance = new AutoStartVmsRunner(); private final AuditLogDirector auditLogDirector = new AuditLogDirector(); /** Records of HA VMs that need to be restarted */ private CopyOnWriteArraySet<AutoStartVmToRestart> autoStartVmsToRestart; public static AutoStartVmsRunner getInstance() { return instance; } private AutoStartVmsRunner() { // There might be HA VMs which went down just before the engine stopped, we detected // the failure and updated the DB but didn't made it to rerun the VM. So here we'll // take all the HA VMs which are down because of an error and add them to the set List<VM> failedAutoStartVms = getVmDao().getAllFailedAutoStartVms(); ArrayList<AutoStartVmToRestart> initialFailedVms = new ArrayList<>(failedAutoStartVms.size()); for (VM vm: failedAutoStartVms) { log.info("Found HA VM which is down because of an error, trying to restart it, VM '{}' ({})", vm.getName(), vm.getId()); initialFailedVms.add(new AutoStartVmToRestart(vm.getId())); } autoStartVmsToRestart = new CopyOnWriteArraySet<>(initialFailedVms); } /** * Add the given VM IDs to the set of VMs which will be started in the next iteration. * * @param vmIds * List of VM IDs to start in the next iteration of the job */ public void addVmsToRun(List<Guid> vmIds) { ArrayList<AutoStartVmToRestart> vmsToAdd = new ArrayList<>(vmIds.size()); for (Guid vmId: vmIds) { vmsToAdd.add(new AutoStartVmToRestart(vmId)); } autoStartVmsToRestart.addAll(vmsToAdd); } @OnTimerMethodAnnotation("startFailedAutoStartVms") public void startFailedAutoStartVms() { LinkedList<AutoStartVmToRestart> vmsToRemove = new LinkedList<>(); final DateTime iterationStartTime = DateTime.getNow(); final Date nextTimeOfRetryToRun = iterationStartTime.addSeconds(RETRY_TO_RUN_HA_VM_INTERVAL); for(AutoStartVmToRestart autoStartVmToRestart: autoStartVmsToRestart) { // if it is not the time to try to run the VM yet, skip it for now // (we'll try again in the next iteration) if (!autoStartVmToRestart.isTimeToRun(iterationStartTime)) { continue; } Guid vmId = autoStartVmToRestart.getVmId(); EngineLock runVmLock = createEngineLockForRunVm(vmId); // try to acquire the required lock for running the VM, if the lock cannot be // acquired, skip for now and we'll try again in the next iteration if (!acquireLock(runVmLock)) { log.debug("Could not acquire lock for running HA VM '{}'", vmId); continue; } if (!isVmNeedsToBeAutoStarted(vmId)) { // if the VM doesn't need to be auto started anymore, release the lock and // remove the VM from the collection of VMs that should be auto started releaseLock(runVmLock); vmsToRemove.add(autoStartVmToRestart); continue; } if (runVm(vmId, runVmLock)) { // the VM reached WaitForLunch, so from now on this job is not responsible // to auto start it, future failures will be detected by the monitoring vmsToRemove.add(autoStartVmToRestart); } else { logFailedAttemptToRestartHighlyAvailableVm(vmId); if (!autoStartVmToRestart.scheduleNextTimeToRun(nextTimeOfRetryToRun)) { // if we could not schedule the next time to run the VM, it means // that we reached the maximum number of tried so don't try anymore vmsToRemove.add(autoStartVmToRestart); logFailureToRestartHighlyAvailableVm(vmId); } } } autoStartVmsToRestart.removeAll(vmsToRemove); } private boolean acquireLock(EngineLock lock) { return LockManagerFactory.getLockManager().acquireLock(lock).getFirst(); } private void releaseLock(EngineLock lock) { LockManagerFactory.getLockManager().releaseLock(lock); } private void logFailedAttemptToRestartHighlyAvailableVm(Guid vmId) { AuditLogableBase event = new AuditLogableBase(); event.setVmId(vmId); auditLogDirector.log(event, AuditLogType.HA_VM_RESTART_FAILED); } private void logFailureToRestartHighlyAvailableVm(Guid vmId) { AuditLogableBase event = new AuditLogableBase(); event.setVmId(vmId); auditLogDirector.log(event, AuditLogType.EXCEEDED_MAXIMUM_NUM_OF_RESTART_HA_VM_ATTEMPTS); } private boolean isVmNeedsToBeAutoStarted(Guid vmId) { VmDynamic vmDynamic = getVmDynamicDao().get(vmId); return vmDynamic.getStatus() == VMStatus.Down && vmDynamic.getExitStatus() == VmExitStatus.Error; } private EngineLock createEngineLockForRunVm(Guid vmId) { return new EngineLock( RunVmCommandBase.getExclusiveLocksForRunVm(vmId, getLockMessage()), RunVmCommandBase.getSharedLocksForRunVm()); } protected String getLockMessage() { return VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED.name(); } protected VmDynamicDAO getVmDynamicDao() { return DbFacade.getInstance().getVmDynamicDao(); } protected VmDAO getVmDao() { return DbFacade.getInstance().getVmDao(); } private boolean runVm(Guid vmId, EngineLock lock) { return Backend.getInstance().runInternalAction( VdcActionType.RunVm, new RunVmParams(vmId), ExecutionHandler.createInternalJobContext(lock)).getSucceeded(); } private static class AutoStartVmToRestart { /** The earliest date in Java */ private static final Date MIN_DATE = DateTime.getMinValue(); /** How many times to try to restart highly available VM that went down */ private static final int MAXIMUM_NUM_OF_TRIES_TO_RESTART_HA_VM = Config.<Integer> getValue(ConfigValues.MaxNumOfTriesToRunFailedAutoStartVm); /** The next time we should try to run the VM */ private Date timeToRunTheVm; /** Number of tries that were made so far to run the VM */ private int numOfRuns; /** The ID of the VM */ private Guid vmId; AutoStartVmToRestart(Guid vmId) { this.vmId = vmId; timeToRunTheVm = MIN_DATE; } /** * Set the next time we should try to rerun the VM. * If we reached the maximum number of tries, the method returns false. */ boolean scheduleNextTimeToRun(Date timeToRunTheVm) { this.timeToRunTheVm = timeToRunTheVm; return ++numOfRuns < MAXIMUM_NUM_OF_TRIES_TO_RESTART_HA_VM; } boolean isTimeToRun(Date time) { return timeToRunTheVm == MIN_DATE || time.compareTo(timeToRunTheVm) >= 0; } Guid getVmId() { return vmId; } @Override public boolean equals(Object obj) { if (obj instanceof AutoStartVmToRestart) { return vmId.equals(((AutoStartVmToRestart) obj).vmId); } return super.equals(obj); } @Override public int hashCode() { return vmId.hashCode(); } } }
40.99569
105
0.671433
cb827ce62eef62a585c79c12811c951c640462a8
7,190
package com.imageServer.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Copyright 2014-2015 the original ql * 文件操作工具类 * * @author qianlong * */ public class FileUtil { private static final Logger log = LoggerFactory.getLogger(FileUtil.class); /** * 获取文本文件的文本内容 若没有此文件,则创建一个新文件,返回空串 * * @param fileName * @return * @throws IOException */ public static String getTextFileContent(String fileName){ StringBuilder text = new StringBuilder(); File f = new File(fileName); if (!f.exists()) { try { if(!f.createNewFile()){ log.warn("文件已存在"); } } catch (IOException e) { log.error("文件读取失败,请检查是否有文件读取权限,或指定文件是否损坏等"); } } try { FileInputStream fis = new FileInputStream(f); InputStreamReader read = new InputStreamReader(fis,"UTF-8"); BufferedReader reader = new BufferedReader(read); String line = ""; while((line = reader.readLine()) != null){ text.append(line); } reader.close(); } catch (Exception e) { log.error("文件读取失败,请检查是否有文件读取权限,或指定文件是否损坏等",e); } return text.toString(); } /** * 获取制定路径下的所有文件中的文本 * 如果不存在则创建传入的路径 * @param path * @return * @throws Exception */ public static List<String> getAllFileTextFromDir(String path){ List<String> filesText = new ArrayList<String>(); File f = new File(path); if (!f.exists()) { if(!f.mkdirs()){ log.warn("目录创建失败"); } } File[] fs = f.listFiles(); if(fs == null){ return new ArrayList<>(); } try { for (File file : fs) { StringBuilder text = new StringBuilder(); FileInputStream fis = new FileInputStream(file); InputStreamReader read = new InputStreamReader(fis,"UTF-8"); BufferedReader reader = new BufferedReader(read); String line = ""; while((line = reader.readLine()) != null){ text.append(line); } filesText.add(text.toString()); reader.close(); } } catch (Exception e) { return new ArrayList<>(); } return filesText; } /** * 获取传入的路径下的文件的文件内容 * 如果文件不存在,将自动根据路径及文件名创建一个新的,返回空串 * @param path * @param fileName * @return * @throws Exception */ public static String getFileTextFromDirFile(String path, String fileName){ StringBuilder text = new StringBuilder(); File f = new File(path); if (!f.exists()) { if(!f.mkdirs()){ log.warn("目录创建失败"); } } f = new File(path + File.separator + fileName); if(!f.exists()){ try { if(!f.createNewFile()){ log.warn("文件已存在"); } } catch (IOException e) { log.error("文件读取失败,请检查是否有文件读取权限,或指定文件是否损坏等",e); } } try { FileInputStream fis = new FileInputStream(f); InputStreamReader read = new InputStreamReader(fis,"UTF-8"); BufferedReader reader = new BufferedReader(read); String line = ""; while((line = reader.readLine()) != null){ text.append(line); } reader.close(); } catch (Exception e) { return "文件读取失败,请检查是否有文件读取权限,或指定文件是否损坏等"; } return text.toString(); } /** * 将制定的字符串写入指定路径下的指定文件中 * 如果路径及文件不存在,将自动创建 * @param text * @param path * @param fileName * @param append : true为在文件后追加内容 * @return */ public static boolean writeTextToTextFile(String text,String path, String fileName,boolean append) { File f = new File(path); if(!f.exists()){ if(!f.mkdirs()){ log.warn("目录创建失败"); } } f = new File(path + File.separator + fileName); if(!f.exists()){ try { if(!f.createNewFile()){ log.warn("文件创建失败"); return false; } } catch (IOException e) { log.error("文件创建异常",e); return false; } } FileOutputStream fos; try { fos = new FileOutputStream(f, append); OutputStreamWriter write = new OutputStreamWriter(fos,"UTF-8"); BufferedWriter writer = new BufferedWriter(write); writer.write(text); writer.close(); return true; } catch (Exception e) { return false; } } /** * 将制定的字符串写入指定路径下的指定文件中 * 如果文件不存在,返回false * @param text * @param file * @param append : true为在文件后追加内容 * @return */ public static boolean writeTextToTextFile(String text,File file,boolean append) { if(!file.exists()){ return false; } FileOutputStream fos; try { fos = new FileOutputStream(file, append); OutputStreamWriter write = new OutputStreamWriter(fos,"UTF-8"); BufferedWriter writer = new BufferedWriter(write); writer.write(text); writer.close(); return true; } catch (Exception e) { return false; } } /** * InputStream输入流转换为File * @param ins * @param file */ public static boolean inputStreamToFile(InputStream ins,File file) { try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); return true; } catch (Exception e) { return false; } } /** * 遍历获取指定路径下的所有文件绝对路径 * 如果不存在则创建传入的路径 * @param path * @return * @throws Exception */ public static List<String> getAllFileNamesFromDir(String path){ List<String> fileNames = new ArrayList<>(); File dir = new File(path); if (!dir.exists()) { if(!dir.mkdirs()){ log.warn("目录创建失败"); } } File[] fs = dir.listFiles(); if(fs == null){ return new ArrayList<>(); } try { for (File file : fs) { appendFileNames(file.getPath(),fileNames); } } catch (Exception e) { log.error("获取文件名时发生异常",e); return new ArrayList<>(); } return fileNames; } private static void appendFileNames(String dir,List<String> fileNames){ File file = new File(dir); if(file.isFile()){ fileNames.add(file.getPath()); }else { File[] fs = file.listFiles(); if(fs != null){ for (File f : fs) { if(f.isDirectory()){ appendFileNames(f.getPath(),fileNames); }else if(f.isFile()){ fileNames.add(f.getPath()); }else { log.warn("发现一文件即非目录也非文件:" + f.getPath()); } } } } } }
26.433824
101
0.527538
c5f45b82af6a11c8d595deaa823f6914c77a82c6
3,832
package cc.mrbird.febs.blog.controller; import cc.mrbird.febs.common.annotation.Log; import cc.mrbird.febs.common.domain.FebsConstant; import cc.mrbird.febs.common.domain.FebsResponse; import cc.mrbird.febs.common.domain.QueryRequest; import cc.mrbird.febs.common.utils.FebsUtil; import cc.mrbird.febs.common.controller.BaseController; import cc.mrbird.febs.common.exception.FebsException; import cc.mrbird.febs.blog.entity.BUser; import cc.mrbird.febs.blog.service.IBUserService; import com.wuwenze.poi.ExcelKit; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.util.List; import java.util.Map; /** * Controller * * @author MrBird * @date 2019-10-08 13:23:19 */ @Slf4j @Validated @Controller public class BUserController extends BaseController { @Autowired private IBUserService bUserService; @GetMapping("bUser") @ResponseBody //@RequiresPermissions("bUser:list") public FebsResponse getAllBUsers(BUser bUser) { return new FebsResponse().success().data(bUserService.findBUsers(bUser)); } @GetMapping("bUser/list") @ResponseBody //@RequiresPermissions("bUser:list") public FebsResponse bUserList(QueryRequest request, BUser bUser) { Map<String, Object> dataTable = getDataTable(this.bUserService.findBUsers(request, bUser)); return new FebsResponse().success().data(dataTable); } @Log("新增BUser") @PostMapping("bUser") @ResponseBody //@RequiresPermissions("bUser:add") public FebsResponse addBUser(@Valid BUser bUser) throws FebsException { try { this.bUserService.createBUser(bUser); return new FebsResponse().success(); } catch (Exception e) { String message = "新增BUser失败"; log.error(message, e); throw new FebsException(message); } } @Log("删除BUser") @GetMapping("bUser/delete") @ResponseBody //@RequiresPermissions("bUser:delete") public FebsResponse deleteBUser(BUser bUser) throws FebsException { try { this.bUserService.deleteBUser(bUser); return new FebsResponse().success(); } catch (Exception e) { String message = "删除BUser失败"; log.error(message, e); throw new FebsException(message); } } @Log("修改BUser") @PostMapping("bUser/update") @ResponseBody //@RequiresPermissions("bUser:update") public FebsResponse updateBUser(BUser bUser) throws FebsException { try { this.bUserService.updateBUser(bUser); return new FebsResponse().success(); } catch (Exception e) { String message = "修改BUser失败"; log.error(message, e); throw new FebsException(message); } } @PostMapping("bUser/excel") @ResponseBody //@RequiresPermissions("bUser:export") public void export(QueryRequest queryRequest, BUser bUser, HttpServletResponse response) throws FebsException { try { List<BUser> bUsers = this.bUserService.findBUsers(queryRequest, bUser).getRecords(); ExcelKit.$Export(BUser.class, response).downXlsx(bUsers, false); } catch (Exception e) { String message = "导出Excel失败"; log.error(message, e); throw new FebsException(message); } } }
33.321739
115
0.688674
474189cb93e70e600adff54f13b4ab2fc76b25b5
665
package io.github.edwinvanrooij.trackmyfuel.util; import android.content.Context; import com.orhanobut.hawk.Hawk; /** * Author: eddy * Date: 14-1-17. */ public class Preferences { public static void setValue(Context context, String key, Object value) { Hawk.init(context).build(); Hawk.put(key, value); } public static Object getValue(Context context, String key) { Hawk.init(context).build(); if (Hawk.contains(key)) { return Hawk.get(key); } return null; } public static void removeAll(Context context) { Hawk.init(context).build(); Hawk.deleteAll(); } }
22.166667
76
0.622556
f59007c87509dd1acaa69b32f7cadeba23237d08
1,177
package com.example.androidstudiotutorial; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class HomeActivity extends AppCompatActivity implements View.OnClickListener{ Button btnComplier,btnTutorial; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); btnComplier=(Button)findViewById(R.id.btnSqlCompiler); btnTutorial=(Button)findViewById(R.id.btnSqlTutorial); btnTutorial.setOnClickListener(this); btnComplier.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnSqlCompiler: { Intent send = new Intent(HomeActivity.this, MainActivity.class); startActivity(send); } case R.id.btnSqlTutorial: { Intent send = new Intent(HomeActivity.this, SQLTutorialActivity.class); startActivity(send); } } } }
31.810811
88
0.650807
a0ac586407f2c50453a009efe2508a91247bd09f
3,964
package me.gaigeshen.wechat.mp.message; import me.gaigeshen.wechat.mp.Config; import org.apache.commons.lang3.Validate; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.StringReader; /** * 抽象消息请求 * * @author gaigeshen */ public abstract class AbstractMessageRequest implements MessageRequest { private static final String MSG_TYPE_FIELD = "//MsgType"; private static final String MSG_EVENT_TYPE_FIELD = "//Event"; private static final String MSG_ENCRYPT_FIELD = "//Encrypt"; private final Config config; private final String timestamp; private final String nonce; private final String signature; private final Document messageBodyDocument; private Message message; private String encryptType; protected AbstractMessageRequest(Config config, String signature, String timestamp, String nonce, String messageBody, String encryptType) { this(config, signature, timestamp, nonce, messageBody); this.encryptType = encryptType; } protected AbstractMessageRequest(Config config, String signature, String timestamp, String nonce, String messageBody) { Validate.notNull(config, "config is required"); Validate.notBlank(signature, "signature is requried"); Validate.notBlank(timestamp, "timestamp is requried"); Validate.notBlank(nonce, "nonce is requried"); Validate.notBlank(messageBody, "messageBody is required"); if (!validateMessageSource(config, signature, timestamp, nonce)) { throw new IllegalArgumentException("Invalid signature of message body: " + messageBody); } this.config = config; this.signature = signature; this.timestamp = timestamp; this.nonce = nonce; try { this.messageBodyDocument = parseToDocument(messageBody); } catch (DocumentException e) { throw new IllegalArgumentException("Invalid message body: " + messageBody, e); } } /** * 校验消息签名 * * @param config 配置 * @param signature 待校验的签名 * @param timestamp 时间戳 * @param nonce 随机值 * @return 签名是否合法 */ private boolean validateMessageSource(Config config, String signature, String timestamp, String nonce) { return MessageSourceValidator.validate(config.getToken(), signature, timestamp, nonce); } @Override public final synchronized Message getMessage() { if (message == null) { // 取消息类型 Element node = (Element) messageBodyDocument.selectSingleNode(MSG_TYPE_FIELD); Validate.notNull(node, "Unable to determine message type from: " + messageBodyDocument); String messageType = node.getTextTrim(); if (isEventMessageType(messageType)) { // 如果消息类型是事件推送 // 则继续取事件类型 node = (Element) messageBodyDocument.selectSingleNode(MSG_EVENT_TYPE_FIELD); Validate.notNull(node, "Unable to determine event type from: " + messageBodyDocument); messageType = node.getTextTrim(); } // 得到的消息类型可能为事件类型,也有可能是普通消息类型 message = MessageRequestXmlUtils.parseToObject(messageBodyDocument, MessageTypeDeclarer.messageClassFromName(messageType)); } return message; } /** * 判断消息类型是否是事件类型,事件类型也属于消息类型 * * @param messageType 消息类型 * @return 是否是事件类型 */ private boolean isEventMessageType(String messageType) { return "event".equals(messageType); } private Document parseToDocument(String messageBody) throws DocumentException { Document document = parseToDocumentInternal(messageBody); Element node = (Element) document.selectSingleNode(MSG_ENCRYPT_FIELD); if (node != null) { String encrypted = node.getTextTrim(); String decrypted = new MessageCodecProcessor(config).decrypt(encrypted, true); document = parseToDocumentInternal(decrypted); } return document; } private Document parseToDocumentInternal(String content) throws DocumentException { return new SAXReader().read(new StringReader(content)); } }
33.59322
141
0.730071
968e0ca6e8a4e9427345d9c8bd878b83eefb32f6
515
package com.japlj.healthydiet.api; import com.japlj.healthydiet.food.FoodParameter; import net.minecraft.item.ItemFood; /* * 栄養素情報が設定された食料 */ public class ItemNutriousFood extends ItemFood { private final FoodParameter param; public ItemNutriousFood(float protein, float carbohydrate, float vitaMine, float satu, boolean feedWolves) { super(0, 0.0F, feedWolves); param = new FoodParameter(protein, carbohydrate, vitaMine, satu); } public FoodParameter getNutritionalValues() { return param; } }
23.409091
109
0.770874
3818631cbdb0aac1576a4d06b9b7394ca2632370
2,765
/* * Copyright (c) 2020. Yuriy Stul */ package com.stulsoft.rxjava.basics; import io.reactivex.rxjava3.core.Single; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author Yuriy Stul */ public class ConcatArrayEx2 { private static final Logger logger = LoggerFactory.getLogger(ConcatArrayEx2.class); public static void main(String[] args) { logger.info("==>main"); var concatArrayEx2 = new ConcatArrayEx2(); concatArrayEx2.test1(); logger.info("<==main"); } @SuppressWarnings("unchecked") private void test1() { logger.info("==>test1"); var counter = new CountDownLatch(1); Single<RunResult>[] array = new Single[]{run(sGood1()), run(sBad()), run(sGood2())}; var goodResults=new ArrayList<RunResult>(); var badResults=new ArrayList<RunResult>(); Single .concatArray(array) .doOnNext(rr -> { logger.info("rr: {}", rr); if (rr.isValid()) goodResults.add(rr); else badResults.add(rr); }) .last(new RunResult(false, "unknown")) .subscribe(rslt -> { logger.info("Good results: {}", goodResults); logger.info("Bad results: {}", badResults); counter.countDown(); }); try { if (counter.await(10, TimeUnit.SECONDS)) logger.info("Completed in time"); else logger.warn("Time expired"); } catch (Exception ignore) { } logger.info("<==test1"); } private Single<RunResult> run(Single<String> s) { return Single.create(source -> s.subscribe( rslt -> source.onSuccess(new RunResult(true, rslt)), err -> source.onSuccess(new RunResult(false, null)) )); } Single<String> sGood1() { return Single.timer(1, TimeUnit.SECONDS) .map(l -> { logger.info("==>sGood1"); return "From sGood1"; }); } Single<String> sGood2() { return Single.timer(1, TimeUnit.SECONDS) .map(l -> { logger.info("==>sGood2"); return "From sGood2"; }); } Single<String> sBad() { return Single.create(source -> { Single.timer(1, TimeUnit.SECONDS) .subscribe(l -> source.onError(new RuntimeException("error in sBad"))); }); } }
28.505155
92
0.517179
62b2e99b9bad37d92b6d72898329a2f20e6274fe
7,415
package project.pamela.slambench.activities; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.appcompat.BuildConfig; import android.text.Html; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import project.pamela.slambench.R; import project.pamela.slambench.SLAMBenchApplication; import project.pamela.slambench.models.SLAMMode; import project.pamela.slambench.utils.ConfigurationTask; import project.pamela.slambench.utils.MessageLog; import project.pamela.slambench.utils.MobileStats; import project.pamela.slambench.utils.RootUtil; /* * SLAMBench for Android * ********************* * Author: Bruno Bodin. * Copyright (c) 2015 University of Edinburgh. * Developed in the PAMELA project, EPSRC Programme Grant EP/K008730/1 * This code is licensed under the MIT License. */ public class MainActivity extends CommonActivity implements View.OnClickListener , ConfigurationTask.OnConfigurationTaskTerminateListener{ private static final int MIN_CACHE_SIZE = 200; private static boolean configuration_launched = false; private static boolean configuration_finished = false; Button _runButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(SLAMBenchApplication.LOG_TAG, getString(R.string.debug_oncreate_happened, this.getLocalClassName())); setContentView(R.layout.activity_main); _runButton = (Button) findViewById(R.id.runButton); TextView message = (TextView) findViewById(R.id.descriptionView); message.setMovementMethod(new ScrollingMovementMethod()); PackageInfo pInfo = null; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String text_msg = getResources().getString(R.string.app_description) + " "; text_msg += "This is the version " + (pInfo != null ? pInfo.versionName : "unknown") + " (" + BuildConfig.BUILD_TYPE + ") of the benchmark." + "<br/>"; text_msg += "<b>" + getString(R.string.app_warning) + "</b>" + "<br/>"; if (RootUtil.isDeviceRooted()) { text_msg += "<font color='red'> <b>" + getResources().getText(R.string.live_mode_available) + "</b></font>" + "<br/>"; } long need_size = MIN_CACHE_SIZE; long current_size = (MobileStats.getAvailableInternalMemorySize() + MobileStats.getUsedInternalMemorySize(this)) / (1024 * 1024); if (current_size < need_size) { text_msg += "<font color='red'> <b>" + getResources().getString(R.string.insufficient_memory, need_size, current_size) + "</b></font>" + "<br/>"; } message.setText(Html.fromHtml(text_msg + ""), TextView.BufferType.SPANNABLE); _runButton.setOnClickListener(this); Log.d(SLAMBenchApplication.LOG_TAG, "Main activity content constructed."); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.runButton: configuration_finished = false; configuration_launched = true; MessageLog.clear(); Log.d(SLAMBenchApplication.LOG_TAG, " Button push in the Main activity"); new ConfigurationTask(this.getApplication()).execute(); v.setEnabled(false); } } void selectMode () { if (SLAMBenchApplication.getBenchmark() == null) { openError(getString(R.string.error_fail_configuration_download)); return; } if (SLAMBenchApplication.getBenchmark().getAvailableModes().size() == 0) { openError(getString(R.string.error_fail_configuration_download)); return; } ArrayList names = new ArrayList(SLAMBenchApplication.getBenchmark().getAvailableModes().size()); for (SLAMMode m : SLAMBenchApplication.getBenchmark().getAvailableModes()) { names.add(m.get_name() + " (" + m.get_description() + ")"); } AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); LinearLayout llayout = new LinearLayout(this); ListView lv = new ListView(this); llayout.addView(lv); alertDialog.setView(llayout); alertDialog.setTitle(getString(R.string.title_select_mode)); alertDialog.setCancelable(false); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names); lv.setAdapter(adapter); final AlertDialog d = alertDialog.show(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) { MessageLog.addInfo(getString(R.string.msg_select_mode,SLAMBenchApplication.getBenchmark().getAvailableModes().get(position).get_name())); runBenchmarkMode(position); d.dismiss(); } }); } void runBenchmarkMode (final int position) { if (SLAMBenchApplication.getBenchmark() == null) { openError(getResources().getString(R.string.error_benchmark_not_found)); return; } if (SLAMBenchApplication.getCurrentTest() != null) { openError(getResources().getString(R.string.error_benchmark_in_progress)); return; } if (SLAMBenchApplication.getBenchmark().getMessage() != null) { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle(getString(R.string.title_information)); alertDialog.setMessage(SLAMBenchApplication.getBenchmark().getMessage()); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.button_start), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); SLAMBenchApplication.resetBenchmark(); Intent intent = new Intent(MainActivity.this, BenchmarkActivity.class); intent.putExtra(SLAMBenchApplication.SELECTED_MODE_TAG, position); startActivity(intent); } }); alertDialog.show(); } else { SLAMBenchApplication.resetBenchmark(); Intent intent = new Intent(this, BenchmarkActivity.class); intent.putExtra(SLAMBenchApplication.SELECTED_MODE_TAG, position); startActivity(intent); } } @Override public void onConfigurationTaskTerminate() { configuration_finished = true; _runButton.setEnabled(true); selectMode(); } }
36.348039
160
0.660283
bee4b0a97c2685eed18f0923ce92707caf9fb533
3,557
package io.github.incplusplus.betterstat.persistence.model; import java.math.BigDecimal; import java.time.LocalDateTime; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; public class StatusReport { @DBRef Thermostat thermostat; @NotNull @Id private String id; private String mostRecentIp; private LocalDateTime dateTimeAccordingToDevice; private LocalDateTime dateTimeReportReceived; private BigDecimal temperature; private States currentState; public StatusReport() {} public StatusReport( Thermostat thermostat, @NotNull String id, String mostRecentIp, LocalDateTime dateTimeAccordingToDevice, LocalDateTime dateTimeReportReceived, BigDecimal temperature, States currentState) { this.thermostat = thermostat; this.id = id; this.mostRecentIp = mostRecentIp; this.dateTimeAccordingToDevice = dateTimeAccordingToDevice; this.dateTimeReportReceived = dateTimeReportReceived; this.temperature = temperature; this.currentState = currentState; } public Thermostat getThermostat() { return thermostat; } public void setThermostat(Thermostat thermostat) { this.thermostat = thermostat; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMostRecentIp() { return mostRecentIp; } public void setMostRecentIp(String mostRecentIp) { this.mostRecentIp = mostRecentIp; } public LocalDateTime getDateTimeAccordingToDevice() { return dateTimeAccordingToDevice; } public void setDateTimeAccordingToDevice(LocalDateTime dateTimeAccordingToDevice) { this.dateTimeAccordingToDevice = dateTimeAccordingToDevice; } public LocalDateTime getDateTimeReportReceived() { return dateTimeReportReceived; } public void setDateTimeReportReceived(LocalDateTime dateTimeReportReceived) { this.dateTimeReportReceived = dateTimeReportReceived; } public BigDecimal getTemperature() { return temperature; } public void setTemperature(BigDecimal temperature) { this.temperature = temperature; } public States getCurrentState() { return currentState; } public void setCurrentState(States currentState) { this.currentState = currentState; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } StatusReport that = (StatusReport) o; return new EqualsBuilder() .append(getThermostat(), that.getThermostat()) .append(getId(), that.getId()) .append(getMostRecentIp(), that.getMostRecentIp()) .append(getDateTimeAccordingToDevice(), that.getDateTimeAccordingToDevice()) .append(getDateTimeReportReceived(), that.getDateTimeReportReceived()) .append(getTemperature(), that.getTemperature()) .append(getCurrentState(), that.getCurrentState()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getThermostat()) .append(getId()) .append(getMostRecentIp()) .append(getDateTimeAccordingToDevice()) .append(getDateTimeReportReceived()) .append(getTemperature()) .append(getCurrentState()) .toHashCode(); } }
26.94697
85
0.720832
0609cd8fc6d699dd6f38c44cf20b6aae6d776825
192
package com.solomatoff.jdbc; import org.junit.Test; public class StylizerTest { @Test public void whenStylizerRunTest() { Stylizer.stylizerRun("1.xsl", "1.xml"); } }
17.454545
47
0.651042
5eb4c4d9c0bd1b673c2b663386dd8fdc84cfa219
2,409
package org.mightyfish.openpgp; import java.io.IOException; import java.io.InputStream; import org.mightyfish.bcpg.HashAlgorithmTags; import org.mightyfish.bcpg.S2K; import org.mightyfish.util.io.Streams; /** * Utility functions for looking a S-expression keys. This class will move when it finds a better home! * <p> * Format documented here: * http://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=agent/keyformat.txt;h=42c4b1f06faf1bbe71ffadc2fee0fad6bec91a97;hb=refs/heads/master * </p> */ class SXprUtils { private static int readLength(InputStream in, int ch) throws IOException { int len = ch - '0'; while ((ch = in.read()) >= 0 && ch != ':') { len = len * 10 + ch - '0'; } return len; } static String readString(InputStream in, int ch) throws IOException { int len = readLength(in, ch); char[] chars = new char[len]; for (int i = 0; i != chars.length; i++) { chars[i] = (char)in.read(); } return new String(chars); } static byte[] readBytes(InputStream in, int ch) throws IOException { int len = readLength(in, ch); byte[] data = new byte[len]; Streams.readFully(in, data); return data; } static S2K parseS2K(InputStream in) throws IOException { skipOpenParenthesis(in); String alg = readString(in, in.read()); byte[] iv = readBytes(in, in.read()); final long iterationCount = Long.parseLong(readString(in, in.read())); skipCloseParenthesis(in); // we have to return the actual iteration count provided. S2K s2k = new S2K(HashAlgorithmTags.SHA1, iv, (int)iterationCount) { public long getIterationCount() { return iterationCount; } }; return s2k; } static void skipOpenParenthesis(InputStream in) throws IOException { int ch = in.read(); if (ch != '(') { throw new IOException("unknown character encountered"); } } static void skipCloseParenthesis(InputStream in) throws IOException { int ch = in.read(); if (ch != ')') { throw new IOException("unknown character encountered"); } } }
23.617647
147
0.572437
08cc595bb7eb6f1bf90128529a75cd68b7cecef1
4,682
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.common.config; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import com.google.inject.Inject; import io.druid.audit.AuditEntry; import io.druid.audit.AuditInfo; import io.druid.audit.AuditManager; import io.druid.common.config.ConfigManager.SetResult; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; /** */ public class JacksonConfigManager { private final ConfigManager configManager; private final ObjectMapper jsonMapper; private final AuditManager auditManager; @Inject public JacksonConfigManager( ConfigManager configManager, ObjectMapper jsonMapper, AuditManager auditManager ) { this.configManager = configManager; this.jsonMapper = jsonMapper; this.auditManager = auditManager; } public <T> AtomicReference<T> watch(String key, Class<? extends T> clazz) { return watch(key, clazz, null); } public <T> AtomicReference<T> watch(String key, Class<? extends T> clazz, T defaultVal) { return configManager.watchConfig(key, create(clazz, defaultVal)); } public <T> AtomicReference<T> watch(String key, TypeReference<T> clazz, T defaultVal) { return configManager.watchConfig(key, create(clazz, defaultVal)); } public <T> SetResult set(String key, T val, AuditInfo auditInfo) { ConfigSerde configSerde = create(val.getClass(), null); // Audit and actual config change are done in separate transactions // there can be phantom audits and reOrdering in audit changes as well. auditManager.doAudit( AuditEntry.builder() .key(key) .type(key) .auditInfo(auditInfo) .payload(configSerde.serializeToString(val)) .build() ); return configManager.set(key, configSerde, val); } private <T> ConfigSerde<T> create(final Class<? extends T> clazz, final T defaultVal) { return new ConfigSerde<T>() { @Override public byte[] serialize(T obj) { try { return jsonMapper.writeValueAsBytes(obj); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } @Override public String serializeToString(T obj) { try { return jsonMapper.writeValueAsString(obj); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } @Override public T deserialize(byte[] bytes) { if (bytes == null) { return defaultVal; } try { return jsonMapper.readValue(bytes, clazz); } catch (IOException e) { throw Throwables.propagate(e); } } }; } private <T> ConfigSerde<T> create(final TypeReference<? extends T> clazz, final T defaultVal) { return new ConfigSerde<T>() { @Override public byte[] serialize(T obj) { try { return jsonMapper.writeValueAsBytes(obj); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } @Override public String serializeToString(T obj) { try { return jsonMapper.writeValueAsString(obj); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } } @Override public T deserialize(byte[] bytes) { if (bytes == null) { return defaultVal; } try { return jsonMapper.readValue(bytes, clazz); } catch (IOException e) { throw Throwables.propagate(e); } } }; } }
27.22093
95
0.644383
7282263a311851852ba6bbdb0b95c46f9a9cdcae
3,808
/** * (C) Copyright ParaSoft Corporation 2010. All rights reserved. * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF ParaSoft * The copyright notice above does not evidence any * actual or intended publication of such source code. */ package com.github.sdarioo.testgen.recorder.values; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.*; import org.junit.Test; import com.github.sdarioo.testgen.generator.TestSuiteBuilder; import com.github.sdarioo.testgen.generator.source.TestMethod; public class SetValueTest { @Test public void testEquals() { Set<String> set = Collections.singleton("s1"); assertEquals(new SetValue(set), new SetValue(set)); assertNotEquals(new SetValue(set), new SetValue(new HashSet<String>())); } @SuppressWarnings("nls") @Test public void testEmptySet() throws Exception { TestSuiteBuilder builder = new TestSuiteBuilder(); SetValue p = new SetValue(new HashSet<String>()); assertEquals("Collections.emptySet()", p.toSourceCode(Set.class, builder)); Method m = getClass().getMethod("foo", Set.class); p = new SetValue(Collections.emptySet()); assertEquals("Collections.<String>emptySet()", p.toSourceCode(m.getGenericParameterTypes()[0], new TestSuiteBuilder())); } @Test public void testSupportedType() throws Exception { Method m = getClass().getMethod("foo", Set.class); SetValue p = new SetValue(Collections.emptySet()); assertTrue(p.isSupported(m.getGenericParameterTypes()[0], new HashSet<String>())); m = getClass().getMethod("foo3", TreeSet.class); p = new SetValue(new TreeSet<String>()); assertFalse(p.isSupported(m.getGenericParameterTypes()[0], new HashSet<String>())); } @Test public void testRawSet() throws Exception { SetValue p = new SetValue(Collections.singleton("x")); testSet(p, Set.class, "asSet(\"x\")", "private static <T> Set<T> asSet(T... elements) {"); } @Test public void testGenericSet() throws Exception { Method m = getClass().getMethod("foo", Set.class); SetValue p = new SetValue(Collections.singleton("x")); testSet(p, m.getGenericParameterTypes()[0], "asSet(\"x\")", "private static <T> Set<T> asSet(T... elements) {"); } @Test public void testWildcardSet() throws Exception { Method m = getClass().getMethod("foo1", Set.class); SetValue p = new SetValue(Collections.singleton("x")); testSet(p, m.getGenericParameterTypes()[0], "asSet(\"x\")", "private static <T> Set<T> asSet(T... elements) {"); } private void testSet(SetValue p, Type targetType, String sourceCode, String helperSignature) { TestSuiteBuilder builder = new TestSuiteBuilder(); assertEquals(sourceCode, p.toSourceCode(targetType, builder)); List<TestMethod> helperMethods = builder.getHelperMethods(); assertEquals(1, helperMethods.size()); assertEquals(helperSignature, getFirstLine(helperMethods.get(0).toSourceCode())); } private static String getFirstLine(String text) { return text.split("\\n")[0]; } // DONT REMOVE - USED IN TEST public void foo(Set<String> set) { } public static <T> void foo1(Set<T> set) { } public void foo2(Set<String[]> list) { } public void foo3(TreeSet set) { } }
33.403509
99
0.639706
605fc0ea019d5db8c3d9f1476d551422f022e4e2
1,009
package com.guosen.zebra.maven.plugin; import java.util.Map; import org.apache.commons.lang3.StringUtils; public final class CommonUtils { private CommonUtils(){ } public static String findPojoTypeFromCache(String sourceType, Map<String, String> pojoTypes) { if(sourceType.equals(".com.guosen.zebra.dto.RetMessage")){ return "com.guosen.zebra.dto.commondto.RetMessage"; }else if(sourceType.equals(".com.guosen.zebra.dto.ResultDTO")){ return "com.guosen.zebra.dto.commondto.ResultDTO"; }else if(sourceType.equals(".com.guosen.zebra.dto.ReturnDTO")){ return "com.guosen.zebra.dto.commondto.ResultDTO"; } String type = StringUtils.substring(sourceType, StringUtils.lastIndexOf(sourceType, ".") + 1); return pojoTypes.get(type); } public static String findNotIncludePackageType(String sourceType) { String type = StringUtils.substring(sourceType, StringUtils.lastIndexOf(sourceType, ".") + 1); return type; } }
32.548387
102
0.70664
e206a232ac55616c75f101e3199b6eee106ae05f
8,829
/* * Copyright 2019 xuelf. * * 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.cointda.dao; import lombok.extern.slf4j.Slf4j; import org.cointda.bean.CoinMarketCapIdBean; import org.cointda.bean.TradeDataBean; import org.cointda.bean.property.TradeDataFXC; import org.cointda.pool.DBHelper; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * @author xuelf */ @Slf4j public class TradeDataDao { public TradeDataDao() { } /** * @param bean 1 * @Description: 插入一条数据 * @return: java.lang.Integer 返回插入行的id * @author: mapleaf * @date: 2020/6/23 18:16 */ public static Integer insert(TradeDataBean bean) { String sql = "insert into tab_tradeinfo" + "(base_id,base_symbol,quote_id,quote_symbol," + "sale_or_buy,price,base_num,quote_num,trade_date) " + "values (?,?,?,?,?,?,?,?,?)"; BigDecimal dec = DBHelper.insert(sql, getInsertParam(bean)); return Integer.valueOf(dec.toBigInteger().toString()); } private static Object[] getInsertParam(TradeDataBean bean) { Object[] param = new Object[9]; param[0] = bean.getBase_id(); param[1] = bean.getBase_symbol(); param[2] = bean.getQuote_id(); param[3] = bean.getQuote_symbol(); param[4] = bean.getSale_or_buy(); param[5] = bean.getPrice(); param[6] = bean.getBase_num(); param[7] = bean.getQuote_num(); param[8] = bean.getTrade_date(); return param; } /** * @param list 1 * @Description: 批量插入数据 * @return: int[] * @author: mapleaf * @date: 2020/6/23 18:16 */ public static int[] batchInsert(List<String[]> list) { String sql = "insert into tab_tradeinfo" + "(base_id,base_symbol,quote_id,quote_symbol," + "sale_or_buy,price,base_num,quote_num,trade_date) " + "values (?,?,?,?,?,?,?,?,?)"; Object[][] params = new Object[list.size()][]; // 组织params for (int i = 0; i < list.size(); i++) { String[] bean = list.get(i); Object[] param = new Object[9]; param[0] = bean[1]; param[1] = bean[2]; param[2] = bean[3]; param[3] = bean[4]; param[4] = bean[5]; param[5] = bean[6]; param[6] = bean[7]; param[7] = bean[8]; param[8] = bean[9]; params[i] = param; } return DBHelper.batch(sql, params); } /** * @param bean 1 * @Description: 修改一条数据 * @return: int * @author: mapleaf * @date: 2020/6/23 18:17 */ public static int update(TradeDataBean bean) { String sql = "update tab_tradeinfo set " + "base_id=?,base_symbol=?,quote_id=?,quote_symbol=?," + "sale_or_buy=?,price=?,base_num=?,quote_num=?,trade_date=? " + "where id=?"; Object[] param = new Object[10]; param[0] = bean.getBase_id(); param[1] = bean.getBase_symbol(); param[2] = bean.getQuote_id(); param[3] = bean.getQuote_symbol(); param[4] = bean.getSale_or_buy(); param[5] = bean.getPrice(); param[6] = bean.getBase_num(); param[7] = bean.getQuote_num(); param[8] = bean.getTrade_date(); param[9] = bean.getId(); return DBHelper.update(sql, param); } /** * @param bean 1 * @Description: 删除一条数据 * @return: int * @author: mapleaf * @date: 2020/6/23 18:17 */ public static int delete(TradeDataBean bean) { return delete(bean.getId()); } public static int delete(Integer id) { String sql = "delete from tab_tradeinfo" + " where id=?"; return DBHelper.update(sql, id); } /** * @Description: 删除全部数据 * @return: boolean * @author: mapleaf * @date: 2020/6/23 18:17 */ public static boolean truncate() { String sql = "TRUNCATE TABLE tab_tradeinfo"; return DBHelper.update(sql) == 0; } /** * @param id 1 * @Description: 查询一条数据 * @return: org.cointda.bean.TradeDataBean * @author: mapleaf * @date: 2020/6/23 18:17 */ public static TradeDataBean queryBean(Integer id) { String sql = "select * from tab_tradeinfo where id=?"; return DBHelper.queryBean(TradeDataBean.class, sql, id); } /** * @param symbol 1 * @Description: 根据简称查询coin信息 * @return: org.cointda.bean.CoinMarketCapIdBean * @author: mapleaf * @date: 2020/6/23 18:18 */ public static CoinMarketCapIdBean queryCoinBySymbol(String symbol) { String sql = "select * from TAB_CoinMarketCap_id_map where symbol=?"; return DBHelper.queryBean(CoinMarketCapIdBean.class, sql, symbol); } /** * 查询全部交易数据 * * @return 返回 list */ public static List<TradeDataBean> queryAll() { String sql = "select * from tab_tradeinfo order by id"; return DBHelper.queryList(TradeDataBean.class, sql); } public static List<TradeDataFXC> queryAllFXC(String symbol) { String sql = "select * from tab_tradeinfo where base_symbol=? order by id DESC"; List<TradeDataBean> list = DBHelper.queryList(TradeDataBean.class, sql, symbol); List<TradeDataFXC> fxcList = new ArrayList<>(); list.stream() .map( (bean) -> { TradeDataFXC fxc = new TradeDataFXC(); fxc.setId(bean.getId()); fxc.setCoinId(bean.getBase_id()); fxc.setSymbolPairs(bean.getBase_symbol() + "/" + bean.getQuote_symbol()); fxc.setSaleOrBuy(bean.getSale_or_buy()); fxc.setPrice(bean.getPrice()); fxc.setBaseNum(bean.getBase_num()); fxc.setQuoteNum(bean.getQuote_num()); fxc.setDate(bean.getTrade_date()); return fxc; }) .forEachOrdered((fxc) -> fxcList.add(fxc)); return fxcList; } public static List<TradeDataFXC> queryAllFXCForCash(String symbol) { String sql = "select * from tab_tradeinfo where base_symbol=? order by id DESC"; List<TradeDataBean> list = DBHelper.queryList(TradeDataBean.class, sql, symbol); List<TradeDataFXC> fxcList = new ArrayList<>(); list.stream() .map( (bean) -> { TradeDataFXC fxc = new TradeDataFXC(); fxc.setId(bean.getId()); fxc.setCoinId(bean.getBase_id()); fxc.setSymbolPairs(bean.getBase_symbol()); if (bean.getSale_or_buy().equals("卖")) { fxc.setSaleOrBuy("入金"); } else { fxc.setSaleOrBuy("出金"); } fxc.setPrice(bean.getPrice()); fxc.setBaseNum(bean.getBase_num()); fxc.setQuoteNum(bean.getQuote_num()); fxc.setDate(bean.getTrade_date()); return fxc; }) .forEachOrdered((fxc) -> fxcList.add(fxc)); return fxcList; } public static void main(String[] args) { TradeDataBean bean = new TradeDataBean(); List<TradeDataBean> list = new ArrayList<>(); bean.setBase_id(1); bean.setBase_symbol("BTC"); bean.setQuote_id(825); bean.setQuote_symbol("USTD"); bean.setSale_or_buy("买"); bean.setPrice("7455.001"); bean.setBase_num("1.000"); bean.setQuote_num("7455.001"); bean.setTrade_date("2019-12-09"); for (int i = 0; i < 15; i++) { list.add(bean); } log.info("size = " + list.size()); // CoinListingDao dao = new CoinListingDao(); TradeDataDao.truncate(); // log.info(TradeDataDao.batchInsert(list).length); // log.info(TradeDataDao.insert(bean)); // TradeDataBean coin2 = TradeDataDao.queryBean(1); // log.info(coin2); // TradeDataDao.delete(coin2); } }
32.821561
93
0.557821
f3777a52abbece7c175383e3b0d43f8c5a9dce71
433
package com.ag.testapplication; import android.app.Application; import com.ag.lfm.Lfm; public class TestApplication extends Application { @Override public void onCreate() { super.onCreate(); //Initialize here. Lfm.initializeWithSecret(this); //You can initialize without secret,but remember that you cannot use methods that require authentication. //Lfm.initialize(this); } }
22.789474
113
0.692841
f6cb8b3046143bc4bf6aee820e91e6d012a968f2
15,013
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.jaxws; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.dom.DOMSource; import javax.xml.ws.BindingProvider; import javax.xml.ws.EndpointReference; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; import javax.xml.ws.wsaddressing.W3CEndpointReference; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.apache.cxf.BusFactory; import org.apache.cxf.helpers.DOMUtils; import org.apache.cxf.jaxws.spi.ProviderImpl; import org.apache.cxf.staxutils.StaxUtils; import org.apache.hello_world_soap_http.Greeter; import org.apache.hello_world_soap_http.GreeterImpl; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class EndpointReferenceTest extends AbstractJaxWsTest { private final QName serviceName = new QName("http://apache.org/hello_world_soap_http", "SOAPService"); private final QName portName = new QName("http://apache.org/hello_world_soap_http", "SoapPort"); @Before public void setUp() throws Exception { } @Test public void testBindingProviderSOAPBinding() throws Exception { javax.xml.ws.Service s = javax.xml.ws.Service .create(new QName("http://apache.org/hello_world_soap_http", "SoapPort")); assertNotNull(s); Greeter greeter = s.getPort(Greeter.class); BindingProvider bindingProvider = (BindingProvider)greeter; EndpointReference er = bindingProvider.getEndpointReference(); assertNotNull(er); //If the BindingProvider instance has a binding that is either SOAP 1.1/HTTP or SOAP //1.2/HTTP, then a W3CEndpointReference MUST be returned. assertTrue(er instanceof W3CEndpointReference); } @Test public void testBindingProviderSOAPBindingStaicService() throws Exception { org.apache.hello_world_soap_http.SOAPService s = new org.apache.hello_world_soap_http.SOAPService(); Greeter greeter = s.getPort(Greeter.class); BindingProvider bindingProvider = (BindingProvider)greeter; EndpointReference er = bindingProvider.getEndpointReference(); assertNotNull(er); //If the BindingProvider instance has a binding that is either SOAP 1.1/HTTP or SOAP //1.2/HTTP, then a W3CEndpointReference MUST be returned. assertTrue(er instanceof W3CEndpointReference); } @Test public void testBindingProviderXMLBindingStaticService() throws Exception { org.apache.hello_world_xml_http.bare.XMLService s = new org.apache.hello_world_xml_http.bare.XMLService(); org.apache.hello_world_xml_http.bare.Greeter greeter = s.getXMLPort(); BindingProvider bindingProvider = (BindingProvider)greeter; //If the binding is XML/HTTP an java.lang.UnsupportedOperationException MUST be thrown. try { bindingProvider.getEndpointReference(); fail("Did not get expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { //do nothing } } /* * Any JAX-WS supported epr metadata MUST match the Service instances * ServiceName, otherwise a WebServiceExeption MUST be thrown. Any JAX-WS * supported epr metadata MUST match the PortName for the sei, otherwise a * WebServiceException MUST be thrown. If the Service instance has an * associated WSDL, its WSDL MUST be used to determine any binding * information, anyWSDL in a JAX-WS suppported epr metadata MUST be ignored. * If the Service instance does not have a WSDL, then any WSDL inlined in * the JAX-WS supported metadata of the epr MUST be used to determine * binding information. If there is not enough metadata in the Service * instance or in the epr metadata to determine a port, then a * WebServiceException MUST be thrown. */ @Test public void testServiceGetPortUsingEndpointReference() throws Exception { BusFactory.setDefaultBus(getBus()); GreeterImpl greeter1 = new GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) { endpoint.publish("http://localhost:8080/test"); javax.xml.ws.Service s = javax.xml.ws.Service .create(new QName("http://apache.org/hello_world_soap_http", "SoapPort")); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); DOMSource erXML = new DOMSource(doc); EndpointReference endpointReference = EndpointReference.readFrom(erXML); WebServiceFeature[] wfs = new WebServiceFeature[] {}; Greeter greeter = s.getPort(endpointReference, Greeter.class, wfs); String response = greeter.greetMe("John"); assertEquals("Hello John", response); } } @Test public void testEndpointReferenceGetPort() throws Exception { BusFactory.setDefaultBus(getBus()); GreeterImpl greeter1 = new GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) { endpoint.publish("http://localhost:8080/test"); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); DOMSource erXML = new DOMSource(doc); EndpointReference endpointReference = EndpointReference.readFrom(erXML); WebServiceFeature[] wfs = new WebServiceFeature[] {}; Greeter greeter = endpointReference.getPort(Greeter.class, wfs); String response = greeter.greetMe("John"); assertEquals("Hello John", response); } } @Test public void testEndpointGetEndpointReferenceSOAPBinding() throws Exception { GreeterImpl greeter = new GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter, (String)null)) { endpoint.publish("http://localhost:8080/test"); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); Element referenceParameters = fetchElementByNameAttribute(doc.getDocumentElement(), "wsa:ReferenceParameters", ""); EndpointReference endpointReference = endpoint.getEndpointReference(referenceParameters); assertNotNull(endpointReference); assertTrue(endpointReference instanceof W3CEndpointReference); //A returned W3CEndpointReferenceMUST also contain the specified referenceParameters. //W3CEndpointReference wer = (W3CEndpointReference)endpointReference; endpoint.stop(); } } @Test public void testEndpointGetEndpointReferenceXMLBinding() throws Exception { org.apache.hello_world_xml_http.bare.Greeter greeter = new org.apache.hello_world_xml_http.bare.GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter, (String)null)) { endpoint.publish("http://localhost:8080/test"); try { InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); Element referenceParameters = fetchElementByNameAttribute(doc.getDocumentElement(), "wsa:ReferenceParameters", ""); endpoint.getEndpointReference(referenceParameters); fail("Did not get expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { //do nothing } endpoint.stop(); } } @Test public void testEndpointGetEndpointReferenceW3C() throws Exception { GreeterImpl greeter = new GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter, (String)null)) { endpoint.publish("http://localhost:8080/test"); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); Element referenceParameters = fetchElementByNameAttribute(doc.getDocumentElement(), "wsa:ReferenceParameters", ""); EndpointReference endpointReference = endpoint.getEndpointReference(W3CEndpointReference.class, referenceParameters); assertNotNull(endpointReference); assertTrue(endpointReference instanceof W3CEndpointReference); //A returned W3CEndpointReferenceMUST also contain the specified referenceParameters. //W3CEndpointReference wer = (W3CEndpointReference)endpointReference; endpoint.stop(); } } @Test public void testEndpointGetEndpointReferenceInvalid() throws Exception { GreeterImpl greeter = new GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter, (String)null)) { endpoint.publish("http://localhost:8080/test"); try { InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); Element referenceParameters = fetchElementByNameAttribute(doc.getDocumentElement(), "wsa:ReferenceParameters", ""); endpoint.getEndpointReference(MyEndpointReference.class, referenceParameters); fail("Did not get expected WebServiceException"); } catch (WebServiceException e) { // do nothing } endpoint.stop(); } } @Test public void testProviderReadEndpointReference() throws Exception { ProviderImpl provider = new ProviderImpl(); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); DOMSource erXML = new DOMSource(doc); EndpointReference endpointReference = provider.readEndpointReference(erXML); assertNotNull(endpointReference); assertTrue(endpointReference instanceof W3CEndpointReference); } @Test public void testProviderCreateW3CEndpointReference() throws Exception { ProviderImpl provider = new ProviderImpl(); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); Element referenceParameter = fetchElementByNameAttribute(doc.getDocumentElement(), "wsa:ReferenceParameters", ""); List<Element> referenceParameters = new ArrayList<>(); if (referenceParameter != null) { referenceParameters.add(referenceParameter); } Element metadata = fetchElementByNameAttribute(doc.getDocumentElement(), "wsa:metadata", ""); List<Element> metadataList = new ArrayList<>(); if (metadata != null) { metadataList.add(metadata); } W3CEndpointReference endpointReference = provider .createW3CEndpointReference("http://localhost:8080/test", serviceName, portName, metadataList, "wsdlDocumentLocation", referenceParameters); assertNotNull(endpointReference); } @Test public void testProviderGetPort() throws Exception { BusFactory.setDefaultBus(getBus()); GreeterImpl greeter1 = new GreeterImpl(); try (EndpointImpl endpoint = new EndpointImpl(getBus(), greeter1, (String)null)) { endpoint.publish("http://localhost:8080/test"); ProviderImpl provider = new ProviderImpl(); InputStream is = getClass().getResourceAsStream("resources/hello_world_soap_http_infoset.xml"); Document doc = StaxUtils.read(is); DOMSource erXML = new DOMSource(doc); EndpointReference endpointReference = EndpointReference.readFrom(erXML); WebServiceFeature[] wfs = new WebServiceFeature[] {}; Greeter greeter = provider.getPort(endpointReference, Greeter.class, wfs); String response = greeter.greetMe("John"); assertEquals("Hello John", response); } } final class MyEndpointReference extends EndpointReference { protected MyEndpointReference() { } public void writeTo(Result result) { // NOT_IMPLEMENTED } } public static Element fetchElementByNameAttribute(Element parent, String elementName, String nameValue) { if (elementName.equals(parent.getTagName()) && parent.getAttribute("name").equals(nameValue)) { return parent; } Element elem = DOMUtils.getFirstElement(parent); while (elem != null) { Element el = fetchElementByNameAttribute(elem, elementName, nameValue); if (el != null) { return el; } elem = DOMUtils.getNextElement(elem); } return null; } }
42.290141
111
0.64997
c1028101dcb31f304bd6dff38077add2b58ab9c1
364
package com.zerobase.fastlms.course.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.zerobase.fastlms.course.dto.CourseDto; import com.zerobase.fastlms.course.model.CourseParam; @Mapper public interface CourseMapper { List<CourseDto> selectList(CourseParam courseParam); long selectListCount(CourseParam courseParam); }
24.266667
53
0.824176
8973bb118375dcaa224efe87d394a02342ff1fb3
2,995
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.validator; import org.openmrs.Field; import org.openmrs.annotation.Handler; import org.openmrs.api.APIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; /** * Validator for {@link Field} class * * @since 1.10 */ @Handler(supports = { Field.class }, order = 50) public class FieldValidator implements Validator { private static final Logger log = LoggerFactory.getLogger(FieldValidator.class); /** * Returns whether or not this validator supports validating a given class. * * @param c The class to check for support. * @see org.springframework.validation.Validator#supports(java.lang.Class) */ @Override public boolean supports(Class<?> c) { if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + ".supports: " + c.getName()); } return Field.class.isAssignableFrom(c); } /** * Validates the given Field. * Ensures that the field name is present and valid * * @param obj The Field to validate. * @param errors Errors * @see org.springframework.validation.Validator#validate(java.lang.Object, * org.springframework.validation.Errors) * @should fail if field name is null * @should fail if field name is empty * @should fail if field name is all whitespace * @should fail if selectMultiple is null * @should fail if retired is null * @should pass if name is ok and fieldType, selectMultiple, and retired are non-null * @should pass validation if field lengths are correct * @should fail validation if field lengths are not correct * should not fail if fieldType is null */ @Override public void validate(Object obj, Errors errors) throws APIException { if (log.isDebugEnabled()) { log.debug(this.getClass().getName() + ".validate..."); } if (obj == null || !(obj instanceof Field)) { throw new IllegalArgumentException("The parameter obj should not be null and must be of type " + Field.class); } Field field = (Field) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.null", "Field name is required"); if (field.getSelectMultiple() == null) { errors.rejectValue("selectMultiple", "error.general"); } if (field.getRetired() == null) { errors.rejectValue("retired", "error.general"); } ValidateUtil.validateFieldLengths(errors, obj.getClass(), "name", "tableName", "attributeName", "retireReason"); } }
35.235294
114
0.722871
4a8e4ccdedab93f3b9a027211698fe157f117509
1,644
package com.tvajjala.web.resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tvajjala.exception.ServiceException; import com.tvajjala.persistence.vo.User; import com.tvajjala.web.service.UserService; /** * It is combination of two annotations @Controller and @ResponseBody * * @author ThirupathiReddy V * */ @RestController @RequestMapping(value = "/user", produces = { "application/json" }) public class UserResource { @Autowired private UserService userService; @RequestMapping(value = "/username/{username}", method = RequestMethod.GET) public ResponseEntity<User> getUserByUsername(@PathVariable String username) { System.out.println("Reading user with username : " + username); final User user = userService.getUserByUsername(username); if (user == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } else { return new ResponseEntity<User>(user, HttpStatus.OK); } } @RequestMapping(method = RequestMethod.POST, value = "/save", consumes = { "application/json" }) public ResponseEntity<User> saveUser(User user) throws ServiceException { userService.saveUser(user); return new ResponseEntity<User>(HttpStatus.CREATED); } }
31.018868
100
0.739051
cc2fff1c8ba669158b64e2573eb2b1cad69fc2a3
25,759
package it.polimi.ingsw.server.model.player.board; import it.polimi.ingsw.network.jsonutils.JsonUtility; import it.polimi.ingsw.server.model.*; import it.polimi.ingsw.server.model.cards.DevelopmentCard; import it.polimi.ingsw.server.model.cards.DevelopmentCardColor; import it.polimi.ingsw.server.model.cards.production.Production; import it.polimi.ingsw.server.model.cards.production.ProductionCardCell; import javafx.util.Pair; import org.junit.Before; import org.junit.Test; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import static org.junit.Assert.*; public class PersonalBoardTest { PersonalBoard board; @Before public void setUp() { board = new PersonalBoard(); board.addDevelopmentCardToCell(new DevelopmentCard( 0, DevelopmentCardColor.GREEN, new Production(new int[]{2,1},new int[]{0,1})), 1); board.addDevelopmentCardToCell(new DevelopmentCard( 0, DevelopmentCardColor.BLUE, new Production(new int[]{20,1,1},new int[]{0,1})), 2); board.addDevelopmentCardToCell(new DevelopmentCard( 1, DevelopmentCardColor.PURPLE, new Production(new int[]{1},new int[]{2,0,0,0,1,1,1})), 1); board.addProduction(new Production(new int[]{0,1,1},new int[]{1,0,0,1,1})); Pair[] pa = Stream.of( new Pair<>(0,Resource.SERVANT), new Pair<>(2,Resource.GOLD), new Pair<>(5,Resource.SHIELD) ).toArray(Pair[]::new); board.getWarehouseLeadersDepots().addResources(pa); board.getStrongBox().addResources(new int[]{5,15,2}); board.getDiscardBox().addResources(new int[]{3,2,1,3}); } public void setUpCorrectly() { //Test Empty PersonalBoard emptyBoard = new PersonalBoard(); assertFalse(emptyBoard.playerHasSixOrMoreCards()); assertArrayEquals(new Boolean[]{false}, emptyBoard.getSelectedProduction()); assertArrayEquals(new Boolean[]{false}, emptyBoard.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,true,true}, emptyBoard.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(0,emptyBoard.getFaithToAdd()); assertEquals(0,emptyBoard.getBadFaithToAdd()); assertEquals(Optional.empty(),emptyBoard.firstProductionSelectedWithChoice()); //Test storage units setup assertArrayEquals(new int[]{0,0,0,0},Resource.getStream(4).mapToInt((a)->emptyBoard.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{0,0,0,0},Resource.getStream(4).mapToInt((a)->emptyBoard.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{0,0,0,0},Resource.getStream(4).mapToInt(emptyBoard::getNumberOf).toArray()); assertEquals(0,emptyBoard.numOfResources()); assertEquals( JsonUtility.toPrettyFormat("{0:[{key:EMPTY,value:false}]," + "1:[{key:EMPTY,value:false},{key:EMPTY,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:EMPTY,value:false}]}"), emptyBoard.getWarehouseLeadersDepots().structuredTableJson()); //Test board assertFalse(board.playerHasSixOrMoreCards()); assertArrayEquals(new Boolean[]{false,false,false,false}, board.getSelectedProduction()); assertArrayEquals(new Boolean[]{true,true,false,true}, board.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); //Test depot setup assertArrayEquals(new int[]{5,15,2,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{6,5,4,6},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{6,16,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertEquals(25,board.numOfResources()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:false}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); } @Test public void testProduction() { board.addProduction(new Production(new int[]{4,8,0,0,0,0,1},new int[]{0,0,1,0,2,3,1})); assertArrayEquals(new Boolean[]{true,false,true,false,true,true}, board.getAvailableProductions()); //Select first production board.selectProductionAt(5); board.performChoiceOnInput(-8); board.performChoiceOnOutput(Resource.STONE); board.getStrongBox().selectN(4,Resource.GOLD); board.getStrongBox().selectN(7,Resource.SERVANT); board.getWarehouseLeadersDepots().selectResourceAt(0); assertArrayEquals(new int[]{5,7,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals( JsonUtility.toPrettyFormat("{0:[{key:SERVANT,value:true}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); assertEquals(0, board.remainingToSelectForProduction()); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); //Select second production board.selectProductionAt(2); assertNotEquals(Optional.empty(), board.firstProductionSelectedWithChoice()); assertEquals(1, board.remainingToSelectForProduction()); board.getWarehouseLeadersDepots().selectResourceAt(2); assertEquals(0, board.remainingToSelectForProduction()); board.performChoiceOnOutput(Resource.STONE); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); assertArrayEquals(new int[]{5,7,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:true}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:true}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson() ); //Production board.produce(); assertArrayEquals(new Boolean[]{false,false,false,false,false,false}, board.getSelectedProduction()); assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(3,board.getFaithToAdd()); assertEquals(4,board.getBadFaithToAdd()); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); assertArrayEquals(new int[]{2,8,3,2},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{2,8,4,2},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertEquals(16,board.numOfResources()); assertArrayEquals(new int[]{0,0,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:EMPTY,value:false}]," + "1:[{key:EMPTY,value:false},{key:EMPTY,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); } @Test public void setFaithToZero() { board.addProduction(new Production(new int[]{4,8,0,0,0,0,1},new int[]{1,2,1,3,3,4,1})); board.selectProductionAt(5); board.performChoiceOnInput(-8); board.performChoiceOnOutput(Resource.STONE); board.getStrongBox().selectN(4,Resource.GOLD); board.getStrongBox().selectN(7,Resource.SERVANT); board.getWarehouseLeadersDepots().selectResourceAt(0); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); board.produce(); assertEquals(3,board.getFaithToAdd()); assertEquals(4,board.getBadFaithToAdd()); board.setFaithToZero(); assertEquals(0,board.getFaithToAdd()); assertEquals(4,board.getBadFaithToAdd()); } @Test public void setBadFaithToZero() { board.addProduction(new Production(new int[]{4,8,0,0,0,0,1},new int[]{1,2,1,3,5,5})); board.selectProductionAt(5); board.performChoiceOnOutput(Resource.STONE); board.getStrongBox().selectN(4,Resource.GOLD); board.getStrongBox().selectN(7,Resource.SERVANT); board.getWarehouseLeadersDepots().selectResourceAt(0); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); board.produce(); assertEquals(5,board.getFaithToAdd()); assertEquals(5,board.getBadFaithToAdd()); board.setBadFaithToZero(); assertEquals(5,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); } @Test public void testChoices() { board.selectProductionAt(0); //Perform choice on input board.performChoiceOnInput(-7); assertArrayEquals(new Boolean[]{true,false,false,false,false,false}, board.getSelectedProduction()); assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); assertArrayEquals(new int[]{5,15,2,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{3,2,1,3},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{6,16,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertEquals(25,board.numOfResources()); assertArrayEquals(new int[]{0,1,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:false}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); //Perform choice on input board.performChoiceOnInput(2); assertArrayEquals(new Boolean[]{true,false,false,false,false,false}, board.getSelectedProduction()); assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); assertArrayEquals(new int[]{5,15,2,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{3,2,1,3},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{6,16,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertEquals(25,board.numOfResources()); assertArrayEquals(new int[]{0,1,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:false}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:true}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); //Perform choice on output board.performChoiceOnOutput(Resource.STONE); assertArrayEquals(new Boolean[]{true,false,false,false,false,false}, board.getSelectedProduction()); assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); board.selectProductionAt(2); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); assertArrayEquals(new int[]{5,15,2,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{3,2,1,3},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{6,16,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertEquals(25,board.numOfResources()); assertArrayEquals(new int[]{0,1,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:false}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:true}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); //Perform choice on output board.performChoiceOnOutput(Resource.GOLD); assertArrayEquals(new Boolean[]{true,false,true,false,false,false}, board.getSelectedProduction()); assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); assertArrayEquals( new Boolean[]{true,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); assertArrayEquals(new int[]{5,15,2,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{3,2,1,3},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{6,16,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertEquals(25,board.numOfResources()); assertArrayEquals(new int[]{0,1,0,0},Resource.getStream(4).mapToInt((a)->board.getStrongBox().getNSelected(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:false}]," + "1:[{key:EMPTY,value:false},{key:GOLD,value:true}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); } @Test public void resetChoices(){ board.selectProductionAt(0); board.performChoiceOnInput(-8); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); board.performChoiceOnOutput(Resource.STONE); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); board.resetChoices(); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); board.performChoiceOnInput(-8); board.performChoiceOnInput(-6); board.performChoiceOnOutput(Resource.STONE); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); board.selectProductionAt(2); assertNotEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); board.performChoiceOnOutput(Resource.GOLD); assertEquals(Optional.empty(),board.firstProductionSelectedWithChoice()); } @Test public void getAvailableProductions() { assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); board.getStrongBox().addResources(new int[]{100,0,0,0}); assertArrayEquals(new Boolean[]{true,false,true,true,true,false}, board.getAvailableProductions()); board.getStrongBox().removeResources(new int[]{105,0,0,0}); assertArrayEquals(new Boolean[]{true,false,true,false,true,false}, board.getAvailableProductions()); board.getWarehouseLeadersDepots().removeResource(2); assertArrayEquals(new Boolean[]{true,false,false,false,true,false}, board.getAvailableProductions()); board.getStrongBox().removeResources(new int[]{0,15,1,0}); assertArrayEquals(new Boolean[]{true,false,false,false,true,false}, board.getAvailableProductions()); board.getWarehouseLeadersDepots().removeResource(0); assertEquals(2,board.numOfResources()); assertArrayEquals(new Boolean[]{true,false,false,false,false,false}, board.getAvailableProductions()); board.getStrongBox().removeResources(new int[]{0,0,1,0}); assertEquals(1,board.numOfResources()); assertArrayEquals(new Boolean[]{false,false,false,false,false,false}, board.getAvailableProductions()); } @Test public void testProductionSelection() { board.addProduction(new Production(new int[]{1,2},new int[]{0,1})); board.addProduction(new Production(new int[]{0,1,1},new int[]{1})); assertArrayEquals(new Boolean[]{false,false,false,false,false,false,false}, board.getSelectedProduction()); board.toggleSelectProductionAt(0); assertArrayEquals(new Boolean[]{true,false,false,false,false,false,false}, board.getSelectedProduction()); board.selectProductionAt(1); assertArrayEquals(new Boolean[]{true,false,false,false,false,false,false}, board.getSelectedProduction()); board.toggleSelectProductionAt(1); board.toggleSelectProductionAt(5); assertArrayEquals(new Boolean[]{true,false,false,false,false,true,false}, board.getSelectedProduction()); board.deselectProductionAt(2); board.selectProductionAt(1); board.selectProductionAt(4); board.selectProductionAt(5); assertArrayEquals(new Boolean[]{true,false,false,false,true,true,false}, board.getSelectedProduction()); board.resetSelectedProductions(); assertArrayEquals(new Boolean[]{false,false,false,false,false,false,false}, board.getSelectedProduction()); } @Test public void addProduction() { Production p = new Production(new int []{},new int[]{0,0,0,0,0,0,1}); board.addProduction(p); assertEquals(6, board.getSelectedProduction().length); board.performChoiceOnInput(-9); board.performChoiceOnInput(-7); board.performChoiceOnOutput(Resource.STONE); board.performChoiceOnOutput(Resource.GOLD); assertNotEquals(Optional.of(p),board.firstProductionSelectedWithChoice()); board.selectProductionAt(5); assertEquals(Optional.of(p),board.firstProductionSelectedWithChoice()); assertArrayEquals(p.getOutputs(),board.firstProductionSelectedWithChoice().get().getOutputs()); } @Test public void addDevelopmentCardToCell() { Production p = new Production(new int []{},new int[]{0,0,0,0,0,0,1}); DevelopmentCard card4 = new DevelopmentCard(1,DevelopmentCardColor.GREEN,p); board.addDevelopmentCardToCell(card4,0); assertArrayEquals( new Boolean[]{false,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertFalse(board.playerHasSixOrMoreCards()); DevelopmentCard addedCard = board.getCardCells().get(0).getFrontCard(); assertEquals(card4,addedCard); DevelopmentCard card5 = new DevelopmentCard(1,DevelopmentCardColor.BLUE,p); DevelopmentCard card6 = new DevelopmentCard(2,DevelopmentCardColor.PURPLE,p); DevelopmentCard card7 = new DevelopmentCard(2,DevelopmentCardColor.GREEN,p); board.addDevelopmentCardToCell(card5,2); assertFalse(board.playerHasSixOrMoreCards()); board.addDevelopmentCardToCell(card6,1); assertTrue(board.playerHasSixOrMoreCards()); board.addDevelopmentCardToCell(card7,0); assertTrue(board.playerHasSixOrMoreCards()); assertArrayEquals( new Boolean[]{false,false,false}, board.getCardCells().stream().map(ProductionCardCell::getFrontCard).map(Objects::isNull).toArray()); assertTrue(board.playerHasSixOrMoreCards()); DevelopmentCard addedCard0 = board.getCardCells().get(0).getFrontCard(); assertEquals(card7,addedCard0); assertTrue(board.playerHasSixOrMoreCards()); DevelopmentCard addedCard1 = board.getCardCells().get(1).getFrontCard(); assertEquals(card6,addedCard1); assertTrue(board.playerHasSixOrMoreCards()); DevelopmentCard addedCard2 = board.getCardCells().get(2).getFrontCard(); assertEquals(card5,addedCard2); } @Test public void discardResources() { Box discardBox = Box.discardBox(); discardBox.addResources(new int[]{12,3,4,5,7}); //Set marketBox board.setMarketBox(discardBox); assertEquals(discardBox,board.getDiscardBox()); assertArrayEquals(new int[]{12,3,4,5,7},Resource.getStream(5).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertArrayEquals(new int[]{0,0,0,0,0},Resource.getStream(5).mapToInt((a)->board.getDiscardBox().getNSelected(a)).toArray()); assertEquals(0,board.getFaithToAdd()); assertEquals(0,board.getBadFaithToAdd()); discardBox.removeResources(new int[]{2,0,1,0}); assertArrayEquals(new int[]{10,3,3,5,7},Resource.getStream(5).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); //Discard market box board.discardResources(); assertEquals(7,board.getFaithToAdd()); assertEquals(21,board.getBadFaithToAdd()); } public void testMove() { //From box to warehouse board.move(-4,1); assertArrayEquals(new int[]{7,16,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertArrayEquals(new int[]{5,5,4,6},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SERVANT,value:false}]," + "1:[{key:GOLD,value:false},{key:GOLD,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); //From warehouse to box board.move(0,-3); assertArrayEquals(new int[]{7,15,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertArrayEquals(new int[]{5,6,4,6},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:EMPTY,value:false}]," + "1:[{key:GOLD,value:false},{key:GOLD,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:SHIELD,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); //Between Warehouse board.move(5,0); assertArrayEquals(new int[]{7,15,3,0},Resource.getStream(4).mapToInt(board::getNumberOf).toArray()); assertArrayEquals(new int[]{5,6,4,6},Resource.getStream(4).mapToInt((a)->board.getDiscardBox().getNumberOf(a)).toArray()); assertEquals(JsonUtility.toPrettyFormat( "{0:[{key:SHIELD,value:false}]," + "1:[{key:GOLD,value:false},{key:GOLD,value:false}]," + "2:[{key:EMPTY,value:false},{key:EMPTY,value:false},{key:EMPTY,value:false}]}"), board.getWarehouseLeadersDepots().structuredTableJson()); } }
57.497768
135
0.661982
e2398f37dde120b86f1a9f57dc359a924b82fcdb
9,147
package ru.job4j.logic; import org.apache.commons.dbcp2.BasicDataSource; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * @author Alexander Belov (whiterabbit.nsk@gmail.com) * @since 06.09.18 * Класс-слушатель развертывает БД и таблицы. */ public class DBConnect implements ServletContextListener { private BasicDataSource sourceForServletsDB; private BasicDataSource sourceForMusicCourtDB; private BasicDataSource sourceForInitDB; /** * Инициализирует Базы данных и таблицы в них в соответствии с настройками дескриптора развертывания. * @param sce */ @Override public void contextInitialized(final ServletContextEvent sce) { ServletContext context = sce.getServletContext(); String driver = context.getInitParameter("SQLDriver"); String url = context.getInitParameter("url"); String user = context.getInitParameter("user"); String password = context.getInitParameter("password"); String dbName = context.getInitParameter("dbName"); String mcDBName = context.getInitParameter("mcDBName"); this.sourceForServletsDB = getSource(driver, url + dbName, user, password); this.sourceForMusicCourtDB = getSource(driver, url + mcDBName, user, password); this.sourceForInitDB = getSource(driver, url, user, password); initDB(dbName); initDB(mcDBName); DBStore.getInstance().init(sourceForServletsDB); MCStore.getInstance().init(sourceForMusicCourtDB); } /** * Создает пул коннектов. * @param url БД * @return пул коннектов */ private BasicDataSource getSource(final String driver, final String url, final String user, final String password) { BasicDataSource source = new BasicDataSource(); source.setDriverClassName(driver); source.setUrl(url); source.setUsername(user); source.setPassword(password); source.setMinIdle(5); source.setMaxIdle(10); source.setMaxOpenPreparedStatements(100); return source; } /** * Класс проверяет наличие БД. Если ее не обнаружено - содает новую БД и таблицы. * @param db имя БД */ private void initDB(final String db) { String sql = String.format( "SELECT EXISTS(SELECT datname FROM pg_catalog.pg_database WHERE datname = '%s');", db ); try (Connection conn = sourceForInitDB.getConnection()) { ResultSet rs = conn.createStatement().executeQuery(sql); Statement st = conn.createStatement(); rs.next(); boolean haveBase = rs.getBoolean(1); if (!haveBase) { sql = String.format("CREATE database %s", db); st.executeUpdate(sql); if (db.equals("servlets_db")) { createTableUsers(); } else if (db.equals("music_court")) { createTablesForMC(); } } rs.close(); st.close(); } catch (Exception e) { e.printStackTrace(); } } /** * Создает таблицу users в БД servlets_db. */ private void createTableUsers() { StringBuilder sb = new StringBuilder("CREATE TABLE users") .append("(id integer PRIMARY KEY, user_name varchar(30), login varchar(30), ") .append("email varchar(30), password varchar(20), createDate date, role varchar(5), ") .append("city varchar(30), country varchar(30));"); try (Connection conn = sourceForServletsDB.getConnection()) { Statement st = conn.createStatement(); st.executeUpdate(sb.toString()); String sql = "INSERT INTO users(id, user_name, login, email, password, createDate, role, city, country)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, 0); ps.setString(2, "alexander"); ps.setString(3, "admin"); ps.setString(4, "example@mail.com"); ps.setString(5, "123"); ps.setDate(6, new Date(System.currentTimeMillis())); ps.setString(7, "admin"); ps.setString(8, "Norilsk"); ps.setString(9, "Russia"); ps.execute(); st.close(); ps.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * Создает в БД music_court таблицы music, roles, address, users, music_pref. */ private void createTablesForMC() throws SQLException { //todo: переделать на Prepared Statement List<String> updates = new ArrayList<>(); updates.add("CREATE TABLE music(id serial PRIMARY KEY, name varchar(20), UNIQUE(name));"); updates.add("CREATE TABLE roles(id serial PRIMARY KEY, name varchar(20), UNIQUE(name));"); updates.add("CREATE TABLE addresses(id serial PRIMARY KEY, name varchar(100), UNIQUE (name))"); updates.add("CREATE TABLE users(id integer PRIMARY KEY, login varchar(30), " + "password varchar(20), address_id integer REFERENCES addresses(id), " + "role_id integer REFERENCES roles(id), UNIQUE(login));"); updates.add("CREATE TABLE music_pref(user_id integer REFERENCES users(id), " + "music_id integer REFERENCES music(id), CONSTRAINT pk PRIMARY KEY(user_id, music_id));"); executeUpdates(updates); fillTablesForMC(); } /** * Заполняет таблицы roles, music, addresses, users, music_pref. */ private void fillTablesForMC() throws SQLException { Connection conn = sourceForMusicCourtDB.getConnection(); String sql = "INSERT INTO roles(name) VALUES(?), (?), (?);"; Object[] values = new String[]{"admin", "mandatory", "user"}; prepareStatement(sql, values, conn); sql = "INSERT INTO music(name) VALUES(?), (?), (?), (?), (?);"; values = new String[]{"rock", "rap", "drum & bass", "jazz", "classic"}; prepareStatement(sql, values, conn); sql = "INSERT INTO addresses(name) VALUES(?);"; values = new String[]{"Russia, Norilsk"}; prepareStatement(sql, values, conn); sql = "INSERT INTO users(id, login, password, address_id, role_id) VALUES(?, ?, ?, ?, ?);"; values = new Object[]{0, "admin", "123", 1, 1}; prepareStatement(sql, values, conn); sql = "INSERT INTO music_pref(user_id, music_id) VALUES(0, ?);"; values = new Integer[]{1}; prepareStatement(sql, values, conn); conn.close(); } /** * Выполняет список запросов. * @param updates список запросов */ private void executeUpdates(final List<String> updates) { try (Connection connection = sourceForMusicCourtDB.getConnection()) { Statement st = connection.createStatement(); for (String sql : updates) { st.executeUpdate(sql); } st.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * Выполняет запрос, связанный с инициализацией таблиц. * @param query sql-запрос * @param values список используемых в запросе значений * @param conn соединение с БД */ private void prepareStatement(String query, Object[] values, Connection conn) throws SQLException { PreparedStatement ps = conn.prepareStatement(query); for (int i = 0; i < values.length; i++) { ps.setObject(i + 1, values[i]); } ps.execute(); ps.close(); } @Override public void contextDestroyed(final ServletContextEvent sce) { try { cleanTablesMC(); cleanTableUsers(); } catch (SQLException e) { e.printStackTrace(); } } /** * Удаляет из БД servlets_db всех пользователей, кроме администратора. */ private void cleanTableUsers() throws SQLException { try (Connection conn = sourceForServletsDB.getConnection()) { Statement st = conn.createStatement(); st.executeUpdate("DELETE FROM users WHERE id != 0;"); st.close(); } } /** * Удаляет из БД music_court все данные, кроме заданных по умолчанию. */ private void cleanTablesMC() throws SQLException { try (Connection connection = sourceForMusicCourtDB.getConnection()) { Statement st = connection.createStatement(); st.executeUpdate("DELETE FROM music_pref WHERE user_id > 0;"); st.executeUpdate("DELETE FROM users WHERE id > 0;"); st.executeUpdate("DELETE FROM roles WHERE id > 3;"); st.executeUpdate("DELETE FROM music WHERE id > 5;"); st.executeUpdate("DELETE FROM addresses WHERE id > 1;"); st.close(); } } }
38.758475
120
0.601509
43f722635ff5b170e32ebebd1e3399a6c22404f0
992
package org.usfirst.frc1123.RecycleRushCode.subsystems; import org.usfirst.frc1123.RecycleRushCode.Robot; import org.usfirst.frc1123.RecycleRushCode.RobotMap; import org.usfirst.frc1123.RecycleRushCode.commands.*; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.CANTalon;; public class Wings extends Subsystem { public CANTalon innerwing = RobotMap.innerWings; public CANTalon outerwing = RobotMap.outerWings; public DoubleSolenoid left = RobotMap.leftSolenoid; public DoubleSolenoid right = RobotMap.rightSolenoid; public void initDefaultCommand() { setDefaultCommand(new StopWings()); } public void stopWings() { innerwing.set(0); outerwing.set(0); } public void setInner(double d) { innerwing.set(d); } public void setOuter(double d) { outerwing.set(d); } public DoubleSolenoid getLeftSolenoid() { return left; } public DoubleSolenoid getRightSolenoid() { return right; } }
19.45098
55
0.760081
6b4eb636e8d7f4c89cb1a0014cd794f46ece6db7
6,079
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.river.test.impl.fiddler.joinadmin; import java.util.logging.Level; import org.apache.river.test.spec.discoveryservice.AbstractBaseTest; import org.apache.river.test.share.GroupsUtil; import org.apache.river.test.share.JoinAdminUtil; import org.apache.river.qa.harness.QAConfig; import org.apache.river.qa.harness.TestException; import net.jini.admin.JoinAdmin; import net.jini.discovery.DiscoveryGroupManagement; import java.util.ArrayList; import org.apache.river.qa.harness.AbstractServiceAdmin; import org.apache.river.qa.harness.Test; /** * This class determines whether or not the lookup discovery service can * successfully remove a set of groups from the set of groups with which * it has been configured to join. * * This test attempts to remove a finite set of groups from a finite set of * groups, where <i>finite</i> means: * <p> * 'not <code>net.jini.discovery.DiscoveryGroupManagement.ALL_GROUPS</code>' * 'not <code>net.jini.discovery.DiscoveryGroupManagement.NO_GROUPS</code>'. * <p> * In addition to verifying the capabilities of the service with respect to * group addition, this test also verifies that the <code>removeGroups</code> * method of the <code>net.jini.discovery.DiscoveryGroupManagement</code> * interface functions as specified. That is, * <p> * "The <code>removeGroups</code> method deletes a set of group names from * the managed set of groups." * * * @see <code>net.jini.discovery.DiscoveryGroupManagement</code> */ public class RemoveLookupGroups extends AbstractBaseTest { String[] removeGroupSet = null; private String[] expectedGroups = null; /** Constructs and returns the set of groups to remove (can be * overridden by sub-classes) */ String[] getTestGroupSet() { AbstractServiceAdmin admin = (AbstractServiceAdmin) getManager().getAdmin(discoverySrvc); return GroupsUtil.getSubset(admin.getGroups()); } /** Performs actions necessary to prepare for execution of the * current test. * * Starts one lookup discovery service, and then constructs the set * of groups that should be expected after removing a set of groups. */ public Test construct(QAConfig config) throws Exception { super.construct(config); removeGroupSet = getTestGroupSet(); AbstractServiceAdmin admin = (AbstractServiceAdmin) getManager().getAdmin(discoverySrvc); if (admin == null) { return this; } String[] configGroups = admin.getGroups(); /* Construct the set of groups expected after removal by selecting * each element from the set of groups with which the service is * currently configured that were not selected for removal. */ if(configGroups == DiscoveryGroupManagement.ALL_GROUPS){ logger.log(Level.FINE, "expectedGroups = UnsupportedOperationException"); } else {//configGroups != DiscoveryGroupManagement.ALL_GROUPS if(removeGroupSet == DiscoveryGroupManagement.ALL_GROUPS) { logger.log(Level.FINE, "expectedGroups = NullPointerException"); } else {//removeGroupSet & configGroups != ALL_GROUPS ArrayList eList = new ArrayList(); iLoop: for(int i=0;i<configGroups.length;i++) { for(int j=0;j<removeGroupSet.length;j++) { if(configGroups[i].equals(removeGroupSet[j])) { continue iLoop; } } eList.add(configGroups[i]); } expectedGroups = (String[])(eList).toArray(new String[eList.size()]); GroupsUtil.displayGroupSet(expectedGroups, "expectedGroups", Level.FINE); } } return this; } /** Executes the current test by doing the following: * * 1. Retrieves the admin instance of the service under test. * 2. Through the admin, removes from the service's current set of groups * the indicated set of groups to join * 3. Through the admin, retrieves the set of groups that the service * is now configured to join. * 4. Determines if the set of groups retrieved through the admin is * equivalent to the expected set of groups */ public void run() throws Exception { logger.log(Level.FINE, "run()"); if(discoverySrvc == null) { throw new TestException("could not successfully start service " + serviceName); } JoinAdmin joinAdmin = JoinAdminUtil.getJoinAdmin(discoverySrvc); String[] oldGroups = joinAdmin.getLookupGroups(); GroupsUtil.displayGroupSet(oldGroups, "oldGroups", Level.FINE); GroupsUtil.displayGroupSet(removeGroupSet, "removeGroups", Level.FINE); joinAdmin.removeLookupGroups(removeGroupSet); String[] newGroups = joinAdmin.getLookupGroups(); GroupsUtil.displayGroupSet(newGroups, "newGroups", Level.FINE); if (!GroupsUtil.compareGroupSets(expectedGroups,newGroups,Level.FINE)) { throw new TestException("Group sets are not equivalent"); } } }
40.258278
80
0.67725
ff92ea2e963a06419444a1ae5d3af5ac1ae0b5fe
706
package io.pckt.restc.contract; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.rest.client.annotation.ClientHeaderParam; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; @Path("/api/json") @RegisterRestClient(baseUri = WorldClockApi.BASE_URL) public interface WorldClockApi { static final String BASE_URL = "http://worldclockapi.com/api/json"; @GET @Path("/utc/now") @Produces(MediaType.APPLICATION_JSON) Now utc(); @GET @Path("{tz}/now") @Produces(MediaType.APPLICATION_JSON) Now tz(@PathParam("tz") String tz); }
26.148148
73
0.740793
a403c81984c9f3192137738460c406e98ea1983f
4,278
/* * citygson - A Gson based library for parsing and serializing CityJSON * https://github.com/citygml4j/citygson * * citygson is part of the citygml4j project * * Copyright 2018-2019 Claus Nagel <claus.nagel@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.citygml4j.cityjson.metadata; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class LineageType { private String statement; private String scope; private String additionalDocumentation; private List<String> featureIDs; private List<String> thematicModels; @SerializedName("source") private List<SourceType> sources; private ProcessStepType processStep; public boolean isSetStatement() { return statement != null; } public String getStatement() { return statement; } public void setStatement(String statement) { this.statement = statement; } public void unsetStatement() { statement = null; } public boolean isSetScope() { return scope != null; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public void unsetScope() { scope = null; } public boolean isSetAdditionalDocumentation() { return additionalDocumentation != null; } public String getAdditionalDocumentation() { return additionalDocumentation; } public void setAdditionalDocumentation(String additionalDocumentation) { if (additionalDocumentation != null && additionalDocumentation.matches("^(https?|ftp)://.*")) this.additionalDocumentation = additionalDocumentation; } public void unsetAdditionalDocumentation() { additionalDocumentation = null; } public boolean isSetFeatureIDs() { return featureIDs != null && !featureIDs.isEmpty(); } public List<String> getFeatureIDs() { return featureIDs; } public void addFeatureID(String featureID) { if (featureIDs == null) featureIDs = new ArrayList<>(); featureIDs.add(featureID); } public void setFeatureID(List<String> featureIDs) { this.featureIDs = featureIDs; } public void unsetFeatureIDs() { featureIDs = null; } public boolean isSetThematicModels() { return thematicModels != null; } public List<String> getThematicModels() { return thematicModels; } public void addThematicModel(String thematicModel) { if (thematicModels == null) { thematicModels = new ArrayList<>(); } thematicModels.add(thematicModel); } public void setThematicModels(List<String> thematicModels) { this.thematicModels = thematicModels; } public void unsetThematicModels() { thematicModels = null; } public boolean isSetSources() { return sources != null; } public List<SourceType> getSources() { return sources; } public void addSource(SourceType source) { if (sources == null) sources = new ArrayList<>(); sources.add(source); } public void setSources(List<SourceType> sources) { this.sources = sources; } public void unsetSources() { sources = null; } public boolean isSetProcessStep() { return processStep != null; } public ProcessStepType getProcessStep() { return processStep; } public void setProcessStep(ProcessStepType processStep) { this.processStep = processStep; } public void unsetProcessStep() { processStep = null; } }
24.586207
101
0.654979
ae5ec41c9360339daed0df5b80b616d7793b942a
5,454
package org.plugins.simplefreeze.managers; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.plugins.simplefreeze.SimpleFreezeMain; /** * Created by Rory on 3/2/2017. */ public class SoundManager { private final SimpleFreezeMain plugin; private Sound freezeSound; private float freezeVolume; private float freezePitch; private Sound unfreezeSound; private float unfreezeVolume; private float unfreezePitch; public SoundManager(SimpleFreezeMain plugin) { this.plugin = plugin; String freezeString = this.plugin.getConfig().getString("freeze-sound.sound"); try { this.freezeSound = Sound.valueOf(this.plugin.getConfig().getString("freeze-sound.sound")); } catch (IllegalArgumentException e) { if (freezeString.startsWith("BLOCK_") && freezeString.length() > 6) { this.freezeSound = Sound.valueOf(freezeString.substring(6)); } else { Bukkit.getConsoleSender().sendMessage(this.plugin.placeholders("[SimpleFreeze] &c&lERROR: &7Invalid freeze sound: &c" + freezeString)); } } String unfreezeString = this.plugin.getConfig().getString("unfreeze-sound.sound"); try { this.unfreezeSound = Sound.valueOf(unfreezeString); } catch (IllegalArgumentException e) { if (unfreezeString.startsWith("BLOCK_") && unfreezeString.length() > 6) { this.unfreezeSound = Sound.valueOf(unfreezeString.substring(6)); } else { Bukkit.getConsoleSender().sendMessage(this.plugin.placeholders("[SimpleFreeze] &c&lERROR: &7Invalid unfreeze sound: &c" + unfreezeString)); } } this.freezeVolume = (float) this.plugin.getConfig().getDouble("freeze-sound.volume"); this.freezePitch = (float) this.plugin.getConfig().getDouble("freeze-sound.pitch"); this.unfreezeVolume = (float) this.plugin.getConfig().getDouble("unfreeze-sound.volume"); this.unfreezePitch = (float) this.plugin.getConfig().getDouble("unfreeze-sound.pitch"); } public void reset() { String freezeString = this.plugin.getConfig().getString("freeze-sound.sound"); try { this.freezeSound = Sound.valueOf(this.plugin.getConfig().getString("freeze-sound.sound")); } catch (IllegalArgumentException e) { if (freezeString.startsWith("BLOCK_") && freezeString.length() > 6) { this.freezeSound = Sound.valueOf(freezeString.substring(6)); } else { Bukkit.getConsoleSender().sendMessage(this.plugin.placeholders("[SimpleFreeze] &c&lERROR: &7Invalid freeze sound: &c" + freezeString)); } } String unfreezeString = this.plugin.getConfig().getString("unfreeze-sound.sound"); try { this.unfreezeSound = Sound.valueOf(unfreezeString); } catch (IllegalArgumentException e) { if (unfreezeString.startsWith("BLOCK_") && unfreezeString.length() > 6) { this.unfreezeSound = Sound.valueOf(unfreezeString.substring(6)); } else { Bukkit.getConsoleSender().sendMessage(this.plugin.placeholders("[SimpleFreeze] &c&lERROR: &7Invalid unfreeze sound: &c" + unfreezeString)); } } this.freezeVolume = (float) this.plugin.getConfig().getDouble("freeze-sound.volume"); this.freezePitch = (float) this.plugin.getConfig().getDouble("freeze-sound.pitch"); this.unfreezeVolume = (float) this.plugin.getConfig().getDouble("unfreeze-sound.volume"); this.unfreezePitch = (float) this.plugin.getConfig().getDouble("unfreeze-sound.pitch"); } public void playFreezeSound(Player p) { if (this.freezeSound != null) { p.playSound(p.getLocation().clone().add(0, 2, 0), this.freezeSound, this.freezeVolume, this.freezePitch); } } public void playUnfreezeSound(Player p) { if (this.unfreezeSound != null) { p.playSound(p.getLocation().clone().add(0, 2, 0), this.unfreezeSound, this.unfreezeVolume, this.unfreezePitch); } } public boolean setFreezeSound(String soundString) { try { this.freezeSound = Sound.valueOf(soundString); } catch (IllegalArgumentException e) { if (soundString.startsWith("BLOCK_") && soundString.length() > 6) { this.freezeSound = Sound.valueOf(soundString.substring(6)); } return false; } return true; } public boolean setUnfreezeSound(String soundString) { try { this.unfreezeSound = Sound.valueOf(soundString); } catch (IllegalArgumentException e) { if (soundString.startsWith("BLOCK_") && soundString.length() > 6) { this.unfreezeSound = Sound.valueOf(soundString.substring(6)); } return false; } return true; } public void setFreezeVolume(float freezeVolume) { this.freezeVolume = freezeVolume; } public void setUnfreezeVolume(float unfreezeVolume) { this.unfreezeVolume = unfreezeVolume; } public void setFreezePitch(float freezePitch) { this.freezePitch = freezePitch; } public void setUnfreezePitch(float unfreezePitch) { this.unfreezePitch = unfreezePitch; } }
39.521739
155
0.638431
c0b5a9c6dad2681fdb3edb577232683f0fccb9ad
13,007
/* * Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. */ /* * Calculation * You use the Calculation service for SAP Omnichannel Promotion Pricing in your sales channel application to determine the effective sales prices by applying promotional rules in the relevant customer context. The service can be called for a single product or for an entire shopping cart. The calculation is based on the data you uploaded to the cloud environment, and sends back prices and additional information about customer rewards to the calling application. * * OpenAPI spec version: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sap.cloud.sdk.generated.promopricing.model; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.sap.cloud.sdk.generated.promopricing.model.ItemID; import com.sap.cloud.sdk.generated.promopricing.model.MerchSetType; import com.sap.cloud.sdk.generated.promopricing.model.PriceDerivationRuleBase; import com.sap.cloud.sdk.generated.promopricing.model.QuantityCommonData; import com.sap.cloud.sdk.generated.promopricing.model.QuantityDifference; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import java.io.Serializable; import com.google.gson.annotations.SerializedName; import javax.annotation.Nonnull; /** * A flavor of a line item whereby customers have a product for free in the basket. This line item is used in the response */ @ApiModel(description = "A flavor of a line item whereby customers have a product for free in the basket. This line item is used in the response ") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") // CHECKSTYLE:OFF public class AdditionalBonusDiscountType // CHECKSTYLE:ON { @JsonProperty("any") @SerializedName("any") private List<Object> any = new ArrayList<>(); @JsonProperty("AdditionalBonusID") @SerializedName("AdditionalBonusID") private String additionalBonusID; @JsonProperty("ItemID") @SerializedName("ItemID") private ItemID itemID; @JsonProperty("TotalGrantedQuantity") @SerializedName("TotalGrantedQuantity") private QuantityCommonData totalGrantedQuantity; @JsonProperty("QuantityDifference") @SerializedName("QuantityDifference") private QuantityDifference quantityDifference; @JsonProperty("MerchandiseSet") @SerializedName("MerchandiseSet") private MerchSetType merchandiseSet; @JsonProperty("PriceDerivationRule") @SerializedName("PriceDerivationRule") private PriceDerivationRuleBase priceDerivationRule; /** * Set the any of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param any This is currently not supported. * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType any(@Nonnull final List<Object> any) { this.any = any; return this; } /** * Add one Any instance to this {@link AdditionalBonusDiscountType}. * @param anyItem The Any that should be added * @return The same instance of type {@link AdditionalBonusDiscountType} */ @Nonnull public AdditionalBonusDiscountType addAnyItem( @Nonnull final Object anyItem) { if (this.any == null) { this.any = new ArrayList<>(); } this.any.add(anyItem); return this; } /** * This is currently not supported. * @return any The any of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "This is currently not supported.") @Nonnull public List<Object> getAny() { return any; } /** * Set the any of this {@link AdditionalBonusDiscountType} instance. * * @param any This is currently not supported. */ public void setAny( @Nonnull final List<Object> any) { this.any = any; } /** * Set the additionalBonusID of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param additionalBonusID The additionalBonusID of this {@link AdditionalBonusDiscountType} * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType additionalBonusID(@Nonnull final String additionalBonusID) { this.additionalBonusID = additionalBonusID; return this; } /** * Get additionalBonusID * @return additionalBonusID The additionalBonusID of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "") @Nonnull public String getAdditionalBonusID() { return additionalBonusID; } /** * Set the additionalBonusID of this {@link AdditionalBonusDiscountType} instance. * * @param additionalBonusID The additionalBonusID of this {@link AdditionalBonusDiscountType} */ public void setAdditionalBonusID( @Nonnull final String additionalBonusID) { this.additionalBonusID = additionalBonusID; } /** * Set the itemID of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param itemID The itemID of this {@link AdditionalBonusDiscountType} * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType itemID(@Nonnull final ItemID itemID) { this.itemID = itemID; return this; } /** * Get itemID * @return itemID The itemID of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "") @Nonnull public ItemID getItemID() { return itemID; } /** * Set the itemID of this {@link AdditionalBonusDiscountType} instance. * * @param itemID The itemID of this {@link AdditionalBonusDiscountType} */ public void setItemID( @Nonnull final ItemID itemID) { this.itemID = itemID; } /** * Set the totalGrantedQuantity of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param totalGrantedQuantity The totalGrantedQuantity of this {@link AdditionalBonusDiscountType} * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType totalGrantedQuantity(@Nonnull final QuantityCommonData totalGrantedQuantity) { this.totalGrantedQuantity = totalGrantedQuantity; return this; } /** * Get totalGrantedQuantity * @return totalGrantedQuantity The totalGrantedQuantity of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "") @Nonnull public QuantityCommonData getTotalGrantedQuantity() { return totalGrantedQuantity; } /** * Set the totalGrantedQuantity of this {@link AdditionalBonusDiscountType} instance. * * @param totalGrantedQuantity The totalGrantedQuantity of this {@link AdditionalBonusDiscountType} */ public void setTotalGrantedQuantity( @Nonnull final QuantityCommonData totalGrantedQuantity) { this.totalGrantedQuantity = totalGrantedQuantity; } /** * Set the quantityDifference of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param quantityDifference The quantityDifference of this {@link AdditionalBonusDiscountType} * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType quantityDifference(@Nonnull final QuantityDifference quantityDifference) { this.quantityDifference = quantityDifference; return this; } /** * Get quantityDifference * @return quantityDifference The quantityDifference of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "") @Nonnull public QuantityDifference getQuantityDifference() { return quantityDifference; } /** * Set the quantityDifference of this {@link AdditionalBonusDiscountType} instance. * * @param quantityDifference The quantityDifference of this {@link AdditionalBonusDiscountType} */ public void setQuantityDifference( @Nonnull final QuantityDifference quantityDifference) { this.quantityDifference = quantityDifference; } /** * Set the merchandiseSet of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param merchandiseSet The merchandiseSet of this {@link AdditionalBonusDiscountType} * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType merchandiseSet(@Nonnull final MerchSetType merchandiseSet) { this.merchandiseSet = merchandiseSet; return this; } /** * Get merchandiseSet * @return merchandiseSet The merchandiseSet of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "") @Nonnull public MerchSetType getMerchandiseSet() { return merchandiseSet; } /** * Set the merchandiseSet of this {@link AdditionalBonusDiscountType} instance. * * @param merchandiseSet The merchandiseSet of this {@link AdditionalBonusDiscountType} */ public void setMerchandiseSet( @Nonnull final MerchSetType merchandiseSet) { this.merchandiseSet = merchandiseSet; } /** * Set the priceDerivationRule of this {@link AdditionalBonusDiscountType} instance and return the same instance. * * @param priceDerivationRule The priceDerivationRule of this {@link AdditionalBonusDiscountType} * @return The same instance of this {@link AdditionalBonusDiscountType} class */ @Nonnull public AdditionalBonusDiscountType priceDerivationRule(@Nonnull final PriceDerivationRuleBase priceDerivationRule) { this.priceDerivationRule = priceDerivationRule; return this; } /** * Get priceDerivationRule * @return priceDerivationRule The priceDerivationRule of this {@link AdditionalBonusDiscountType} instance. **/ @ApiModelProperty(value = "") @Nonnull public PriceDerivationRuleBase getPriceDerivationRule() { return priceDerivationRule; } /** * Set the priceDerivationRule of this {@link AdditionalBonusDiscountType} instance. * * @param priceDerivationRule The priceDerivationRule of this {@link AdditionalBonusDiscountType} */ public void setPriceDerivationRule( @Nonnull final PriceDerivationRuleBase priceDerivationRule) { this.priceDerivationRule = priceDerivationRule; } @Override public boolean equals(@Nonnull final java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final AdditionalBonusDiscountType additionalBonusDiscountType = (AdditionalBonusDiscountType) o; return Objects.equals(this.any, additionalBonusDiscountType.any) && Objects.equals(this.additionalBonusID, additionalBonusDiscountType.additionalBonusID) && Objects.equals(this.itemID, additionalBonusDiscountType.itemID) && Objects.equals(this.totalGrantedQuantity, additionalBonusDiscountType.totalGrantedQuantity) && Objects.equals(this.quantityDifference, additionalBonusDiscountType.quantityDifference) && Objects.equals(this.merchandiseSet, additionalBonusDiscountType.merchandiseSet) && Objects.equals(this.priceDerivationRule, additionalBonusDiscountType.priceDerivationRule); } @Override public int hashCode() { return Objects.hash(any, additionalBonusID, itemID, totalGrantedQuantity, quantityDifference, merchandiseSet, priceDerivationRule); } @Override @Nonnull public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("class AdditionalBonusDiscountType {\n"); sb.append(" any: ").append(toIndentedString(any)).append("\n"); sb.append(" additionalBonusID: ").append(toIndentedString(additionalBonusID)).append("\n"); sb.append(" itemID: ").append(toIndentedString(itemID)).append("\n"); sb.append(" totalGrantedQuantity: ").append(toIndentedString(totalGrantedQuantity)).append("\n"); sb.append(" quantityDifference: ").append(toIndentedString(quantityDifference)).append("\n"); sb.append(" merchandiseSet: ").append(toIndentedString(merchandiseSet)).append("\n"); sb.append(" priceDerivationRule: ").append(toIndentedString(priceDerivationRule)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(final java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
37.592486
465
0.749212
c1cec467fa8648a232119b14995d1f327a0676c6
1,947
/* * Copyright 2017 Antonio Vieiro (antonio@vieiro.net) * * 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.nbdemo.gui.features.model; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; /** * * @author antonio */ public class NetBeansPlatformFeatureListIO { public static final NetBeansPlatformFeatureList read() throws IOException { InputStream input = NetBeansPlatformFeatureListIO.class.getResourceAsStream("nbp-features.yml"); if (input == null) { return new NetBeansPlatformFeatureList(); } Yaml yaml = new Yaml(new Constructor(NetBeansPlatformFeatureList.class)); NetBeansPlatformFeatureList featureList = yaml.load(input); input.close(); return featureList; } static void write(NetBeansPlatformFeatureList list, PrintStream out) { PrintWriter pw = new PrintWriter(out); DumperOptions options = new DumperOptions(); options.setAllowUnicode(true); options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setDefaultScalarStyle(DumperOptions.ScalarStyle.LITERAL); Yaml yaml = new Yaml(options); yaml.dump(list, pw); pw.flush(); } }
35.4
104
0.725218
ece478eb9759e97b475a14d607f57ea021669bda
7,455
/******************************************************************************* * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license *******************************************************************************/ package org.caleydo.view.idbrowser.internal.model; import gleem.linalg.Vec2f; import java.util.BitSet; import java.util.List; import java.util.Set; import org.caleydo.core.data.collection.EDimension; import org.caleydo.core.data.collection.table.Table; import org.caleydo.core.data.datadomain.ATableBasedDataDomain; import org.caleydo.core.data.perspective.table.TablePerspective; import org.caleydo.core.data.virtualarray.VirtualArray; import org.caleydo.core.event.EventListenerManager.ListenTo; import org.caleydo.core.event.EventPublisher; import org.caleydo.core.id.IDType; import org.caleydo.core.util.color.Color; import org.caleydo.core.view.opengl.layout.Column.VAlign; import org.caleydo.core.view.opengl.layout2.GLElement; import org.caleydo.core.view.opengl.layout2.GLGraphics; import org.caleydo.core.view.opengl.layout2.IGLElementContext; import org.caleydo.core.view.opengl.layout2.ISWTLayer.ISWTLayerRunnable; import org.caleydo.core.view.opengl.layout2.renderer.GLRenderers; import org.caleydo.vis.lineup.event.FilterEvent; import org.caleydo.vis.lineup.model.ABasicFilterableRankColumnModel; import org.caleydo.vis.lineup.model.IRow; import org.caleydo.vis.lineup.ui.AFilterDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import com.jogamp.common.util.IntObjectHashMap; /** * @author Samuel Gratzl * */ public abstract class ADataDomainRankTableModel extends ABasicFilterableRankColumnModel { protected final ATableBasedDataDomain d; protected final EDimension dim; protected final IntObjectHashMap cache = new IntObjectHashMap(); /** * virtual array to use for the other dimension than {@link #dim} */ protected final VirtualArray others; private boolean filterMissingEntries = false; /** * @param d * @param dim */ public ADataDomainRankTableModel(ATableBasedDataDomain d, EDimension dim) { super(Color.GRAY, new Color(0.95f, .95f, .95f)); this.d = d; this.dim = dim; setHeaderRenderer(GLRenderers.drawText(d.getLabel(), VAlign.CENTER)); final Table table = d.getTable(); this.others = dim.opposite() .select(table.getDefaultDimensionPerspective(false), table.getDefaultRecordPerspective(false)) .getVirtualArray(); } public ADataDomainRankTableModel(TablePerspective t, EDimension dim) { super(Color.GRAY, new Color(0.95f, .95f, .95f)); this.d = t.getDataDomain(); this.dim = dim; setHeaderRenderer(GLRenderers.drawText(d.getLabel(), VAlign.CENTER)); this.others = dim.opposite().select(t.getDimensionPerspective(), t.getRecordPerspective()).getVirtualArray(); } /** * @param distributionRankTableModel */ public ADataDomainRankTableModel(ADataDomainRankTableModel clone) { super(clone); this.d = clone.d; this.dim = clone.dim; this.others = clone.others; this.cache.putAll(clone.cache); setHeaderRenderer(GLRenderers.drawText(d.getLabel(), VAlign.CENTER)); } public final IDType getIDType() { return dim.select(d.getDimensionIDType(), d.getRecordIDType()); } private boolean hasValue(IRow row) { Set<Object> ids = ((IIDRow) row).get(getIDType()); if (ids == null || ids.isEmpty()) return false; return true; } @Override public GLElement createSummary(boolean interactive) { return new SummaryElement(); } @Override public boolean isFiltered() { return filterMissingEntries; } public void setFilter(boolean filterMissing, boolean isFilterGlobally, boolean isRankIndependentFilter) { if (this.filterMissingEntries == filterMissing && this.isGlobalFilter == isFilterGlobally && this.isRankIndependentFilter == isRankIndependentFilter) return; invalidAllFilter(); this.filterMissingEntries = filterMissing; this.isGlobalFilter = isFilterGlobally; this.isRankIndependentFilter = isRankIndependentFilter; propertySupport.firePropertyChange(PROP_FILTER, false, true); } /** * @return the filterMissingEntries, see {@link #filterMissingEntries} */ public boolean isFilterMissingEntries() { return filterMissingEntries; } @Override public void editFilter(final GLElement summary, IGLElementContext context) { final Vec2f location = summary.getAbsoluteLocation(); context.getSWTLayer().run(new ISWTLayerRunnable() { @Override public void run(Display display, Composite canvas) { Point loc = canvas.toDisplay((int) location.x(), (int) location.y()); FilterDialog dialog = new FilterDialog(canvas.getShell(), getLabel(), summary, ADataDomainRankTableModel.this, getTable() .hasSnapshots(), loc); dialog.open(); } }); } @Override protected void updateMask(BitSet todo, List<IRow> rows, BitSet mask) { for (int i = todo.nextSetBit(0); i >= 0; i = todo.nextSetBit(i + 1)) { boolean has = hasValue(rows.get(i)); mask.set(i, !filterMissingEntries || has); } } private static class FilterDialog extends AFilterDialog { private final boolean filterMissing; private Button filterNotMappedUI; public FilterDialog(Shell parentShell, String title, Object receiver, ADataDomainRankTableModel model, boolean hasSnapshots, Point loc) { super(parentShell, title, receiver, model, hasSnapshots, loc); this.filterMissing = model.isFilterMissingEntries(); } @Override public void create() { super.create(); getShell().setText("Edit Filter"); } @Override protected void createSpecificFilterUI(Composite composite) { filterNotMappedUI = new Button(composite, SWT.CHECK); filterNotMappedUI.setText("Filter missing entries?"); filterNotMappedUI.setLayoutData(twoColumns(new GridData(SWT.LEFT, SWT.CENTER, true, true))); filterNotMappedUI.setSelection(filterMissing); SelectionAdapter adapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { triggerEvent(false); } }; filterNotMappedUI.addSelectionListener(adapter); addButtonAndOption(composite); } @Override protected void triggerEvent(boolean cancel) { if (cancel) // original values EventPublisher.trigger(new FilterEvent(null, filterMissing, filterGlobally, filterRankIndependent) .to(receiver)); else { EventPublisher.trigger(new FilterEvent(null, filterNotMappedUI.getSelection(), isFilterGlobally(), isFilterRankIndependent()) .to(receiver)); } } } private class SummaryElement extends GLElement { @ListenTo(sendToMe = true) private void onFilterEvent(FilterEvent event) { setFilter(event.isFilterNA(), event.isFilterGlobally(), event.isFilterRankIndendent()); } @Override protected void renderImpl(GLGraphics g, float w, float h) { super.renderImpl(g, w, h); if (w < 20) return; if (isFiltered()) { g.drawText("Filter:", 4, 2, w - 4, 12); String t = "Missing"; g.drawText(t, 4, 18, w - 4, 12); } } } }
32.986726
111
0.734406
2a26f0d1e8ecc35aea4b9028323cda72f5c38787
769
package com.javarush.task.task18.task1817; /* Пробелы */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class Solution { public static void main(String[] args) throws IOException { //C:/Users/Dimka/Documents/JavaRushHomeWork/JavaRushHomeWork_2_0/JavaRushTasks/2.JavaCore/src/com/javarush/task/task17/task1721/File2.txt FileInputStream stream = new FileInputStream(args[0]); int count = stream.available(); int space = 0; while (stream.available()>0) { if(' '==(char)stream.read()) { space++; } } stream.close(); System.out.printf("%.2f",((float)space/count)*100); } }
21.971429
145
0.616385
9d378f479cd696ddb2278b9707e0d1c4880b7308
3,885
package com.free4lab.webrtc.action.filter; import java.io.IOException; import java.util.HashSet; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.free4lab.webrtc.common.APIConstants; public abstract class PermissionFilter implements Filter{ private String failPage = null; private HashSet<String> excludeURIs = new HashSet<String>(); public void destroy() { failPage = null; excludeURIs = null; } /** * 子类验证权限或者检查是否在放行列表中<br/> * 常量定义 {@link APIConstants} */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse)response; if (excludeURIs.contains(req.getRequestURI()) || checkPermission(req, res)) { System.out.println(chain.getClass()); chain.doFilter(request, response); } else { String schemeServerPort = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort(); if(req.getQueryString() == null) { System.out.println(APIConstants.APIPrefix_FreeAccount+"login?customId=webrtc&handleUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getContextPath() + "/login" + "?redirectUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getRequestURI(),"utf-8"),"utf-8")); res.sendRedirect(APIConstants.APIPrefix_FreeAccount+"login?customId=webrtc&handleUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getContextPath() + "/login" + "?redirectUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getRequestURI(),"utf-8"),"utf-8")); } else { System.out.println(APIConstants.APIPrefix_FreeAccount+"login?customId=webrtc&handleUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getContextPath() + "/login" + "?redirectUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getRequestURI() + "?" + req.getQueryString(),"utf-8"),"utf-8")); res.sendRedirect(APIConstants.APIPrefix_FreeAccount+"login?customId=webrtc&handleUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getContextPath() + "/login" + "?redirectUrl=" + java.net.URLEncoder.encode(schemeServerPort + req.getRequestURI() + "?" + req.getQueryString(),"utf-8"),"utf-8")); } // StringBuffer redirectUrl = new StringBuffer(req.getRequestURL()); // String params = req.getQueryString(); // System.out.println("redirectUrl in permissionfilter is " + redirectUrl); // if (params != null){ // redirectUrl.append("?" + params); // } // String url = new String(redirectUrl); // url = failPage + "&redirectUrl=" + url; // // ((HttpServletResponse) response).sendRedirect(url); } } public void init(FilterConfig config) throws ServletException { String contextPath = config.getServletContext().getContextPath(); failPage = contextPath + config.getInitParameter("failPage"); String excludeURIString = config.getInitParameter("excludeURIs"); StringBuilder uris = new StringBuilder(); if (excludeURIString != null && !excludeURIString.trim().equals("")) { excludeURIString = excludeURIString.replaceAll("[\t\n]", ""); for (String uri : excludeURIString.split(";")) { uri = contextPath + uri.trim(); excludeURIs.add(uri.trim()); uris.append(uri); uris.append(';'); } if (uris.length() > 0) { uris.deleteCharAt(uris.length() - 1); } } } abstract protected boolean checkPermission(HttpServletRequest request, HttpServletResponse response); }
41.774194
143
0.701931
0717ca233099a78347bdcce6919c75ce7bc3a3c2
1,196
package org.gbif.occurrence.download.license; import org.gbif.api.vocabulary.License; import com.google.common.base.Preconditions; /** * Builder type that returns concrete implementation(s) of LicenseSelector. */ public class LicenseSelectors { /** * Return a LicenseSelector implementation that will collect all licenses and return the most restrictive one * based on the defaultLicense. * Note that null and non-concrete licenses are ignored. * * @param defaultLicense the default (or base) license. */ public static LicenseSelector getMostRestrictiveLicenseSelector(final License defaultLicense) { Preconditions.checkNotNull(defaultLicense, "LicenseSelector requires a default license"); Preconditions.checkArgument(defaultLicense.isConcrete(), "LicenseSelector can only work on concrete license"); return new LicenseSelector() { private License license = defaultLicense; @Override public void collectLicense(License license) { this.license = License.getMostRestrictive(this.license, license, defaultLicense); } @Override public License getSelectedLicense() { return license; } }; } }
30.666667
114
0.737458
6c9835e8d1b40447f99d8373817858b1e0051e88
2,204
package com.payu.ratel.tests; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.payu.ratel.Discover; import com.payu.ratel.context.ProcessContext; import com.payu.ratel.tests.service.tracing.ProcessIdPassingService; import com.payu.ratel.tests.service.tracing.ProcessIdTargetService; import com.payu.ratel.tests.service.tracing.TracingTestConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @RatelTest(registerServices = TracingTestConfiguration.class) public class ProcessTracingTest { @Discover private ProcessIdPassingService passingService; @Discover private ProcessIdTargetService targetService; @Test public void shouldGenerateProcessIdWhenNotSetInThread() throws Exception { //given assertThat((targetService.getProcessId())).isNull(); //when ProcessContext.getInstance().clearProcessIdentifier(); passingService.passProcessId(); //then assertThat((targetService.getProcessId())).isNotNull(); } @Test public void shouldGenerateNewProcessIdWithEveryCall() throws Exception { //given assertThat((targetService.getProcessId())).isNull(); ProcessContext.getInstance().clearProcessIdentifier(); //when passingService.passProcessId(); String processId1 = targetService.getProcessId(); ProcessContext.getInstance().clearProcessIdentifier(); passingService.passProcessId(); String processId2 = targetService.getProcessId(); //then assertThat(processId1).isNotEqualTo(processId2); } @Test public void shouldPassProcessIdThroughNetworkCall() throws Exception { //given assertThat((targetService.getProcessId())).isNull(); //when ProcessContext.getInstance().setProcessIdentifier("123"); passingService.passProcessId(); //then assertThat((targetService.getProcessId())).isEqualTo("123"); assertThat((passingService.getProcessId())).isEqualTo(targetService.getProcessId()); } }
29.386667
92
0.723684
78dd6507e937df786d572f3e13a1dfc1c6f4aa9f
2,010
package it.unive.quadcore.smartmeal.model; import androidx.annotation.NonNull; import java.util.Objects; /** * Classe che rappresenta i prodotti del locale */ public class Product implements Comparable<Product>{ @NonNull private final String name; @NonNull private final Money price; // Categoria del prodotto @NonNull private final FoodCategory category; @NonNull private final String description; public Product(@NonNull String name,@NonNull Money price,@NonNull FoodCategory category,@NonNull String description) { this.name = name; this.price = price; this.category = category; this.description = description; } @NonNull public String getName() { return name; } @NonNull public Money getPrice() { return price; } @NonNull public String getDescription() { return description; } @NonNull public FoodCategory getCategory() { return category; } @NonNull @Override public String toString() { return "Product{" + "name='" + name + '\'' + ", category=" + category + '}'; } // Due prodotti sono uguali se hanno lo stesso nome e hanno la stessa categoria @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return Objects.equals(name, product.name) && category == product.category; } @Override public int hashCode() { return Objects.hash(name, category); } // Prodotti confrontabili rispetto alla categoria. Se hanno stessa categoria, sono confrontabili rispetto al nome // (lessicografico) @Override public int compareTo(Product o) { if(category==o.category) return name.compareTo(o.name); return category.compareTo(o.category); } }
25.769231
122
0.616418
a6fc0cf3f2ac7b93a60c16f242f7febf0c312fc2
145
package fr.javatronic.blog.massive.annotation1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_503 { }
18.125
51
0.827586
f7c1f8fdb792907e59c060a4921f41ef8b5863b5
649
/** * Project "HRUtils-SB" * * @author Victor Kryzhanivskyi */ package victor.kryz.hr.sb.tracing.specific; import java.sql.SQLException; import org.slf4j.Logger; import victor.kryz.hr.sb.tracing.ObjectTracer; import victor.kryz.hrutils.generated.ents.HrUtilsCountriesEntryT; import victor.kryz.hrutils.generated.ents.HrUtilsRegionsEntryT; public class HrUtilsCountriesEntryT_Tracer implements ObjectTracer<HrUtilsCountriesEntryT> { @Override public String getString(HrUtilsCountriesEntryT item) throws SQLException { final String template = "%s (id: %s)"; return String.format(template, item.getName(), item.getId().toString()); } }
29.5
92
0.784284
1be6d118bb81ccdef44d596020040f7985563553
704
package com.gentics.mesh.util; import com.google.common.collect.ImmutableSet; import java.util.Set; /** * Various utility functions regarding nodes. */ public class NodeUtil { private static final Set<String> processableImageTypes = ImmutableSet.of( "image/gif", "image/png", "image/jpeg", "image/bmp", // Not an actual mime type, but with this, // Mesh will behave as intended by the user even if he made a mistake. "image/jpg" ); /** * Tests if a binary is a readable image by checking its mime type. * The formats ImageIO can read are bmp, jpg, png and gif. */ public static boolean isProcessableImage(String mimeType) { return processableImageTypes.contains(mimeType); } }
27.076923
74
0.725852
2d42f842ba9116c58bc52c3818ad8476abf5a429
1,181
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.layout.service; import java.sql.SQLException; import org.dspace.content.Item; import org.dspace.core.Context; import org.dspace.eperson.EPerson; import org.dspace.layout.CrisLayoutBox; /** * Service to be used to check box access rights * * @author Corrado Lombardi (corrado.lombardi at 4science.it) */ public interface CrisLayoutBoxAccessService { /** * Establishes wether or not, user is enabled to have access to layout data * contained in a layout box for a given Item. * * @param context current Context * @param user user to be checked * @param box layout box * @param item item to whom metadata contained in the box belong to * @return true if access has to be granded, false otherwise * @throws SQLException in case of error during database access */ boolean hasAccess(Context context, EPerson user, CrisLayoutBox box, Item item) throws SQLException; }
31.078947
82
0.713802
3944f34a6019d503c63c73a154ec87204ec68454
11,269
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.olingo.fit.tecsvc.client; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.net.URI; import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.communication.ODataClientErrorException; import org.apache.olingo.client.api.communication.request.retrieve.ODataEntitySetRequest; import org.apache.olingo.client.api.communication.response.ODataRetrieveResponse; import org.apache.olingo.client.api.domain.ClientEntity; import org.apache.olingo.client.api.domain.ClientEntitySet; import org.apache.olingo.client.core.ODataClientFactory; import org.apache.olingo.commons.api.http.HttpHeader; import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.commons.api.http.HttpStatusCode; import org.apache.olingo.fit.AbstractBaseTestITCase; import org.apache.olingo.fit.tecsvc.TecSvcConst; import org.junit.Test; public class SystemQueryOptionITCase extends AbstractBaseTestITCase { private static final String PROPERTY_INT16 = "PropertyInt16"; private static final String ES_SERVER_SIDE_PAGING = "ESServerSidePaging"; private static final String ES_ALL_PRIM = "ESAllPrim"; private static final String SERVICE_URI = TecSvcConst.BASE_URI; @Test public void testCountSimple() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_ALL_PRIM) .count(true) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(Integer.valueOf(3), response.getBody().getCount()); assertEquals(3, response.getBody().getEntities().size()); } @Test public void testServerSidePagingCount() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .count(true) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(10, response.getBody().getEntities().size()); assertEquals(Integer.valueOf(503), response.getBody().getCount()); } @Test public void testTopSimple() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .top(5) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(5, response.getBody().getEntities().size()); for (int i = 0; i < 5; i++) { ClientEntity entity = response.getBody().getEntities().get(i); assertEquals(new Integer(i + 1).toString(), entity.getProperty(PROPERTY_INT16).getValue().toString()); } } @Test public void testSkipSimple() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .skip(5) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(10, response.getBody().getEntities().size()); for (int i = 0; i < 10; i++) { ClientEntity entity = response.getBody().getEntities().get(i); assertEquals(new Integer(i + 6).toString(), entity.getProperty(PROPERTY_INT16).getValue().toString()); } } @Test public void testTopNothing() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .top(20) .skip(503) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(0, response.getBody().getEntities().size()); } @Test public void testSkipNothing() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .skip(10000) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(0, response.getBody().getEntities().size()); } @Test public void testFilterWithTopSkipOrderByAndServerSidePaging() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .filter("PropertyInt16 le 105") // 1, 2, ... , 105 .orderBy("PropertyInt16 desc") // 105, 104, ..., 2, 1 .count(true) // 105 .skip(3) // 102, 101, ..., 2, 1 .top(43) // 102, 101, ...., 59 .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); assertEquals(Integer.valueOf(105), response.getBody().getCount()); assertEquals(10, response.getBody().getEntities().size()); int id = 102; // Check first 10 entities for (int i = 0; i < 10; i++) { ClientEntity entity = response.getBody().getEntities().get(i); assertEquals(new Integer(id).toString(), entity.getProperty(PROPERTY_INT16).getValue().toString()); id--; } // Get 3 * 10 = 30 Entities and check the key for (int j = 0; j < 3; j++) { response = client.getRetrieveRequestFactory().getEntitySetRequest(response.getBody().getNext()).execute(); assertEquals(Integer.valueOf(105), response.getBody().getCount()); assertEquals(10, response.getBody().getEntities().size()); for (int i = 0; i < 10; i++) { ClientEntity entity = response.getBody().getEntities().get(i); assertEquals(new Integer(id).toString(), entity.getProperty(PROPERTY_INT16).getValue().toString()); id--; } } // Get the last 3 items response = client.getRetrieveRequestFactory().getEntitySetRequest(response.getBody().getNext()).execute(); assertEquals(Integer.valueOf(105), response.getBody().getCount()); assertEquals(3, response.getBody().getEntities().size()); for (int i = 0; i < 3; i++) { ClientEntity entity = response.getBody().getEntities().get(i); assertEquals(new Integer(id).toString(), entity.getProperty(PROPERTY_INT16).getValue().toString()); id--; } // Make sure that the body no not contain a next link assertEquals(null, response.getBody().getNext()); } @Test public void testNextLinkFormat() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); // Check initial next link format URI nextLink = response.getBody().getNext(); assertEquals(SERVICE_URI + "/ESServerSidePaging?%24skiptoken=1%2A10", nextLink.toASCIIString()); // Check subsequent next links response = client.getRetrieveRequestFactory() .getEntitySetRequest(nextLink) .execute(); nextLink = response.getBody().getNext(); assertEquals(SERVICE_URI + "/ESServerSidePaging?%24skiptoken=2%2A10", nextLink.toASCIIString()); } @Test public void testNextLinkFormatWithQueryOptions() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_SERVER_SIDE_PAGING) .count(true) .build(); ODataRetrieveResponse<ClientEntitySet> response = client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); // Check initial next link format URI nextLink = response.getBody().getNext(); assertEquals(SERVICE_URI + "/ESServerSidePaging?%24count=true&%24skiptoken=1%2A10", nextLink.toASCIIString()); int token = 1; while (nextLink != null) { token++; // Check subsequent next links response = client.getRetrieveRequestFactory() .getEntitySetRequest(nextLink) .execute(); nextLink = response.getBody().getNext(); if (nextLink != null) { assertEquals(SERVICE_URI + "/ESServerSidePaging?%24count=true&%24skiptoken=" + token + "%2A10", nextLink.toASCIIString()); } } assertEquals(50 + 1, token); } @Test public void nextLinkFormatWithClientPageSize() { final ODataClient client = getClient(); final URI uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_SERVER_SIDE_PAGING).build(); ODataEntitySetRequest<ClientEntitySet> request = client.getRetrieveRequestFactory().getEntitySetRequest(uri); request.setPrefer(getClient().newPreferences().maxPageSize(7)); final ODataRetrieveResponse<ClientEntitySet> response = request.execute(); assertEquals("odata.maxpagesize=7", response.getHeader(HttpHeader.PREFERENCE_APPLIED).iterator().next()); assertEquals(SERVICE_URI + '/' + ES_SERVER_SIDE_PAGING + "?%24skiptoken=1%2A" + 7, response.getBody().getNext().toASCIIString()); } @Test public void testNegativeSkip() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_ALL_PRIM) .skip(-5) .build(); try { client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); fail(); } catch (ODataClientErrorException e) { assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusLine().getStatusCode()); } } @Test public void testNegativeTop() { ODataClient client = getClient(); URI uri = client.newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_ALL_PRIM) .top(-5) .build(); try { client.getRetrieveRequestFactory() .getEntitySetRequest(uri) .execute(); fail(); } catch (ODataClientErrorException e) { assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusLine().getStatusCode()); } } @Override protected ODataClient getClient() { ODataClient odata = ODataClientFactory.getClient(); odata.getConfiguration().setDefaultPubFormat(ContentType .JSON); return odata; } }
35.437107
113
0.694915
f8e08c42084c16b7a9cae453accfbc75f596a014
405
package com.todos.webapp.validator; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.todos.webapp.models.User; public class UserValidator implements Validator { public boolean supports(Class<?> clazz) { return User.class.equals(clazz); } public void validate(Object target, Errors errors) { // TODO Auto-generated method stub } }
20.25
53
0.77037
b57534cebf85fc81a66c60c0a3a4ab573f93f3a1
31,351
package aitoa.structure; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.function.LongSupplier; import java.util.function.Supplier; import oshi.SystemInfo; import oshi.hardware.Baseboard; import oshi.hardware.CentralProcessor; import oshi.hardware.CentralProcessor.ProcessorIdentifier; import oshi.hardware.ComputerSystem; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.NetworkParams; import oshi.software.os.OSProcess; import oshi.software.os.OperatingSystem; import oshi.software.os.OperatingSystem.OSVersionInfo; /** * An internal class for creating and holding the system data. * The system data is queried only exactly once and then stored * for the rest of the session. */ final class SystemData { /** * get the system data * * @return the system data */ static char[] getSystemData() { return Holder.SYSTEM_DATA; } /** forbidden */ private SystemData() { throw new UnsupportedOperationException(); } /** the internal holder class */ private static final class Holder { /** make the system data */ static final char[] SYSTEM_DATA = Maker.makeSystemData(); /** the internal maker class */ private static final class Maker { /** * add a value to the map * * @param map * the map * @param key * the key * @param rawvalue * the value */ private static void add(final TreeMap<String, String> map, final String key, final String rawvalue) { if (rawvalue == null) { return; } final String value = rawvalue.trim(); if (value.isEmpty()// || "null".equalsIgnoreCase(value) //$NON-NLS-1$ || "unknown".equalsIgnoreCase(value)) { //$NON-NLS-1$ return; } if (map.put(Objects.requireNonNull(key), value) != null) { throw new IllegalStateException("duplicate key: "//$NON-NLS-1$ + key); } } /** * add a value to the map * * @param map * the map * @param key * the key * @param value * the value * @param threshold * the threshold */ private static void addgt( final TreeMap<String, String> map, final String key, final LongSupplier value, final long threshold) { final long l; try { l = value.getAsLong(); } catch (@SuppressWarnings("unused") final Throwable ignore) { return; } if (l > threshold) { Maker.add(map, key, Long.toString(l)); } } /** * add a value to the map * * @param map * the map * @param key * the key * @param value * the value */ private static void addgt0( final TreeMap<String, String> map, final String key, final LongSupplier value) { Maker.addgt(map, key, value, 0L); } /** * add a value to the map * * @param map * the map * @param key * the key * @param value * the value */ private static void add(final TreeMap<String, String> map, final String key, final Supplier<String> value) { final String s; try { s = value.get(); } catch (@SuppressWarnings("unused") final Throwable ignore) { return; } if (s != null) { Maker.add(map, key, s); } } /** * the internal system data maker * * @return the system data */ static char[] makeSystemData() { final StringBuilder out = new StringBuilder(); // print the system information out.append(LogFormat.asComment(LogFormat.BEGIN_SYSTEM)); out.append(System.lineSeparator()); final TreeMap<String, String> data = new TreeMap<>(); Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_VERSION, System.getProperty("java.version"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_VENDOR, System.getProperty("java.vendor"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_VM_VERSION, System.getProperty("java.vm.version"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_VM_VENDOR, System.getProperty("java.vm.vendor"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_VM_NAME, System.getProperty("java.vm.name"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_SPECIFICATION_VERSION, System.getProperty("java.specification.version"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_SPECIFICATION_VENDOR, System.getProperty("java.specification.vendor"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_SPECIFICATION_NAME, System.getProperty("java.specification.name"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_JAVA_COMPILER, System.getProperty("java.compiler"));//$NON-NLS-1$ Maker.add(data, LogFormat.SYSTEM_INFO_SESSION_START_DATE_TIME, BlackBoxProcessData.getSessionStart().toString()); final String[] osInfo = new String[2]; try { final SystemInfo sys = new SystemInfo(); try { final HardwareAbstractionLayer hal = sys.getHardware(); if (hal != null) { try { final CentralProcessor cpu = hal.getProcessor(); Maker.addgt0(data, LogFormat.SYSTEM_INFO_CPU_LOGICAL_CORES, () -> cpu.getLogicalProcessorCount()); Maker.addgt0(data, LogFormat.SYSTEM_INFO_CPU_PHYSICAL_CORES, () -> cpu.getPhysicalProcessorCount()); Maker.addgt0(data, LogFormat.SYSTEM_INFO_CPU_PHYSICAL_SLOTS, () -> cpu.getPhysicalPackageCount()); try { final ProcessorIdentifier pi = cpu.getProcessorIdentifier(); if (pi != null) { Maker.add(data, LogFormat.SYSTEM_INFO_CPU_NAME, () -> pi.getName()); Maker.add(data, LogFormat.SYSTEM_INFO_CPU_FAMILY, () -> pi.getFamily()); Maker.add(data, LogFormat.SYSTEM_INFO_CPU_IDENTIFIER, () -> pi.getIdentifier()); Maker.add(data, LogFormat.SYSTEM_INFO_CPU_MODEL, () -> pi.getModel()); Maker.add(data, LogFormat.SYSTEM_INFO_CPU_ID, () -> pi.getProcessorID()); Maker.add(data, LogFormat.SYSTEM_INFO_CPU_VENDOR, () -> pi.getVendor()); Maker.addgt0(data, LogFormat.SYSTEM_INFO_CPU_FREQUENCY, () -> pi.getVendorFreq()); Maker.add(data, LogFormat.SYSTEM_INFO_CPU_IS_64_BIT, () -> Boolean.toString(pi.isCpu64bit())); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end cpu info } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end cpu try { final GlobalMemory mem = hal.getMemory(); if (mem != null) { Maker.addgt(data, LogFormat.SYSTEM_INFO_MEM_PAGE_SIZE, () -> mem.getPageSize(), 1L); Maker.addgt0(data, LogFormat.SYSTEM_INFO_MEM_TOTAL, () -> mem.getTotal()); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end memory try { final ComputerSystem cs = hal.getComputerSystem(); if (cs != null) { Maker.add(data, LogFormat.SYSTEM_INFO_COMPUTER_MANUFACTURER, () -> cs.getManufacturer()); Maker.add(data, LogFormat.SYSTEM_INFO_COMPUTER_MODEL, () -> cs.getModel()); try { final Baseboard bb = cs.getBaseboard(); if (bb != null) { Maker.add(data, LogFormat.SYSTEM_INFO_MAINBOARD_MANUFACTURER, () -> bb.getManufacturer()); Maker.add(data, LogFormat.SYSTEM_INFO_MAINBOARD_MODEL, () -> bb.getModel()); Maker.add(data, LogFormat.SYSTEM_INFO_MAINBOARD_SERIAL_NUMBER, () -> bb.getSerialNumber()); Maker.add(data, LogFormat.SYSTEM_INFO_MAINBOARD_VERSION, () -> bb.getVersion()); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // base board } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end computer system } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end hal try { final OperatingSystem os = sys.getOperatingSystem(); if (os != null) { Maker.add(data, LogFormat.SYSTEM_INFO_OS_FAMILY, () -> { final String s = os.getFamily(); osInfo[0] = s; return s; }); Maker.addgt0(data, LogFormat.SYSTEM_INFO_OS_BITS, () -> os.getBitness()); Maker.add(data, LogFormat.SYSTEM_INFO_OS_MANUFACTURER, () -> { final String s = os.getManufacturer(); osInfo[1] = s; return s; }); Maker.addgt(data, LogFormat.SYSTEM_INFO_PROCESS_ID, () -> os.getProcessId(), Long.MIN_VALUE); try { final OSProcess po = os.getProcess(os.getProcessId()); if (po != null) { final String cmd = po.getCommandLine(); if (cmd != null) { final String usecmd = cmd.replaceAll("\\p{Cntrl}", " ") //$NON-NLS-1$ //$NON-NLS-2$ .replaceAll("[^\\p{Print}]", " ")//$NON-NLS-1$ //$NON-NLS-2$ .replaceAll("\\p{C}", " ")//$NON-NLS-1$ //$NON-NLS-2$ .replaceAll("[\\p{C}\\p{Z}]", " ") //$NON-NLS-1$ //$NON-NLS-2$ .trim(); Maker.add(data, LogFormat.SYSTEM_INFO_PROCESS_COMMAND_LINE, usecmd); } } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end os version try { final OSVersionInfo ovi = os.getVersionInfo(); if (ovi != null) { Maker.add(data, LogFormat.SYSTEM_INFO_OS_BUILD, () -> ovi.getBuildNumber()); Maker.add(data, LogFormat.SYSTEM_INFO_OS_CODENAME, () -> ovi.getCodeName()); Maker.add(data, LogFormat.SYSTEM_INFO_OS_VERSION, () -> ovi.getVersion()); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end os version try { final NetworkParams net = os.getNetworkParams(); if (net != null) { Maker.add(data, LogFormat.SYSTEM_INFO_NET_DOMAIN_NAME, () -> net.getDomainName()); Maker.add(data, LogFormat.SYSTEM_INFO_NET_HOST_NAME, () -> net.getHostName()); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end net version } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end os } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end system try ( final InputStream is = SystemData.class .getResourceAsStream("versions.txt"); //$NON-NLS-1$ final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr)) { String line = null; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) { continue; } final int i = line.indexOf('='); if ((i < 1) || (i >= (line.length() - 1))) { continue; } final String a = line.substring(0, i).trim(); if (a.isEmpty()) { continue; } final String b = line.substring(i + 1).trim(); if (b.isEmpty()) { continue; } Maker.add(data, a, b); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } try { // detect GPU final String os = (((osInfo[0] != null) ? osInfo[0] : "") + //$NON-NLS-1$ ((osInfo[1] != null) ? osInfo[1] : ""))//$NON-NLS-1$ .toLowerCase(); boolean detected = false; if (os.isEmpty() || // os.contains("linux") || //$NON-NLS-1$ os.contains("unbuntu")) { //$NON-NLS-1$ detected = Maker.tryDetectGPULinux(data); } if ((!detected) && (os.isEmpty() || // os.contains("win"))) { //$NON-NLS-1$ detected = Maker.tryDetectGPUWindows(data); } } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } // end detect GPU for (final Map.Entry<String, String> entry : data .entrySet()) { out.append(LogFormat.mapEntry(entry.getKey(), entry.getValue())); out.append(System.lineSeparator()); } out.append(LogFormat.asComment(LogFormat.END_SYSTEM)); out.append(System.lineSeparator()); final int length = out.length(); final char[] res = new char[length]; out.getChars(0, length, res, 0); return res; } /** * split a pci string into name, vendor id, and device id * * @param s * the string * @return the split string */ private static String[] pciSplit(final String s) { int firstDots = s.indexOf(':'); if (firstDots > 0) { firstDots = s.indexOf(':', firstDots + 1); if (firstDots > 0) { final int firstBracket = s.lastIndexOf('['); if (firstBracket > firstDots) { final int secondDots = s.indexOf(':', firstBracket + 1); if (secondDots > firstBracket) { final int lastBracket = s.indexOf(']', secondDots + 1); if (lastBracket > secondDots) { final String name = s.substring(firstDots + 1, firstBracket) .trim(); if (!name.isEmpty()) { final String vendorId = s.substring(firstBracket + 1, secondDots) .trim(); try { Integer.parseUnsignedInt(vendorId, 16); } catch (@SuppressWarnings("unused") final Throwable error) { return new String[] { name }; } if (!vendorId.isEmpty()) { final String pciId = s .substring(secondDots + 1, lastBracket) .trim(); if (!pciId.isEmpty()) { try { Integer.parseUnsignedInt(pciId, 16); } catch (@SuppressWarnings("unused") final Throwable error) { return new String[] { name }; } // register name, vendor id, and pci ID return new String[] { name, vendorId, pciId }; } } } } } } else { // no vendor/pci ID final String t = s.substring(firstDots + 1).trim(); if (!t.isEmpty()) { return new String[] { t }; } } } } return null; } /** * Look up one device or vendor in the PCI device * repository. * * @param id * the device or vendor id * @return the string */ private static String pciLookup(final String id) { for (final String base : new String[] { "https://pci-ids.ucw.cz/read/PC/", //$NON-NLS-1$ "http://pci-ids.ucw.cz/read/PC/" //$NON-NLS-1$ }) { try { try ( final InputStream is = new URL(base + id).openStream(); final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr)) { String line = null; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) { continue; } final String linelc = line.toLowerCase(); final int index = linelc.indexOf("<p>name:");//$NON-NLS-1$ if (index >= 0) { final int end = linelc.indexOf("</", //$NON-NLS-1$ index + 8); if (end > index) { final String res = line.substring(index + 8, end).trim(); if (!res.isEmpty()) { return res; } } } } } return null; } catch (@SuppressWarnings("unused") final Throwable error) { // ignore } } return null; } /** * Add a GPU information * * @param vendor * the vendor * @param device * the device * @param map * the destination map */ private static void addGPU(final String vendor, final String device, final TreeMap<String, String> map) { String vendorId = null; String deviceId = null; if (vendor != null) { vendorId = Integer.toUnsignedString(// Integer.parseUnsignedInt(vendor, 16), 16) .toLowerCase(); while (vendorId.length() < 4) { vendorId = '0' + vendorId; } Maker.add(map, LogFormat.SYSTEM_INFO_GPU_PCI_VENDOR_ID, vendorId); } if (device != null) { deviceId = Integer.toUnsignedString(// Integer.parseUnsignedInt(device, 16), 16) .toLowerCase(); while (deviceId.length() < 4) { deviceId = '0' + deviceId; } Maker.add(map, LogFormat.SYSTEM_INFO_GPU_PCI_DEVICE_ID, deviceId); } if (vendorId != null) { final String vn = Maker.pciLookup(vendorId); if (vn != null) { Maker.add(map, LogFormat.SYSTEM_INFO_GPU_PCI_VENDOR, vn); } if (deviceId != null) { final String dc = Maker.pciLookup(vendorId + '/' + deviceId); if (dc != null) { Maker.add(map, LogFormat.SYSTEM_INFO_GPU_PCI_DEVICE, dc); } } } } /** * Try to detect the GPU under Linux * * @param map * the destination map * @return {@code true} if a graphics card was detected, * {@code false} otherwise */ private static boolean tryDetectGPULinux(// final TreeMap<String, String> map) { try { final Process p = new ProcessBuilder()// .command("lspci", //$NON-NLS-1$ "-nn") //$NON-NLS-1$ .redirectErrorStream(true)// .start(); try { try { String[] vga = null; String[] displayController = null; try (final InputStream is = p.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr)) { String s = null; while ((s = br.readLine()) != null) { s = s.trim(); final String t = s.toLowerCase(); if (t.contains("vga compatible controller")) { //$NON-NLS-1$ final String[] q = Maker.pciSplit(s); if ((q != null) && ((vga == null) || (vga.length < q.length))) { vga = q; if ((displayController != null) && (displayController.length >= 3) && (q.length >= 3)) { break; } } } else { if (t.contains("display controller")) { //$NON-NLS-1$ final String[] q = Maker.pciSplit(s); if ((q != null) && ((displayController == null) || (displayController.length < q.length))) { displayController = q; if ((vga != null) && (vga.length >= 3) && (q.length >= 3)) { break; } } } } } } if (displayController != null) { vga = displayController; } if (vga != null) { Maker.add(map, LogFormat.SYSTEM_INFO_GPU_NAME, vga[0]); if (vga.length > 1) { Maker.addGPU(vga[1], (vga.length > 2) ? vga[2] : null, map); } return true; } } finally { p.waitFor(); } } finally { p.destroy(); } } catch (@SuppressWarnings("unused") final Throwable error) { // ignore } return false; } /** * Try to detect the GPU under Windows * * @param map * the destination map * @return {@code true} if a graphics card was detected, * {@code false} otherwise */ private static boolean tryDetectGPUWindows( final TreeMap<String, String> map) { try { final Path tempFile = Files.createTempFile("gd", //$NON-NLS-1$ ".txt"); //$NON-NLS-1$ try { // use dxdiag to get the graphics card info final Process p = new ProcessBuilder()// .command("dxdiag", //$NON-NLS-1$ "/whql:off", //$NON-NLS-1$ "/t", //$NON-NLS-1$ tempFile.toFile().getCanonicalPath()) .redirectErrorStream(true)// .start(); try { p.waitFor(); if (p.exitValue() != 0) { return false; } // Wait until the text file has fully been written. // When doing dxdiag via command line, I saw some slightly // strange effects where it seemed as if the file was still // written while the process had already been returned. Maybe // there was some spawning of a sub-processes or something. So we // better be on the safe side and wait until we can expect that // the file won't change anymore. long lastSize = 0L; int waitNonIncreased = 5; for (int i = 300; (--i) >= 0;) { final long size = Files.size(tempFile); if (size > lastSize) { waitNonIncreased = 5; lastSize = size; } else { if (size > 0L) { if ((--waitNonIncreased) <= 0) { break; } } } try { Thread.sleep(100L); } catch (@SuppressWarnings("unused") final Throwable ignore) { // ignore } } String name = null; String vendorId = null; String deviceId = null; // OK, if we get here, the file has probably been written fully try (final BufferedReader br = Files.newBufferedReader(tempFile)) { String s = null; boolean inDashes = false; boolean inDisplay = false; readFile: while ((s = br.readLine()) != null) { s = s.trim(); if (s.isEmpty()) { continue readFile; } boolean isAllDashes = true; inner: for (int i = s.length(); (--i) >= 0;) { if (s.charAt(i) != '-') { isAllDashes = false; break inner; } } if (isAllDashes) { inDashes = !inDashes; continue readFile; } if (inDashes) { inDisplay = s.toLowerCase().contains(// "display devices"); //$NON-NLS-1$ continue readFile; } if (!inDisplay) { continue readFile; } final int dots = s.indexOf(':'); if (dots <= 0) { continue readFile; } final String key = s.substring(0, dots).trim().toLowerCase(); if (key.isEmpty()) { continue readFile; } if (key.contains("card name")) { //$NON-NLS-1$ if (name == null) { name = s.substring(dots + 1).trim(); if (!name.isEmpty()) { if ((vendorId != null) && (deviceId != null)) { break readFile; } continue readFile; } name = null; } continue readFile; } if (key.contains("vendor id")) { //$NON-NLS-1$ if (vendorId == null) { vendorId = s.substring(dots + 1).trim() .toLowerCase(); if ((vendorId.length() > 2) && vendorId.startsWith("0x")) { //$NON-NLS-1$ vendorId = vendorId.substring(2); try { Integer.parseUnsignedInt(vendorId, 16); if ((name != null) && (deviceId != null)) { break readFile; } continue readFile; } catch (@SuppressWarnings("unused") final Throwable error2) { // ignore } } vendorId = null; } continue readFile; } if (key.contains("device id")) { //$NON-NLS-1$ if (deviceId == null) { deviceId = s.substring(dots + 1).trim() .toLowerCase(); if ((deviceId.length() > 2) && deviceId.startsWith("0x")) { //$NON-NLS-1$ deviceId = deviceId.substring(2); try { Integer.parseUnsignedInt(deviceId, 16); if ((name != null) && (vendorId != null)) { break readFile; } continue readFile; } catch (@SuppressWarnings("unused") final Throwable error2) { // ignore } } deviceId = null; } continue readFile; } } // end read file } // close writer // write back the infos if (name != null) { Maker.add(map, LogFormat.SYSTEM_INFO_GPU_NAME, name); Maker.addGPU(vendorId, deviceId, map); return true; } } finally { p.destroy(); } } finally { Files.delete(tempFile); } } catch (@SuppressWarnings("unused") final Throwable error) { // ignore } return false; } } } }
34.989955
90
0.439029
bdc65ff517197ec4e94969ed268ccab4a0d6b7d1
2,341
package FinancialCalc.EvalModules; import FinancialCalc.EvalModule; import FinancialCalc.MenuActionListener; public class NetPresentValue extends EvalModule { private double d_NCF; private double d_INV; private double d_Result; private static final int FIELD_NCF = 0; private static final int FIELD_INV = 1; public String getModuleName(MenuActionListener _listener) { return "Net Present Value"; } public void beginTransaction() { d_NCF = 0d; d_INV = 0d; d_Result = 0d; } public void calculate() { d_Result = d_NCF - d_INV; } public String checkFields() { return null; } public int getFieldsNumber() { return 2; } public String getFieldValue(int _field) { switch (_field) { case FIELD_INV: return convertDoubleToString(d_INV); case FIELD_NCF: return convertDoubleToString(d_NCF); } return null; } public String getNameForField(int _field, MenuActionListener _listener) { switch (_field) { case FIELD_INV: return "Инвестиции"; case FIELD_NCF: return "Доходы"; } return null; } public String getNameForResult(int _result, MenuActionListener _listener) { return "Чистый дисконт.поток"; } public String getResult(int _result) { switch (_result) { case 0: return convertDoubleToString(d_Result); } return null; } public int getResultsNumber() { return 1; } public String setFieldValue(int _field, String _value) { double p_dbl = 0; try { p_dbl = Double.parseDouble(_value); } catch (NumberFormatException e) { return "Ошибочное значение"; } switch (_field) { case FIELD_INV: { d_INV = p_dbl; } ; break; case FIELD_NCF: { d_NCF = p_dbl; } ; break; } return null; } }
20.008547
77
0.512601
263bde15522ce35e7ad6f88a06b616354d29d939
316
package com.zyplayer.doc.data.service.manage; import com.zyplayer.doc.data.repository.manage.entity.UserGroup; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 用户组 服务类 * </p> * * @author 暮光:城中城 * @since 2021-02-08 */ public interface UserGroupService extends IService<UserGroup> { }
18.588235
64
0.734177
aade0c55d9b2fceb0685ebaa7652ca49ecbb9132
15,300
/* * Copyright @ 2017 Atlassian Pty Ltd * * 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.jitsi.videobridge; import static org.jitsi.videobridge.EndpointMessageBuilder.createServerHelloEvent; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.HashSet; import java.util.Objects; import java.util.Set; import org.jitsi.eventadmin.EventAdmin; import org.jitsi.util.Logger; import org.jitsi.videobridge.rest.ColibriWebSocket; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * Handles the functionality related to sending and receiving COLIBRI messages * for an {@link Endpoint}. Supports two underlying transport mechanisms -- * WebRTC data channels and {@code WebSocket}s. * * @author Boris Grozev */ class EndpointMessageTransport extends AbstractEndpointMessageTransport implements WebRtcDataStream.DataCallback { /** * The {@link Logger} used by the {@link Endpoint} class to print debug * information. */ private static final Logger classLogger = Logger.getLogger(EndpointMessageTransport.class); /** * The {@link Endpoint} associated with this {@link EndpointMessageTransport}. * */ private final Endpoint endpoint; /** * The {@link Logger} to be used by this instance to print debug information. */ private final Logger logger; /** * The last accepted web-socket by this instance, if any. */ private ColibriWebSocket webSocket; /** * User to synchronize access to {@link #webSocket} */ private final Object webSocketSyncRoot = new Object(); /** * Whether the last active transport channel (i.e. the last to receive a message * from the remote endpoint) was the web socket (if {@code true}), or the WebRTC * data channel (if {@code false}). */ private boolean webSocketLastActive = false; /** * SCTP connection bound to this endpoint. */ private WeakReference<SctpConnection> sctpConnection = new WeakReference<>(null); /** * The listener which will be added to {@link SctpConnection}s associated with * this endpoint, which will be notified when {@link SctpConnection}s become * ready. * * Note that we just want to make sure that the initial messages (e.g. a * dominant speaker notification) are sent. Because of this we only add * listeners to {@link SctpConnection}s which are not yet ready, and we remove * the listener after an {@link SctpConnection} becomes ready. */ private final WebRtcDataStreamListener webRtcDataStreamListener = new WebRtcDataStreamListener() { @Override public void onSctpConnectionReady(SctpConnection source) { if (source != null) { if (source.equals(getSctpConnection())) { try { WebRtcDataStream dataStream = source.getDefaultDataStream(); dataStream.setDataCallback(EndpointMessageTransport.this); notifyTransportChannelConnected(); } catch (IOException e) { logger.error("Could not get the default data stream.", e); } } source.removeChannelListener(this); } } }; /** * Initializes a new {@link EndpointMessageTransport} instance. * * @param endpoint the associated {@link Endpoint}. */ EndpointMessageTransport(Endpoint endpoint) { super(endpoint); this.endpoint = endpoint; this.logger = Logger.getLogger(classLogger, endpoint.getConference().getLogger()); } /** * {@inheritDoc} */ @Override protected void notifyTransportChannelConnected() { EventAdmin eventAdmin = endpoint.getConference().getEventAdmin(); if (eventAdmin != null) { eventAdmin.postEvent(EventFactory.endpointMessageTransportReady(endpoint)); } endpoint.getConference().endpointMessageTransportConnected(endpoint); for (RtpChannel channel : endpoint.getChannels()) { channel.endpointMessageTransportConnected(); } } /** * {@inheritDoc} */ @Override protected void onClientHello(Object src, JSONObject jsonObject) { // ClientHello was introduced for functional testing purposes. It // triggers a ServerHello response from Videobridge. The exchange // reveals (to the client) that the transport channel between the // remote endpoint and the Videobridge is operational. // We take care to send the reply using the same transport channel on // which we received the request.. sendMessage(src, createServerHelloEvent(), "response to ClientHello"); } /** * Sends a string via a particular transport channel. * * @param dst the transport channel. * @param message the message to send. */ private void sendMessage(Object dst, String message) { sendMessage(dst, message, ""); } /** * Sends a string via a particular transport channel. * * @param dst the transport channel. * @param message the message to send. * @param errorMessage an error message to be logged in case of failure. */ private void sendMessage(Object dst, String message, String errorMessage) { if (dst instanceof WebRtcDataStream) { sendMessage((WebRtcDataStream) dst, message, errorMessage); } else if (dst instanceof ColibriWebSocket) { sendMessage((ColibriWebSocket) dst, message, errorMessage); } else { throw new IllegalArgumentException("unknown transport:" + dst); } } /** * Sends a string via a particular {@link WebRtcDataStream} instance. * * @param dst the {@link WebRtcDataStream} through which to send the * message. * @param message the message to send. * @param errorMessage an error message to be logged in case of failure. */ private void sendMessage(WebRtcDataStream dst, String message, String errorMessage) { try { dst.sendString(message); endpoint.getConference().getVideobridge().getStatistics().totalDataChannelMessagesSent.incrementAndGet(); } catch (IOException ioe) { logger.error("Failed to send a message over a WebRTC data channel" + " (endpoint=" + endpoint.getID() + "): " + errorMessage, ioe); } } /** * Sends a string via a particular {@link ColibriWebSocket} instance. * * @param dst the {@link ColibriWebSocket} through which to send the * message. * @param message the message to send. * @param errorMessage an error message to be logged in case of failure. */ private void sendMessage(ColibriWebSocket dst, String message, String errorMessage) { // We'll use the async version of sendString since this may be called // from multiple threads. It's just fire-and-forget though, so we // don't wait on the result dst.getRemote().sendStringByFuture(message); endpoint.getConference().getVideobridge().getStatistics().totalColibriWebSocketMessagesSent.incrementAndGet(); } /** * {@inheritDoc} */ @Override protected void onPinnedEndpointChangedEvent(Object src, JSONObject jsonObject) { // Find the new pinned endpoint. String newPinnedEndpointID = (String) jsonObject.get("pinnedEndpoint"); Set<String> newPinnedIDs = Collections.EMPTY_SET; if (newPinnedEndpointID != null && !"".equals(newPinnedEndpointID)) { newPinnedIDs = Collections.singleton(newPinnedEndpointID); } endpoint.pinnedEndpointsChanged(newPinnedIDs); } /** * {@inheritDoc} */ @Override protected void onPinnedEndpointsChangedEvent(Object src, JSONObject jsonObject) { // Find the new pinned endpoint. Object o = jsonObject.get("pinnedEndpoints"); if (!(o instanceof JSONArray)) { logger.warn("Received invalid or unexpected JSON (" + endpoint.getLoggingId() + "):" + jsonObject); return; } JSONArray jsonArray = (JSONArray) o; Set<String> newPinnedEndpoints = new HashSet<>(); for (Object endpointId : jsonArray) { if (endpointId != null && endpointId instanceof String) { newPinnedEndpoints.add((String) endpointId); } } if (logger.isDebugEnabled()) { logger.debug(Logger.Category.STATISTICS, "pinned," + endpoint.getLoggingId() + " pinned=" + newPinnedEndpoints); } endpoint.pinnedEndpointsChanged(newPinnedEndpoints); } /** * {@inheritDoc} */ @Override protected void onSelectedEndpointChangedEvent(Object src, JSONObject jsonObject) { // Find the new pinned endpoint. String newSelectedEndpointID = (String) jsonObject.get("selectedEndpoint"); Set<String> newSelectedIDs = Collections.EMPTY_SET; if (newSelectedEndpointID != null && !"".equals(newSelectedEndpointID)) { newSelectedIDs = Collections.singleton(newSelectedEndpointID); } endpoint.selectedEndpointsChanged(newSelectedIDs); } /** * {@inheritDoc} */ @Override protected void onSelectedEndpointsChangedEvent(Object src, JSONObject jsonObject) { // Find the new pinned endpoint. Object o = jsonObject.get("selectedEndpoints"); if (!(o instanceof JSONArray)) { logger.warn("Received invalid or unexpected JSON: " + jsonObject); return; } JSONArray jsonArray = (JSONArray) o; Set<String> newSelectedEndpoints = new HashSet<>(); for (Object endpointId : jsonArray) { if (endpointId != null && endpointId instanceof String) { newSelectedEndpoints.add((String) endpointId); } } endpoint.selectedEndpointsChanged(newSelectedEndpoints); } /** * {@inheritDoc} */ @Override public void onStringData(WebRtcDataStream src, String msg) { webSocketLastActive = false; endpoint.getConference().getVideobridge().getStatistics().totalDataChannelMessagesReceived.incrementAndGet(); onMessage(src, msg); } /** * {@inheritDoc} */ @Override protected void sendMessage(String msg) throws IOException { Object dst = getActiveTransportChannel(); if (dst == null) { logger.warn("No available transport channel, can't send a message:\n" + msg); } else { sendMessage(dst, msg); } } /** * @return the active transport channel for this * {@link EndpointMessageTransport} (either the {@link #webSocket}, or * the WebRTC data channel represented by a {@link WebRtcDataStream}). * </p> * The "active" channel is determined based on what channels are * available, and which one was the last to receive data. That is, if * only one channel is available, it will be returned. If two channels * are available, the last one to have received data will be returned. * Otherwise, {@code null} will be returned. */ private Object getActiveTransportChannel() throws IOException { SctpConnection sctpConnection = getSctpConnection(); ColibriWebSocket webSocket = this.webSocket; String endpointId = endpoint.getID(); Object dst = null; if (webSocketLastActive) { dst = webSocket; } // Either the socket was not the last active channel, // or it has been closed. if (dst == null) { if (sctpConnection != null && sctpConnection.isReady()) { dst = sctpConnection.getDefaultDataStream(); if (dst == null) { logger.warn("SCTP ready, but WebRtc data channel with " + endpointId + " not opened yet."); } } else { logger.warn("SCTP connection with " + endpointId + " not ready yet."); } } // Maybe the WebRTC data channel is the last active, but it is not // currently available. If so, and a web-socket is available -- use it. if (dst == null && webSocket != null) { dst = webSocket; } return dst; } /** * Notifies this {@link EndpointMessageTransport} that a specific * {@link ColibriWebSocket} instance associated with its {@link Endpoint} has * connected. * * @param ws the {@link ColibriWebSocket} which has connected. */ void onWebSocketConnect(ColibriWebSocket ws) { synchronized (webSocketSyncRoot) { // If we already have a web-socket, discard it and use the new one. if (webSocket != null) { webSocket.getSession().close(200, "replaced"); } webSocket = ws; webSocketLastActive = true; sendMessage(ws, createServerHelloEvent(), "initial ServerHello"); } notifyTransportChannelConnected(); } /** * Notifies this {@link EndpointMessageTransport} that a specific * {@link ColibriWebSocket} instance associated with its {@link Endpoint} has * been closed. * * @param ws the {@link ColibriWebSocket} which has been closed. */ public void onWebSocketClose(ColibriWebSocket ws, int statusCode, String reason) { synchronized (webSocketSyncRoot) { if (ws != null && ws.equals(webSocket)) { webSocket = null; webSocketLastActive = false; if (logger.isDebugEnabled()) { logger.debug( "Web socket closed for endpoint " + endpoint.getID() + ": " + statusCode + " " + reason); } } } } /** * {@inheritDoc} */ @Override protected void close() { synchronized (webSocketSyncRoot) { if (webSocket != null) { // 410 Gone indicates that the resource requested is no longer // available and will not be available again. webSocket.getSession().close(410, "replaced"); webSocket = null; if (logger.isDebugEnabled()) { logger.debug("Endpoint expired, closed colibri web-socket."); } } } } /** * Notifies this {@link EndpointMessageTransport} that a message has been * received from a specific {@link ColibriWebSocket} instance associated with * its {@link Endpoint}. * * @param ws the {@link ColibriWebSocket} from which a message was received. */ public void onWebSocketText(ColibriWebSocket ws, String message) { if (ws == null || !ws.equals(webSocket)) { logger.warn("Received text from an unknown web socket " + "(endpoint=" + endpoint.getID() + ")."); return; } endpoint.getConference().getVideobridge().getStatistics().totalColibriWebSocketMessagesReceived .incrementAndGet(); webSocketLastActive = true; onMessage(ws, message); } /** * @return the {@link SctpConnection} associated with this endpoint. */ SctpConnection getSctpConnection() { return sctpConnection.get(); } /** * Sets the {@link SctpConnection} associated with this endpoint. * * @param sctpConnection the new {@link SctpConnection}. */ void setSctpConnection(SctpConnection sctpConnection) { SctpConnection oldValue = getSctpConnection(); if (!Objects.equals(oldValue, sctpConnection)) { if (oldValue != null && sctpConnection != null) { // This is not necessarily invalid, but with the current // codebase it likely indicates a problem. If we start to // actually use it, this warning should be removed. logger.warn("Replacing an Endpoint's SctpConnection."); } this.sctpConnection = new WeakReference<>(sctpConnection); if (sctpConnection != null) { if (sctpConnection.isReady()) { notifyTransportChannelConnected(); } else { sctpConnection.addChannelListener(webRtcDataStreamListener); } } if (oldValue != null) { oldValue.removeChannelListener(webRtcDataStreamListener); } } } }
31.677019
114
0.706928
98b5e3805803d5dbbb4518873a0c4bf1e709d199
444
package vini2003.xyz.bodyshuffle.registry.client; import net.fabricmc.fabric.api.client.screenhandler.v1.ScreenRegistry; import vini2003.xyz.bodyshuffle.client.screen.BodyPartSelectorScreen; import vini2003.xyz.bodyshuffle.registry.common.BodyShuffleScreenHandlers; public class BodyShuffleScreens { public static void initialize() { ScreenRegistry.register(BodyShuffleScreenHandlers.BODY_PART_SELECTOR, BodyPartSelectorScreen::new); } }
37
101
0.851351
d5325ac43c85fdf4d277cbc0e2f1bb243ddce8d7
4,656
package com.mohsenoid.androidutils.location; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.util.Log; public class LocationHelper { String TAG = this.getClass().getSimpleName(); Context context; private final LocationManager locationManager; private final CurrentLocationListener listener; private final LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.i(TAG, "onStatusChanged() Status=" + status); if (listener != null) switch (status) { case LocationProvider.AVAILABLE: listener.onProviderAvailable(); break; case LocationProvider.OUT_OF_SERVICE: locationManager.removeUpdates(locationListener); listener.onProviderUnavailable(); break; case LocationProvider.TEMPORARILY_UNAVAILABLE: locationManager.removeUpdates(locationListener); listener.onProviderUnavailable(); break; } } @Override public void onProviderEnabled(String provider) { Log.i(TAG, "onProviderEnabled()"); if (listener != null) listener.onProviderAvailable(); } @Override public void onProviderDisabled(String provider) { Log.i(TAG, "onProviderDisabled()"); if (listener != null) listener.onProviderUnavailable(); } @Override public void onLocationChanged(Location location) { Log.i(TAG, "onLocationChanged() Location=" + location.toString()); locationManager.removeUpdates(locationListener); if (listener != null) listener.onLocationChanged(location); } }; public LocationHelper(Context context, String provider, CurrentLocationListener listener) { Log.i(TAG, "Cunstructor! Provider=" + provider); this.context = context; this.listener = listener; locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); try { locationManager.requestLocationUpdates(provider, 5000, 0, locationListener); } catch (Exception e) { if (listener != null) listener.onProviderUnavailable(); e.printStackTrace(); } } public LocationHelper(Context context, CurrentLocationListener listener) { Log.i(TAG, "Cunstructor!"); this.context = context; this.listener = listener; locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); boolean gpsEnabled = false; boolean networkEnabled = false; try { gpsEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { ex.printStackTrace(); } try { networkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception ex) { ex.printStackTrace(); } // don't start listeners if no provider is enabled if (!gpsEnabled && !networkEnabled) { Log.i(TAG, "onProviderUnavailable()"); if (listener != null) listener.onProviderUnavailable(); } if (gpsEnabled) { Log.i(TAG, "GPS Provider Available!"); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 0, locationListener); } if (networkEnabled) { Log.i(TAG, "Network Provider Available!"); locationManager .requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener); } } public void pause() { Log.i(TAG, "Paused!"); locationManager.removeUpdates(locationListener); } public interface CurrentLocationListener { void onProviderAvailable(); void onProviderUnavailable(); void onLocationChanged(Location location); } }
32.333333
81
0.587414
bb9becaa537a7a0ff2be9601804cfb62833dd6dd
5,432
package de.unistuttgart.vis.vita.persistence; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import javax.persistence.Query; import org.junit.Test; import de.unistuttgart.vis.vita.data.EntityRelationTestData; import de.unistuttgart.vis.vita.data.PersonTestData; import de.unistuttgart.vis.vita.data.PlaceTestData; import de.unistuttgart.vis.vita.model.entity.EntityRelation; import de.unistuttgart.vis.vita.model.entity.Person; import de.unistuttgart.vis.vita.model.entity.Place; /** * Performs tests whether instances of EntityRelation can be persisted correctly. */ public class EntityRelationPersistenceTest extends AbstractPersistenceTest { private PersonTestData personTestData; private PlaceTestData placeTestData; private EntityRelationTestData relationTestData; @Override public void setUp() { super.setUp(); // set up test data this.personTestData = new PersonTestData(); this.placeTestData = new PlaceTestData(); this.relationTestData = new EntityRelationTestData(); } /** * Reads EntityRelations from database and returns them. * * @return list of entity relations */ private List<?> readEntityRelationsFromDb() { Query query = em.createQuery("from EntityRelation", EntityRelation.class); return query.getResultList(); } /** * Checks whether one EntityRelation can be persisted. */ @SuppressWarnings("unchecked") @Test public void testPersistOnePersonRelation() { // first set up a entity relation Person testPerson = personTestData.createTestPerson(1); Person relatedPerson = personTestData.createTestPerson(2); EntityRelation rel = relationTestData.createTestRelation(testPerson, relatedPerson); testPerson.getEntityRelations().add(rel); // persist this entity relation em.persist(testPerson); em.persist(relatedPerson); em.persist(rel); startNewTransaction(); // read persisted entity relations List<EntityRelation> relations = (List<EntityRelation>) readEntityRelationsFromDb(); // check whether data is correct assertEquals(1, relations.size()); EntityRelation readRelation = relations.get(0); relationTestData.checkData(readRelation); } @SuppressWarnings("unchecked") @Test public void testPersistOnePlaceRelation() { // first set up a entity relation Place testPlace = placeTestData.createTestPlace(1); Place relatedPlace = placeTestData.createTestPlace(2); EntityRelation rel = relationTestData.createTestRelation(testPlace, relatedPlace); testPlace.getEntityRelations().add(rel); // persist entities and their relation em.persist(testPlace); em.persist(relatedPlace); em.persist(rel); startNewTransaction(); // read persisted entity relations List<EntityRelation> relations = (List<EntityRelation>) readEntityRelationsFromDb(); // check whether data is correct assertEquals(1, relations.size()); EntityRelation readRelation = relations.get(0); relationTestData.checkData(readRelation); } /** * Checks whether all Named Queries of EntityRelation are working correctly. */ @SuppressWarnings("unchecked") @Test public void testNamedQueries() { Person testPerson = personTestData.createTestPerson(1); Person relatedPerson = personTestData.createTestPerson(2); EntityRelation rel = relationTestData.createTestRelation(testPerson, relatedPerson); testPerson.getEntityRelations().add(rel); EntityRelation backRel = relationTestData.createTestRelation(relatedPerson, testPerson); testPerson.getEntityRelations().add(backRel); // persist entities and their relation em.persist(testPerson); em.persist(relatedPerson); em.persist(rel); startNewTransaction(); // check Named Query finding all entity relations Query allQ = em.createNamedQuery("EntityRelation.findAllEntityRelations"); List<EntityRelation> allEntityRelations = allQ.getResultList(); assertTrue(allEntityRelations.size() > 0); EntityRelation readRelation = allEntityRelations.get(0); relationTestData.checkData(readRelation); String id = readRelation.getId(); // check Named Query finding entity relation for entities List<String> entityIdList = new ArrayList<>(); entityIdList.add(testPerson.getId()); entityIdList.add(relatedPerson.getId()); Query entQ = em.createNamedQuery("EntityRelation.findRelationsForEntities"); entQ.setParameter("entityIds", entityIdList); List<EntityRelation> relations = entQ.getResultList(); assertEquals(1, relations.size()); relationTestData.checkData(relations.get(0)); // check Named Query finding entity relation for entities Query entityTypeQ = em.createNamedQuery("EntityRelation.findRelationsForEntitiesAndType"); entityTypeQ.setParameter("entityIds", entityIdList); entityTypeQ.setParameter("type", "Person"); List<EntityRelation> entTypeRelations = entityTypeQ.getResultList(); assertEquals(1, entTypeRelations.size()); relationTestData.checkData(entTypeRelations.get(0)); // check Named Query finding entity relation by id Query idQ = em.createNamedQuery("EntityRelation.findEntityRelationById"); idQ.setParameter("entityRelationId", id); EntityRelation idRelation = (EntityRelation) idQ.getSingleResult(); relationTestData.checkData(idRelation); } }
34.379747
94
0.74908
b0fee0bdbebad042d5c28c516589b6ce2224a0fb
144
package com.major94.TetrisX.input; public interface StandardInput { public boolean isClicked(Key key); public boolean isPressed(Key key); }
18
35
0.784722
30ea51f2643f29839a9db14e8d6e3b866fffb716
3,716
package com.sdl.selenium.extjs3.form; import com.sdl.selenium.extjs3.ExtJsComponent; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.form.IField; import com.sdl.selenium.web.form.ITextField; import com.sdl.selenium.web.utils.MultiThreadClipboardUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.hamcrest.MatcherAssert.assertThat; public class TextField extends ExtJsComponent implements ITextField { private static final Logger LOGGER = LoggerFactory.getLogger(TextField.class); public TextField() { setClassName("TextField"); setTag("input"); setElPathSuffix("not-hidden", "not(@type='hidden')"); setLabelPosition("//following-sibling::*//"); } public TextField(String cls) { this(); setClasses(cls); } public TextField(WebLocator container) { this(); setContainer(container); } public TextField(WebLocator container, String label) { this(container); setLabel(label); } public TextField(String name, WebLocator container) { this(container); setName(name); } /** * @param value value * @param searchTypes accept only SearchType.EQUALS, SearchType.CONTAINS, SearchType.STARTS_WITH, SearchType.TRIM * @return current element */ public <T extends IField> T setPlaceholder(String value, SearchType... searchTypes) { setAttribute("placeholder", value, searchTypes); return (T) this; } // methods public boolean pasteInValue(String value) { assertReady(); if (value != null) { doClear(); MultiThreadClipboardUtils.copyString(value); MultiThreadClipboardUtils.pasteString(this); LOGGER.info("Set value(" + this + "): " + value + "'"); return true; } return false; } public boolean setValue(String value) { assertReady(); boolean setted = executor.setValue(this, value); assertThat("Could not setValue on : " + this, setted); return true; } public boolean doSetValue(String value) { boolean setted = false; if (ready()) { setted = executor.setValue(this, value); if (!setted) { LOGGER.warn("Could not setValue on {}", this); } } else { LOGGER.info("Element was not rendered {}", toString()); } return setted; } /** * getValue using xPath only, depending on the parameter * * @return string */ public String getValue() { assertReady(); return executor.getValue(this); } public String getTriggerPath(String icon) { return "/parent::*//*[contains(@class,'x-form-" + icon + "-trigger')]"; } public boolean clickIcon(String icon) { assertReady(); String triggerPath = getTriggerPath(icon); WebLocator iconLocator = new WebLocator(this).setElPath(triggerPath); iconLocator.setRenderMillis(500); iconLocator.setInfoMessage(this + " -> trigger-" + icon); iconLocator.click(); return true; } /** * @return true is the element doesn't have attribute readonly */ public boolean isEditable() { return !"true".equals(getAttribute("readonly")); } /** * @return true is the element does have attribute disabled */ public boolean isDisabled() { return "true".equals(getAttribute("disabled")); } public boolean isEnabled() { return !"true".equals(getAttribute("disabled")); } }
29.03125
117
0.616254
9872c7ba717c1761141be67a1d342446ec76b35f
2,395
/* * Copyright 2017-2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.configuration.jasync.health; import com.github.jasync.sql.db.Connection; import io.micronaut.context.annotation.Requires; import io.micronaut.core.util.StringUtils; import io.micronaut.health.HealthStatus; import io.micronaut.management.endpoint.health.HealthEndpoint; import io.micronaut.management.health.indicator.HealthIndicator; import io.micronaut.management.health.indicator.HealthResult; import jakarta.inject.Singleton; import org.reactivestreams.Publisher; import reactor.core.publisher.Mono; import java.util.HashMap; import java.util.Map; /** * A {@link HealthIndicator} for reactive Postgres client. * * @author puneetbehl * @since 1.0 */ @Requires(beans = HealthEndpoint.class) @Requires(property = HealthEndpoint.PREFIX + ".jasync.enabled", notEquals = StringUtils.FALSE) @Singleton public class JasyncHealthIndicator implements HealthIndicator { public static final String NAME = "postgres-reactive"; public static final String QUERY = "SELECT version();"; private final Connection client; /** * Constructor. * * @param client A pool of connections. */ public JasyncHealthIndicator(Connection client) { this.client = client; } @Override public Publisher<HealthResult> getResult() { return Mono.fromFuture(client.sendQuery(QUERY)) .map(queryResult -> { Map<String, String> error = new HashMap<>(1); error.put("version", String.valueOf(queryResult.getRows().get(0).get(0))); return HealthResult.builder(NAME, HealthStatus.UP).details(error).build(); }) .onErrorResume(error -> Mono.just(HealthResult.builder(NAME, HealthStatus.DOWN).exception(error).build())); } }
35.220588
123
0.715658
e50a2c8fb6bcb5635dc0ed26e4e2d5ef1a66bf17
2,033
/* * $Id$ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.util; /** * Interface to represent any thing that can take a log message and output it * to a destination (could be stderr, email, syslogd, etc.) */ public interface LogTarget{ /** * Output a message to a log target. Implementations may prepend * the date and/or message level to the message, if appropriate, * * @param log the <code>Logger</code> instance making the call. * @param msglevel severity level of log call. * @param message string to output. */ public void handleMessage(Logger log, int msglevel, String message); /** Called the first time target is added to a logger */ public void init(); }
37.648148
78
0.765371
8c6fecab60841d98ca63e47f7856588c0292e95c
992
package org.dwcj.panels; import com.basis.bbj.proxies.sysgui.BBjWindow; import com.basis.startup.type.BBjException; import org.dwcj.App; import org.dwcj.Environment; /** * This class represents a div container, which behaves as a panel and * can be styled and hold other divs (panels) and controls */ public final class Div extends AbstractDwcjPanel { public Div() { } void create(AbstractDwcjPanel p) { App.consoleLog("reached create"); BBjWindow w = p.getBBjWindow(); try { byte[] flags = new byte[]{(byte) 0x00, (byte) 0x10, (byte) 0x88, (byte) 0x00}; //todo honor visible flag if set before addition to panel wnd = w.addChildWindow(w.getAvailableControlID(), BASISNUMBER_1, BASISNUMBER_1, BASISNUMBER_1, BASISNUMBER_1, "", flags, Environment.getInstance().getSysGui().getAvailableContext()); ctrl = wnd; } catch (BBjException e) { e.printStackTrace(); } } }
26.810811
194
0.654234
a29c4abe63b2b6479562236d3915c8dd1096d1df
274
package com.south.worker.ui.user_info; import com.bumptech.glide.annotation.GlideModule; import com.bumptech.glide.module.AppGlideModule; /** * 描述 : * <p> * 作者 :Created by DR on 2018/6/15. */ @GlideModule public class MyAppGlideModule extends AppGlideModule { }
17.125
54
0.733577
c9710784ca8919cbc7fbc3325af588ea47746686
6,995
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.impl.source.codeStyle; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.jsp.JavaJspRecursiveElementVisitor; import com.intellij.psi.jsp.JspFile; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; /** * @author max */ public class BraceEnforcer extends JavaJspRecursiveElementVisitor { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.codeStyle.BraceEnforcer"); private final PostFormatProcessorHelper myPostProcessor; public BraceEnforcer(CodeStyleSettings settings) { myPostProcessor = new PostFormatProcessorHelper(settings.getCommonSettings(JavaLanguage.INSTANCE)); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { visitElement(expression); } @Override public void visitIfStatement(PsiIfStatement statement) { if (checkElementContainsRange(statement)) { final SmartPsiElementPointer pointer = SmartPointerManager.getInstance(statement.getProject()).createSmartPsiElementPointer(statement); super.visitIfStatement(statement); statement = (PsiIfStatement)pointer.getElement(); if (statement == null) { return; } processStatement(statement, statement.getThenBranch(), myPostProcessor.getSettings().IF_BRACE_FORCE); final PsiStatement elseBranch = statement.getElseBranch(); if (!(elseBranch instanceof PsiIfStatement) || !myPostProcessor.getSettings().SPECIAL_ELSE_IF_TREATMENT) { processStatement(statement, elseBranch, myPostProcessor.getSettings().IF_BRACE_FORCE); } } } @Override public void visitForStatement(PsiForStatement statement) { if (checkElementContainsRange(statement)) { super.visitForStatement(statement); processStatement(statement, statement.getBody(), myPostProcessor.getSettings().FOR_BRACE_FORCE); } } @Override public void visitForeachStatement(PsiForeachStatement statement) { if (checkElementContainsRange(statement)) { super.visitForeachStatement(statement); processStatement(statement, statement.getBody(), myPostProcessor.getSettings().FOR_BRACE_FORCE); } } @Override public void visitWhileStatement(PsiWhileStatement statement) { if (checkElementContainsRange(statement)) { super.visitWhileStatement(statement); processStatement(statement, statement.getBody(), myPostProcessor.getSettings().WHILE_BRACE_FORCE); } } @Override public void visitDoWhileStatement(PsiDoWhileStatement statement) { if (checkElementContainsRange(statement)) { super.visitDoWhileStatement(statement); processStatement(statement, statement.getBody(), myPostProcessor.getSettings().DOWHILE_BRACE_FORCE); } } @Override public void visitJspFile(JspFile file) { final PsiClass javaRoot = file.getJavaClass(); if (javaRoot != null) { javaRoot.accept(this); } } private void processStatement(PsiStatement statement, PsiStatement blockCandidate, int options) { if (blockCandidate instanceof PsiBlockStatement || blockCandidate == null) return; if (options == CommonCodeStyleSettings.FORCE_BRACES_ALWAYS || (options == CommonCodeStyleSettings.FORCE_BRACES_IF_MULTILINE && PostFormatProcessorHelper.isMultiline(statement))) { replaceWithBlock(statement, blockCandidate); } } private void replaceWithBlock(@NotNull PsiStatement statement, PsiStatement blockCandidate) { if (!statement.isValid()) { LOG.assertTrue(false); } if (!checkRangeContainsElement(blockCandidate)) return; final PsiManager manager = statement.getManager(); LOG.assertTrue(manager != null); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); String oldText = blockCandidate.getText(); // There is a possible case that target block to wrap ends with single-line comment. Example: // if (true) i = 1; // Cool assignment // We can't just surround target block of code with curly braces because the closing one will be treated as comment as well. // Hence, we perform a check if we have such situation at the moment and insert new line before the closing brace. int lastLineFeedIndex = oldText.lastIndexOf("\n"); lastLineFeedIndex = Math.max(0, lastLineFeedIndex); int lastLineCommentIndex = oldText.indexOf("//", lastLineFeedIndex); StringBuilder buf = new StringBuilder(oldText.length() + 5); buf.append("{ ").append(oldText); if (lastLineCommentIndex >= 0) { buf.append("\n"); } buf.append(" }"); final int oldTextLength = statement.getTextLength(); try { CodeEditUtil.replaceChild(SourceTreeToPsiMap.psiElementToTree(statement), SourceTreeToPsiMap.psiElementToTree(blockCandidate), SourceTreeToPsiMap.psiElementToTree(factory.createStatementFromText(buf.toString(), null))); CodeStyleManager.getInstance(statement.getProject()).reformat(statement, true); } catch (IncorrectOperationException e) { LOG.error(e); } finally { updateResultRange(oldTextLength , statement.getTextLength()); } } protected void updateResultRange(final int oldTextLength, final int newTextLength) { myPostProcessor.updateResultRange(oldTextLength, newTextLength); } protected boolean checkElementContainsRange(final PsiElement element) { return myPostProcessor.isElementPartlyInRange(element); } protected boolean checkRangeContainsElement(final PsiElement element) { return myPostProcessor.isElementFullyInRange(element); } public PsiElement process(PsiElement formatted) { LOG.assertTrue(formatted.isValid()); formatted.accept(this); return formatted; } public TextRange processText(final PsiFile source, final TextRange rangeToReformat) { myPostProcessor.setResultTextRange(rangeToReformat); source.accept(this); return myPostProcessor.getResultTextRange(); } }
40.668605
141
0.75025
8fff2bd9c0cbae79c70d0f818de540fd50acca58
6,577
package com.chimericdream.minekea.block.furniture.seating; import com.chimericdream.minekea.ModInfo; import com.chimericdream.minekea.compat.ModCompatLayer; import com.chimericdream.minekea.util.MinekeaBlockCategory; import net.fabricmc.fabric.api.client.rendereregistry.v1.EntityRendererRegistry; import net.fabricmc.fabric.api.object.builder.v1.entity.FabricEntityTypeBuilder; import net.minecraft.entity.EntityType; import net.minecraft.entity.SpawnGroup; import net.minecraft.util.Identifier; import net.minecraft.util.registry.Registry; import java.util.List; import java.util.Map; public class Seats implements MinekeaBlockCategory { public static final GenericChair ACACIA_CHAIR; public static final GenericChair BIRCH_CHAIR; public static final GenericChair CRIMSON_CHAIR; public static final GenericChair DARK_OAK_CHAIR; public static final GenericChair JUNGLE_CHAIR; public static final GenericChair OAK_CHAIR; public static final GenericChair SPRUCE_CHAIR; public static final GenericChair WARPED_CHAIR; public static final GenericStool ACACIA_STOOL; public static final GenericStool BIRCH_STOOL; public static final GenericStool CRIMSON_STOOL; public static final GenericStool DARK_OAK_STOOL; public static final GenericStool JUNGLE_STOOL; public static final GenericStool OAK_STOOL; public static final GenericStool SPRUCE_STOOL; public static final GenericStool WARPED_STOOL; public static EntityType<SeatEntity> SEAT_ENTITY; static { ACACIA_CHAIR = new GenericChair( "acacia", Map.of( "planks", new Identifier("minecraft:acacia_planks"), "log", new Identifier("minecraft:acacia_log") ) ); BIRCH_CHAIR = new GenericChair( "birch", Map.of( "planks", new Identifier("minecraft:birch_planks"), "log", new Identifier("minecraft:birch_log") ) ); CRIMSON_CHAIR = new GenericChair( "crimson", Map.of( "planks", new Identifier("minecraft:crimson_planks"), "log", new Identifier("minecraft:crimson_stem") ) ); DARK_OAK_CHAIR = new GenericChair( "dark_oak", Map.of( "planks", new Identifier("minecraft:dark_oak_planks"), "log", new Identifier("minecraft:dark_oak_log") ) ); JUNGLE_CHAIR = new GenericChair( "jungle", Map.of( "planks", new Identifier("minecraft:jungle_planks"), "log", new Identifier("minecraft:jungle_log") ) ); OAK_CHAIR = new GenericChair( "oak", Map.of( "planks", new Identifier("minecraft:oak_planks"), "log", new Identifier("minecraft:oak_log") ) ); SPRUCE_CHAIR = new GenericChair( "spruce", Map.of( "planks", new Identifier("minecraft:spruce_planks"), "log", new Identifier("minecraft:spruce_log") ) ); WARPED_CHAIR = new GenericChair( "warped", Map.of( "planks", new Identifier("minecraft:warped_planks"), "log", new Identifier("minecraft:warped_stem") ) ); ACACIA_STOOL = new GenericStool( "acacia", Map.of( "planks", new Identifier("minecraft:acacia_planks"), "log", new Identifier("minecraft:acacia_log") ) ); BIRCH_STOOL = new GenericStool( "birch", Map.of( "planks", new Identifier("minecraft:birch_planks"), "log", new Identifier("minecraft:birch_log") ) ); CRIMSON_STOOL = new GenericStool( "crimson", Map.of( "planks", new Identifier("minecraft:crimson_planks"), "log", new Identifier("minecraft:crimson_stem") ) ); DARK_OAK_STOOL = new GenericStool( "dark_oak", Map.of( "planks", new Identifier("minecraft:dark_oak_planks"), "log", new Identifier("minecraft:dark_oak_log") ) ); JUNGLE_STOOL = new GenericStool( "jungle", Map.of( "planks", new Identifier("minecraft:jungle_planks"), "log", new Identifier("minecraft:jungle_log") ) ); OAK_STOOL = new GenericStool( "oak", Map.of( "planks", new Identifier("minecraft:oak_planks"), "log", new Identifier("minecraft:oak_log") ) ); SPRUCE_STOOL = new GenericStool( "spruce", Map.of( "planks", new Identifier("minecraft:spruce_planks"), "log", new Identifier("minecraft:spruce_log") ) ); WARPED_STOOL = new GenericStool( "warped", Map.of( "planks", new Identifier("minecraft:warped_planks"), "log", new Identifier("minecraft:warped_stem") ) ); } @Override public void initializeClient() { EntityRendererRegistry.INSTANCE.register(SEAT_ENTITY, SeatEntity.EmptyRenderer::new); } @Override public void registerBlocks() { ACACIA_CHAIR.register(); BIRCH_CHAIR.register(); CRIMSON_CHAIR.register(); DARK_OAK_CHAIR.register(); JUNGLE_CHAIR.register(); OAK_CHAIR.register(); SPRUCE_CHAIR.register(); WARPED_CHAIR.register(); ACACIA_STOOL.register(); BIRCH_STOOL.register(); CRIMSON_STOOL.register(); DARK_OAK_STOOL.register(); JUNGLE_STOOL.register(); OAK_STOOL.register(); SPRUCE_STOOL.register(); WARPED_STOOL.register(); SEAT_ENTITY = Registry.register( Registry.ENTITY_TYPE, new Identifier(ModInfo.MOD_ID, "seats/seat_entity"), FabricEntityTypeBuilder.<SeatEntity>create(SpawnGroup.MISC, SeatEntity::new).build() ); } @Override public void registerBlockEntities(List<ModCompatLayer> otherMods) { } @Override public void registerEntities(List<ModCompatLayer> otherMods) { } @Override public void setupResources() { } }
33.385787
96
0.585221
039592d9df981cc9c5b296c7593931cf77433993
3,073
package com.movetogbg; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; public class AccountCreationBasicInfo extends AppCompatActivity { TextView tvTitle, tvContent; Spinner spinnerGender; Button continue_button; EditText inputName, inputAge; String UserGender = null; boolean inTransition = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_createaccount_basicinfo); fadeInClass(); initObjects(); setSpinnerObjects(); } private void validateInput(){ if(inputName.getText().toString().length() > 0 && inputAge.getText().toString().length() > 0 && UserGender != null && !inTransition){ Account.setUserName(inputName.getText().toString()); Account.setUserAge(inputAge.getText().toString()); Account.setUserGender(UserGender); Transition.fadeOutToClass(this, (RelativeLayout) findViewById(R.id.relativeLayout), AccountCreationFamilyInfo.class); inTransition = true; } } private void setSpinnerObjects(){ spinnerGender = findViewById(R.id.spinnerGender); final String[] genders = {"Select your sex", "Male","Female"}; ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.spinner_textview, genders); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerGender.setAdapter(adapter); spinnerGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(position != 0){ UserGender = genders[position]; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void initObjects(){ tvTitle = findViewById(R.id.tvWelcomeTitle); tvContent = findViewById(R.id.tvWelcomeContent); continue_button = findViewById(R.id.button_continue); inputName = findViewById(R.id.editTextName); inputAge = findViewById(R.id.editTextAge); String[] titleText = getResources().getStringArray(R.array.UserInfoPage1); tvTitle.setText(titleText[0]); tvContent.setText(titleText[1]); continue_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { validateInput(); } }); } private void fadeInClass(){ Transition.fadeInFromClass(this, (RelativeLayout) findViewById(R.id.relativeLayout)); } }
32.010417
141
0.665148
e591bfbfaa35660632076403669b4f7fecb6efe7
951
package com.chat.zipchat.clone; public class UserRegister { private String id; private String name; private String mobile_number; private String profile_url; private String status; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobile_number() { return mobile_number; } public void setMobile_number(String mobile_number) { this.mobile_number = mobile_number; } public String getProfile_url() { return profile_url; } public void setProfile_url(String profile_url) { this.profile_url = profile_url; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
18.647059
56
0.616193
6ff31664e502ddc5c8d464e9d93fa5eec7ea37e0
867
package com.detroitlabs.katalonmobileutil.component.mobile; import com.detroitlabs.katalonmobileutil.component.TwoStatePressableComponent; import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords; import com.kms.katalon.core.model.FailureHandling; import com.kms.katalon.core.testobject.TestObject; /** * MobileTwoStatePressableComponent */ public class MobileTwoStatePressableComponent extends MobilePressableComponent implements TwoStatePressableComponent { protected final TestObject altTestObject; public MobileTwoStatePressableComponent(TestObject toSwitch, TestObject altState) { super(toSwitch); altTestObject = altState; } @Override public void pressAlternate(int timeoutInSeconds, FailureHandling failureHandling) { MobileBuiltInKeywords.tap(altTestObject, timeoutInSeconds, failureHandling); } }
37.695652
118
0.811995
fdd23fbe91dd3fa61f7685679fb75f0e4a03ae59
265
package com.xuchg.dao; import java.util.List; import com.xuchg.base.dao.BaseDAO; import com.xuchg.vo.ConnectVO; public interface ConnectDAO extends BaseDAO<ConnectVO>{ /** * 查找是否重名 * @param name * @return */ List<ConnectVO> findByName(String name); }
15.588235
55
0.720755
63107161dd31f14ed366f0ec515fd904c7e6e135
4,558
package com.machinestalk.android.utilities; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.BatteryManager; import android.os.Build; import android.provider.Settings; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.WindowManager; /** * Utility class which is responsible for returning device specific information. * * */ public final class DeviceUtility { /** The device id. */ private static String deviceID = ""; /** The os version. */ private static String osVersion = ""; /** The mobile app version. */ private static String mobileAppVersion = ""; private DeviceUtility() { } /** * A 64-bit number (as a hex string) that is randomly generated on the * device's first boot and should remain constant for the lifetime of the * device. (The value may change if a factory reset is performed on the * device). * * @param context A valid context * @return Unique device ID */ public static String getDeviceID (Context context) { if (StringUtility.isEmptyOrNull (deviceID)) { deviceID = Settings.Secure.getString (context.getContentResolver (), Settings.Secure.ANDROID_ID); } return deviceID; } /** * Returns current percentage of battery left on the device. * * @param context A valid context * @return Battery level percentage */ public static int getBatteryLevel (Context context) { Intent batteryStatus = context.registerReceiver (null, new IntentFilter (Intent.ACTION_BATTERY_CHANGED)); if(batteryStatus == null) { return -1; } int level = batteryStatus.getIntExtra (BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra (BatteryManager.EXTRA_SCALE, -1); return (int) ((level / (float) scale) * 100); } /** * Gets the Android's version being run by the device. * * @return Android's version number as string */ public static String getOSVersion () { if (StringUtility.isEmptyOrNull (osVersion)) { osVersion = "Android " + Build.VERSION.RELEASE; } return osVersion; } /** * Gets the app's version as specified in the manifest file. * * @param context A valid context * @return The application's version number as string */ public static String getAppVersion (Context context) { if (StringUtility.isEmptyOrNull (mobileAppVersion)) { try { PackageInfo pInfo = context.getPackageManager ().getPackageInfo (context.getPackageName (), 0); mobileAppVersion = pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { } } return mobileAppVersion; } /** * Converts density independent pixels (dip) into pixels (px) according to * the current device configuration. * * @param dp The dp input value * @param context A valid context * @return Equivalent pixels value against the specified dp value. */ public static int getPixelsFromDps (int dp, Context context) { Resources r = context.getResources (); return (int) TypedValue.applyDimension (TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics ()); } /** * Determines the network connection state. Network can be either Wifi/Data. * * @param context A valid context * @return {@code true} if a trace of an active Wifi/data connection found, * {@code false} otherwise */ public static boolean isInternetConnectionAvailable (Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo (); return (netInfo != null) && netInfo.isAvailable() && netInfo.isConnectedOrConnecting(); } public static boolean isBelowKitKat() { return Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2; } public static int getScreenWidthInPixels(Context context) { DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); return metrics.widthPixels; } public static int getScreenHeightInPixels(Context context) { DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); return metrics.heightPixels; } }
28.848101
107
0.735849
de7995053b310b1f8382d21212ae39ee98d74229
1,588
/* * ----------------------------------------------------------------------- * Copyright 2013 - Alistair Rutherford - www.netthreads.co.uk * ----------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netthreads.easycp.annotation; import android.provider.BaseColumns; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Content Provider annotation. * */ @Retention(RetentionPolicy.RUNTIME) @Target( { ElementType.TYPE }) public @interface ContentProvider { public static final String DEFAULT_ID = BaseColumns._ID; public static final String DEFAULT_DB = ""; public static final String DEFAULT_AUTHORITY = ""; public String database() default DEFAULT_DB; public String authority() default DEFAULT_AUTHORITY; public Class<?> tableClass(); public int version(); public String idField() default DEFAULT_ID; }
29.962264
76
0.661839
b48859e6415a9dccdf17921adeb4c4421ad09967
19,128
/* * The MIT License * * Copyright 2019 Tom. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.bicycleGeometryWorkshop.app; import org.bicycleGeometryWorkshop.database.BGWDataBase; import org.bicycleGeometryWorkshop.components.BicycleListener; import org.bicycleGeometryWorkshop.geometry.Utilities; import org.bicycleGeometryWorkshop.components.Bicycle; import org.bicycleGeometryWorkshop.components.ComponentOwner; import org.bicycleGeometryWorkshop.report.Report; import org.bicycleGeometryWorkshop.components.RiderMeasurements; import org.bicycleGeometryWorkshop.components.RiderPose; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.File; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JOptionPane; import org.bicycleGeometryWorkshop.app.undo.AttributeUndo; import org.bicycleGeometryWorkshop.app.undo.BaseUndo; import org.bicycleGeometryWorkshop.app.undo.BicycleAddUndo; import org.bicycleGeometryWorkshop.app.undo.BicycleDeleteUndo; import org.bicycleGeometryWorkshop.app.undo.BicycleMoveUndo; import org.bicycleGeometryWorkshop.app.undo.UndoManager; import org.bicycleGeometryWorkshop.attributes.AttributeChangeEvent; import org.bicycleGeometryWorkshop.components.BicycleChangeEvent; import org.bicycleGeometryWorkshop.components.BicycleDisplay; import org.bicycleGeometryWorkshop.components.BicycleEventType; import org.bicycleGeometryWorkshop.components.ComponentChangeEvent; import org.bicycleGeometryWorkshop.report.ReportValue; import org.bicycleGeometryWorkshop.ui.BicycleGeometryWorkshopUI; /** * This is the main class for the project presented in the UI. The project * consists of the rider measurements, the rider pose, project preferences, and * the collection of bicycles. * <p> * The project's undo queue is managed internally in the UndoManager class. * Component change events are captured at the project level and added to the * undo queue. * <p> * The BGWProject class handles file IO internally in the BGWDataBAse class. The * majority of IO is done through that class with the exception of the * BGWLibrary class which serves as a wrapper over the database. * * * @author Tom */ public class BGWProject implements ComponentOwner, BicycleListener { private RiderMeasurements _riderSize; private RiderPose _riderPose; private ArrayList<Bicycle> _bicycles; //private Bicycle _activeBicycle; private VisualPreferences _visualPrefs; private ProjectListener _listener; private BGWDataBase _db; private boolean _isDirty; private UndoManager _undo; /** * Class constructor. The class is initialized with the project listener * (UI). * * @param listener The project listener. */ public BGWProject(ProjectListener listener) { _isDirty = false; //no chenges to save _db = new BGWDataBase(); _listener = listener; _riderSize = new RiderMeasurements(this); _riderPose = new RiderPose(this); //visual preferences _visualPrefs = new VisualPreferences(this); //intialize list _bicycles = new ArrayList(); _undo = new UndoManager(); //create default bicycle createDefaultBicycle(); } /** * Add a default bicycle without notifying the listener. */ private void createDefaultBicycle() { Bicycle bicycle = new Bicycle("Bicycle 1", _riderSize, _riderPose, _visualPrefs); //set listener bicycle.setBicycleListener(this); //add to the collection _bicycles.add(bicycle); } //<editor-fold defaultstate="collapsed" desc="Undo Methods"> /** * Perform an undo action. */ public void undo() { _undo.undo(); } /** * Perform a redo action. */ public void redo() { _undo.redo(); } /** * Add an undo to the stack from outside the project. This is done for UI * changes (background color, etc). * * @param undo The undo object to push to the undo stack. */ public void pushUndo(BaseUndo undo) { _undo.pushUndo(undo); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="File Methods (open, save,etc)"> /** * Do a file dirty check (save changes to file?). * * @return True if the operation can continue, false is the flag to cancel. */ public boolean dirtyCheck() { boolean proceed = false; if (_isDirty) { String mssg = "The project has unsaved changes, save changes?"; JFrame frame = BicycleGeometryWorkshopUI.getActiveFrame(); int result = JOptionPane.showConfirmDialog(frame, mssg, "Project changed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); //check results if (result == JOptionPane.YES_OPTION) { //atempt to save proceed = _db.saveFile(this); } else if (result == JOptionPane.NO_OPTION) { //discard changes proceed = true; } else { proceed = false; } } else { //file not dirty proceed = true; } return proceed; } /** * Save the file */ public void saveFile() { _db.saveFile(this); _isDirty = false; } /** * Save file to new file. */ public void saveFileAs() { _db.saveFileAs(this); _isDirty = false; } public void openFile() { if (!dirtyCheck()) { return; } boolean opened = _db.openFile(this); if (opened) { postLoadUpdate(); // _undo.reset(); // System.out.println("--Updating after open..."); // //attach geometry listeners to bicycles // for (Bicycle b : _bicycles) { // b.setBicycleListener(this); // b.updateAllComponents(); // } // // _listener.projectedLoadedFromDB(); // // _listener.updateReport(); // // _listener.redrawViewer(); // // _isDirty = false; } } /** * Open the default file if it exists. */ public void openDefaultFile() { String workingDir = System.getProperty("user.dir"); String ps = File.separator; String path = workingDir + ps + "Library" + ps + "default" + "." + BGWDataBase.FILE_EXT; File defaultFile = new File(path); //open if it exists if (defaultFile.exists()) { //do update on successfull load if (_db.openFile(this, path)) { postLoadUpdate(); //reset the database flags for open file _db.resetOpenFlags(); } } } /** * Update the project after it has been loaded from disk. */ private void postLoadUpdate() { _undo.reset(); System.out.println("--Updating after open..."); //attach geometry listeners to bicycles for (Bicycle b : _bicycles) { b.setBicycleListener(this); b.updateAllComponents(); } _listener.projectedLoadedFromDB(); _listener.updateReport(); _listener.redrawViewer(); _isDirty = false; } /** * Get the saved file path (path and file name). If the file has not been * saved this will be an empty string. * * @return The file path or an empty string. */ public String getFilePath() { return _db.getFilePath(); } /** * Get the flag for changes to the project. * * @return True if the project needs to be saved, false otherwise. */ public boolean isDirty() { return _isDirty; } //</editor-fold> /** * Add a Bicycle to the Collection at the specified index. If index == -1, * then add to the end, otherwise insert into position. * * @param name The name of the Bicycle * * * */ public final void addBicycle(String name) { Bicycle bicycle = new Bicycle(name, _riderSize, _riderPose, _visualPrefs); //set listener bicycle.setBicycleListener(this); _bicycles.add(bicycle); //project changed _isDirty = true; BicycleAddUndo addUndo = new BicycleAddUndo(this, bicycle); _undo.pushUndo(addUndo); //notify listener _listener.bicycleAdded(bicycle); //return bicycle; } /** * Restore a Bicycle - used from undo delete. * * @param bicycle The bicycle to add. * @param index The index in the list */ public final void restoreBicycle(Bicycle bicycle, int index) { //set listener bicycle.setBicycleListener(this); //check index for range int pos = index; if(pos == -1) { //add to list _bicycles.add( bicycle); } else { //insert into list _bicycles.add(pos, bicycle); } //project changed _isDirty = true; //notify listener - use orignal index for -1 signal _listener.bicycleRestored(bicycle, index); } /** * Delete a Bicycle from the project. * * @param bicycle Bicycle to delete. * */ public void deleteBicycle(Bicycle bicycle) { //don't delete the last bicycle if (_bicycles.size() > 1) { //double check and delete if (_bicycles.contains(bicycle)) { int index = _bicycles.indexOf(bicycle); _bicycles.remove(bicycle); //push undo BicycleDeleteUndo deleteUndo = new BicycleDeleteUndo(this, bicycle, index); _undo.pushUndo(deleteUndo); updateUI(); //send event for deletd (updates navigator); _listener.bicycleDeleted(bicycle); //project changed _isDirty = true; } }//end if size } /** * Move Bicycle up in the list. This moves * the bicycle higher up the draw order, it * will be drawn over lower bicycles. * * @param bicycle The bicycle to move up. * */ public void moveBicycleUp(Bicycle bicycle) { int index = _bicycles.indexOf(bicycle); if (index >= 0) { //int index = _bicycles.indexOf(bicycle); if (index - 1 >= 0) { _bicycles.remove(bicycle); _bicycles.add(index - 1, bicycle); BicycleMoveUndo moveUndo = new BicycleMoveUndo(this, bicycle, true); _undo.pushUndo(moveUndo); //update ui updateUI(); //notify listener _listener.bicycleMovedUp(bicycle); //project changed _isDirty = true; } } } /** * Move a bicycle down in the list. * This will move it lower and the draw order. * It will be draw below bicycles higher in the list. * * @param bicycle The bicycle to move down the list. * */ public void moveBicycleDown(Bicycle bicycle) { int index = _bicycles.indexOf(bicycle); if (index >= 0) { int count = _bicycles.size(); if (index < count - 1) { _bicycles.remove(bicycle); _bicycles.add(index + 1, bicycle); BicycleMoveUndo moveUndo = new BicycleMoveUndo(this, bicycle, false); _undo.pushUndo(moveUndo); updateUI(); //notify listener _listener.bicycleMovedDown(bicycle); //project changed _isDirty = true; } } } /** * Set all the Bicycles to this visibility (all on or off). * * @param visible True to turn all bicycles on, false to turn all bicycles * off. */ public void setAllVisibility(boolean visible) { for (Bicycle b : _bicycles) { b.setBicycleVisibility(visible); } } /** * Set all Bicycles to this display mode. * * @param display The display mode to apply to all the bicycles. */ public void setAllDisplay(BicycleDisplay display) { for (Bicycle b : _bicycles) { b.setBicycleDisplay(display); } } public void bicycleIsolate(Bicycle bicycle) { for (Bicycle b : _bicycles) { if (b.equals(bicycle)) { b.setBicycleVisibility(true); } else { b.setBicycleVisibility(false); } } } /** * Common UI Update tasks to call on listener */ private void updateUI() { _listener.updateReport(); _listener.redrawViewer(); } /** * Get the report data for the JPanel. * * @return The column header and data array. */ public ReportValue[][] getReportData() { int bCount = _bicycles.size(); ReportValue[] cols = Report.getColumnHeads(); ReportValue[][] data = new ReportValue[bCount][]; for (int i = 0; i < bCount; i++) { Bicycle b = _bicycles.get(i); Report r = b.getReport(); ReportValue[] dataRow = r.getDataRow(cols); data[i] = dataRow; } return data; } /** * Update the Model - this is called when Rider Size or Rider Pose is changed. * * @param compEvent The component event object. */ @Override public void componentChanged(ComponentChangeEvent compEvent) { String compName = compEvent.getComponent().getName(); System.out.println(">>Shared Component Changed: " + compName); for (Bicycle b : _bicycles) { b.updateFromRiderPose(compEvent); } //update the report _listener.updateReport(); //redraw the viewer _listener.redrawViewer(); //add the undo AttributeUndo au = new AttributeUndo(compEvent.getAttributeEvent()); _undo.pushUndo(au); //project changed _isDirty = true; _listener.bicycleChanged(); } /** * Called by a bicycle to notify geometry. * * @param bicycleEvent attribute change */ @Override public void bicycleChanged(BicycleChangeEvent bicycleEvent) { //project changed _isDirty = true; //notify UI to redraw viewer // System.out.println("Bicycle in project changed"); _listener.updateReport(); _listener.redrawViewer(); _listener.bicycleChanged(); //create undo BicycleEventType eType = bicycleEvent.getEventType(); AttributeChangeEvent attEvent = null; switch (eType) { case ComponentAttribute: attEvent = bicycleEvent.getComponentEvent().getAttributeEvent(); break; case BicycleAttribute: attEvent = bicycleEvent.getAttributeEvent(); break; } if (attEvent != null) { AttributeUndo au = new AttributeUndo(attEvent); _undo.pushUndo(au); } } /** * Start an undo group. Catch all undo events in a group. (used mainly for * import) */ public void undoOpenGroup() { _undo.openGroup(); } /** * Close an undo group. Stops grouping undos. * */ public void undoCloseGroup() { _undo.closeGroup(); } /** * Get the rider measurements. * * @return The rider measurements component. */ public RiderMeasurements getRiderSize() { return _riderSize; } /** * Get the rider pose. * @return The rider pose component. */ public RiderPose getRiderPose() { return _riderPose; } /** * Get the visual preferences. The visual preferences * controls color and appearance items like background color, etc. * @return The visual preferences object. */ public VisualPreferences getVisualPreferences() { return _visualPrefs; } /** * Get the list of bicycles. * * @return A list of all bicycles in the project. */ public ArrayList<Bicycle> getBicycles() { return _bicycles; } /** * Get the bounds of the project - used for the viewer. * This is the bounding box that encompasses all the bicycles * so that the viewer can perform an auto "zoom extents" operation. * * @return The bounds of the project. */ public Rectangle2D getBounds() { Rectangle2D bounds = new Rectangle2D.Double(0, 0, 1, 1); boolean hasFirst = false; for (Bicycle b : _bicycles) { //get the bounds Rectangle2D cb = b.getBounds(); //get the area of the bounds - invisible bouns have area < 1 double area = cb.getWidth() * cb.getHeight(); if (area > 1) { if (!hasFirst) { bounds.setFrame(cb); hasFirst = true; } else { bounds = Utilities.getUnionBoolean(bounds, cb); } } }//end for return bounds; } /** * Renders the bicycles in the project. This is called from the project viewer. * * @param g2 The graphics object to render to. * @param scale The scale of the current view - used for scaling line weights, etc. */ public void render(Graphics2D g2, float scale) { int bikeCount = _bicycles.size(); //render for (int i = bikeCount - 1; i >= 0; i--) { Bicycle b = _bicycles.get(i); b.render(g2, scale, _visualPrefs); } } }
26.383448
150
0.593632
84430331cdf62f5d6e94160234053ce8d363d794
928
package com.buddy.sdk; import java.io.File; import java.io.InputStream; public class BuddyFile { File file; InputStream stream; String contentType; public BuddyFile(File file, String contentType) { if (file == null || contentType == null) throw new IllegalArgumentException(); this.contentType = contentType; this.file = file; } public BuddyFile(InputStream stream, String contentType) { if (stream == null || contentType == null) throw new IllegalArgumentException(); this.contentType = contentType; this.stream = stream; } public Object getValue() { if (file != null) { return file; } return stream; } public InputStream getStream() { return stream; } public File getFile() { return file; } public String getContentType() { return contentType; } }
21.090909
88
0.607759
30fbeb9dbf65c4008365bb4e5d7d29444633b9c8
153
package mp.jprime.rest.v1; /** * Урлы базовых контроллеров */ public final class Controllers { public static final String API_MAPPING = "api/v1"; }
17
52
0.718954
8a4e1aaff764d151305860cc07219c4f0523bcbf
4,314
package eu.scape_project.planning.application; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.annotation.PreDestroy; import javax.enterprise.context.ContextNotActiveException; import javax.enterprise.context.ConversationScoped; import javax.enterprise.inject.Alternative; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import org.jboss.weld.context.ManagedConversation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Alternative @ConversationScoped public class MockConversation implements ManagedConversation, Serializable { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory.getLogger(MockConversation.class); private static Set<String> ACTIVE_CONVERSATIONS = new HashSet<String>(); private static long CONVERSATION_ID_COUNTER = 1; private boolean _transient; private BeanManager beanManager; private String id; private long timeout; // --------------------------- CONSTRUCTORS --------------------------- public MockConversation() { } @Inject public MockConversation(BeanManager beanManager) { this.beanManager = beanManager; this._transient = true; this.timeout = 0; } // --------------------- GETTER / SETTER METHODS --------------------- public long getTimeout() { verifyConversationContextActive(); return timeout; } public void setTimeout(long timeout) { verifyConversationContextActive(); this.timeout = timeout; } // ------------------------ CANONICAL METHODS ------------------------ @Override public String toString() { if (_transient) { return "Transient conversation"; } else { return "Conversation with id: " + id; } } // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface Conversation --------------------- public void begin() { verifyConversationContextActive(); if (!_transient) { throw new IllegalStateException("BEGIN_CALLED_ON_LONG_RUNNING_CONVERSATION"); } _transient = false; if (this.id == null) { // This a conversation that was made transient previously in this // request this.id = "" + CONVERSATION_ID_COUNTER++; ACTIVE_CONVERSATIONS.add(this.id); } } public void begin(String id) { verifyConversationContextActive(); if (!_transient) { throw new IllegalStateException("BEGIN_CALLED_ON_LONG_RUNNING_CONVERSATION"); } if (ACTIVE_CONVERSATIONS.contains(id)) { throw new IllegalStateException("CONVERSATION_ID_ALREADY_IN_USE:" + id); } _transient = false; this.id = id; } public void end() { if (_transient) { throw new IllegalStateException("END_CALLED_ON_TRANSIENT_CONVERSATION"); } _transient = true; ACTIVE_CONVERSATIONS.remove(this.id); } public String getId() { verifyConversationContextActive(); if (!_transient) { return id; } else { return null; } } public boolean isTransient() { verifyConversationContextActive(); return _transient; } @PreDestroy private void onDestroy() { ACTIVE_CONVERSATIONS.remove(this.id); } private void verifyConversationContextActive() { try { beanManager.getContext(ConversationScoped.class); } catch (ContextNotActiveException e) { throw new ContextNotActiveException("Conversation Context not active when method called on conversation " + this, e); } } @Override public long getLastUsed() { // TODO Auto-generated method stub return 0; } @Override public boolean lock(long arg0) { // TODO Auto-generated method stub return false; } @Override public void touch() { // TODO Auto-generated method stub } @Override public boolean unlock() { // TODO Auto-generated method stub return false; } }
26.304878
117
0.605471
aa4bff7fe6d95beb97f9a75e74cb7b9fcefcef2f
1,306
package com.tinkerpop.pipes.util.structures; import com.tinkerpop.pipes.util.AsPipe; import com.tinkerpop.pipes.util.FluentUtility; import com.tinkerpop.pipes.util.MetaPipe; import java.util.HashMap; import java.util.Map; /** * The current object at a named step in a PipesFluentPipeline can be accessed via AsMap. * AsMap maintains an internal HashMap that maps a String name to an AsPipe. * The AsPipe.getCurrentEnd() allows access to the last object to be emitted from the AsPipe. * This is used in conjunction with PipesFunction to allow PipeFunctions to access objects. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class AsMap { private final MetaPipe metaPipe; private final Map<String, AsPipe> map = new HashMap<String, AsPipe>(); public AsMap(final MetaPipe metaPipe) { this.metaPipe = metaPipe; } public void refresh() { for (final AsPipe asPipe : FluentUtility.getAsPipes(this.metaPipe)) { this.map.put(asPipe.getName(), asPipe); } } public Object get(final String name) { final AsPipe asPipe = this.map.get(name); if (null == asPipe) throw new RuntimeException("Named step does not exist: " + name); else return asPipe.getCurrentEnd(); } }
31.095238
93
0.692956