hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1cde4c326874f85d4f5c68ba10addca8cd48b6 | 1,065 | java | Java | elastic-search/src/main/java/com/example/elasticsearch/controller/EsSaveController.java | colin-kyang/youngmail | f3f415c58dfcf7310ce744c9c6a8e71ef1f06db8 | [
"Apache-2.0"
] | null | null | null | elastic-search/src/main/java/com/example/elasticsearch/controller/EsSaveController.java | colin-kyang/youngmail | f3f415c58dfcf7310ce744c9c6a8e71ef1f06db8 | [
"Apache-2.0"
] | 1 | 2022-03-01T13:53:33.000Z | 2022-03-01T13:53:33.000Z | elastic-search/src/main/java/com/example/elasticsearch/controller/EsSaveController.java | colin-kyang/youngmall | f3f415c58dfcf7310ce744c9c6a8e71ef1f06db8 | [
"Apache-2.0"
] | null | null | null | 29.583333 | 75 | 0.746479 | 12,249 | package com.example.elasticsearch.controller;
import com.example.common.utils.R;
import com.example.elasticsearch.mappings.SkuEsModel;
import com.example.elasticsearch.service.skuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("/es/search")
@RestController
@Slf4j
public class EsSaveController {
@Autowired
com.example.elasticsearch.service.skuService skuService;
/**
* 上架商品
* @return
*/
@PostMapping("/save")
public R productStatusUp(@RequestBody List<SkuEsModel> skuEsModelList){
log.info("检查收到的数据");
for(SkuEsModel e: skuEsModelList){
log.info(e.toString());
}
skuService.saveSkuEsModels(skuEsModelList);
return R.ok();
}
}
|
3e1ce060a83489064cb05214b0bd2cc33818de79 | 810 | java | Java | src/main/java/wooteco/security/web/authentication/handler/SaveSessionSuccessHandler.java | KimSeongGyu1/atdd-subway-2020 | d67735f0d487cc9775cef321869d479de68df10c | [
"MIT"
] | null | null | null | src/main/java/wooteco/security/web/authentication/handler/SaveSessionSuccessHandler.java | KimSeongGyu1/atdd-subway-2020 | d67735f0d487cc9775cef321869d479de68df10c | [
"MIT"
] | null | null | null | src/main/java/wooteco/security/web/authentication/handler/SaveSessionSuccessHandler.java | KimSeongGyu1/atdd-subway-2020 | d67735f0d487cc9775cef321869d479de68df10c | [
"MIT"
] | null | null | null | 38.571429 | 99 | 0.817284 | 12,250 | package wooteco.security.web.authentication.handler;
import static wooteco.security.core.context.SecurityContextHolder.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wooteco.security.core.Authentication;
import wooteco.security.core.context.SecurityContext;
public class SaveSessionSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
HttpSession httpSession = request.getSession();
httpSession.setAttribute(SPRING_SECURITY_CONTEXT_KEY, new SecurityContext(authentication));
response.setStatus(HttpServletResponse.SC_OK);
}
}
|
3e1ce0ac904e1f1e4b48609dfb7742733baadb3f | 911 | java | Java | autumn-reporting/src/main/java/com/autumn/reporting/listeners/ITestStatusListener.java | autumn-framework/autumn | 7418804584f0796149bb3e87ed957ab64853e344 | [
"Apache-2.0"
] | 2 | 2021-08-23T14:48:29.000Z | 2021-12-23T02:07:07.000Z | autumn-reporting/src/main/java/com/autumn/reporting/listeners/ITestStatusListener.java | autumn-framework/autumn | 7418804584f0796149bb3e87ed957ab64853e344 | [
"Apache-2.0"
] | null | null | null | autumn-reporting/src/main/java/com/autumn/reporting/listeners/ITestStatusListener.java | autumn-framework/autumn | 7418804584f0796149bb3e87ed957ab64853e344 | [
"Apache-2.0"
] | 1 | 2021-10-30T15:00:57.000Z | 2021-10-30T15:00:57.000Z | 26.794118 | 75 | 0.731065 | 12,251 | package com.autumn.reporting.listeners;
/*-
* #%L
* autumn-reporting
* %%
* Copyright (C) 2021 Deutsche Telekom AG
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.testng.ITestResult;
public interface ITestStatusListener {
void performOnSuccess(ITestResult result);
void performOnFailure(ITestResult result);
void performOnSkip(ITestResult result);
}
|
3e1ce183181b44d952f813f4ab3bf131e8c7839f | 4,244 | java | Java | ui/data/RD freemind/model/src/freemind/modes/mindmapmode/actions/NodeBackgroundColorAction.java | fetteradler/Getaviz | 9e80d842312f55b798044c069a1ef297e64da86f | [
"Apache-2.0"
] | 9 | 2020-01-03T08:48:19.000Z | 2021-11-02T04:14:03.000Z | ui/data/RD freemind/model/src/freemind/modes/mindmapmode/actions/NodeBackgroundColorAction.java | fetteradler/Getaviz | 9e80d842312f55b798044c069a1ef297e64da86f | [
"Apache-2.0"
] | null | null | null | ui/data/RD freemind/model/src/freemind/modes/mindmapmode/actions/NodeBackgroundColorAction.java | fetteradler/Getaviz | 9e80d842312f55b798044c069a1ef297e64da86f | [
"Apache-2.0"
] | 10 | 2020-02-26T21:22:20.000Z | 2022-02-16T06:34:11.000Z | 35.07438 | 94 | 0.779689 | 12,252 | /*
* FreeMind - A Program for creating and viewing Mindmaps Copyright (C)
* 2000-2004 Joerg Mueller, Daniel Polansky, Christian Foltin and others.
*
* See COPYING for Details
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Created on 19.09.2004
*/
package freemind.modes.mindmapmode.actions;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.ListIterator;
import freemind.controller.Controller;
import freemind.controller.actions.generated.instance.NodeBackgroundColorFormatAction;
import freemind.controller.actions.generated.instance.XmlAction;
import freemind.main.Tools;
import freemind.modes.MindMapNode;
import freemind.modes.mindmapmode.MindMapController;
import freemind.modes.mindmapmode.MindMapMapModel;
import freemind.modes.mindmapmode.MindMapNodeModel;
import freemind.modes.mindmapmode.actions.xml.ActionPair;
import freemind.modes.mindmapmode.actions.xml.ActorXml;
public class NodeBackgroundColorAction extends FreemindAction implements
ActorXml {
private final MindMapController controller;
public NodeBackgroundColorAction(MindMapController controller) {
super("node_background_color", (String) null, controller);
this.controller = controller;
addActor(this);
}
public void actionPerformed(ActionEvent e) {
Color color = Controller.showCommonJColorChooserDialog(controller
.getView().getSelected(), controller
.getText("choose_node_background_color"), controller
.getSelected().getBackgroundColor());
if (color == null) {
return;
}
for (ListIterator it = controller.getSelecteds().listIterator(); it
.hasNext();) {
MindMapNodeModel selected = (MindMapNodeModel) it.next();
setNodeBackgroundColor(selected, color);
}
}
public static class RemoveNodeBackgroundColorAction extends
NodeGeneralAction {
private final MindMapController controller;
public RemoveNodeBackgroundColorAction(
final MindMapController controller) {
super(controller, "remove_node_background_color", (String) null);
this.controller = controller;
setSingleNodeOperation(new SingleNodeOperation() {
public void apply(MindMapMapModel map, MindMapNodeModel node) {
controller.setNodeBackgroundColor(node, null);
}
});
}
}
public void setNodeBackgroundColor(MindMapNode node, Color color) {
NodeBackgroundColorFormatAction doAction = createNodeBackgroundColorFormatAction(
node, color);
NodeBackgroundColorFormatAction undoAction = createNodeBackgroundColorFormatAction(
node, node.getBackgroundColor());
controller.doTransaction(this.getClass().getName(),
new ActionPair(doAction, undoAction));
}
public NodeBackgroundColorFormatAction createNodeBackgroundColorFormatAction(
MindMapNode node, Color color) {
NodeBackgroundColorFormatAction nodeAction = new NodeBackgroundColorFormatAction();
nodeAction.setNode(node.getObjectId(controller));
nodeAction.setColor(Tools.colorToXml(color));
return nodeAction;
}
public void act(XmlAction action) {
if (action instanceof NodeBackgroundColorFormatAction) {
NodeBackgroundColorFormatAction nodeColorAction = (NodeBackgroundColorFormatAction) action;
Color color = Tools.xmlToColor(nodeColorAction.getColor());
MindMapNode node = controller.getNodeFromID(nodeColorAction
.getNode());
Color oldColor = node.getBackgroundColor();
if (!Tools.safeEquals(color, oldColor)) {
node.setBackgroundColor(color); // null
controller.nodeChanged(node);
}
}
}
public Class getDoActionClass() {
return NodeBackgroundColorFormatAction.class;
}
} |
3e1ce2066b899eb0af16287b9772294a57cc7f3c | 16,612 | java | Java | js4ms-jsdk/ip/src/main/java/org/js4ms/ip/IPEncapsulatingSecurityPayload.java | chenxiuheng/js4ms | 6cdf70f726a07cccdb2544e3706386d6efd22374 | [
"Apache-2.0"
] | null | null | null | js4ms-jsdk/ip/src/main/java/org/js4ms/ip/IPEncapsulatingSecurityPayload.java | chenxiuheng/js4ms | 6cdf70f726a07cccdb2544e3706386d6efd22374 | [
"Apache-2.0"
] | null | null | null | js4ms-jsdk/ip/src/main/java/org/js4ms/ip/IPEncapsulatingSecurityPayload.java | chenxiuheng/js4ms | 6cdf70f726a07cccdb2544e3706386d6efd22374 | [
"Apache-2.0"
] | null | null | null | 44.298667 | 170 | 0.649711 | 12,253 | package org.js4ms.ip;
/*
* #%L
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* IPEncapsulatingSecurityPayload.java [org.js4ms.jsdk:ip]
* %%
* Copyright (C) 2009 - 2014 Cisco Systems, Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.js4ms.common.exception.ParseException;
import org.js4ms.common.util.buffer.BufferBackedObject;
import org.js4ms.common.util.buffer.parser.MissingParserException;
/**
* An Encapsulating Security Payload packet.
* See <a href="http://tools.ietf.org/html/rfc2406">[RFC-2406]</a>
* <p>
* The protocol header (IPv4, IPv6, or Extension) immediately preceding the ESP header
* will contain the value 50 in its Protocol (IPv4) or Next Header (IPv6, Extension) field
* [STD-2].
* <h3>Header Format</h3> <blockquote>
*
* <pre>
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ----
* | Security Parameters Index (SPI) | ^Auth.
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Cov-
* | Sequence Number | |erage
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ----
* | Payload Data* (variable) | | ^
* ~ ~ | |
* | | |Conf.
* + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Cov-
* | | Padding (0-255 bytes) | |erage*
* +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
* | | Pad Length | Next Header | v v
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ------
* | Authentication Data (variable) |
* ~ ~
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* </pre>
*
* <blockquote> *If included in the Payload field, cryptographic synchronization data,
* e.g., an Initialization Vector (IV, see Section 2.3), usually is not encrypted per se,
* although it often is referred to as being part of the ciphertext. </blockquote>
* <p>
* In the following field descriptions "Optional" means that the field is omitted if the
* option is not selected, i.e., it is present in neither the packet as transmitted nor as
* formatted for computation of an Integrity Check Value (ICV, see Section 2.7). Whether
* or not an option is selected is defined as part of Security Association (SA)
* establishment. Thus the format of ESP packets for a given SA is fixed, for the duration
* of the SA. In contrast, "mandatory" fields are always present in the ESP packet format,
* for all SAs.
* <dl>
* <dt><u>Security Parameters Index</u></dt>
* <p>
* <dd>The SPI is an arbitrary 32-bit value that, in combination with the destination IP
* address and security protocol (ESP), uniquely identifies the Security Association for
* this datagram. The set of SPI values in the range 1 through 255 are reserved by the
* Internet Assigned Numbers Authority (IANA) for future use; a reserved SPI value will
* not normally be assigned by IANA unless the use of the assigned SPI value is specified
* in an RFC. It is ordinarily selected by the destination system upon establishment of an
* SA (see the Security Architecture document for more details). The SPI field is
* mandatory.
* <p>
* The SPI value of zero (0) is reserved for local, implementation- specific use and MUST
* NOT be sent on the wire. For example, a key management implementation MAY use the zero
* SPI value to mean "No Security Association Exists" during the period when the IPsec
* implementation has requested that its key management entity establish a new SA, but the
* SA has not yet been established.</dd>
* <p>
* <dt><u>Sequence Number</u></dt>
* <p>
* <dd>This unsigned 32-bit field contains a monotonically increasing counter value
* (sequence number). It is mandatory and is always present even if the receiver does not
* elect to enable the anti-replay service for a specific SA. Processing of the Sequence
* Number field is at the discretion of the receiver, i.e., the sender MUST always
* transmit this field, but the receiver need not act upon it (see the discussion of
* Sequence Number Verification in the "Inbound Packet Processing" section below).
* <p>
* The sender's counter and the receiver's counter are initialized to 0 when an SA is
* established. (The first packet sent using a given SA will have a Sequence Number of 1;
* see Section 3.3.3 for more details on how the Sequence Number is generated.) If
* anti-replay is enabled (the default), the transmitted Sequence Number must never be
* allowed to cycle. Thus, the sender's counter and the receiver's counter MUST be reset
* (by establishing a new SA and thus a new key) prior to the transmission of the 2^32nd
* packet on an SA.</dd>
* <p>
* <dt><u>Payload Data</u></dt>
* <p>
* <dd>Payload Data is a variable-length field containing data described by the Next
* Header field. The Payload Data field is mandatory and is an integral number of bytes in
* length. If the algorithm used to encrypt the payload requires cryptographic
* synchronization data, e.g., an Initialization Vector (IV), then this data MAY be
* carried explicitly in the Payload field. Any encryption algorithm that requires such
* explicit, per-packet synchronization data MUST indicate the length, any structure for
* such data, and the location of this data as part of an RFC specifying how the algorithm
* is used with ESP. If such synchronization data is implicit, the algorithm for deriving
* the data MUST be part of the RFC.
* <p>
* Note that with regard to ensuring the alignment of the (real) ciphertext in the
* presence of an IV:
* <p>
* <ul>
* <li>For some IV-based modes of operation, the receiver treats the IV as the start of
* the ciphertext, feeding it into the algorithm directly. In these modes, alignment of
* the start of the (real) ciphertext is not an issue at the receiver.
* <li>In some cases, the receiver reads the IV in separately from the ciphertext. In
* these cases, the algorithm specification MUST address how alignment of the (real)
* ciphertext is to be achieved.
* </ul>
* </dd>
* <dt><u>Padding (for Encryption)</u></dt>
* <p>
* <dd>Several factors require or motivate use of the Padding field.
* <p>
* <ul>
* <li>If an encryption algorithm is employed that requires the plaintext to be a multiple
* of some number of bytes, e.g., the block size of a block cipher, the Padding field is
* used to fill the plaintext (consisting of the Payload Data, Pad Length and Next Header
* fields, as well as the Padding) to the size required by the algorithm.
* <li>Padding also may be required, irrespective of encryption algorithm requirements, to
* ensure that the resulting ciphertext terminates on a 4-byte boundary. Specifically, the
* Pad Length and Next Header fields must be right aligned within a 4-byte word, as
* illustrated in the ESP packet format figure above, to ensure that the Authentication
* Data field (if present) is aligned on a 4-byte boundary.
* <li>Padding beyond that required for the algorithm or alignment reasons cited above,
* may be used to conceal the actual length of the payload, in support of (partial)
* traffic flow confidentiality. However, inclusion of such additional padding has adverse
* bandwidth implications and thus its use should be undertaken with care.
* </ul>
* The sender MAY add 0-255 bytes of padding. Inclusion of the Padding field in an ESP
* packet is optional, but all implementations MUST support generation and consumption of
* padding.
* <p>
* <ul>
* <li>For the purpose of ensuring that the bits to be encrypted are a multiple of the
* algorithm's blocksize (first bullet above), the padding computation applies to the
* Payload Data exclusive of the IV, the Pad Length, and Next Header fields.
* <li>For the purposes of ensuring that the Authentication Data is aligned on a 4-byte
* boundary (second bullet above), the padding computation applies to the Payload Data
* inclusive of the IV, the Pad Length, and Next Header fields.
* </ul>
* If Padding bytes are needed but the encryption algorithm does not specify the padding
* contents, then the following default processing MUST be used. The Padding bytes are
* initialized with a series of (unsigned, 1-byte) integer values. The first padding byte
* appended to the plaintext is numbered 1, with subsequent padding bytes making up a
* monotonically increasing sequence: 1, 2, 3, ... When this padding scheme is employed,
* the receiver SHOULD inspect the Padding field. (This scheme was selected because of its
* relative simplicity, ease of implementation in hardware, and because it offers limited
* protection against certain forms of "cut and paste" attacks in the absence of other
* integrity measures, if the receiver checks the padding values upon decryption.)
* <p>
* Any encryption algorithm that requires Padding other than the default described above,
* MUST define the Padding contents (e.g., zeros or random data) and any required receiver
* processing of these Padding bytes in an RFC specifying how the algorithm is used with
* ESP. In such circumstances, the content of the Padding field will be determined by the
* encryption algorithm and mode selected and defined in the corresponding algorithm RFC.
* The relevant algorithm RFC MAY specify that a receiver MUST inspect the Padding field
* or that a receiver MUST inform senders of how the receiver will handle the Padding
* field.</dd>
* <p>
* <dt><u>Pad Length</u></dt>
* <p>
* <dd>The Pad Length field indicates the number of pad bytes immediately preceding it.
* The range of valid values is 0-255, where a value of zero indicates that no Padding
* bytes are present. The Pad Length field is mandatory.</dd>
* <p>
* <dt><u>Next Header</u></dt>
* <p>
* <dd>The Next Header is an 8-bit field that identifies the type of data contained in the
* Payload Data field, e.g., an extension header in IPv6 or an upper layer protocol
* identifier. The value of this field is chosen from the set of IP Protocol Numbers
* defined in the most recent "Assigned Numbers" [STD-2] RFC from the Internet Assigned
* Numbers Authority (IANA). The Next Header field is mandatory.</dd>
* <p>
* <dt><u>Authentication Data</u></dt>
* <p>
* <dd>The Authentication Data is a variable-length field containing an Integrity Check
* Value (ICV) computed over the ESP packet minus the Authentication Data. The length of
* the field is specified by the authentication function selected. The Authentication Data
* field is optional, and is included only if the authentication service has been selected
* for the SA in question. The authentication algorithm specification MUST specify the
* length of the ICV and the comparison rules and processing steps for validation.</dd>
* </dl>
* </blockquote>
*
* @author Gregory Bumgardner (gbumgard)
*/
public class IPEncapsulatingSecurityPayload
extends BufferBackedObject
implements IPMessage {
/*-- Inner Classes ---------------------------------------------------*/
public static class Parser
implements IPMessage.ParserType {
@Override
public IPMessage parse(final ByteBuffer buffer) throws ParseException {
return new IPEncapsulatingSecurityPayload(buffer);
}
@Override
public boolean verifyChecksum(final ByteBuffer buffer, final byte[] sourceAddress, final byte[] destinationAddress)
throws MissingParserException, ParseException {
return true; // Does nothing in this class
}
@Override
public Object getKey() {
return IP_PROTOCOL_NUMBER;
}
}
/*-- Static Variables ---------------------------------------------------*/
public static final Logger logger = Logger.getLogger(IPEncapsulatingSecurityPayload.class.getName());
public static final byte IP_PROTOCOL_NUMBER = 50;
protected static final int BASE_HEADER_LENGTH = 8;
/*-- Member Variables ---------------------------------------------------*/
private ByteBuffer payload;
/*-- Member Variables ---------------------------------------------------*/
/**
* @param buffer
*/
public IPEncapsulatingSecurityPayload(final ByteBuffer buffer) {
super(consume(buffer, BASE_HEADER_LENGTH));
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.log.entry("IPAuthenticationHeader.IPAuthenticationHeader", buffer));
}
this.payload = consume(buffer, buffer.remaining());
if (logger.isLoggable(Level.FINER)) {
logState(logger, Level.FINER);
}
}
@Override
public Logger getLogger() {
return logger;
}
@Override
public void log(final Logger logger, final Level level) {
super.log(logger,level);
logState(logger,level);
}
/**
* Logs value of member variables declared or maintained by this class.
*
* @param logger
*/
private void logState(final Logger logger, final Level level) {
logger.log(level, this.log.msg(": payload array=" + this.payload.array() +
" offset=" + this.payload.arrayOffset() +
" limit=" + this.payload.limit()));
}
@Override
public void writeTo(final ByteBuffer buffer) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.log.entry("IPEncapsulatingSecurityPayload.writeTo", buffer));
}
super.writeTo(buffer);
this.payload.rewind();
buffer.put(this.payload);
this.payload.rewind();
}
@Override
public void writeChecksum(final ByteBuffer buffer,
final byte[] sourceAddress,
final byte[] destinationAddress) {
// NO-OP
}
public ByteBuffer getPayload() {
return this.payload.slice();
}
@Override
public int getHeaderLength() {
// TODO: This only works with original unparsed content
return BASE_HEADER_LENGTH + this.payload.limit();
}
@Override
public int getTotalLength() {
return getHeaderLength();
}
@Override
public byte getProtocolNumber() {
return IP_PROTOCOL_NUMBER;
}
@Override
public void setProtocolNumber(final byte protocolNumber) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.log.entry("IPEncapsulatingSecurityPayload.setProtocolNumber", protocolNumber));
}
throw new UnsupportedOperationException();
}
@Override
public byte getNextProtocolNumber() {
// TODO - could read this from decrypted packet?
return IPMessage.NO_NEXT_HEADER;
}
@Override
public IPMessage getNextMessage() {
return null;
}
@Override
public void setNextMessage(final IPMessage message) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.log.entry("IPEncapsulatingSecurityPayload.setNextMessage", message));
}
throw new UnsupportedOperationException();
}
@Override
public void removeNextMessage() {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.log.entry("IPEncapsulatingSecurityPayload.removeNextMessage"));
}
throw new UnsupportedOperationException();
}
}
|
3e1ce24c5a6bbc6af279e7761222457616ff741f | 986 | java | Java | java/client/src/org/openqa/selenium/devtools/tracing/model/StreamFormat.java | jigarmehta1999/selenium | 69e3deb4377476005f16fd91cffefd0f79f94d30 | [
"Apache-2.0"
] | null | null | null | java/client/src/org/openqa/selenium/devtools/tracing/model/StreamFormat.java | jigarmehta1999/selenium | 69e3deb4377476005f16fd91cffefd0f79f94d30 | [
"Apache-2.0"
] | null | null | null | java/client/src/org/openqa/selenium/devtools/tracing/model/StreamFormat.java | jigarmehta1999/selenium | 69e3deb4377476005f16fd91cffefd0f79f94d30 | [
"Apache-2.0"
] | null | null | null | 27.388889 | 246 | 0.684584 | 12,254 | package org.openqa.selenium.devtools.tracing.model;
import org.openqa.selenium.Beta;
import org.openqa.selenium.json.JsonInput;
/**
* Data format of a trace. Can be either the legacy JSON format or the
* protocol buffer format. Note that the JSON format will be deprecated soon.
*/
public enum StreamFormat {
JSON("json"), PROTO("proto");
private String value;
StreamFormat(String value) {
this.value = value;
}
public static StreamFormat fromString(String s) {
return java.util.Arrays.stream(StreamFormat.values()).filter(rs -> rs.value.equalsIgnoreCase(s)).findFirst().orElseThrow(() -> new org.openqa.selenium.devtools.DevToolsException("Given value " + s + " is not found within StreamFormat "));
}
public String toString() {
return value;
}
public String toJson() {
return value;
}
private static StreamFormat fromJson(JsonInput input) {
return fromString(input.nextString());
}
}
|
3e1ce2bc3ad5da98f6c2c02005c30f9c3811a278 | 1,143 | java | Java | src/main/java/es/awkidev/corp/biblio/infrastructure/mongodb/daos/DatabaseSeederDev.java | crismartin/biblio-core | 5151e29355fb9991622685f51222eb2cda828ef5 | [
"MIT"
] | null | null | null | src/main/java/es/awkidev/corp/biblio/infrastructure/mongodb/daos/DatabaseSeederDev.java | crismartin/biblio-core | 5151e29355fb9991622685f51222eb2cda828ef5 | [
"MIT"
] | 1 | 2022-03-27T14:30:49.000Z | 2022-03-27T14:30:49.000Z | src/main/java/es/awkidev/corp/biblio/infrastructure/mongodb/daos/DatabaseSeederDev.java | crismartin/biblio-core | 5151e29355fb9991622685f51222eb2cda828ef5 | [
"MIT"
] | null | null | null | 29.307692 | 94 | 0.656168 | 12,255 | package es.awkidev.corp.biblio.infrastructure.mongodb.daos;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service // @Profile("dev")
public class DatabaseSeederDev {
// private RepoDao repoDao;
private DatabaseStarting databaseStarting;
@Autowired
public DatabaseSeederDev() {
// this.repoDao = repoDao;
//this.deleteAllAndInitializeAndSeedDataBase();
}
public void deleteAllAndInitializeAndSeedDataBase() {
this.deleteAllAndInitialize();
this.seedDataBaseJava();
}
private void deleteAllAndInitialize() {
LogManager.getLogger(this.getClass()).warn("------- Delete All -------");
this.databaseStarting.initialize();
}
private void seedDataBaseJava() {
LogManager.getLogger(this.getClass()).warn("------- Initial Load from JAVA --------");
/*
Entity[] entities = {};
this.repoDao.saveAll(List.of(entities));
LogManager.getLogger(this.getClass()).warn(" ------- entities");
*/
}
}
|
3e1ce30588d56762ea5e094944302e9d2a8a79df | 303 | java | Java | src/main/java/java4d/sections/data/SSQSdata.java | pcan/java-4d | f4dec521261c19e21e3260f89aae72287c7dc3a7 | [
"MIT"
] | 3 | 2017-01-12T20:51:23.000Z | 2019-02-16T17:14:54.000Z | src/main/java/java4d/sections/data/SSQSdata.java | pcan/java-4d | f4dec521261c19e21e3260f89aae72287c7dc3a7 | [
"MIT"
] | null | null | null | src/main/java/java4d/sections/data/SSQSdata.java | pcan/java-4d | f4dec521261c19e21e3260f89aae72287c7dc3a7 | [
"MIT"
] | 2 | 2017-01-12T20:52:44.000Z | 2020-12-05T19:50:11.000Z | 14.428571 | 52 | 0.653465 | 12,256 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package java4d.sections.data;
import java4d.sections.*;
/**
*
* @author Pierantonio
*/
public class SSQSdata extends MTLSdata {
public SSQSdata(sect owner)
{
super(owner);
}
} |
3e1ce3e6f711572da3a3ec065f5054173490eb1c | 717 | java | Java | src/main/java/social/amoeba/jeyson/Script.java | nishants/jeyson-wiremock | b3eaae87f385a728d4a03a9f9d66555b2145cb76 | [
"MIT"
] | 2 | 2017-03-30T06:50:06.000Z | 2018-11-20T10:14:56.000Z | src/main/java/social/amoeba/jeyson/Script.java | nishants/jeyson-wiremock | b3eaae87f385a728d4a03a9f9d66555b2145cb76 | [
"MIT"
] | 6 | 2016-10-21T03:59:53.000Z | 2019-09-09T18:44:23.000Z | src/main/java/social/amoeba/jeyson/Script.java | nishants/jeyson-java | b3eaae87f385a728d4a03a9f9d66555b2145cb76 | [
"MIT"
] | null | null | null | 31.173913 | 105 | 0.794979 | 12,257 | package social.amoeba.jeyson;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.IOException;
import java.net.URISyntaxException;
public class Script {
private final Invocable scriptEnginge;
public Script(String code) throws IOException, ScriptException, URISyntaxException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(code);
this.scriptEnginge = (Invocable) engine;
}
public Object execute(String function, Object...params) throws ScriptException, NoSuchMethodException {
return scriptEnginge.invokeFunction(function, params);
}
}
|
3e1ce4249f942f673fa041b57ff2ee12e7acd623 | 320 | java | Java | chapter_11/shopCar/src/main/java/ru/job4j/repository/BrandRepository.java | andreiHi/hincuA | 6d1321d508b87aa68241bccc7f286162b388f245 | [
"Apache-2.0"
] | 2 | 2017-10-17T11:13:25.000Z | 2018-11-18T19:35:16.000Z | chapter_11/shopCar/src/main/java/ru/job4j/repository/BrandRepository.java | andreiHi/hincuA | 6d1321d508b87aa68241bccc7f286162b388f245 | [
"Apache-2.0"
] | 7 | 2020-03-04T21:57:32.000Z | 2022-03-28T19:19:59.000Z | chapter_11/shopCar/src/main/java/ru/job4j/repository/BrandRepository.java | andreiHi/hincuA | 6d1321d508b87aa68241bccc7f286162b388f245 | [
"Apache-2.0"
] | null | null | null | 23.142857 | 82 | 0.765432 | 12,258 | package ru.job4j.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import ru.job4j.model.car.Brand;
/**
* @author Hincu Andrei (ychag@example.com)on 23.05.2018.
* @version $Id$.
* @since 0.1.
*/
public interface BrandRepository extends PagingAndSortingRepository<Brand, Long> {
}
|
3e1ce4a9aec8512d41f14ea01543e4d236418d82 | 849 | java | Java | src/pet/hp/state/CardsState.java | brunetton/poker | f098395758ced687d1da3bbd9543349cb58fc85d | [
"MIT"
] | 120 | 2015-02-09T22:44:36.000Z | 2022-03-24T06:56:09.000Z | src/pet/hp/state/CardsState.java | brunetton/poker | f098395758ced687d1da3bbd9543349cb58fc85d | [
"MIT"
] | 6 | 2015-04-29T04:58:10.000Z | 2020-05-28T15:56:09.000Z | src/pet/hp/state/CardsState.java | brunetton/poker | f098395758ced687d1da3bbd9543349cb58fc85d | [
"MIT"
] | 74 | 2015-01-30T03:35:35.000Z | 2022-03-29T04:10:22.000Z | 25.727273 | 101 | 0.713781 | 12,259 | package pet.hp.state;
import java.util.Arrays;
import java.util.List;
import pet.eq.Draw;
/**
* player hole cards as string array, plus meta data to indicate discarded cards
* and if cards were guessed
*/
public class CardsState {
/** hole cards for display/equity purposes - may contain nulls for stud */
public final String[] cards;
/** discarded cards if any */
public final String[] discarded;
/** are hole cards guessed */
public final boolean guess;
public final List<Draw> suggestedDraws;
public CardsState(String[] cards, String[] discarded, boolean guess, List<Draw> l) {
this.cards = cards;
this.discarded = discarded;
this.guess = guess;
this.suggestedDraws = l;
}
@Override
public String toString() {
return String.format("Cards[%s %s %s]", Arrays.toString(cards), Arrays.toString(discarded), guess);
}
}
|
3e1ce5a2c1bb3aa72dcd8d7a8803eff05895824c | 5,469 | java | Java | src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java | WSN-2012/BPF | 88957dd60f064f893c1eb50fc18fa88915e14bd4 | [
"Apache-2.0"
] | 1 | 2019-09-15T13:57:19.000Z | 2019-09-15T13:57:19.000Z | src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java | WSN-2012/BPF | 88957dd60f064f893c1eb50fc18fa88915e14bd4 | [
"Apache-2.0"
] | null | null | null | src/se/kth/ssvl/tslab/wsn/general/servlib/contacts/interfaces/InterfaceTable.java | WSN-2012/BPF | 88957dd60f064f893c1eb50fc18fa88915e14bd4 | [
"Apache-2.0"
] | null | null | null | 26.138756 | 100 | 0.663738 | 12,260 | /*
* Copyright 2012 KTH
*
* 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 se.kth.ssvl.tslab.wsn.general.servlib.contacts.interfaces;
import java.util.Iterator;
import se.kth.ssvl.tslab.wsn.general.bpf.BPF;
import se.kth.ssvl.tslab.wsn.general.servlib.config.settings.InterfacesSetting.InterfaceEntry;
import se.kth.ssvl.tslab.wsn.general.servlib.conv_layers.ConvergenceLayer;
import se.kth.ssvl.tslab.wsn.general.servlib.conv_layers.connection.TCPConvergenceLayer;
import se.kth.ssvl.tslab.wsn.general.systemlib.util.List;
/**
* The list of interfaces
*
* @author Maria Jose Peroza Marval (efpyi@example.com)
*/
public class InterfaceTable {
/**
* TAG for Android Logging mechanism
*/
private static final String TAG = "InterfaceTable";
/**
* Singleton pattern for InterfaceTable
*/
private static InterfaceTable instance_ = null;
public static InterfaceTable getInstance() {
if (instance_ == null) {
instance_ = new InterfaceTable();
}
return instance_;
}
/**
* Parsing the interface's parameters specified in the configuration file
* (config). Create he interfaces and add them to the InterfaceTable.
*/
public static void init() {
List<InterfaceEntry> EntriesList = BPF.getInstance().getConfig()
.interfaces_setting().interface_entries();
Iterator<InterfaceEntry> i = EntriesList.iterator();
Interface.set_iface_counter(0);
while (i.hasNext()) {
InterfaceEntry element = i.next();
String conv_layer_type_ = element.conv_layer_type().getCaption();
String id = element.id();
short local_port = element.local_port();
boolean fixed_local_port_ = element.fixed_local_port();
BPF.getInstance().getBPFLogger().debug(TAG, conv_layer_type_ + " - " + id + " - " + local_port);
if (!fixed_local_port_) {
local_port = TCPConvergenceLayer.TCPCL_DEFAULT_PORT;
}
ConvergenceLayer cl = ConvergenceLayer
.find_clayer(conv_layer_type_);
if (cl == null) {
BPF.getInstance().getBPFLogger()
.error(TAG, "can't find convergence layer for " + id);
}
cl.set_local_port(local_port);
if (!InterfaceTable.getInstance().add(id, cl, conv_layer_type_)) {
BPF.getInstance().getBPFLogger()
.debug(TAG, "error adding interface %s" + id);
}
}
}
/**
* Constructor
*/
public InterfaceTable() {
iflist_ = new InterfaceList();
}
/**
* "Add a new interface to the table. Returns true if the interface is
* successfully added, false if the interface specification is invalid (or
* it already exists)"[DTN2].
*/
public boolean add(String name, ConvergenceLayer cl, String proto) {
Iterator<Interface> iter = iflist_.iterator();
if (find(name, iter)) {
String text = String.format("Interface %s already exists", name);
BPF.getInstance().getBPFLogger().error(TAG, text);
return false;
}
String text = String.format("adding interface " + name, proto);
BPF.getInstance().getBPFLogger().info(TAG, text);
Interface iface = new Interface(name, proto, cl);
if (!cl.interface_up(iface)) {
BPF.getInstance()
.getBPFLogger()
.error(TAG,
"convergence layer error adding interface" + name);
return false;
}
iflist_.add(iface);
return true;
}
/**
* "Remove the specified interface"[DTN2].
*/
public void shutdown() {
Iterator<Interface> iter = iflist_.iterator();
Interface iface;
BPF.getInstance().getBPFLogger().info(TAG, "removing interfaces");
while (iter.hasNext()) {
iface = iter.next();
iter.remove();
if (iface.clayer().interface_down(iface)) {
BPF.getInstance().getBPFLogger()
.info(TAG, "shutdown interface " + iface.name());
} else {
BPF.getInstance()
.getBPFLogger()
.error(TAG,
"error deleting interfaces from the convergence layer");
}
}
instance_ = null;
}
/**
* "List the current interfaces" [DTN2].
*/
public void list(StringBuffer buf) {
Iterator<Interface> iter = iflist_.iterator();
Interface iface;
while (iter.hasNext()) {
iface = iter.next();
String text = String.format("%s: Convergence Layer: %s\n",
iface.name(), iface.proto());
buf.append(text);
iface.clayer().dump_interface(iface, buf);
}
}
/**
* "All interfaces are tabled in-memory in a flat list. It's non-obvious
* what else would be better since we need to do a prefix match on demux
* strings in matching_interfaces" [DTN2].
*/
protected List<Interface> iflist_;
/**
* "Internal method to find the location of the given interface in the list"
* [DTN2].
*/
protected boolean find(String name, Iterator<Interface> iter) {
Interface iface;
while (iter.hasNext()) {
iface = iter.next();
if (iface.name() == name) {
return true;
}
}
return false;
}
}
|
3e1ce768d95490989fe38b7e14596afe6b3125c8 | 15,920 | java | Java | tddl-atom/src/main/java/com/taobao/tddl/atom/jdbc/TStatementWrapper.java | loye168/tddl5 | fd1972bd3acf090c8d7580ab0f7c2bb837ab3c41 | [
"Apache-2.0"
] | 19 | 2017-07-17T02:21:28.000Z | 2021-07-19T02:23:06.000Z | tddl-atom/src/main/java/com/taobao/tddl/atom/jdbc/TStatementWrapper.java | loye168/tddl5 | fd1972bd3acf090c8d7580ab0f7c2bb837ab3c41 | [
"Apache-2.0"
] | null | null | null | tddl-atom/src/main/java/com/taobao/tddl/atom/jdbc/TStatementWrapper.java | loye168/tddl5 | fd1972bd3acf090c8d7580ab0f7c2bb837ab3c41 | [
"Apache-2.0"
] | 46 | 2017-03-23T12:24:11.000Z | 2021-12-20T09:59:52.000Z | 32.757202 | 136 | 0.641332 | 12,261 | package com.taobao.tddl.atom.jdbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import com.taobao.tddl.atom.TAtomDbStatusEnum;
import com.taobao.tddl.common.jdbc.SqlTypeParser;
import com.taobao.tddl.common.model.SqlMetaData;
import com.taobao.tddl.monitor.eagleeye.EagleeyeHelper;
import com.taobao.tddl.monitor.unit.RouterUnitsHelper;
import com.taobao.tddl.common.utils.logger.Logger;
import com.taobao.tddl.common.utils.logger.LoggerFactory;
/**
* Statement 包装类
*
* @author shenxun
*/
public class TStatementWrapper implements TStatement {
private static Logger log = LoggerFactory.getLogger(TStatementWrapper.class);
protected static final String UPDATE = "UPDATE";
protected static final String QUERY = "QUERY";
protected Statement targetStatement;
protected final TConnectionWrapper connectionWrapper;
protected final TDataSourceWrapper datasourceWrapper;
/**
* 经过计算后的结果集,允许使用 getResult函数调用. 一个statement只允许有一个结果集
*/
protected TResultSetWrapper currentResultSet;
/**
* sql元信息持有
*/
protected SqlMetaData sqlMetaData = null;
public TStatementWrapper(Statement targetStatement, TConnectionWrapper connectionWrapper,
TDataSourceWrapper tdsWrapper, String appName){
this.targetStatement = targetStatement;
this.connectionWrapper = connectionWrapper;
this.datasourceWrapper = tdsWrapper;
this.sqlMetaData = connectionWrapper.getSqlMetaData();
this.appName = appName;
}
@Override
public void addBatch(String sql) throws SQLException {
this.targetStatement.addBatch(sql);
}
@Override
public void cancel() throws SQLException {
this.targetStatement.cancel();
}
@Override
public void clearBatch() throws SQLException {
this.targetStatement.clearBatch();
}
@Override
public void clearWarnings() throws SQLException {
this.targetStatement.clearWarnings();
}
@Override
public void close() throws SQLException {
close(true);
}
void close(boolean removeThis) throws SQLException {
try {
if (currentResultSet != null) {
currentResultSet.close();
}
} catch (SQLException e) {
log.warn("Close currentResultSet failed.", e);
} finally {
currentResultSet = null;
}
try {
if (this.targetStatement != null) this.targetStatement.close();
} finally {
this.targetStatement = null; // 端口与物理statement的引用,底下可能会有ps
// cache,导致节点无法被gc
if (removeThis) {
// 关闭之后,移除
connectionWrapper.removeOpenedStatements(this);
}
}
}
protected void recordReadTimes() throws SQLException {
TAtomDbStatusEnum status = datasourceWrapper.connectionProperties.dbStatus;
if (status != TAtomDbStatusEnum.R_STATUS && status != TAtomDbStatusEnum.RW_STATUS) {
throw new SQLException("db do not allow to execute read ! dbStatus is " + status);
}
/*
* int readRestrictionTimes =
* datasourceWrapper.connectionProperties.readRestrictionTimes; int
* currentReadTimes = datasourceWrapper.readTimes.incrementAndGet(); if
* (readRestrictionTimes != 0) { if (currentReadTimes >
* readRestrictionTimes) {
* datasourceWrapper.readTimesReject.incrementAndGet(); throw new
* SQLException("max read times ," + currentReadTimes); } }
*/
if (!datasourceWrapper.readFlowControl.allow()) {
throw new SQLException(datasourceWrapper.readFlowControl.reportExceed());
}
}
protected void recordWriteTimes() throws SQLException {
TAtomDbStatusEnum status = datasourceWrapper.connectionProperties.dbStatus;
if (status != TAtomDbStatusEnum.W_STATUS && status != TAtomDbStatusEnum.RW_STATUS) {
throw new SQLException("db do not allow to execute write ! dbStatus is " + status);
}
/*
* int writeRestrictionTimes =
* datasourceWrapper.connectionProperties.writeRestrictionTimes; int
* currentWriteTimes = datasourceWrapper.writeTimes.incrementAndGet();
* if (writeRestrictionTimes != 0) { if (currentWriteTimes >
* writeRestrictionTimes) {
* datasourceWrapper.writeTimesReject.incrementAndGet(); throw new
* SQLException("max write times , " + currentWriteTimes); } }
*/
if (!datasourceWrapper.writeFlowControl.allow()) {
throw new SQLException(datasourceWrapper.writeFlowControl.reportExceed());
}
}
// 增加并发读计数并判断阀值
protected void increaseConcurrentRead() throws SQLException {
int maxConcurrentReadRestrict = datasourceWrapper.connectionProperties.maxConcurrentReadRestrict;
int concurrentReadCount = datasourceWrapper.concurrentReadCount.incrementAndGet();
if (maxConcurrentReadRestrict != 0) {
if (concurrentReadCount > maxConcurrentReadRestrict) {
datasourceWrapper.readTimesReject.incrementAndGet();
throw new SQLException("maxConcurrentReadRestrict reached , " + maxConcurrentReadRestrict);
}
}
}
// 增加并发写计数并判断阀值
protected void increaseConcurrentWrite() throws SQLException {
int maxConcurrentWriteRestrict = datasourceWrapper.connectionProperties.maxConcurrentWriteRestrict;
int concurrentWriteCount = datasourceWrapper.concurrentWriteCount.incrementAndGet();
if (maxConcurrentWriteRestrict != 0) {
if (concurrentWriteCount > maxConcurrentWriteRestrict) {
datasourceWrapper.writeTimesReject.incrementAndGet();
throw new SQLException("maxConcurrentWriteRestrict reached , " + maxConcurrentWriteRestrict);
}
}
}
// 减少并发读计数
protected void decreaseConcurrentRead() throws SQLException {
datasourceWrapper.concurrentReadCount.decrementAndGet();
}
// 减少并发写计数
protected void decreaseConcurrentWrite() throws SQLException {
datasourceWrapper.concurrentWriteCount.decrementAndGet();
}
@Override
public boolean execute(String sql) throws SQLException {
return executeInternal(sql, -1, null, null);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return executeInternal(sql, autoGeneratedKeys, null, null);
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return executeInternal(sql, -1, columnIndexes, null);
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return executeInternal(sql, -1, null, columnNames);
}
private boolean executeInternal(String sql, int autoGeneratedKeys, int[] columnIndexes, String[] columnNames)
throws SQLException {
if (SqlTypeParser.isQuerySql(sql)) {
executeQuery(sql);
return true;
} else {
executeUpdateInternal(sql, autoGeneratedKeys, columnIndexes, columnNames);
return false;
}
}
private int executeUpdateInternal(String sql, int autoGeneratedKeys, int[] columnIndexes, String[] columnNames)
throws SQLException {
// if (sqlMetaData == null) throw new
// NullPointerException("miss sql meta data.");
ensureResultSetIsEmpty();
recordWriteTimes();
increaseConcurrentWrite();
Exception e0 = null;
startRpc(UPDATE);
try {
RouterUnitsHelper.unitDeployProtect(this.getAppName());
if (autoGeneratedKeys == -1 && columnIndexes == null && columnNames == null) {
return this.targetStatement.executeUpdate(sql);
} else if (autoGeneratedKeys != -1) {
return this.targetStatement.executeUpdate(sql, autoGeneratedKeys);
} else if (columnIndexes != null) {
return this.targetStatement.executeUpdate(sql, columnIndexes);
} else if (columnNames != null) {
return this.targetStatement.executeUpdate(sql, columnNames);
} else {
return this.targetStatement.executeUpdate(sql);
}
} catch (SQLException e) {
e0 = e;
throw e;
} finally {
endRpc(sql, e0);
decreaseConcurrentWrite();
}
}
@Override
public int[] executeBatch() throws SQLException {
ensureResultSetIsEmpty();
recordWriteTimes();
increaseConcurrentWrite();
try {
return this.targetStatement.executeBatch();
} finally {
decreaseConcurrentWrite();
}
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
// if (sqlMetaData == null) throw new
// NullPointerException("miss sql meta data.");
ensureResultSetIsEmpty();
recordReadTimes();
increaseConcurrentRead();
Exception e0 = null;
startRpc(QUERY);
try {
currentResultSet = new TResultSetWrapper(this, this.targetStatement.executeQuery(sql));
return currentResultSet;
} catch (SQLException e) {
decreaseConcurrentRead();
e0 = e;
throw e;
} finally {
endRpc(sql, e0);
}
}
protected void startRpc(String sqlType) {
if (sqlMetaData != null) {
EagleeyeHelper.startRpc(datasourceWrapper.runTimeConf.getIp(),
datasourceWrapper.runTimeConf.getPort(),
datasourceWrapper.runTimeConf.getDbName(),
sqlType);
}
}
protected void endRpc(String sql, Exception e) {
if (sqlMetaData != null) {
EagleeyeHelper.endRpc(sqlMetaData, e);
}
}
@Override
public int executeUpdate(String sql) throws SQLException {
return executeUpdateInternal(sql, -1, null, null);
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return executeUpdateInternal(sql, autoGeneratedKeys, null, null);
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return executeUpdateInternal(sql, -1, columnIndexes, null);
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return executeUpdateInternal(sql, -1, null, columnNames);
}
@Override
public Connection getConnection() throws SQLException {
return connectionWrapper;
}
@Override
public int getFetchDirection() throws SQLException {
return this.targetStatement.getFetchDirection();
}
@Override
public int getFetchSize() throws SQLException {
return this.targetStatement.getFetchSize();
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return new TResultSetWrapper(this, this.targetStatement.getGeneratedKeys());
}
@Override
public int getMaxFieldSize() throws SQLException {
return this.targetStatement.getMaxFieldSize();
}
@Override
public int getMaxRows() throws SQLException {
return this.targetStatement.getMaxRows();
}
@Override
public boolean getMoreResults() throws SQLException {
return this.targetStatement.getMoreResults();
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return this.targetStatement.getMoreResults(current);
}
@Override
public int getQueryTimeout() throws SQLException {
return this.targetStatement.getQueryTimeout();
}
@Override
public ResultSet getResultSet() throws SQLException {
/*
* ResultSet targetRS = this.targetStatement.getResultSet(); if
* (targetRS == null) { return null; } return new
* TResultSetWrapper(this, targetRS);
*/
return currentResultSet;
}
@Override
public int getResultSetConcurrency() throws SQLException {
return this.targetStatement.getResultSetConcurrency();
}
@Override
public int getResultSetHoldability() throws SQLException {
return this.targetStatement.getResultSetHoldability();
}
@Override
public int getResultSetType() throws SQLException {
return this.targetStatement.getResultSetType();
}
@Override
public int getUpdateCount() throws SQLException {
return this.targetStatement.getUpdateCount();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return this.targetStatement.getWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
this.targetStatement.setCursorName(name);
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
this.targetStatement.setEscapeProcessing(enable);
}
@Override
public void setFetchDirection(int direction) throws SQLException {
this.targetStatement.setFetchDirection(direction);
}
@Override
public void setFetchSize(int rows) throws SQLException {
this.targetStatement.setFetchSize(rows);
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
this.targetStatement.setMaxFieldSize(max);
}
@Override
public void setMaxRows(int max) throws SQLException {
this.targetStatement.setMaxRows(max);
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
this.targetStatement.setQueryTimeout(seconds);
}
/**
* 如果新建了查询,那么上一次查询的结果集应该被显示的关闭掉。这才是符合jdbc规范的
*
* @throws SQLException
*/
protected void ensureResultSetIsEmpty() throws SQLException {
if (currentResultSet != null) {
try {
currentResultSet.close();
} catch (SQLException e) {
log.error("exception on close last result set . can do nothing..", e);
} finally {
currentResultSet = null;
}
}
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.getClass().isAssignableFrom(iface);
}
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
return (T) this;
} catch (Exception e) {
throw new SQLException(e);
}
}
@Override
public boolean isClosed() throws SQLException {
return this.targetStatement.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
this.targetStatement.setPoolable(poolable);
}
@Override
public boolean isPoolable() throws SQLException {
return this.targetStatement.isPoolable();
}
@Override
public void setLocalInfileInputStream(InputStream stream) {
throw new IllegalAccessError();
}
@Override
public InputStream getLocalInfileInputStream() {
throw new IllegalAccessError();
}
final String appName;
@Override
public String getAppName() {
return this.appName;
}
}
|
3e1ce80810b47be70bee17cb6dccb005c72055df | 6,063 | java | Java | tests/time/qmosa/tests/s1009/105_freemind/evosuite-tests/freemind/controller/Controller_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | null | null | null | tests/time/qmosa/tests/s1009/105_freemind/evosuite-tests/freemind/controller/Controller_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | 3 | 2020-11-16T20:40:56.000Z | 2021-03-23T00:18:04.000Z | tests/time/qmosa/tests/s1009/105_freemind/evosuite-tests/freemind/controller/Controller_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | null | null | null | 30.77665 | 176 | 0.671285 | 12,262 | /*
* This file was automatically generated by EvoSuite
* Sun Nov 29 22:01:59 GMT 2020
*/
package freemind.controller;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import freemind.controller.Controller;
import freemind.controller.filter.condition.IconContainedCondition;
import freemind.main.FreeMindMain;
import freemind.preferences.FreemindPropertyListener;
import java.awt.Color;
import java.awt.Component;
import java.awt.HeadlessException;
import java.awt.event.MouseWheelEvent;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class Controller_ESTest extends Controller_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test0() throws Throwable {
JToggleButton jToggleButton0 = new JToggleButton();
MouseWheelEvent mouseWheelEvent0 = new MouseWheelEvent(jToggleButton0, 0, 4, 10, 74, (-1357), 4, false, 8217, 0, 3136);
mouseWheelEvent0.setSource((Object) null);
Controller.DisposeOnClose controller_DisposeOnClose0 = new Controller.DisposeOnClose();
// Undeclared exception!
try {
controller_DisposeOnClose0.componentHidden(mouseWheelEvent0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("freemind.controller.Controller$DisposeOnClose", e);
}
}
/**
//Test case number: 1
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test1() throws Throwable {
JColorChooser jColorChooser0 = Controller.getCommonJColorChooser();
assertTrue(jColorChooser0.getFocusTraversalKeysEnabled());
}
/**
//Test case number: 2
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test2() throws Throwable {
IconContainedCondition iconContainedCondition0 = new IconContainedCondition("o1VDMN ");
JComponent jComponent0 = iconContainedCondition0.getListCellRendererComponent();
Color color0 = Color.darkGray;
try {
Controller.showCommonJColorChooserDialog(jComponent0, (String) null, color0);
fail("Expecting exception: HeadlessException");
} catch(HeadlessException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.awt.GraphicsEnvironment", e);
}
}
/**
//Test case number: 3
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test3() throws Throwable {
JRadioButton jRadioButton0 = new JRadioButton();
Color color0 = Color.YELLOW;
try {
Controller.showCommonJColorChooserDialog(jRadioButton0, "", color0);
fail("Expecting exception: HeadlessException");
} catch(HeadlessException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.awt.GraphicsEnvironment", e);
}
}
/**
//Test case number: 4
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test4() throws Throwable {
Controller.Closer controller_Closer0 = new Controller.Closer();
}
/**
//Test case number: 5
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test5() throws Throwable {
Controller.CloseAction controller_CloseAction0 = null;
try {
controller_CloseAction0 = new Controller.CloseAction((Controller) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("freemind.controller.Controller$CloseAction", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=1.5607104090414063
*/
@Test(timeout = 4000)
public void test6() throws Throwable {
Controller controller0 = null;
try {
controller0 = new Controller((FreeMindMain) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("freemind.controller.Controller", e);
}
}
/**
//Test case number: 7
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test7() throws Throwable {
// Undeclared exception!
try {
Controller.addPropertyChangeListenerAndPropagate((FreemindPropertyListener) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("freemind.controller.Controller", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test8() throws Throwable {
try {
Controller.showCommonJColorChooserDialog((Component) null, "R$b(J", (Color) null);
fail("Expecting exception: HeadlessException");
} catch(HeadlessException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.awt.GraphicsEnvironment", e);
}
}
/**
//Test case number: 9
/*Coverage entropy=-0.0
*/
@Test(timeout = 4000)
public void test9() throws Throwable {
Controller.removePropertyChangeListener((FreemindPropertyListener) null);
}
}
|
3e1ce8f6fd8f25db9e74f43706a61f45987cdab5 | 893 | java | Java | syncservice/src/dao/Conn.java | JohnHsiao/syncservice | e65f516b2591a3e144897a65436285c592f6e0bd | [
"MIT"
] | null | null | null | syncservice/src/dao/Conn.java | JohnHsiao/syncservice | e65f516b2591a3e144897a65436285c592f6e0bd | [
"MIT"
] | null | null | null | syncservice/src/dao/Conn.java | JohnHsiao/syncservice | e65f516b2591a3e144897a65436285c592f6e0bd | [
"MIT"
] | null | null | null | 17.86 | 99 | 0.670773 | 12,263 | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLException;
import javax.sql.DataSource;
/**
* 資料庫連線
* @author shawn
*
*/
public class Conn {
/**
* 結束連線
* @param ps
* @param con
* @throws java.sql.SQLException
*/
public static void DisConDB(PreparedStatement ps, Connection con) throws java.sql.SQLException {
if (ps != null)ps.close();
if (con != null)con.close();
ps = null;
con = null;
}
/**
* 開啟連線
* @param uri
* @param user
* @param pass
* @return
* @throws SQLException
*/
public static Connection getConnection(String uri, String user, String pass) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
}
Connection con = java.sql.DriverManager.getConnection(uri, user, pass);
return con;
}
}
|
3e1ce9c89dd3dd4d07743fe9651b940f0da63ded | 1,193 | java | Java | src/com/coderbd/pos/entity/pojo/ShopBalance.java | coderbdsust/pos | 61e421e5e25158d8fbc4ef03d0c368fa4dcd4443 | [
"MIT"
] | 2 | 2019-06-10T13:08:56.000Z | 2021-11-20T01:05:26.000Z | src/com/coderbd/pos/entity/pojo/ShopBalance.java | coderbdsust/pos | 61e421e5e25158d8fbc4ef03d0c368fa4dcd4443 | [
"MIT"
] | null | null | null | src/com/coderbd/pos/entity/pojo/ShopBalance.java | coderbdsust/pos | 61e421e5e25158d8fbc4ef03d0c368fa4dcd4443 | [
"MIT"
] | null | null | null | 24.854167 | 97 | 0.654652 | 12,264 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.coderbd.pos.entity.pojo;
import com.coderbd.pos.entity.Shop;
import com.coderbd.pos.entity.pojo.ShopDailyProfit;
import java.util.List;
/**
*
* @author Biswajit Debnath
*/
public class ShopBalance {
private Shop shop;
private List<ShopDailyProfit> shopDailyProfits;
public ShopBalance(Shop shop, List<ShopDailyProfit> shopDailyProfits) {
this.shop = shop;
this.shopDailyProfits = shopDailyProfits;
}
public Shop getShop() {
return shop;
}
public void setShop(Shop shop) {
this.shop = shop;
}
public List<ShopDailyProfit> getShopDailyProfits() {
return shopDailyProfits;
}
public void setShopDailyProfits(List<ShopDailyProfit> shopDailyProfits) {
this.shopDailyProfits = shopDailyProfits;
}
@Override
public String toString() {
return "ShopBalance{" + "shop=" + shop + ", shopDailyProfits=" + shopDailyProfits + '}';
}
}
|
3e1cea1c9cfa29287e8921fec4fc788e18abd166 | 7,848 | java | Java | src/main/java/org/spongepowered/api/block/BlockState.java | CreonC/SpongeAPI | 868b03911f69cf867d74333941d1c8ab260f2a51 | [
"MIT"
] | 787 | 2015-01-01T05:38:36.000Z | 2022-03-25T04:29:53.000Z | src/main/java/org/spongepowered/api/block/BlockState.java | CreonC/SpongeAPI | 868b03911f69cf867d74333941d1c8ab260f2a51 | [
"MIT"
] | 1,816 | 2015-01-01T00:10:09.000Z | 2022-03-26T17:43:57.000Z | src/main/java/org/spongepowered/api/block/BlockState.java | CreonC/SpongeAPI | 868b03911f69cf867d74333941d1c8ab260f2a51 | [
"MIT"
] | 512 | 2015-01-01T19:45:19.000Z | 2022-03-16T17:21:27.000Z | 39.437186 | 112 | 0.683359 | 12,265 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.spongepowered.api.block;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.entity.BlockEntity;
import org.spongepowered.api.data.DataManipulator;
import org.spongepowered.api.data.DirectionRelativeDataHolder;
import org.spongepowered.api.data.value.Value;
import org.spongepowered.api.fluid.FluidState;
import org.spongepowered.api.state.State;
import org.spongepowered.api.state.StateMatcher;
import org.spongepowered.api.util.mirror.Mirror;
import org.spongepowered.api.util.rotation.Rotation;
import org.spongepowered.api.world.server.ServerLocation;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Represents a particular "state" that can exist at a {@link ServerLocation} with
* a particular {@link BlockType} and various {@link org.spongepowered.api.data.value.Value.Immutable}s defining
* the information for the "block". Note that normally, there may exist only
* a single instance of a particular {@link BlockState} as they are immutable,
* a particular instance may be cached for various uses.
*/
public interface BlockState extends State<BlockState>, DirectionRelativeDataHolder.Immutable<BlockState> {
/**
* Creates a new {@link Builder} for building {@link BlockState}s.
*
* @return The builder
*/
static Builder builder() {
return Sponge.game().builderProvider().provide(Builder.class);
}
static BlockState fromString(final String id) {
Objects.requireNonNull(id);
return Sponge.game().builderProvider().provide(Builder.class).fromString(id).build();
}
/**
* Constructs a new builder to construct a {@link StateMatcher}.
*
* @param type The block type
* @return The builder
*/
static StateMatcher.Builder<BlockState, BlockType> matcher(final Supplier<? extends BlockType> type) {
return BlockState.matcher(type.get());
}
/**
* Constructs a new builder to construct a {@link StateMatcher}.
*
* @param type The block type
* @return The builder
*/
static StateMatcher.Builder<BlockState, BlockType> matcher(final BlockType type) {
return StateMatcher.blockStateMatcherBuilder().type(type);
}
/**
* Gets the base type of block.
*
* <p>The type does not include block data such as the contents of
* inventories.</p>
*
* @return The type of block
*/
BlockType type();
/**
* Gets the associated {@link FluidState} for this block state.
* Depending on whether this block state is considered "waterlogged"
* or not, and with which fluid.
*
* @return The fluid state
*/
FluidState fluidState();
/**
* Creates a new {@link BlockSnapshot} with this current {@link BlockState}
* at the desired {@link ServerLocation}. If the {@link ServerLocation} has the same
* {@link BlockState}, and the {@link BlockType} can house a
* {@link BlockEntity}, the data from the block entity may be included in the
* returned {@link BlockSnapshot}.
*
* @param location The location for the snapshot
* @return The newly created snapshot
*/
BlockSnapshot snapshotFor(ServerLocation location);
/**
* Gets the appropriate {@link BlockState} for the desired {@link Rotation}. It may
* return the same state, but some states may have extra logic associated with rotating
* on its axis, much like mirroring.
*
* @param rotation The rotation
* @return The rotated state if not this state
*/
BlockState rotate(Rotation rotation);
/**
* Gets the appropriate {@link BlockState} for the desired {@link Rotation}. It may
* return the same state, but some states may have extra logic associated with rotating
* on its axis, much like mirroring.
*
* @param rotation The rotation
* @return The rotated state if not this state
*/
default BlockState rotate(final Supplier<? extends Rotation> rotation) {
return this.rotate(rotation.get());
}
/**
* Gets the appropriate {@link BlockState} for the desired {@link Mirror}. It may
* return the same state, but some states may have extra logic associated with mirroring
* on its axis, much like rotation.
*
* @param mirror The mirror
* @return The mirrored state if not this state
*/
BlockState mirror(Mirror mirror);
/**
* Gets the appropriate {@link BlockState} for the desired {@link Mirror}. It may
* return the same state, but some states may have extra logic associated with mirroring
* on its axis, much like rotation.
*
* @param mirror The mirror
* @return The mirrored state if not this state
*/
default BlockState mirror(final Supplier<? extends Mirror> mirror) {
return this.mirror(mirror.get());
}
/**
* An {@link org.spongepowered.api.data.DataHolderBuilder.Immutable} for a {@link BlockState}. Just like the
* {@link org.spongepowered.api.data.DataHolderBuilder.Immutable}, the {@link Value}s passed in to
* create a {@link BlockState} are copied on creation.
*
* <p>Note that upon creation, the {@link BlockType} must be set for validation
* of {@link DataManipulator}s, otherwise exceptions may be thrown.</p>
*/
interface Builder extends State.Builder<BlockState, Builder> {
/**
* Sets the {@link BlockType} for the {@link BlockState} to build.
*
* <p>The {@link BlockType} is used for some pre-validation on addition of
* {@link DataManipulator}s through {@link #add(DataManipulator)}. It is
* important to understand that not all manipulators are compatible with
* all {@link BlockType}s.</p>
*
* @param blockType The block type
* @return This builder, for chaining
*/
default Builder blockType(final Supplier<? extends BlockType> blockType) {
return this.blockType(blockType.get());
}
/**
* Sets the {@link BlockType} for the {@link BlockState} to build.
*
* <p>The {@link BlockType} is used for some pre-validation on addition of
* {@link DataManipulator}s through {@link #add(DataManipulator)}. It is
* important to understand that not all manipulators are compatible with
* all {@link BlockType}s.</p>
*
* @param blockType The block type
* @return This builder, for chaining
*/
Builder blockType(BlockType blockType);
}
}
|
3e1cea3865560e2843fa719e754a7c7967075a31 | 3,303 | java | Java | src-jflap/gui/action/ConvertCFGLL.java | lta-disco-unimib-it/BCT | 1c7fcb52f42bae9f5169c94032ded919cb1c42c4 | [
"Apache-2.0"
] | null | null | null | src-jflap/gui/action/ConvertCFGLL.java | lta-disco-unimib-it/BCT | 1c7fcb52f42bae9f5169c94032ded919cb1c42c4 | [
"Apache-2.0"
] | null | null | null | src-jflap/gui/action/ConvertCFGLL.java | lta-disco-unimib-it/BCT | 1c7fcb52f42bae9f5169c94032ded919cb1c42c4 | [
"Apache-2.0"
] | null | null | null | 31.759615 | 70 | 0.745686 | 12,266 | /* -- JFLAP 4.0 --
*
* Copyright information:
*
* Susan H. Rodger, Thomas Finley
* Computer Science Department
* Duke University
* April 24, 2003
* Supported by National Science Foundation DUE-9752583.
*
* Copyright (c) 2003
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the author. The name of the author may not be used to
* endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
package gui.action;
import grammar.Grammar;
import grammar.Production;
import grammar.cfg.CFGToPDALLConverter;
import gui.environment.GrammarEnvironment;
import gui.environment.Universe;
import gui.environment.tag.CriticalTag;
import gui.grammar.convert.ConvertPane;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import javax.swing.JOptionPane;
import automata.graph.AutomatonGraph;
import automata.graph.GEMLayoutAlgorithm;
import automata.graph.LayoutAlgorithm;
import automata.pda.PushdownAutomaton;
/**
* This is the action that initiates the conversion of a context free
* grammar to a PDA using LL conversion.
*
* @author Thomas Finley
*/
public class ConvertCFGLL extends GrammarAction {
/**
* Instantiates a new <CODE>ConvertCFGLL</CODE> action.
* @param environment the grammar environment
*/
public ConvertCFGLL(GrammarEnvironment environment) {
super("Convert CFG to PDA (LL)", null);
this.environment = environment;
}
/**
* Performs the action.
*/
public void actionPerformed(ActionEvent e) {
Grammar grammar = environment.getGrammar();
if (grammar == null) return;
if (grammar.getProductions().length == 0) {
JOptionPane.showMessageDialog
(Universe.frameForEnvironment(environment),
"The grammar should exist.");
return;
}
// Create the initial automaton.
PushdownAutomaton pda = new PushdownAutomaton();
CFGToPDALLConverter convert = new CFGToPDALLConverter();
convert.createStatesForConversion(grammar, pda);
// Create the map of productions to transitions.
HashMap ptot = new HashMap();
Production[] prods = grammar.getProductions();
for (int i=0; i<prods.length; i++)
ptot.put(prods[i], convert.getTransitionForProduction(prods[i]));
// Add the view to the environment.
final ConvertPane cp = new ConvertPane(grammar, pda, ptot,
environment);
environment.add(cp, "Convert to PDA (LL)", new CriticalTag() {});
// Do the layout of the states.
AutomatonGraph graph = new AutomatonGraph(pda);
LayoutAlgorithm layout = new GEMLayoutAlgorithm();
layout.layout(graph, null);
graph.moveAutomatonStates();
environment.setActive(cp);
environment.validate();
cp.getEditorPane().getAutomatonPane().fitToBounds(20);
}
/** The grammar environment. */
private GrammarEnvironment environment;
}
|
3e1cea9a7c6ff00fd5eade4f5a64cb4374d48f86 | 3,516 | java | Java | qingcheng_service_business/src/main/java/com/qingcheng/service/impl/ActivityServiceImpl.java | qianyeba/qingchengmall | 20058d8863c49044820063befb2b5d717577bdd1 | [
"MIT"
] | 3 | 2020-08-10T22:46:38.000Z | 2021-04-11T12:53:26.000Z | qingcheng_parent/qingcheng_service_business/src/main/java/com/qingcheng/service/impl/ActivityServiceImpl.java | liuconglook/qingcheng | b8387497c4200b89e1b79cbc04671e74e9f2abd9 | [
"Apache-2.0"
] | 4 | 2020-04-23T21:03:40.000Z | 2021-12-09T22:13:12.000Z | qingcheng_parent/qingcheng_service_business/src/main/java/com/qingcheng/service/impl/ActivityServiceImpl.java | liuconglook/qingcheng | b8387497c4200b89e1b79cbc04671e74e9f2abd9 | [
"Apache-2.0"
] | null | null | null | 27.046154 | 93 | 0.603527 | 12,267 | package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.ActivityMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.business.Activity;
import com.qingcheng.service.business.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
import java.util.Map;
@Service
public class ActivityServiceImpl implements ActivityService {
@Autowired
private ActivityMapper activityMapper;
/**
* 返回全部记录
* @return
*/
public List<Activity> findAll() {
return activityMapper.selectAll();
}
/**
* 分页查询
* @param page 页码
* @param size 每页记录数
* @return 分页结果
*/
public PageResult<Activity> findPage(int page, int size) {
PageHelper.startPage(page,size);
Page<Activity> activitys = (Page<Activity>) activityMapper.selectAll();
return new PageResult<Activity>(activitys.getTotal(),activitys.getResult());
}
/**
* 条件查询
* @param searchMap 查询条件
* @return
*/
public List<Activity> findList(Map<String, Object> searchMap) {
Example example = createExample(searchMap);
return activityMapper.selectByExample(example);
}
/**
* 分页+条件查询
* @param searchMap
* @param page
* @param size
* @return
*/
public PageResult<Activity> findPage(Map<String, Object> searchMap, int page, int size) {
PageHelper.startPage(page,size);
Example example = createExample(searchMap);
Page<Activity> activitys = (Page<Activity>) activityMapper.selectByExample(example);
return new PageResult<Activity>(activitys.getTotal(),activitys.getResult());
}
/**
* 根据Id查询
* @param id
* @return
*/
public Activity findById(Integer id) {
return activityMapper.selectByPrimaryKey(id);
}
/**
* 新增
* @param activity
*/
public void add(Activity activity) {
activityMapper.insert(activity);
}
/**
* 修改
* @param activity
*/
public void update(Activity activity) {
activityMapper.updateByPrimaryKeySelective(activity);
}
/**
* 删除
* @param id
*/
public void delete(Integer id) {
activityMapper.deleteByPrimaryKey(id);
}
/**
* 构建查询条件
* @param searchMap
* @return
*/
private Example createExample(Map<String, Object> searchMap){
Example example=new Example(Activity.class);
Example.Criteria criteria = example.createCriteria();
if(searchMap!=null){
// 活动标题
if(searchMap.get("title")!=null && !"".equals(searchMap.get("title"))){
criteria.andLike("title","%"+searchMap.get("title")+"%");
}
// 状态
if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
criteria.andLike("status","%"+searchMap.get("status")+"%");
}
// 活动内容
if(searchMap.get("content")!=null && !"".equals(searchMap.get("content"))){
criteria.andLike("content","%"+searchMap.get("content")+"%");
}
// ID
if(searchMap.get("id")!=null ){
criteria.andEqualTo("id",searchMap.get("id"));
}
}
return example;
}
}
|
3e1cec3973428abb64968a71ea77468b7daa519a | 3,200 | java | Java | netty-demo/src/main/java/com/nio/TestBuffer.java | chengyan0079/netty | 8c0e00fa2ae27dd45ec1dcda6a189580da817283 | [
"Apache-2.0"
] | null | null | null | netty-demo/src/main/java/com/nio/TestBuffer.java | chengyan0079/netty | 8c0e00fa2ae27dd45ec1dcda6a189580da817283 | [
"Apache-2.0"
] | 1 | 2020-07-16T06:22:47.000Z | 2020-07-16T06:22:47.000Z | netty-demo/src/main/java/com/nio/TestBuffer.java | chengyan0079/netty | 8c0e00fa2ae27dd45ec1dcda6a189580da817283 | [
"Apache-2.0"
] | null | null | null | 22.857143 | 68 | 0.609688 | 12,268 | package com.nio;
import java.nio.ByteBuffer;
/**
* 一、缓冲区(Buffer):在 Java NIO 中负责数据的存取。缓冲区就是数组。用于存储不同数据类型的数据
*
* 根据数据类型不同(boolean 除外),提供了相应类型的缓冲区:
* ByteBuffer
* CharBuffer
* ShortBuffer
* IntBuffer
* LongBuffer
* FloatBuffer
* DoubleBuffer
*
* 上述缓冲区的管理方式几乎一致,通过 allocate() 获取缓冲区
*
* 二、缓冲区存取数据的两个核心方法:
* put() : 存入数据到缓冲区中
* get() : 获取缓冲区中的数据
*
* 三、缓冲区中的四个核心属性:
* capacity : 容量,表示缓冲区中最大存储数据的容量。一旦声明不能改变。
* limit : 界限,表示缓冲区中可以操作数据的大小。(limit 后数据不能进行读写)
* position : 位置,表示缓冲区中正在操作数据的位置。
*
* mark : 标记,表示记录当前 position 的位置。可以通过 reset() 恢复到 mark 的位置
*
* 0 <= mark <= position <= limit <= capacity
*
* 四、直接缓冲区与非直接缓冲区:
* 非直接缓冲区:通过 allocate() 方法分配缓冲区,将缓冲区建立在 JVM 的内存中
* 直接缓冲区:通过 allocateDirect() 方法分配直接缓冲区,将缓冲区建立在物理内存中。可以提高效率
*/
public class TestBuffer {
public static void test3(){
//分配直接缓冲区
ByteBuffer buf = ByteBuffer.allocateDirect(10);
System.out.println(buf.isDirect());
}
public static void test2(){
String str = "abcde";
ByteBuffer buf = ByteBuffer.allocate(10);
buf.put(str.getBytes());
buf.flip();
byte[] dst = new byte[buf.limit()];
buf.get(dst, 0, 2);
System.out.println(new String(dst, 0, 2));
System.out.println(buf.position());
//mark() : 标记
buf.mark();
buf.get(dst, 2, 2);
System.out.println(new String(dst, 2, 2));
System.out.println(buf.position());
//reset() : 恢复到 mark 的位置
buf.reset();
System.out.println(buf.position());
//判断缓冲区中是否还有剩余数据
if(buf.hasRemaining()){
//获取缓冲区中可以操作的数量
System.out.println(buf.remaining());
}
}
public static void test1(){
String str = "abcde";
//1. 分配一个指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(10);
System.out.println("-----------------allocate()----------------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//2. 利用 put() 存入数据到缓冲区中
buf.put(str.getBytes());
System.out.println("-----------------put()----------------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//3. 切换读取数据模式
buf.flip();
System.out.println("-----------------flip()----------------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//4. 利用 get() 读取缓冲区中的数据
byte[] dst = new byte[buf.limit()];
buf.get(dst);
System.out.println(new String(dst, 0, dst.length));
System.out.println("-----------------get()----------------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//5. rewind() : 可重复读
buf.rewind();
System.out.println("-----------------rewind()----------------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
//6. clear() : 清空缓冲区. 但是缓冲区中的数据依然存在,但是处于“被遗忘”状态
buf.clear();
System.out.println("-----------------clear()----------------");
System.out.println(buf.position());
System.out.println(buf.limit());
System.out.println(buf.capacity());
System.out.println((char)buf.get());
}
public static void main(String[] args) {
test3();
}
}
|
3e1ced292632bcb225776aaff36eed6224848ad7 | 349 | java | Java | ssh/src/com/yeelight/dao/ProductDAO.java | axdlee/java-study | f5142ee6c33840aec79581eb26b4ee0171f90d94 | [
"MIT"
] | null | null | null | ssh/src/com/yeelight/dao/ProductDAO.java | axdlee/java-study | f5142ee6c33840aec79581eb26b4ee0171f90d94 | [
"MIT"
] | null | null | null | ssh/src/com/yeelight/dao/ProductDAO.java | axdlee/java-study | f5142ee6c33840aec79581eb26b4ee0171f90d94 | [
"MIT"
] | null | null | null | 16.666667 | 43 | 0.682857 | 12,269 | package com.yeelight.dao;
import com.yeelight.pojo.Product;
import java.util.List;
/**
* Created by Sheldon
* User: sheldon
* Date: 18-8-1
* Time: 下午1:46
*
* @author Sheldon Lee <anpch@example.com>
* @link https://www.yeelight.com
*/
public interface ProductDAO {
public List<Product> list();
public void add(Product product);
}
|
3e1ceda157556a96716a2116e438ee19b6209fad | 2,350 | java | Java | core/src/main/java/com/sequenceiq/cloudbreak/service/cluster/ClusterService.java | karim7262/cloudbreak | 5ed2d5ff9533a0c015de1ccc384a4206416f1011 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/sequenceiq/cloudbreak/service/cluster/ClusterService.java | karim7262/cloudbreak | 5ed2d5ff9533a0c015de1ccc384a4206416f1011 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/com/sequenceiq/cloudbreak/service/cluster/ClusterService.java | karim7262/cloudbreak | 5ed2d5ff9533a0c015de1ccc384a4206416f1011 | [
"Apache-2.0"
] | null | null | null | 39.166667 | 124 | 0.825106 | 12,270 | package com.sequenceiq.cloudbreak.service.cluster;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.sequenceiq.cloudbreak.api.model.ClusterResponse;
import com.sequenceiq.cloudbreak.api.model.HostGroupAdjustmentJson;
import com.sequenceiq.cloudbreak.api.model.Status;
import com.sequenceiq.cloudbreak.api.model.StatusRequest;
import com.sequenceiq.cloudbreak.api.model.UserNamePasswordJson;
import com.sequenceiq.cloudbreak.cloud.model.HDPRepo;
import com.sequenceiq.cloudbreak.core.CloudbreakSecuritySetupException;
import com.sequenceiq.cloudbreak.domain.CbUser;
import com.sequenceiq.cloudbreak.domain.Cluster;
import com.sequenceiq.cloudbreak.domain.Component;
import com.sequenceiq.cloudbreak.domain.HostGroup;
import com.sequenceiq.cloudbreak.service.stack.flow.HttpClientConfig;
public interface ClusterService {
Cluster create(CbUser user, Long stackId, Cluster clusterRequest, List<Component> component);
void delete(CbUser user, Long stackId);
Cluster retrieveClusterByStackId(Long stackId);
ClusterResponse retrieveClusterForCurrentUser(Long stackId);
Cluster updateAmbariClientConfig(Long clusterId, HttpClientConfig ambariClientConfig);
void updateHostCountWithAdjustment(Long clusterId, String hostGroupName, Integer adjustment);
void updateHostMetadata(Long clusterId, Map<String, List<String>> hostsPerHostGroup);
String getClusterJson(String ambariIp, Long stackId);
void updateHosts(Long stackId, HostGroupAdjustmentJson hostGroupAdjustment) throws CloudbreakSecuritySetupException;
void updateStatus(Long stackId, StatusRequest statusRequest);
Cluster updateClusterStatusByStackId(Long stackId, Status status, String statusReason);
Cluster updateClusterStatusByStackId(Long stackId, Status status);
Cluster updateCluster(Cluster cluster);
Cluster updateClusterMetadata(Long stackId);
Cluster updateClusterUsernameAndPassword(Cluster cluster, String userName, String password);
Cluster recreate(Long stackId, Long blueprintId, Set<HostGroup> hostGroups, boolean validateBlueprint, HDPRepo hdpRepo);
Cluster updateUserNamePassword(Long stackId, UserNamePasswordJson userNamePasswordJson);
ClusterResponse getClusterResponse(ClusterResponse response, String clusterJson);
Cluster getById(Long clusterId);
}
|
3e1cef634eeedbc773cc862e839ab0e5d1a7659d | 6,209 | java | Java | src/main/java/net/ihiroky/niotty/nio/NioSocketTransport.java | ihiroky/niotty | 725478d258227f137526281753f70d8ded0c9951 | [
"MIT"
] | null | null | null | src/main/java/net/ihiroky/niotty/nio/NioSocketTransport.java | ihiroky/niotty | 725478d258227f137526281753f70d8ded0c9951 | [
"MIT"
] | null | null | null | src/main/java/net/ihiroky/niotty/nio/NioSocketTransport.java | ihiroky/niotty | 725478d258227f137526281753f70d8ded0c9951 | [
"MIT"
] | null | null | null | 34.494444 | 118 | 0.579965 | 12,271 | package net.ihiroky.niotty.nio;
import net.ihiroky.niotty.*;
import net.ihiroky.niotty.buffer.Packet;
import net.ihiroky.niotty.util.Arguments;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.util.concurrent.TimeUnit;
/**
* A skeletal implementation of {@link net.ihiroky.niotty.Transport} for NIO.
* @param <S> a type of selector
*/
public abstract class NioSocketTransport extends AbstractTransport {
private final DefaultPipeline pipeline_;
private SelectionKey key_;
private static Logger logger_ = LoggerFactory.getLogger(NioSocketTransport.class);
NioSocketTransport(String name, PipelineComposer pipelineComposer, NioEventDispatcherGroup eventDispatcherGroup) {
super(name, pipelineComposer, eventDispatcherGroup);
Stage ioStage = ((NioEventDispatcher) eventDispatcher()).ioStage();
pipeline_ = new DefaultPipeline(name, this, eventDispatcherGroup, Pipeline.IO_STAGE_KEY, ioStage);
}
@Override
public String toString() {
return (key_ != null) ? key_.channel().toString() : "unregistered";
}
final void setSelectionKey(SelectionKey key) {
Arguments.requireNonNull(key, "key");
this.key_ = key;
}
final TransportFuture closeSelectableChannel() {
NioEventDispatcher dispatcher = (NioEventDispatcher) eventDispatcher();
if (dispatcher == null) {
pipeline_.close();
return new SuccessfulTransportFuture(this);
}
dispatcher.offer(new Event() {
@Override
public long execute() {
NioSocketTransport.this.doCloseSelectableChannel();
return DONE;
}
});
return closeFuture();
}
/**
* Closes the channel.
*
* The key is cancelled and the channel is closed if the key is non null and valid.
* The load pipeline and onStore pipeline (optional) is called
* after the channel is closed. This method calls {@code #onCloseSelectableChannel} and
* closes its pipeline after the channel close operation.
* @return close future
*/
final TransportFuture doCloseSelectableChannel() {
DefaultTransportFuture closeFuture = closeFuture();
if (key_ != null && key_.isValid() && closeFuture.executing()) {
SelectableChannel channel = key_.channel();
try {
unregister(); // deactivate and decrement register count
channel.close();
closeFuture.done();
} catch (Exception e) {
closeFuture.setThrowable(e);
}
onCloseSelectableChannel();
pipeline_.close();
}
return closeFuture;
}
void onCloseSelectableChannel() {
}
final SelectionKey key() {
return key_;
}
void setInterestOp(int op) {
int interestOps = key_.interestOps();
if ((interestOps & op) == 0) {
key_.interestOps(interestOps | op);
}
}
void clearInterestOp(int op) {
int interestOps = key_.interestOps();
if ((interestOps & op) != 0) {
key_.interestOps(interestOps & ~op);
}
}
void register(final SelectableChannel channel, final int ops) throws IOException {
if (key_ != null && key_.isValid()) {
return;
}
final NioEventDispatcher dispatcher = (NioEventDispatcher) eventDispatcher();
if (dispatcher.isInDispatcherThread()) {
if (ops == SelectionKey.OP_READ) {
pipeline().activate();
}
key_ = dispatcher.register(channel, ops, NioSocketTransport.this);
} else {
// case: ConnectorSelector <-> TcpIOSelector
dispatcher.offer(new Event() {
@Override
public long execute() {
try {
if (ops == SelectionKey.OP_READ) {
pipeline().activate();
}
key_ = dispatcher.register(channel, ops, NioSocketTransport.this);
} catch (Exception e) {
logger_.warn("[register] Failed to register a channel:" + this, e);
}
return DONE;
}
});
}
}
// This method needs to be called by I/O thread.
void unregister() {
SelectionKey key = key_;
if (key != null) {
if ((key.interestOps() & SelectionKey.OP_READ) != 0) {
try {
pipeline().deactivate();
} catch (RuntimeException re) {
logger_.warn("[unregister] {}'s deactivation is failed.", this);
}
}
key.cancel();
}
eventDispatcher().reject(this);
logger_.debug("[unregister] {} is unregistered from {}.", this, Thread.currentThread());
}
protected void handleFlushStatus(FlushStatus status) {
switch (status) {
case FLUSHED:
clearInterestOp(SelectionKey.OP_WRITE);
return;
case FLUSHING:
clearInterestOp(SelectionKey.OP_WRITE);
eventDispatcher().schedule(new Event() {
@Override
public long execute() throws Exception {
setInterestOp(SelectionKey.OP_WRITE);
return DONE;
}
}, status.waitTimeMillis_, TimeUnit.MILLISECONDS);
return;
case SKIPPED:
setInterestOp(SelectionKey.OP_WRITE);
return;
default:
throw new AssertionError("Unexpected flush status: " + status);
}
}
abstract void onSelected(SelectionKey key, NioEventDispatcher selectDispatcher);
abstract void readyToWrite(Packet message, Object parameter);
abstract void flush(ByteBuffer writeBuffer) throws IOException;
}
|
3e1cefcecc138771390bdfd311ee31d930d93f35 | 33,624 | java | Java | WEB-INF/classes/org/usip/osp/networking/SessionObjectBase.java | skipcole/opensimplatform | 872ab7636cc704b82386ec0e503b5f042a8222cf | [
"BSD-3-Clause"
] | 1 | 2018-01-31T01:59:37.000Z | 2018-01-31T01:59:37.000Z | WEB-INF/classes/org/usip/osp/networking/SessionObjectBase.java | skipcole/opensimplatform | 872ab7636cc704b82386ec0e503b5f042a8222cf | [
"BSD-3-Clause"
] | null | null | null | WEB-INF/classes/org/usip/osp/networking/SessionObjectBase.java | skipcole/opensimplatform | 872ab7636cc704b82386ec0e503b5f042a8222cf | [
"BSD-3-Clause"
] | null | null | null | 26.749403 | 99 | 0.659321 | 12,272 | package org.usip.osp.networking;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.usip.osp.baseobjects.RunningSimulation;
import org.usip.osp.baseobjects.Simulation;
import org.usip.osp.baseobjects.USIP_OSP_Properties;
import org.usip.osp.baseobjects.USIP_OSP_Util;
import org.usip.osp.baseobjects.User;
import org.usip.osp.baseobjects.UserAssignment;
import org.usip.osp.baseobjects.UserTrailGhost;
import org.usip.osp.communications.Emailer;
import org.usip.osp.communications.Event;
import org.usip.osp.communications.InjectFiringHistory;
import org.usip.osp.communications.TimeLine;
import org.usip.osp.coursemanagementinterface.UserRegistrationInvite;
import org.usip.osp.persistence.BaseUser;
import org.usip.osp.persistence.MultiSchemaHibernateUtil;
import org.usip.osp.persistence.OSPErrors;
import org.usip.osp.persistence.SchemaInformationObject;
import org.usip.osp.persistence.UILanguageObject;
import com.seachangesimulations.osp.gametime.GamePhaseCurrentTime;
/**
* This object contains all of the methods and data to create users, and to
* allow users to log in as either an administrator, author, instructor or
* player.
*
*/
/*
*
* This file is part of the USIP Open Simulation Platform.<br>
*
* The USIP Open Simulation Platform is free software; you can redistribute it
* and/or modify it under the terms of the new BSD Style license associated with
* this distribution.<br>
*
* The USIP Open Simulation Platform is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. <BR>
*/
public class SessionObjectBase {
public static final int NO_ACTION = -1;
public static final int ALL_GOOD = 0;
public static final int CAPTCHA_WRONG = 1;
public static final int USERNAME_MISMATCH = 2;
public static final int INSUFFICIENT_INFORMATION = 3;
public static final int PASSWORDS_MISMATCH = 4;
public static final int WRONG_OLD_PASSWORD = 5;
public static final int PASSWORDS_CHANGED = 6;
public static final int FORCED_PASSWORD_CHANGED = 7;
public static final int USERNAME_CHANGED = 8;
public static final int CONFIRM_DEFAULT = 9;
public static final int USER_FOUND = 10;
public static final int USER_NOT_FOUND = 11;
public static final int INSUFFICIENT_PRIVLEGE = 12;
// //////////////////////////////////////////
public static final int ADMIN_LOGIN = 0;
public static final int AUTHOR_LOGIN = 1;
public static final int FACILITATOR_LOGIN = 2;
public static final int PLAYER_LOGIN = 3;
// //////////////////////////////////////////
public SessionObjectBase() {
}
/** Page to forward the user on to. */
public boolean forward_on = false;
/**
* Returns the simulation based on what sim_id is currently stored in this
* Session Object Base.
*
* @return
*/
public Simulation giveMeSim() {
Simulation simulation = new Simulation();
if (sim_id == null) {
return simulation;
}
try {
simulation = Simulation.getById(schema, sim_id);
} catch (Exception e) {
OSPErrors.storeInternalWarning(
"Error encountered trying to get simulation in SOB "
+ e.getMessage(), this);
simulation = new Simulation();
}
if (simulation == null) {
simulation = new Simulation();
}
return simulation;
}
/** Schema of the database that the user is working in. */
public String schema = ""; //$NON-NLS-1$
public String schemaDisplayName = ""; //$NON-NLS-1$
/** The page to take them back to if needed. */
public String backPage = "index.jsp"; //$NON-NLS-1$
/**
* In the rare cases where the user will need to go back to a point even
* further back.
*/
public int backBackPageCode = 0; //$NON-NLS-1$
/** Code to indicate what kind of error was returned. */
public int errorCode = 0;
/** Error message to be shown to the user. */
public String errorMsg = ""; //$NON-NLS-1$
/** An event that is being worked on. */
public Long draft_event_id;
/**
* We use a language code to indicate what language to show the interface
* in. It can be set by the simulation, or over ridden by the player.
*/
public int languageCode = UILanguageObject.ENGLISH_LANGUAGE_CODE;
public int getLanguageCode() {
return languageCode;
}
public void setLanguageCode(int languageCode) {
this.languageCode = languageCode;
}
/** Records if user is an admin. */
protected boolean isAdmin = false;
/** Records if user is authorized to create simulations. */
protected boolean isSimAuthor = false;
/** Records if user is authorized to facilitate simulations. */
protected boolean isFacilitator = false;
public boolean isAdmin() {
return isAdmin;
}
public boolean isAuthor() {
return isSimAuthor;
}
public boolean isFacilitator() {
return isFacilitator;
}
/** Records the email of this user. */
public String user_email = ""; //$NON-NLS-1$
/** Determines if actor is logged in. */
protected boolean loggedin = false;
public void setLoggedin(boolean loggedin) {
this.loggedin = loggedin;
}
public boolean isLoggedin() {
return loggedin;
}
/** ID of Simulation being conducted or worked on. */
public Long sim_id;
/** Name of simulation being conducted or worked on. */
public String simulation_name = ""; //$NON-NLS-1$
/** Version of the simulation be conducted or worked on. */
public String simulation_version = ""; //$NON-NLS-1$
/** Organization that created the simulation. */
public String simulation_org = ""; //$NON-NLS-1$
/** Id of the actor being developed */
public Long actor_being_worked_on_id;
/** ID of Phase being worked on. */
public Long phase_id;
/**
* Copyright string to display at the bottom of every page in the
* simulation.
*/
public String sim_copyright_info = ""; //$NON-NLS-1$
/** ID of the Running Simulation being conducted or worked on. */
public Long runningSimId;
public Long getRunningSimId() {
return runningSimId;
}
public void setRunningSimId(Long runningSimId) {
this.runningSimId = runningSimId;
}
/** Name of the running simulation session. */
public String run_sim_name = ""; //$NON-NLS-1$
/** Records the display name of this user. */
public String userDisplayName = ""; //$NON-NLS-1$
/** User trail ghost of this user. */
public UserTrailGhost myUserTrailGhost = new UserTrailGhost();
/**
* Pulls the running sim whose id is being stored out of the database.
*
* @return
*/
public RunningSimulation giveMeRunningSim() {
if (runningSimId == null) {
Logger.getRootLogger().warn(
"Warning RunningSimId is null in pso.giveMeRunningSim");
return null;
}
MultiSchemaHibernateUtil.beginTransaction(schema);
RunningSimulation rs = (RunningSimulation) MultiSchemaHibernateUtil
.getSession(schema).get(RunningSimulation.class, runningSimId);
MultiSchemaHibernateUtil.getSession(schema).evict(rs);
MultiSchemaHibernateUtil.commitAndCloseTransaction(schema);
return rs;
}
/**
* Returns all of the planned events for a phase.
*
* @param schema
* @param sim_id
* @param phase_id
* @return
*/
public static String getEventsForTimeline(String schema, Long timeLineId) {
if (timeLineId == null) {
return "";
}
// TODO - below is what it eventually should be.
// TimeLine.packupArray(TimeLineObjectAssignment.getAllForTimeline(schema,
// timeLineId));
return TimeLine
.packupArray(Event.getAllForTimeLine(schema, timeLineId));
}
public static String getInjectFiredForTimeline(String schema, Long rs_id) {
if (rs_id == null) {
return "";
}
return TimeLine.packupArray(InjectFiringHistory.getAllTLForRunningSim(
schema, rs_id));
}
public static String getBaseSimURL() {
return USIP_OSP_Properties.getValue("base_sim_url");
}
/** Id of User that is logged on. */
public Long user_id;
/**
* Username/ Email address of user that is logged in and using this
* AuthorFacilitatorSessionObject.
*/
public String user_name;
/**
* Returns the user associated with this session.
*
* @return
*/
public User giveMeUser() {
if (this.user_id != null) {
return User.getUser(schema, this.user_id);
} else {
return null;
}
}
/**
* Creates a user assignment based on parameters passed into it on a web
* form.
*
* @param request
* @return
*/
public UserAssignment getUserAssignBasedOnParameters(
HttpServletRequest request) {
UserAssignment ua = new UserAssignment();
String ua_id = request.getParameter("ua_id"); //$NON-NLS-1$
if ((ua_id != null) && (!(ua_id.equalsIgnoreCase("null")))) {
ua.setId(new Long(ua_id));
}
String uname = request.getParameter("uname"); //$NON-NLS-1$
ua.setUsername(uname);
String a_id = request.getParameter("a_id"); //$NON-NLS-1$
String s_id = request.getParameter("s_id"); //$NON-NLS-1$
String rs_id = request.getParameter("rs_id"); //$NON-NLS-1$
try {
if (a_id != null) {
ua.setActor_id(new Long(a_id));
}
if (s_id != null) {
ua.setSim_id(new Long(s_id));
}
if (rs_id != null) {
ua.setRunning_sim_id(new Long(rs_id));
}
} catch (Exception e) {
return ua;
}
return ua;
}
/**
* Handles just assigning a user email to a role in a simulation (and not a
* completely registered student).
*
* @param request
* @return
*/
public UserAssignment handleAssignUserEmail(HttpServletRequest request) {
UserAssignment ua = getUserAssignBasedOnParameters(request);
String sending_page = request.getParameter("sending_page");
if ((sending_page != null)
&& (sending_page.equalsIgnoreCase("assign_just_email"))) {
String command = request.getParameter("command");
if (command != null) {
this.forward_on = true;
if (command.equalsIgnoreCase("Cancel")) {
backPage = "../simulation_facilitation/facilitate_assign_user_to_simulation.jsp";
return ua;
}
if (command.equalsIgnoreCase("Create")) {
ua.saveMe(schema);
backPage = "../simulation_user_admin/create_user.jsp?create_for_role=true&ua_id="
+ ua.getId();
return ua;
}
if (command.equalsIgnoreCase("Add")) {
ua.setUser_id(new Long(-1));
ua.saveMe(schema);
backPage = "../simulation_facilitation/facilitate_assign_user_to_simulation.jsp";
return ua;
}
}
}
return ua;
}
/** Assigns a user to a simulation. */
public UserAssignment handleAssignUser(HttpServletRequest request) {
UserAssignment ua = new UserAssignment();
String command = request.getParameter("command"); //$NON-NLS-1$
String user_assignment_id = request.getParameter("user_assignment_id"); //$NON-NLS-1$
Long a_id = null;
Long s_id = null;
Long r_id = null;
Long ua_id = null;
Long user_to_add_id = null;
if (command != null) {
// User selected '-' icon to remove assignment.
if (command.equalsIgnoreCase("remove_ua")) {
UserAssignment.removeMe(schema, new Long(user_assignment_id));
return ua;
}
String actor_id = request
.getParameter("actor_to_add_to_simulation"); //$NON-NLS-1$
String sim_id = request.getParameter("simulation_adding_to"); //$NON-NLS-1$
String running_sim_id = request
.getParameter("running_simulation_adding_to"); //$NON-NLS-1$
// Email address of user to assign role to
String user_to_add_to_simulation = request
.getParameter("user_to_add_to_simulation"); //$NON-NLS-1$
String user_id = request.getParameter("user_id"); //$NON-NLS-1$
try {
a_id = new Long(actor_id);
s_id = new Long(sim_id);
r_id = new Long(running_sim_id);
if ((user_assignment_id != null)
&& (!(user_assignment_id.equalsIgnoreCase("null")))) {
ua_id = new Long(user_assignment_id);
ua.setId(ua_id);
}
} catch (Exception e) {
e.printStackTrace();
return ua;
}
if ((command != null) && (command.equalsIgnoreCase("Assign User"))) { //$NON-NLS-1$
if (user_id != null) {
user_to_add_id = new Long(user_id);
User thisUser = User.getById(schema, user_to_add_id);
user_to_add_to_simulation = thisUser.getBu_username();
} else {
if ((user_to_add_to_simulation == null)
|| (user_to_add_to_simulation.trim().length() == 0)) {
return ua;
}
user_to_add_id = USIP_OSP_Cache.getUserIdByName(schema,
request, user_to_add_to_simulation);
}
// User was not found, so must add assignment to just the
// useremail entered.
if (user_to_add_id == null) {
ua.setUsername(user_to_add_to_simulation);
ua.setSim_id(s_id);
ua.setActor_id(a_id);
ua.setRunning_sim_id(r_id);
forward_on = true;
return ua;
}
// //////////////////////////////////////////////////////////
// Add user to an existing userAssignment object
if (ua_id != null) {
ua = UserAssignment.getById(schema, ua_id);
}
if (ua != null) {
ua.setSim_id(s_id);
ua.setRunning_sim_id(r_id);
ua.setActor_id(a_id);
ua.setUser_id(user_to_add_id);
ua.setUsername(user_to_add_to_simulation);
ua.saveMe(schema);
}
// ///////////////////////////////////////////////////////
} else if (command.equalsIgnoreCase("add_assignment")) {
// Creating a new blank user assignment
ua = new UserAssignment(schema, s_id, r_id, a_id, null);
} // end of adding a ua object
} // End of if command is not null
return ua;
}
/** Allows a user to change his or her password. */
public int changePassword(HttpServletRequest request) {
String sending_page = (String) request.getParameter("sending_page");
String update = (String) request.getParameter("update");
String forcepasswordchange = request
.getParameter("forcepasswordchange");
if ((sending_page != null)
&& (sending_page.equalsIgnoreCase("change_password"))) {
if (update != null) {
String old_password = request.getParameter("old_password");
String new_password = request.getParameter("new_password");
String new_password2 = request.getParameter("new_password2");
if ((old_password == null) || (new_password == null)
|| (new_password == null)) {
return INSUFFICIENT_INFORMATION;
}
if (!(new_password.equals(new_password2))) {
return PASSWORDS_MISMATCH;
}
BaseUser bu = BaseUser.validateUser(this.user_name,
old_password);
if (bu == null) {
return WRONG_OLD_PASSWORD;
}
bu.setPassword(new_password);
bu.setTempPassword(false);
bu.setTemppasswordCleartext("");
bu.saveMe();
if ((forcepasswordchange != null)
&& (forcepasswordchange.equalsIgnoreCase("true"))) {
return FORCED_PASSWORD_CHANGED;
} else {
return PASSWORDS_CHANGED;
}
}
}
return ALL_GOOD;
}
/** Allows an admin to change his or her password. */
public int changeUserPassword(HttpServletRequest request) {
String sending_page = (String) request.getParameter("sending_page");
String update = (String) request.getParameter("update");
String user_email = (String) request.getParameter("user_email");
if ((sending_page == null)
|| (!(sending_page.equalsIgnoreCase("change_userpassword")))) {
return NO_ACTION;
}
BaseUser bu = BaseUser.getByUsername(user_email);
if (bu == null) {
return USER_NOT_FOUND;
}
String forcepasswordchange = request
.getParameter("forcepasswordchange");
if ((sending_page != null)
&& (sending_page.equalsIgnoreCase("change_userpassword"))) {
if (update != null) {
String new_password = request.getParameter("new_password");
String new_password2 = request.getParameter("new_password2");
if ((new_password == null) || (new_password2 == null)) {
return INSUFFICIENT_INFORMATION;
}
if (!(new_password.equals(new_password2))) {
return PASSWORDS_MISMATCH;
}
bu.setPassword(new_password);
bu.setTempPassword(false);
bu.setTemppasswordCleartext("");
bu.saveMe();
if ((forcepasswordchange != null)
&& (forcepasswordchange.equalsIgnoreCase("true"))) {
return FORCED_PASSWORD_CHANGED;
} else {
return PASSWORDS_CHANGED;
}
}
}
return ALL_GOOD;
}
/**
* Handles a request sent to update the user profile.
*
* @param request
*/
public void handleMyProfile(HttpServletRequest request) {
String sending_page = (String) request.getParameter("sending_page");
String update = (String) request.getParameter("update");
// /////////////////////////////////
if ((sending_page != null) && (update != null)
&& (sending_page.equalsIgnoreCase("my_profile"))) {
OSP_UserAdmin pu = new OSP_UserAdmin(this);
pu.handleMyProfile(request, user_id);
}
}
/** The captcha set by the captcha jsp that the user must match. */
public String sessionCaptchaCode = "";
/** Indicates if the schema has been specified. */
public boolean sioSet = false;
/** Holds the value of the User Assignment Object, if it was passed in. */
public Long uaId = null;
/** Holds the value of the User Registration Information Object, if it was passed in. */
public Long uriId = null;
/** Holds the value of the Contest Team Object, if it was passed in. */
public Long ctId = null;
/**
* Handles the auto-registration of players. This method can be called
* reached in several ways 1.) When a student responds to a bulk invite. 2.)
* When a student responds to an invite to a particular simulation. 3.) When
* a student responds to a contest invitation.
*
* @param request
* @return
*/
public User handleAutoRegistration(HttpServletRequest request) {
// Get clean values to prepare to return.
User user = new User();
errorMsg = "";
// Determine the type of registration (bulk, specific sim, contest) being attempted.
setRegistrationType(request);
// Set the schema if it was passed in
setSchema(request);
String command = request.getParameter("command"); //$NON-NLS-1$
// Coming here from user action.
if ((command != null) && (command.equalsIgnoreCase("Register"))) {
// Create a helper object and use it to load data into the user
// object
OSP_UserAdmin osp_ua = new OSP_UserAdmin(this);
osp_ua.getUserNameDetails(request);
osp_ua.loadUserWithData(user);
// Verify that all required information has been submitted, else
// return
boolean returnForLackOfInformation = returnUnFinishedUserRegGauntlet(
user, request.getParameter("captchacode"), osp_ua);
if (returnForLackOfInformation) {
return user;
}
try {
user = new User(schema, user.getUserName(),
request.getParameter("password"),
user.getBu_first_name(), user.getBu_last_name(),
user.getBu_middle_name(), user.getBu_full_name(),
false, false, false);
// ///////////////////////////////////////
if (uriId != null) {
UserRegistrationInvite uri = UserRegistrationInvite
.getById(schema, uriId);
uri.setEmailAddressRegistered(user.getUserName());
uri.setRegistrationDate(new Date());
uri.saveMe();
}
// ///////////////////////////////////////
if (uaId != null) {
UserAssignment ua = UserAssignment.getById(schema, uaId);
//user.setUser_name(ua.getUsername());
//user.setBu_username(ua.getUsername());
ua.setUser_id(user.getId());
ua.advanceStatus(UserAssignment.STATUS_REGISTERED);
ua.saveMe(schema);
}
} catch (Exception e) {
errorMsg += e.getMessage();
OSPErrors.storeWebErrors(e, request);
}
// Set so they forward on to the 'Thank You for registering' page.
forward_on = true;
} // End of if this is a registration attempt.
handleComingFromBulkInvite(request, user);
handleComingFromInstructorAssignedRole(user);
return user;
}
private void handleComingFromInstructorAssignedRole(User user) {
if (uaId != null) {
UserAssignment ua = UserAssignment.getById(schema, uaId);
user.setUser_name(ua.getUsername());
user.setBu_username(ua.getUsername());
}
}
private void setRegistrationType(HttpServletRequest request) {
this.uaId = null;
this.uriId = null;
this.ctId = null;
// A 'User Assignment ID' indicates this is from an invitation to join a
// simulation.
String ua_id = request.getParameter("ua_id");
// A UserRegistrationInvite ID indicates this is from a bulk invite.
String uri_id = (String) request.getParameter("uri");
// A Contest Team ID this is from an invitation to join a contest team.
String ct_id = (String) request.getParameter("ct_id");
if (USIP_OSP_Util.stringFieldHasValue(ua_id)) {
this.uaId = new Long(ua_id);
}
if (USIP_OSP_Util.stringFieldHasValue(uri_id)) {
this.uriId = new Long(uri_id);
}
if (USIP_OSP_Util.stringFieldHasValue(ct_id)) {
this.ctId = new Long(ct_id);
}
}
/** Sets the schema selected to be the one that was passed in. */
private void setSchema(HttpServletRequest request) {
String schema = (String) request.getParameter("schema");
sioSet = false;
if (USIP_OSP_Util.stringFieldHasValue(schema)) {
try {
SchemaInformationObject sio = SchemaInformationObject
.lookUpSIOByName(schema);
if (sio != null) {
this.schema = schema;
this.schemaDisplayName = sio.getSchema_organization();
this.sioSet = true;
}
} catch (Exception e) {
errorMsg += "Invalid Database Selected.<br/>";
OSPErrors.storeWebErrors(e, request);
}
}
}
/**
* Checks to see if this has been activated from a bulk invitation email.
*
* @param request
* @param user
*/
private void handleComingFromBulkInvite(HttpServletRequest request,
User user) {
String initial_entry = (String) request.getParameter("initial_entry");
UserRegistrationInvite uri = new UserRegistrationInvite();
if ((uriId != null) && (USIP_OSP_Util.stringFieldHasValue(initial_entry))
&& (USIP_OSP_Util.stringFieldHasValue(schema))
){
uri = UserRegistrationInvite.getById(schema, uriId);
user.setBu_username(uri.getOriginalInviteEmailAddress());
}
}
/**
* Checks to see if requisit information has been passed in.
*
* @param user
* @param captchacodeTypedByUser
* @param osp_ua
* @return
*/
public boolean returnUnFinishedUserRegGauntlet(User user,
String captchacodeTypedByUser, OSP_UserAdmin osp_ua) {
boolean returnForLackOfInformation = false;
if (!(captchacodeTypedByUser.equalsIgnoreCase(sessionCaptchaCode))) {
errorMsg += "Incorrect Captcha Code<br/>";
errorCode = CAPTCHA_WRONG;
returnForLackOfInformation = true;
}
if (User.getByUsername(schema, user.getUserName()) != null) {
errorMsg += "This username/email already has been registered. <br/>";
returnForLackOfInformation = true;
}
if (!(osp_ua.hasEnoughInfoToCreateUser(true))) {
// This loads its own error information.
returnForLackOfInformation = true;
}
if (schema == null) {
errorMsg += "No database selected.<br/>";
returnForLackOfInformation = true;
}
return returnForLackOfInformation;
}
/**
*
* @param request
* @return
*/
public User handleCreateUser(HttpServletRequest request) {
String username = request.getParameter("email");
String command = request.getParameter("command");
if ((command != null) && (command.equalsIgnoreCase("Clear"))) { //$NON-NLS-1$
return new User();
}
User user = User.getByUsername(schema, username);
if (user != null) {
this.errorMsg = "The user " + username + " already exists.";
return user;
} else {
OSP_UserAdmin pu = new OSP_UserAdmin(this);
return pu.handleCreateUser(request, schema);
}
}
/**
* Handles the entry of the player to the confirmation page.
*
* @param request
* @return
*/
public int processConfirmation(HttpServletRequest request) {
System.out.println("Doing confirmation");
String schema = request.getParameter("schema");
String er_id = request.getParameter("er_id");
String ua_id = request.getParameter("ua_id");
if ((schema != null) && (er_id != null) & (ua_id != null)) {
this.schema = schema;
this.sioSet = true;
this.uaId = new Long(ua_id);
UserAssignment ua = UserAssignment.getById(schema, uaId);
if (ua != null) {
ua.advanceStatus("confirmed");
ua.saveMe(schema);
if (ua.getUser_id() != null) {
if (ua.getUser_id().intValue() == -1){
return USER_NOT_FOUND;
}
return USER_FOUND;
} else {
return USER_NOT_FOUND;
}
} else {
OSPErrors.storeInternalWarning("ua null for uaId = " + uaId,
this);
}
}
return CONFIRM_DEFAULT;
}
/**
* Called from the head of the login jsp, this attempts to log the user in.
*
* @param request
* @return
*/
public static BaseUser handleLoginAttempt(HttpServletRequest request,
PlayerSessionObject pso) {
String attempting_login = (String) request
.getParameter("attempting_login");
if ((attempting_login != null)
&& (attempting_login.equalsIgnoreCase("true"))) {
BaseUser bu = validate(request);
if (bu != null) {
pso.languageCode = bu.getPreferredLanguageCode().intValue();
pso.user_id = bu.getId();
pso.user_name = bu.getUsername();
pso.setLoggedin(true);
}
return bu;
}
return null;
}
/**
* Pulls the base user (if found) out of the database.
*
* @param request
* @return
*/
public static BaseUser validate(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
BaseUser bu = BaseUser.validateUser(username, password);
return bu;
}
public static int debugNumber = 1;
public void debugTag() {
debugNumber += 1;
System.out.flush();
}
public void debugTag(String marker) {
debugTag();
}
public boolean listOfActorsInvalidated = true;
private List setOfActors = new ArrayList();
public List getSetOfActors(Simulation simulation) {
if (!(listOfActorsInvalidated)) {
debugTag("get stored set");
return setOfActors;
} else {
debugTag("getting new set");
setOfActors = simulation.getActors(schema);
listOfActorsInvalidated = false;
return setOfActors;
}
}
/**
* Handles the changing of a players user name.
*
* @param request
* @return
*/
public int changeUserName(HttpServletRequest request) {
if (!(this.isAdmin)) {
return INSUFFICIENT_PRIVLEGE;
}
String sending_page = request.getParameter("sending_page");
String old_username = request.getParameter("old_username");
String new_username = request.getParameter("new_username");
String new_username2 = request.getParameter("new_username2");
if ((sending_page != null)
&& (sending_page.equalsIgnoreCase("change_password"))) {
// Check that new emails match
if ((new_username == null) || (new_username2 == null)) {
return INSUFFICIENT_INFORMATION;
}
if (new_username.trim().length() == 0) {
return INSUFFICIENT_INFORMATION;
}
if (!(new_username.equalsIgnoreCase(new_username2))) {
return USERNAME_MISMATCH;
}
BaseUser bu = BaseUser.getByUsername(old_username);
if (bu == null) {
return USER_NOT_FOUND;
} else {
// change user name in in base u
bu.setUsername(new_username);
bu.saveMe();
// change user name in user table
User user = User.getById(schema, bu.getId());
user.setUser_name(new_username);
user.saveMe(schema);
// change user name user assignment table
List ua_s = UserAssignment.getAllByUserName(schema,
new_username);
for (ListIterator<UserAssignment> li = ua_s.listIterator(); li
.hasNext();) {
UserAssignment ua = li.next();
ua.setUsername(new_username);
ua.saveMe(schema);
}
String message = "The username '" + old_username
+ "' has been changed to '" + new_username
+ "' on the USIP OSP System "
+ USIP_OSP_Properties.getValue("server_name");
// send email to user at both email addresses
Emailer.quickPostMail(schema, new_username,
"Username Changed on USIP OSP System", message,
user.getUserName(), user.getUserName());
Emailer.quickPostMail(schema, old_username,
"Username Changed on USIP OSP System", message,
user.getUserName(), user.getUserName());
return USERNAME_CHANGED;
} // end if found base user in database.
} else {
return ALL_GOOD;
}
}
protected boolean simUsesGameClock = false;
private GamePhaseCurrentTime gpct = null;
/**
*
* @param request
* @return
*/
public String getGameTime(HttpServletRequest request) {
if (!simUsesGameClock){
return "";
}
return "";
/* TODO - Get this sorted out by following instructions in package.html.
*
if (gpct == null){
gpct = GamePhaseCurrentTime.pullGPCTFromCache(request, schema, sim_id, runningSimId, phase_id);
}
return gpct.getGameTime(request, this);
*/
}
public GamePhaseCurrentTime getGpct() {
return gpct;
}
public void setGpct(GamePhaseCurrentTime gpct) {
this.gpct = gpct;
}
private String schemaOrgLogo = "logo_top.png";
private String schemaOrgName = "";
private String schemaOrgBanner = "top_fade.png";
private String schemaOrgWebsite = "";
public String getSchemaOrgLogo() {
return schemaOrgLogo;
}
public void setSchemaOrgLogo(String schemaOrgLogo) {
this.schemaOrgLogo = schemaOrgLogo;
}
public String getSchemaOrgName() {
return schemaOrgName;
}
public void setSchemaOrgName(String schemaOrgName) {
this.schemaOrgName = schemaOrgName;
}
public String getSchemaOrgBanner() {
return schemaOrgBanner;
}
public void setSchemaOrgBanner(String schemaOrgBanner) {
this.schemaOrgBanner = schemaOrgBanner;
}
public String getSchemaOrgWebsite() {
return schemaOrgWebsite;
}
public void setSchemaOrgWebsite(String schemaOrgWebsite) {
this.schemaOrgWebsite = schemaOrgWebsite;
}
/**
* If user has selected an author, instructor or admin entry point into the
* system, this is called to set their AFSO object.
*
* @param request
* @param schema_id
*/
public static void handleInitialEntry(HttpServletRequest request) {
String initial_entry = (String) request.getParameter("initial_entry");
if ((initial_entry != null) && (initial_entry.equalsIgnoreCase("true"))) {
PlayerSessionObject pso = PlayerSessionObject.getPSO(request
.getSession(true));
String schema_id = (String) request.getParameter("schema_id");
SchemaInformationObject sio = SchemaInformationObject
.getById(new Long(schema_id));
sio.loadInfoIntoSessionObjectBase(pso);
User user = null;
BaseUser bu = null;
if (pso.user_id != null) {
user = User.getById(pso.schema, pso.user_id);
bu = BaseUser.getByUserId(pso.user_id);
}
if (user != null) {
pso.user_id = user.getId();
pso.userDisplayName = bu.getFull_name();
pso.user_name = bu.getUsername();
pso.loggedin = true;
pso.preview_mode = false;
pso.languageCode = bu.getPreferredLanguageCode().intValue();
user.setLastLogin(new Date());
user.saveJustUser(pso.schema);
pso.myUserTrailGhost.setTrail_id(user.getTrail_id());
pso.myUserTrailGhost.setUser_id(pso.user_id);
Hashtable<Long, UserTrailGhost> loggedInUsers = (Hashtable<Long, UserTrailGhost>) request
.getSession()
.getServletContext()
.getAttribute(
USIP_OSP_ContextListener.getCacheonLoggedInUsers(sio.getSchema_name()));
if (loggedInUsers == null) {
loggedInUsers = new Hashtable();
request.getSession().getServletContext().setAttribute(
USIP_OSP_ContextListener.getCacheonLoggedInUsers(sio.getSchema_name()),
loggedInUsers);
}
loggedInUsers.put(user.getId(), pso.myUserTrailGhost);
sio.setLastLogin(new Date());
sio.saveMe();
} else {
pso.loggedin = false;
Logger
.getRootLogger()
.warn(
"handling initial entry into simulation and got null user");
}
}
}
/** ID of Actor being played. */
protected Long actorId;
public Long getActorId() {
return actorId;
}
public void setActorId(Long actorId) {
this.actorId = actorId;
}
private boolean showPhaseChanges = false;
public boolean isShowPhaseChanges() {
return showPhaseChanges;
}
public void setShowPhaseChanges(boolean showPhaseChanges) {
this.showPhaseChanges = showPhaseChanges;
}
} // End of class |
3e1cf00c836370666a222f4c41a4024bf4a0e76b | 17,336 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Holodrive.java | WoodrowRookieRoboTeam/RookiesRobotController | 2f80f18d423a2b310a5a958446d3217d243f6b1c | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Holodrive.java | WoodrowRookieRoboTeam/RookiesRobotController | 2f80f18d423a2b310a5a958446d3217d243f6b1c | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Holodrive.java | WoodrowRookieRoboTeam/RookiesRobotController | 2f80f18d423a2b310a5a958446d3217d243f6b1c | [
"MIT"
] | null | null | null | 43.124378 | 165 | 0.656957 | 12,273 | /* Copyright (c) 2017 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
//import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.IntegratingGyroscope;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
@TeleOp(name="HoloTeleOP", group="Linear Opmode")
//@Autonomous(name="Gyro holo drive", group="Linear opmodes")
//@Disabled
public class Holodrive extends LinearOpMode {
// Declare OpMode members.
private ElapsedTime runtime = new ElapsedTime();
private DcMotor frontLeftDrive = null;
private DcMotor frontRightDrive = null;
private DcMotor backLeftDrive = null;
private DcMotor backRightDrive = null;
BNO055IMU imu = null;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// * CONTROL_HUB_ORIENTATION_FACTOR MUST be set correctly depending on whether control hub is on the top or bottom of the robot!!! * //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private int CONTROL_HUB_ORIENTATION_FACTOR = -1; // -1 for top, +1 for bottom
/**
* The following methods are hardware specific and should be changed for each robot
* to match your robot's specific hardware names for motors, gyro etc...
*/
/**
* Initialize the motors
*/
private void initializeMotors(){
// Initialize the motor hardware variables. Note that the strings used here as parameters
// to 'get' must correspond to the names assigned during the robot configuration
// step (using the FTC Robot Controller app on the phone).
frontLeftDrive = hardwareMap.get(DcMotor.class, "frontLeftMotor");
frontRightDrive = hardwareMap.get(DcMotor.class, "frontRightMotor");
backLeftDrive = hardwareMap.get(DcMotor.class, "backLeftMotor");
backRightDrive = hardwareMap.get(DcMotor.class, "backRightMotor");
// Motors on one side need to effectively run 'backwards' to move 'forward'
// Reverse the motors that runs backwards when connected directly to the battery
frontLeftDrive.setDirection(DcMotor.Direction.REVERSE);
frontRightDrive.setDirection(DcMotor.Direction.FORWARD);
backLeftDrive.setDirection(DcMotor.Direction.REVERSE);
backRightDrive.setDirection(DcMotor.Direction.FORWARD);
resetEncoders();
}
private void resetEncoders(){
//Stop the motors and reset the encoders to zero
frontLeftDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
frontRightDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
backLeftDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
backRightDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
//Make sure we re-enable the use of encoders
frontLeftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
frontRightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
backLeftDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
backRightDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
private int[] getMotorEncoders(){
int[] result = new int[4];
result[0] = frontLeftDrive.getCurrentPosition();
result[1] = frontRightDrive.getCurrentPosition();
result[2] = backLeftDrive.getCurrentPosition();
result[3] = backRightDrive.getCurrentPosition();
return result;
}
/**
* Initialize the gyro
*/
private void initializeGyro(){
imu = hardwareMap.get(BNO055IMU.class, "imu");
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.mode = BNO055IMU.SensorMode.IMU;
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.loggingEnabled = false;
imu.initialize(parameters);
// make sure the imu gyro is calibrated before continuing.
while (!isStopRequested() && !imu.isGyroCalibrated()) {
sleep(50);
idle();
}
}
private void resetGyro(){
// imu.resetZAxisIntegrator();
}
private double getGyroHeading(){
// return gyro.getIntegratedZValue();
Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.RADIANS);
return angles.firstAngle * CONTROL_HUB_ORIENTATION_FACTOR;
}
/**
* This is the main op mode and should call all the initialization, wait for start,
* execute your desired auto/tele-op, then stop everything
*/
@Override
public void runOpMode() {
//Must be called at the start to initialize all necessary hardware
//Add other hardware (e.g. vision etc...) in this method
initializeHardware();
// Wait for the game to start (driver presses PLAY)
//Note, we can use this time to be processing the vision to have the skystone location ready ASAP.
//waitForStart();
waitStart();
runtime.reset();
//Make sure the gyro is at zero
resetGyro();
doTeleop();
//Done so turn everything off now
disableHardware();
}
private void waitStart(){
// Wait for the game to start (driver presses PLAY)
//Can use this time to process the vision in order to get the skystone location ASAP
// Abort this loop is started or stopped.
while (!(isStarted() || isStopRequested())) {
idle();
}
}
/**
* Disable all hardware
*/
private void disableHardware() {
//Only the motors really need to be turned off at the moment
setMotors(0, 0, 0, 0);
}
/**
* Initialize all hardware
*/
private void initializeHardware(){
telemetry.addData("Status", "Initializing");
telemetry.update();
initializeMotors();
initializeGyro();
// Tell the driver that initialization is complete.
telemetry.addData("Status", "Initialized");
telemetry.update();
}
public double getCurrentHeading(){
double current;
current = getGyroHeading();
//Convert to +- 180
while (current > Math.PI) current -= 2*Math.PI;
while (current <= -Math.PI) current += 2*Math.PI;
return current;
}
public double calculateHeadingError(double targetHeading, double currentHeading) {
double robotError;
// calculate error in -179 to +180 range : In radians
robotError = targetHeading - currentHeading;
while (robotError > Math.PI) robotError -= 2*Math.PI;
while (robotError <= -Math.PI) robotError += 2*Math.PI;
return robotError;
}
private void setMotors(double FL, double FR, double BL, double BR){
double max;
//If any value is greater than 1.0 normalize all values accordingly
max = Math.max(Math.max(FL,FR),Math.max(BL,BR));
if (max > 1.0){
FL = FL / max;
FR = FR / max;
BL = BL / max;
BR = BR / max;
}
frontLeftDrive.setPower(FL);
frontRightDrive.setPower(FR);
backLeftDrive.setPower(BL);
backRightDrive.setPower(BR);
}
/**
* Calculate normalization factor angle (i.e. where in semi-quadrant for unit square to unit circle transposition)
* @param angle angle to calculate normalization factor for in degrees
*/
private double unitNormalizationAngle(double angle){
double normalizationAngle;
double angleDegrees;
angleDegrees = Math.toDegrees(angle);
if (angleDegrees >= 0)
normalizationAngle = angleDegrees % 90;
else
normalizationAngle = (-angleDegrees) % 90;
if (normalizationAngle >= 45) {
normalizationAngle = 90 - normalizationAngle;
}
//
return normalizationAngle;
}
/**
* Tele-op example
* Right stick will move the robot in field centric world view
* Left stick will point the robot in the field centric direction
* Left/right bumbers will rotate the robot
*/
private void doTeleop(){
double rightJoyX;
double leftJoyX;
double leftJoyY;
boolean leftBumper;
boolean rightBumper;
double translateDirection;
double botCentricDirection;
double translateSpeed;
double targetHeading;
double headingError;
double currentHeading;
double translateDeadband = 0.1;
double rotationSpeedFactor = 1;//Sets maximum rotation speed. Gets multiplied by error in radians
double manualRotationSpeed = .02;//Heading change per loop period in radians. Will need to tune
double minimumHeadingCorrectionSpeed = 0.1;//Minimum rotation correction speed
double headingCorrectionDeadband = 0.05;//Deadband in radians
double frontLeftSpeed;
double frontRightSpeed;
double backLeftSpeed;
double backRightSpeed;
double normalizationAngle;
double finalSpeed;
double normalizationFactor;
double headingCorrectionSpeed;
//Take our initial zero heading from our starting pose
targetHeading = getCurrentHeading();
while(opModeIsActive()){
//Get the joysticks
leftJoyX = gamepad1.left_stick_x;
leftJoyY = -gamepad1.left_stick_y;
rightJoyX = gamepad1.right_stick_x;
leftBumper = gamepad1.left_bumper;
rightBumper = gamepad1.right_bumper;
//Calculate desired translation 'speed' and direction
translateSpeed = Math.sqrt((leftJoyX * leftJoyX) + (leftJoyY * leftJoyY));
if (translateSpeed > translateDeadband){//Create deadband and also ensure no divide by zero in atan2 and stop robot twitching
//Calculate the desired robot base direction from the right joystick
//Forward = 0 radians (0 degrees)
translateDirection = (-Math.atan2(leftJoyY, leftJoyX) + (Math.PI/2));
}
else {
translateDirection = 0;
translateSpeed = 0;
}
//Now check if any rotation requested from the bumpers
if (leftBumper) {
targetHeading = targetHeading - manualRotationSpeed;
}
else if (rightBumper) {
targetHeading = targetHeading + manualRotationSpeed;
}
//Otherwise check if any rotation requested from the bumpers
else if (Math.abs(rightJoyX) > 0.1) {
targetHeading = targetHeading + (rightJoyX * manualRotationSpeed);
}
//Calculate if any rotation is needed to point bot in 'targetHeading' direction
currentHeading = getCurrentHeading();
headingError = calculateHeadingError(targetHeading, currentHeading);
//If the error is small (less than the deadband) then do not correct anything
if (Math.abs(headingError) > headingCorrectionDeadband)
headingCorrectionSpeed = headingError * rotationSpeedFactor;
else
headingCorrectionSpeed = 0.0;
//If the correction power is really small then increase it so it actually does something, unless it really was zero
if ((Math.abs(headingCorrectionSpeed) < minimumHeadingCorrectionSpeed) && (headingCorrectionSpeed != 0.0))
{
if (headingCorrectionSpeed >= 0)
headingCorrectionSpeed = minimumHeadingCorrectionSpeed;
else
headingCorrectionSpeed = -minimumHeadingCorrectionSpeed;
}
//Subtract the current heading to get robot centric direction
botCentricDirection = translateDirection - currentHeading;
/* This version will normalize the joystick position to fully utilize the entire power range for 0, 90, 180 & 270 by mapping from unit square to unit circle
//Adjust to use full range of speed to 'boost' the power for 0, 90, 180, 270 from .707 to 1.0
normalizationAngle = unitNormalizationAngle(targetHeading);
//The following can be optimized to eliminate some sqrt calls
normalizationFactor = Math.sqrt(1+Math.tan(normalizationAngle))/Math.sqrt(2);
finalSpeed = translateSpeed / (normalizationFactor * Math.sqrt(2));
*/
//This version is a simplified version that does not maximize the entire power range of the motors
finalSpeed = translateSpeed;
normalizationFactor = 1.0;
//Now calculate the actual motor speeds
//Note, the diagonally opposite speeds are the same, so only need to calculate 2 values
frontLeftSpeed = finalSpeed*Math.sin(botCentricDirection+(Math.PI/4));
//Now scale to utilize full power
frontLeftSpeed = (frontLeftSpeed/normalizationFactor);
frontRightSpeed = finalSpeed*Math.cos(botCentricDirection+(Math.PI/4));
//Now scale to utilize full power
frontRightSpeed = (frontRightSpeed/normalizationFactor);
//Duplicate diagonal speeds for translation and add in rotation
backLeftSpeed = frontRightSpeed + headingCorrectionSpeed;
backRightSpeed = frontLeftSpeed - headingCorrectionSpeed;
frontRightSpeed = frontRightSpeed - headingCorrectionSpeed;
frontLeftSpeed = frontLeftSpeed + headingCorrectionSpeed;
telemetry.addData("leftJoyX: ", leftJoyX);
telemetry.addData("leftJoyY: ", leftJoyY);
telemetry.addData("HE: ", Math.toDegrees((headingError)));
//telemetry.addData("CH: ", Math.toDegrees(currentHeading));
//telemetry.addData("TD: ", translateDirection);
//telemetry.addData("BCD: ", botCentricDirection);
telemetry.addData("FL: ", frontLeftSpeed);
telemetry.addData("FR: ", frontRightSpeed);
telemetry.addData("BL: ", backLeftSpeed);
telemetry.addData("BR: ", backRightSpeed);
//telemetry.addData("FLE: ", frontLeftDrive.getCurrentPosition());
//telemetry.addData("FRE: ", frontRightDrive.getCurrentPosition());
//telemetry.addData("BLE: ", backLeftDrive.getCurrentPosition());
//telemetry.addData("BRE: ", backRightDrive.getCurrentPosition());
//And actually set the motors accordingly
//Note, this function will also clamp and scale the power to 1.0
setMotors(frontLeftSpeed, frontRightSpeed, backLeftSpeed, backRightSpeed);
telemetry.update();
}
setMotors(0, 0, 0, 0);
}
}
|
3e1cf2f6d4f75ca1cf1587ccadecb4f5bc342ee0 | 3,450 | java | Java | Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldAction.java | bdcht/ghidra | 9e732318148cd11edeb4862afd23d56418551812 | [
"Apache-2.0"
] | 17 | 2022-01-15T03:52:37.000Z | 2022-03-30T18:12:17.000Z | Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldAction.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 9 | 2022-01-15T03:58:02.000Z | 2022-02-21T10:22:49.000Z | Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/data/RenameDataFieldAction.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 3 | 2019-12-02T13:36:50.000Z | 2019-12-04T05:40:12.000Z | 33.173077 | 99 | 0.735652 | 12,274 | /* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.app.plugin.core.data;
import ghidra.app.context.ListingActionContext;
import ghidra.app.util.PluginConstants;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.Program;
import ghidra.program.util.FieldNameFieldLocation;
import ghidra.program.util.ProgramLocation;
import java.awt.event.KeyEvent;
import javax.swing.KeyStroke;
import docking.ActionContext;
import docking.action.*;
/**
* Base class for comment actions to edit and delete comments.
*/
class RenameDataFieldAction extends DockingAction {
private static final KeyStroke KEY_BINDING = KeyStroke.getKeyStroke(KeyEvent.VK_N,0);
private DataPlugin plugin;
private RenameDataFieldDialog dialog;
public RenameDataFieldAction(DataPlugin plugin) {
super("Rename Data Field", plugin.getName());
dialog = new RenameDataFieldDialog(plugin);
// ACTIONS - auto generated
setPopupMenuData(
new MenuData(
new String[] {"Data", "Rename Field"},null,"BasicData" ) );
setKeyBindingData( new KeyBindingData(
KeyEvent.VK_N, 0 ) );
this.plugin = plugin;
setEnabled(true);
}
/**
* Method called when the action is invoked.
*/
@Override
public void actionPerformed(ActionContext context) {
ListingActionContext programActionContext = (ListingActionContext) context.getContextObject();
PluginTool tool = plugin.getTool();
Program program = programActionContext.getProgram();
ProgramLocation loc = programActionContext.getLocation();
Data data = program.getListing().getDataContaining(loc.getAddress());
DataType type = data.getDataType();
if (type instanceof Composite) {
Composite comp = (Composite)type;
int[] compPath = loc.getComponentPath();
for (int i=0; i<compPath.length-1; i++) {
DataTypeComponent subComp = comp.getComponent(compPath[i]);
type = subComp.getDataType();
if (type instanceof Composite)
comp = (Composite)type;
else
return;
}
Data instance = data.getComponent(compPath);
DataTypeComponent subComp = comp.getComponent(compPath[compPath.length-1]);
dialog.setDataComponent(program, subComp, instance.getFieldName());
tool.showDialog(dialog, tool.getComponentProvider(PluginConstants.CODE_BROWSER));
}
}
/*
* @see docking.DockableAction#isValidContext(java.lang.Object)
*/
@Override
public boolean isEnabledForContext(ActionContext context) {
Object contextObject = context.getContextObject();
if (!(contextObject instanceof ListingActionContext)) {
return false;
}
ListingActionContext programActionContext = (ListingActionContext) contextObject;
return (programActionContext.getLocation() instanceof FieldNameFieldLocation);
}
}
|
3e1cf3495ae3fe097999bb302994c516d26c36c8 | 2,657 | java | Java | src/com/lnpdit/woofarm/page/adapter/CropInfoListAdapter.java | yinbingqian/IntelligentPlanting | d104aa7f7bc69280607b8c6fb26ac5fcd1ea4fd8 | [
"Apache-2.0"
] | 1 | 2021-06-07T09:43:28.000Z | 2021-06-07T09:43:28.000Z | src/com/lnpdit/woofarm/page/adapter/CropInfoListAdapter.java | yinbingqian/IntelligentPlanting | d104aa7f7bc69280607b8c6fb26ac5fcd1ea4fd8 | [
"Apache-2.0"
] | null | null | null | src/com/lnpdit/woofarm/page/adapter/CropInfoListAdapter.java | yinbingqian/IntelligentPlanting | d104aa7f7bc69280607b8c6fb26ac5fcd1ea4fd8 | [
"Apache-2.0"
] | null | null | null | 29.197802 | 78 | 0.633045 | 12,275 | package com.lnpdit.woofarm.page.adapter;
import java.util.List;
import com.lnpdit.IntelligentPlanting.R;
import com.lnpdit.woofarm.entity.CropInfoList;
import com.lnpdit.woofarm.instance.Instance;
import com.lnpdit.woofarm.utils.SOAP_UTILS;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CropInfoListAdapter extends BaseAdapter {
private class buttonViewHolder {
private TextView crop_name;
private TextView details_tv;
private TextView plantdays_tv;
}
private CropInfoList appInfo;
private List<CropInfoList> mAppList;
private LayoutInflater mInflater;
private Context mContext;
private buttonViewHolder holder;
public CropInfoListAdapter(Context context, List<CropInfoList> appList) {
mAppList = appList;
mContext = context;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mAppList.size();
}
@Override
public Object getItem(int position) {
return mAppList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void removeItem(int positon) {
mAppList.remove(positon);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// buttonViewHolder holder = null;
// 无convertView,需要new出各个控件
if (convertView == null) {
// 按当前所需的样式,确定new的布局
convertView = mInflater.inflate(R.layout.item_cropinfo, parent,
false);
holder = new buttonViewHolder();
holder.crop_name = (TextView) convertView
.findViewById(R.id.crop_name);
holder.details_tv = (TextView) convertView
.findViewById(R.id.details_tv);
holder.plantdays_tv = (TextView) convertView
.findViewById(R.id.plantdays_tv);
convertView.setTag(holder);
} else {
holder = (buttonViewHolder) convertView.getTag();
}
appInfo = mAppList.get(position);
holder.crop_name.setText(appInfo.getCropname());
holder.details_tv.setText(appInfo.getCropdetails());
holder.plantdays_tv.setText(appInfo.getPlantdays() + "月");
return convertView;
}
} |
3e1cf38f61f7e7bc6fd3cfa1eef0fc9ccbfc3047 | 2,990 | java | Java | springboot-aop-log/src/main/java/cn/infocore/springboot/core/LogAspect.java | liuershi/spring-all | cacac412d1561214318940033e2a9dcb43cbcd7b | [
"Apache-2.0"
] | null | null | null | springboot-aop-log/src/main/java/cn/infocore/springboot/core/LogAspect.java | liuershi/spring-all | cacac412d1561214318940033e2a9dcb43cbcd7b | [
"Apache-2.0"
] | null | null | null | springboot-aop-log/src/main/java/cn/infocore/springboot/core/LogAspect.java | liuershi/spring-all | cacac412d1561214318940033e2a9dcb43cbcd7b | [
"Apache-2.0"
] | null | null | null | 34.022727 | 124 | 0.682365 | 12,276 | package cn.infocore.springboot.core;
import cn.infocore.springboot.domain.SysLogDO;
import cn.infocore.springboot.service.SyslogService;
import cn.infocore.springboot.util.HttpContextUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* @Author upchh@example.com
* @Date 2020/12/3 19:33
* @Description 定义一个LogAspect类,使用@Aspect标注让其成为一个切面,切点为使用@Log注解标注的方法,使用@Around环绕通知
*/
@Aspect
@Component
public class LogAspect {
@Autowired
private SyslogService service;
@Pointcut("@annotation(cn.infocore.springboot.core.Log)")
public void pointcut(){}
@Around(value = "pointcut()")
public Object around(ProceedingJoinPoint point){
Object result = null;
// 开始时间
long start = System.currentTimeMillis();
try {
result = point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
// 执行方法花费时间(毫秒)
long time = System.currentTimeMillis() - start;
saveLog(point, time);
return result;
}
private void saveLog(ProceedingJoinPoint point, long time) {
MethodSignature signature = (MethodSignature)point.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
SysLogDO sysLogDO = new SysLogDO();
if (log != null) {
// 注解所描述的操作
sysLogDO.setOperation(log.value());
}
// 请求方法
String className = point.getTarget().getClass().getName();
String methodName = signature.getName();
sysLogDO.setMethod(className + "." + methodName);
Object[] args = point.getArgs();
// 请求的方法参数名称
LocalVariableTableParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = parameterNameDiscoverer.getParameterNames(method);
if (args != null && parameterNames != null) {
List<String> list = Arrays.asList(parameterNames);
list.forEach(name -> sysLogDO.setParams(name + ":" + args[list.indexOf(name)]));
}
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLogDO.setIp(request.getRemoteAddr());
// 模拟一个用户名
sysLogDO.setUsername("zhangsan");
sysLogDO.setTime(time);
sysLogDO.setCreateTime(new Date());
// 保存系统日志
service.save(sysLogDO);
}
}
|
3e1cf408071c793bef8c9fe6ae24075eed8709e1 | 20,370 | java | Java | cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/container/RuntimeExtension.java | msdian7/aries | 52293d20268de7c98833846ded2b70d6476773de | [
"Apache-2.0"
] | 1 | 2020-03-29T09:59:06.000Z | 2020-03-29T09:59:06.000Z | cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/container/RuntimeExtension.java | msdian7/aries | 52293d20268de7c98833846ded2b70d6476773de | [
"Apache-2.0"
] | null | null | null | cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/container/RuntimeExtension.java | msdian7/aries | 52293d20268de7c98833846ded2b70d6476773de | [
"Apache-2.0"
] | null | null | null | 36.117021 | 133 | 0.769416 | 12,277 | /**
* 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.apache.aries.cdi.container.internal.container;
import static javax.interceptor.Interceptor.Priority.PLATFORM_AFTER;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.AfterDeploymentValidation;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMember;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.BeforeBeanDiscovery;
import javax.enterprise.inject.spi.BeforeShutdown;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.ProcessBean;
import javax.enterprise.inject.spi.ProcessInjectionPoint;
import javax.enterprise.inject.spi.ProcessProducerField;
import javax.enterprise.inject.spi.ProcessProducerMethod;
import javax.enterprise.inject.spi.Producer;
import javax.enterprise.inject.spi.ProducerFactory;
import org.apache.aries.cdi.container.internal.bean.ComponentPropertiesBean;
import org.apache.aries.cdi.container.internal.bean.ReferenceBean;
import org.apache.aries.cdi.container.internal.container.Op.Mode;
import org.apache.aries.cdi.container.internal.container.Op.Type;
import org.apache.aries.cdi.container.internal.model.ComponentPropertiesModel;
import org.apache.aries.cdi.container.internal.model.ExtendedActivationDTO;
import org.apache.aries.cdi.container.internal.model.ExtendedActivationTemplateDTO;
import org.apache.aries.cdi.container.internal.model.ExtendedComponentInstanceDTO;
import org.apache.aries.cdi.container.internal.model.ExtendedComponentTemplateDTO;
import org.apache.aries.cdi.container.internal.model.ExtendedConfigurationTemplateDTO;
import org.apache.aries.cdi.container.internal.model.ExtendedReferenceDTO;
import org.apache.aries.cdi.container.internal.model.ExtendedReferenceTemplateDTO;
import org.apache.aries.cdi.container.internal.model.FactoryComponent;
import org.apache.aries.cdi.container.internal.model.OSGiBean;
import org.apache.aries.cdi.container.internal.model.ReferenceModel;
import org.apache.aries.cdi.container.internal.model.SingleComponent;
import org.apache.aries.cdi.container.internal.util.Annotates;
import org.apache.aries.cdi.container.internal.util.SRs;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.PrototypeServiceFactory;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cdi.CDIConstants;
import org.osgi.service.cdi.ComponentType;
import org.osgi.service.cdi.ServiceScope;
import org.osgi.service.cdi.annotations.ComponentProperties;
import org.osgi.service.cdi.annotations.Reference;
import org.osgi.service.cdi.reference.BindBeanServiceObjects;
import org.osgi.service.cdi.reference.BindService;
import org.osgi.service.cdi.reference.BindServiceReference;
import org.osgi.service.cdi.runtime.dto.ComponentDTO;
import org.osgi.service.cdi.runtime.dto.template.ActivationTemplateDTO;
import org.osgi.service.cdi.runtime.dto.template.ComponentTemplateDTO;
import org.osgi.service.cdi.runtime.dto.template.ConfigurationTemplateDTO;
import org.osgi.service.log.Logger;
import org.osgi.util.promise.Promise;
public class RuntimeExtension implements Extension {
public RuntimeExtension(
ContainerState containerState,
ConfigurationListener.Builder configurationBuilder,
SingleComponent.Builder singleBuilder,
FactoryComponent.Builder factoryBuilder) {
_containerState = containerState;
_log = _containerState.containerLogs().getLogger(getClass());
_log.debug(l -> l.debug("CCR RuntimeExtension {}", containerState.bundle()));
_configurationBuilder = configurationBuilder;
_singleBuilder = singleBuilder;
_factoryBuilder = factoryBuilder;
_containerTemplate = _containerState.containerDTO().template.components.get(0);
}
void beforeBeanDiscovery(@Observes BeforeBeanDiscovery bbd) {
bbd.addQualifier(org.osgi.service.cdi.annotations.ComponentProperties.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.MinimumCardinality.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.PID.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.PrototypeRequired.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.Reference.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.Reluctant.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.Service.class);
bbd.addQualifier(org.osgi.service.cdi.annotations.ServiceInstance.class);
bbd.addScope(org.osgi.service.cdi.annotations.ComponentScoped.class, false, false);
bbd.addStereotype(org.osgi.service.cdi.annotations.FactoryComponent.class);
bbd.addStereotype(org.osgi.service.cdi.annotations.SingleComponent.class);
}
void processBindObject(@Observes ProcessInjectionPoint<?, BindService<?>> pip) {
processInjectionPoint0(pip, true);
}
void processBindServiceObjects(@Observes ProcessInjectionPoint<?, BindBeanServiceObjects<?>> pip) {
processInjectionPoint0(pip, true);
}
void processBindServiceReference(@Observes ProcessInjectionPoint<?, BindServiceReference<?>> pip) {
processInjectionPoint0(pip, true);
}
void processInjectionPoint(@Observes ProcessInjectionPoint<?, ?> pip) {
processInjectionPoint0(pip, false);
}
<X> void processBean(@Observes ProcessBean<X> pb) {
final Class<X> declaringClass = Annotates.declaringClass(pb);
String className = declaringClass.getName();
OSGiBean osgiBean = _containerState.beansModel().getOSGiBean(className);
if (osgiBean == null) {
return;
}
final Annotated annotated = pb.getAnnotated();
try {
List<String> serviceTypes = Annotates.serviceClassNames(annotated);
Map<String, Object> componentProperties = Annotates.componentProperties(annotated);
ServiceScope serviceScope = Annotates.serviceScope(annotated);
if (annotated.isAnnotationPresent(org.osgi.service.cdi.annotations.SingleComponent.class) ||
annotated.isAnnotationPresent(org.osgi.service.cdi.annotations.FactoryComponent.class)) {
ActivationTemplateDTO activationTemplate = osgiBean.getComponent().activations.get(0);
activationTemplate.scope = serviceScope;
activationTemplate.serviceClasses = serviceTypes;
osgiBean.getComponent().properties = componentProperties;
}
else if (annotated.isAnnotationPresent(org.osgi.service.cdi.annotations.ComponentScoped.class)) {
// Explicitly ignore this case
}
else if (!serviceTypes.isEmpty()) {
AnnotatedMember<?> producer = null;
if (pb instanceof ProcessProducerField) {
producer = ((ProcessProducerField<?, ?>) pb).getAnnotatedProducerField();
}
else if (pb instanceof ProcessProducerMethod) {
producer = ((ProcessProducerMethod<?, ?>) pb).getAnnotatedProducerMethod();
}
ExtendedActivationTemplateDTO activationTemplate = null;
for (ActivationTemplateDTO at : _containerTemplate.activations) {
ExtendedActivationTemplateDTO extended = (ExtendedActivationTemplateDTO)at;
if (extended.declaringClass.equals(declaringClass) && Objects.equals(extended.producer, producer)) {
activationTemplate = extended;
break;
}
}
if (activationTemplate == null) {
activationTemplate = new ExtendedActivationTemplateDTO();
activationTemplate.cdiScope = pb.getBean().getScope();
activationTemplate.declaringClass = declaringClass;
activationTemplate.producer = producer;
_containerTemplate.activations.add(activationTemplate);
}
activationTemplate.properties = componentProperties;
activationTemplate.scope = serviceScope;
activationTemplate.serviceClasses = serviceTypes;
}
}
catch (Exception e) {
pb.addDefinitionError(e);
}
}
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager bm) {
abd.addContext(_containerState.componentContext());
_containerState.containerDTO().template.components.forEach(
ct -> addBeans(ct, abd, bm)
);
}
void afterDeploymentValidation(
@Observes @Priority(PLATFORM_AFTER + 100) AfterDeploymentValidation adv,
BeanManager bm) {
_log.debug(l -> l.debug("CCR AfterDeploymentValidation on {}", _containerState.bundle()));
_containerState.beanManager(bm);
ComponentDTO componentDTO = _containerState.containerDTO().components.get(0);
_containerState.submit(
Op.of(Mode.OPEN, Type.CONTAINER_PUBLISH_SERVICES, _containerState.id()),
() -> registerServices(componentDTO, bm)
).then(
s -> initComponents()
).then(s -> {
Dictionary<String, Object> properties = new Hashtable<>();
properties.put(CDIConstants.CDI_CONTAINER_ID, _containerState.id());
properties.put(Constants.SERVICE_DESCRIPTION, "Aries CDI - BeanManager for " + _containerState.bundle());
properties.put(Constants.SERVICE_VENDOR, "Apache Software Foundation");
registerService(
new String[] {BeanManager.class.getName()}, bm,
properties);
return s;
}
);
}
void beforeShutdown(@Observes BeforeShutdown bs) {
_log.debug(l -> l.debug("CCR BeforeShutdown on {}", _containerState.bundle()));
_containerState.beanManager(null);
_configurationListeners.removeIf(
cl -> {
_containerState.submit(cl.closeOp(), cl::close).onFailure(
f -> {
_log.error(l -> l.error("CCR Error while closing configuration listener {} on {}", cl, _containerState.bundle(), f));
}
);
return true;
}
);
_registrations.removeIf(
r -> {
try {
r.unregister();
}
catch (Exception e) {
_log.error(l -> l.error("CCR Error while unregistring {} on {}", r, _containerState.bundle(), e));
}
return true;
}
);
}
private void addBeans(ComponentTemplateDTO componentTemplate, AfterBeanDiscovery abd, BeanManager bm) {
ComponentDTO componentDTO = _containerState.containerDTO().components.get(0);
componentTemplate.references.stream().map(ExtendedReferenceTemplateDTO.class::cast).forEach(
t -> {
ReferenceBean bean = t.bean;
bean.setBeanManager(bm);
if (componentTemplate.type == ComponentType.CONTAINER) {
componentDTO.instances.get(0).references.stream().filter(
r -> r.template == t
).findFirst().map(
ExtendedReferenceDTO.class::cast
).ifPresent(
r -> bean.setReferenceDTO(r)
);
}
_log.debug(l -> l.debug("CCR Adding synthetic bean {} on {}", bean, _containerState.bundle()));
abd.addBean(bean);
}
);
componentTemplate.configurations.stream().map(ExtendedConfigurationTemplateDTO.class::cast).filter(
t -> Objects.nonNull(t.injectionPointType)
).forEach(
t -> {
ComponentPropertiesBean bean = t.bean;
_log.debug(l -> l.debug("CCR Adding synthetic bean {} on {}", bean, _containerState.bundle()));
abd.addBean(bean);
}
);
}
@SuppressWarnings("unchecked")
private Producer<Object> createProducer(Object producerObject, Bean<Object> bean, BeanManager bm) {
ProducerFactory<Object> producerFactory = null;
if (producerObject instanceof AnnotatedField)
producerFactory = bm.getProducerFactory((AnnotatedField<Object>)producerObject, bean);
else if (producerObject instanceof AnnotatedMethod)
producerFactory = bm.getProducerFactory((AnnotatedMethod<Object>)producerObject, bean);
if (producerFactory == null)
return null;
return producerFactory.createProducer(bean);
}
private Promise<Boolean> initComponents() {
_containerState.containerDTO().template.components.stream().filter(
t -> t.type != ComponentType.CONTAINER
).map(ExtendedComponentTemplateDTO.class::cast).forEach(
this::initComponent
);
return null;
}
private void initComponent(ExtendedComponentTemplateDTO componentTemplateDTO) {
if (componentTemplateDTO.type == ComponentType.FACTORY) {
initFactoryComponent(componentTemplateDTO);
}
else {
initSingleComponent(componentTemplateDTO);
}
}
private Promise<Boolean> initFactoryComponent(ExtendedComponentTemplateDTO componentTemplateDTO) {
ConfigurationListener cl = _configurationBuilder.component(
_factoryBuilder.template(componentTemplateDTO).build()
).build();
_configurationListeners.add(cl);
return _containerState.submit(cl.openOp(), cl::open);
}
private Promise<Boolean> initSingleComponent(ExtendedComponentTemplateDTO componentTemplateDTO) {
ConfigurationListener cl = _configurationBuilder.component(
_singleBuilder.template(componentTemplateDTO).build()
).build();
_configurationListeners.add(cl);
return _containerState.submit(cl.openOp(), cl::open);
}
private boolean matchConfiguration(OSGiBean osgiBean, ProcessInjectionPoint<?, ?> pip) {
InjectionPoint injectionPoint = pip.getInjectionPoint();
Class<?> declaringClass = Annotates.declaringClass(injectionPoint.getAnnotated());
ConfigurationTemplateDTO current = new ComponentPropertiesModel.Builder(injectionPoint.getType()).declaringClass(
declaringClass
).injectionPoint(
injectionPoint
).build().toDTO();
return osgiBean.getComponent().configurations.stream().map(
t -> (ExtendedConfigurationTemplateDTO)t
).filter(
t -> current.equals(t)
).findFirst().map(
t -> {
MarkedInjectionPoint markedInjectionPoint = new MarkedInjectionPoint(injectionPoint);
pip.setInjectionPoint(markedInjectionPoint);
t.bean.setInjectionPoint(injectionPoint);
t.bean.setMark(markedInjectionPoint.getMark());
return true;
}
).orElse(false);
}
private boolean matchReference(OSGiBean osgiBean, ProcessInjectionPoint<?, ?> pip) {
InjectionPoint injectionPoint = pip.getInjectionPoint();
Annotated annotated = injectionPoint.getAnnotated();
ReferenceModel.Builder builder = null;
if (annotated instanceof AnnotatedField) {
builder = new ReferenceModel.Builder((AnnotatedField<?>)annotated);
}
else if (annotated instanceof AnnotatedMethod) {
builder = new ReferenceModel.Builder((AnnotatedMethod<?>)annotated);
}
else {
builder = new ReferenceModel.Builder((AnnotatedParameter<?>)annotated);
}
ReferenceModel referenceModel = builder.injectionPoint(injectionPoint).build();
ExtendedReferenceTemplateDTO current = referenceModel.toDTO();
return osgiBean.getComponent().references.stream().map(
t -> (ExtendedReferenceTemplateDTO)t
).filter(
t -> current.equals(t)
).findFirst().map(
t -> {
MarkedInjectionPoint markedInjectionPoint = new MarkedInjectionPoint(injectionPoint);
pip.setInjectionPoint(markedInjectionPoint);
t.bean.setMark(markedInjectionPoint.getMark());
_log.debug(l -> l.debug("CCR maping InjectionPoint {} to reference template {}", injectionPoint, t));
return true;
}
).orElse(false);
}
private void processInjectionPoint0(ProcessInjectionPoint<?, ?> pip, boolean special) {
InjectionPoint injectionPoint = pip.getInjectionPoint();
Class<?> declaringClass = Annotates.declaringClass(injectionPoint.getAnnotated());
String className = declaringClass.getName();
OSGiBean osgiBean = _containerState.beansModel().getOSGiBean(className);
if (osgiBean == null) {
return;
}
Annotated annotated = injectionPoint.getAnnotated();
ComponentProperties componentProperties = annotated.getAnnotation(ComponentProperties.class);
Reference reference = annotated.getAnnotation(Reference.class);
if (((reference != null) || special) && matchReference(osgiBean, pip)) {
return;
}
if (componentProperties != null) {
matchConfiguration(osgiBean, pip);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void registerService(
ExtendedComponentInstanceDTO componentInstance,
ExtendedActivationTemplateDTO activationTemplate,
BeanManager bm) {
ServiceScope scope = activationTemplate.scope;
if (activationTemplate.cdiScope == ApplicationScoped.class) {
scope = ServiceScope.SINGLETON;
}
final Context context = bm.getContext(activationTemplate.cdiScope);
final Bean<Object> bean = (Bean<Object>)bm.resolve(
bm.getBeans(activationTemplate.declaringClass, Any.Literal.INSTANCE));
final Producer producer = createProducer(activationTemplate.producer, bean, bm);
Object serviceObject;
if (scope == ServiceScope.PROTOTYPE) {
serviceObject = new PrototypeServiceFactory<Object>() {
@Override
public Object getService(Bundle bundle, ServiceRegistration<Object> registration) {
CreationalContext<Object> cc = bm.createCreationalContext(bean);
if (producer != null) {
return producer.produce(cc);
}
return context.get(bean, cc);
}
@Override
public void ungetService(Bundle bundle, ServiceRegistration<Object> registration, Object service) {
}
};
}
else if (scope == ServiceScope.BUNDLE) {
serviceObject = new ServiceFactory<Object>() {
@Override
public Object getService(Bundle bundle, ServiceRegistration<Object> registration) {
CreationalContext<Object> cc = bm.createCreationalContext(bean);
if (producer != null) {
return producer.produce(cc);
}
return context.get(bean, cc);
}
@Override
public void ungetService(Bundle bundle, ServiceRegistration<Object> registration, Object service) {
}
};
}
else {
CreationalContext<Object> cc = bm.createCreationalContext(bean);
if (producer != null) {
serviceObject = producer.produce(cc);
}
else {
serviceObject = context.get(bean, cc);
}
}
Objects.requireNonNull(serviceObject, "The service object is somehow null on " + this);
Dictionary<String, Object> properties = new Hashtable<>(
componentInstance.componentProperties(activationTemplate.properties));
ServiceRegistration<?> serviceRegistration = registerService(
activationTemplate.serviceClasses.toArray(new String[0]),
serviceObject, properties);
ExtendedActivationDTO activationDTO = new ExtendedActivationDTO();
activationDTO.errors = new CopyOnWriteArrayList<>();
activationDTO.service = SRs.from(serviceRegistration.getReference());
activationDTO.template = activationTemplate;
componentInstance.activations.add(activationDTO);
}
private ServiceRegistration<?> registerService(String[] serviceTypes, Object serviceObject, Dictionary<String, Object> properties) {
ServiceRegistration<?> serviceRegistration = _containerState.bundleContext().registerService(
serviceTypes, serviceObject, properties);
_registrations.add(serviceRegistration);
return serviceRegistration;
}
private boolean registerServices(ComponentDTO componentDTO, BeanManager bm) {
componentDTO.template.activations.stream().map(
ExtendedActivationTemplateDTO.class::cast
).forEach(
a -> registerService((ExtendedComponentInstanceDTO)componentDTO.instances.get(0), a, bm)
);
return true;
}
private final ConfigurationListener.Builder _configurationBuilder;
private final List<ConfigurationListener> _configurationListeners = new CopyOnWriteArrayList<>();
private final ContainerState _containerState;
private final ComponentTemplateDTO _containerTemplate;
private final FactoryComponent.Builder _factoryBuilder;
private final Logger _log;
private final List<ServiceRegistration<?>> _registrations = new CopyOnWriteArrayList<>();
private final SingleComponent.Builder _singleBuilder;
}
|
3e1cf43dd9157f8440debfb42354a01bd4913fdc | 1,229 | java | Java | src/main/java/org/hzero/swagger/infra/util/RefreshUtil.java | open-hand/hzero-swagger | 5111a1a7750de868d945a9e9e021f8503361c449 | [
"Apache-2.0"
] | 2 | 2021-03-15T07:25:50.000Z | 2021-04-08T14:12:14.000Z | src/main/java/org/hzero/swagger/infra/util/RefreshUtil.java | open-hand/hzero-swagger | 5111a1a7750de868d945a9e9e021f8503361c449 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/hzero/swagger/infra/util/RefreshUtil.java | open-hand/hzero-swagger | 5111a1a7750de868d945a9e9e021f8503361c449 | [
"Apache-2.0"
] | 12 | 2020-09-23T07:53:27.000Z | 2021-11-23T13:57:50.000Z | 29.97561 | 137 | 0.722539 | 12,278 | package org.hzero.swagger.infra.util;
import org.hzero.swagger.infra.feign.ConfigServerClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 配置刷新操作
*
* @author bojiangzhou
* @author wuguokai
*/
@Component
public class RefreshUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RefreshUtil.class);
private final ExecutorService asyncExecutor = Executors.newSingleThreadExecutor();
@Autowired
private ConfigServerClient configServerClient;
/**
* 通知config-server刷新配置
*/
public void refreshRoute() {
LOGGER.debug("Notify gateway refresh route.");
asyncExecutor.submit(() -> {
ResponseEntity<String> responseEntity = configServerClient.refreshRoute();
if (responseEntity.getStatusCode().isError()) {
LOGGER.error("Error notify gateway refresh route {}:{}.", responseEntity.getStatusCodeValue(), responseEntity.getBody());
}
});
}
}
|
3e1cf5aafe2e30d5c8b963a0e1d65cf910bb038a | 2,874 | java | Java | caffeine/src/main/java/com/github/benmanes/caffeine/cache/Weigher.java | gxthrj/caffeine | 1e52b10d9d6b02b054fed0aef78d76cb6fcb6b71 | [
"Apache-2.0"
] | 11,877 | 2015-01-01T01:24:29.000Z | 2022-03-31T16:58:36.000Z | caffeine/src/main/java/com/github/benmanes/caffeine/cache/Weigher.java | kaizhiyu/caffeine | f068f0e6a338c0a7a08b2f2a9009f5d3b20a5952 | [
"Apache-2.0"
] | 629 | 2015-01-06T10:39:36.000Z | 2022-03-29T16:14:24.000Z | caffeine/src/main/java/com/github/benmanes/caffeine/cache/Weigher.java | kaizhiyu/caffeine | f068f0e6a338c0a7a08b2f2a9009f5d3b20a5952 | [
"Apache-2.0"
] | 1,371 | 2015-01-09T02:12:41.000Z | 2022-03-31T08:30:50.000Z | 29.050505 | 100 | 0.695063 | 12,279 | /*
* Copyright 2014 Ben Manes. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.benmanes.caffeine.cache;
import static java.util.Objects.requireNonNull;
import java.io.Serializable;
import org.checkerframework.checker.index.qual.NonNegative;
/**
* Calculates the weights of cache entries. The total weight threshold is used to determine when an
* eviction is required.
*
* @param <K> the type of keys
* @param <V> the type of values
* @author upchh@example.com (Ben Manes)
*/
@FunctionalInterface
public interface Weigher<K extends Object, V extends Object> {
/**
* Returns the weight of a cache entry. There is no unit for entry weights; rather they are simply
* relative to each other.
*
* @param key the key to weigh
* @param value the value to weigh
* @return the weight of the entry; must be non-negative
*/
@NonNegative
int weigh(K key, V value);
/**
* Returns a weigher where an entry has a weight of {@code 1}.
*
* @param <K> the type of keys
* @param <V> the type of values
* @return a weigher where an entry has a weight of {@code 1}
*/
static <K, V> Weigher<K, V> singletonWeigher() {
@SuppressWarnings("unchecked")
Weigher<K, V> self = (Weigher<K, V>) SingletonWeigher.INSTANCE;
return self;
}
/**
* Returns a weigher that enforces that the weight is non-negative.
*
* @param delegate the weigher to weighs the entry
* @param <K> the type of keys
* @param <V> the type of values
* @return a weigher that enforces that the weight is non-negative
*/
static <K, V> Weigher<K, V> boundedWeigher(Weigher<K, V> delegate) {
return new BoundedWeigher<>(delegate);
}
}
enum SingletonWeigher implements Weigher<Object, Object> {
INSTANCE;
@Override public int weigh(Object key, Object value) {
return 1;
}
}
final class BoundedWeigher<K, V> implements Weigher<K, V>, Serializable {
static final long serialVersionUID = 1;
final Weigher<? super K, ? super V> delegate;
BoundedWeigher(Weigher<? super K, ? super V> delegate) {
this.delegate = requireNonNull(delegate);
}
@Override
public int weigh(K key, V value) {
int weight = delegate.weigh(key, value);
Caffeine.requireArgument(weight >= 0);
return weight;
}
Object writeReplace() {
return delegate;
}
}
|
3e1cf5e478d444d53ccf855bbf8e09d1f792a6cd | 265 | java | Java | src/main/java/at/doml/genalg/operators/package-info.java | domagojlatecki/genetic-algorithms | 475ae08855af51c90441916e180bf505ebff8aeb | [
"MIT"
] | 1 | 2016-01-15T23:02:32.000Z | 2016-01-15T23:02:32.000Z | src/main/java/at/doml/genalg/operators/package-info.java | dl1994/genetic-algorithms | 475ae08855af51c90441916e180bf505ebff8aeb | [
"MIT"
] | null | null | null | src/main/java/at/doml/genalg/operators/package-info.java | dl1994/genetic-algorithms | 475ae08855af51c90441916e180bf505ebff8aeb | [
"MIT"
] | null | null | null | 29.444444 | 118 | 0.762264 | 12,280 | /**
* Contains sub-packages which define interfaces and abstract classes for crossover, mutation and selection operators.
* Also contains several implementations of the operators.
*
* @author Domagoj Latečki
* @since 1.8
*/
package at.doml.genalg.operators;
|
3e1cf6f948b5373ae2344907ae1c712bbb1d65ac | 1,286 | java | Java | quarkus-api/src/main/java/net/teumert/prime/api/PrimeResource.java | NetzwergX/primes | 9e175fd0117daef03663c9859833fcaa2f7c15b0 | [
"MIT"
] | null | null | null | quarkus-api/src/main/java/net/teumert/prime/api/PrimeResource.java | NetzwergX/primes | 9e175fd0117daef03663c9859833fcaa2f7c15b0 | [
"MIT"
] | 33 | 2020-10-30T12:28:43.000Z | 2021-01-12T06:47:12.000Z | quarkus-api/src/main/java/net/teumert/prime/api/PrimeResource.java | NetzwergX/primes | 9e175fd0117daef03663c9859833fcaa2f7c15b0 | [
"MIT"
] | null | null | null | 24.264151 | 65 | 0.737947 | 12,281 | package net.teumert.prime.api;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import org.jboss.resteasy.annotations.jaxrs.QueryParam;
@Path("/api/prime/")
public class PrimeResource {
@Inject
PrimeService service;
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("fetch/")
public List<Integer> fetch (
@QueryParam("after") int after,
@DefaultValue("100")
@QueryParam("limit") int limit) {
return service
.getPrimes(after)
.limit(limit)
.mapToObj(i -> i)
.collect(Collectors.toList());
}
// CAN NOT use int/boolean as return type due to error:
// Could not find MessageBodyWriter for response object of type:
// java.lang.Boolean of media type: application/json
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("check/{candidate}")
public String check (@PathParam int candidate) {
return String.valueOf(service.isPrime(candidate));
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("next/{after}")
public String next (@PathParam int after) {
return String.valueOf(service.nextPrime(after));
}
} |
3e1cf734c08fb5e2db2b06bb9c5d380dee23edd4 | 1,965 | java | Java | vividus/src/test/java/org/vividus/bdd/transformer/IteratingTableTransformerTests.java | ananyevN/vividus | aa3151c2ae318c724e929930b5c52921e284a360 | [
"Apache-2.0"
] | 335 | 2019-06-24T06:43:45.000Z | 2022-03-26T08:26:23.000Z | vividus/src/test/java/org/vividus/bdd/transformer/IteratingTableTransformerTests.java | ananyevN/vividus | aa3151c2ae318c724e929930b5c52921e284a360 | [
"Apache-2.0"
] | 2,414 | 2019-08-15T15:24:31.000Z | 2022-03-31T14:38:26.000Z | vividus/src/test/java/org/vividus/bdd/transformer/IteratingTableTransformerTests.java | ananyevN/vividus | aa3151c2ae318c724e929930b5c52921e284a360 | [
"Apache-2.0"
] | 64 | 2019-08-16T11:32:48.000Z | 2022-03-12T06:15:18.000Z | 39.3 | 103 | 0.749618 | 12,282 | /*
* Copyright 2019-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.vividus.bdd.transformer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.jbehave.core.configuration.Keywords;
import org.jbehave.core.model.ExamplesTable.TableProperties;
import org.jbehave.core.steps.ParameterConverters;
import org.junit.jupiter.api.Test;
class IteratingTableTransformerTests
{
private static final String TABLE = "";
private final IteratingTableTransformer tableTransformer = new IteratingTableTransformer();
private final Keywords keywords = new Keywords();
private final ParameterConverters parameterConverters = new ParameterConverters();
@Test
void shouldFailIfNoLimitSet()
{
var tableProperties = new TableProperties("", keywords, parameterConverters);
var exception = assertThrows(IllegalArgumentException.class,
() -> tableTransformer.transform(TABLE, null, tableProperties));
assertEquals("'limit' is not set in ExamplesTable properties", exception.getMessage());
}
@Test
void shouldReturnTableWithDesiredQuantityOfRows()
{
var tableProperties = new TableProperties("limit=2", keywords, parameterConverters);
assertEquals("|iterator|\n|0|\n|1|", tableTransformer.transform(TABLE, null, tableProperties));
}
}
|
3e1cf77450ce07400ddb1770adc77761dc0e4f01 | 1,496 | java | Java | mq/rocketmq/rocketmq-springboot/rocketmq-consume-springcloud-alibaba/src/main/java/com/ithawk/demo/rocketmq/springcloudalibaba/consume/ReceiveService.java | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | mq/rocketmq/rocketmq-springboot/rocketmq-consume-springcloud-alibaba/src/main/java/com/ithawk/demo/rocketmq/springcloudalibaba/consume/ReceiveService.java | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | mq/rocketmq/rocketmq-springboot/rocketmq-consume-springcloud-alibaba/src/main/java/com/ithawk/demo/rocketmq/springcloudalibaba/consume/ReceiveService.java | IThawk/learnCode | 0ac843d28b193eaab33fb33692f18361d71c7331 | [
"MIT"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | 29.92 | 75 | 0.755348 | 12,283 | /*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 com.ithawk.demo.rocketmq.springcloudalibaba.consume;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
/**
* rocketmq 服务订阅服务
*/
@Service
public class ReceiveService {
@StreamListener("input1")
public void receiveInput1(String receiveMsg) {
System.out.println("input1 receive: " + receiveMsg);
}
@StreamListener("input2")
public void receiveInput2(String receiveMsg) {
System.out.println("input2 receive: " + receiveMsg);
}
@StreamListener("input3")
public void receiveInput3(@Payload Foo foo) {
System.out.println("input3 receive: " + foo);
}
@StreamListener("input4")
public void receiveTransactionalMsg(String transactionMsg) {
System.out.println("input4 receive transaction msg: " + transactionMsg);
}
}
|
3e1cf8b4562adb04d42db5eb0202940eb8ca9d2a | 3,722 | java | Java | src/main/java/com/amlinv/mbus/util/TopicSubscriber.java | amlinv/amq-tools | 1c70f316fd993dc6939e41e05889990cc2cb9bc7 | [
"Apache-2.0"
] | 1 | 2019-01-20T21:58:01.000Z | 2019-01-20T21:58:01.000Z | src/main/java/com/amlinv/mbus/util/TopicSubscriber.java | amlinv/amq-tools | 1c70f316fd993dc6939e41e05889990cc2cb9bc7 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/amlinv/mbus/util/TopicSubscriber.java | amlinv/amq-tools | 1c70f316fd993dc6939e41e05889990cc2cb9bc7 | [
"Apache-2.0"
] | null | null | null | 35.113208 | 97 | 0.744492 | 12,284 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amlinv.mbus.util;
import java.io.IOException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.command.ActiveMQDestination;
import com.amlinv.mbus.util.templ.ConsumeToStdout;
import com.amlinv.mbus.util.templ.factory.DefaultConnectionFactory;
import com.amlinv.mbus.util.templ.factory.DefaultMessageConsumerFactory;
import com.amlinv.mbus.util.templ.factory.DefaultTopicFactory;
import com.amlinv.mbus.util.templ.factory.DefaultSessionFactory;
import com.amlinv.mbus.util.templ.factory.MessagingClient;
import com.amlinv.mbus.util.templ.factory.MessagingClientFactory;
import com.amlinv.mbus.util.templ.factory.Processor;
import com.amlinv.mbus.util.templ.factory.ProcessorFactory;
import com.amlinv.mbus.util.templ.impl.ActiveMQEngineImpl;
import com.amlinv.mbus.util.templ.impl.FixedTimeoutStrategy;
@BusUtil
public class TopicSubscriber {
protected ActiveMQEngineImpl engine;
protected long timeout;
public static void main (String[] args) {
TopicSubscriber consumerProc;
consumerProc = new TopicSubscriber();
consumerProc.runCmdline(args);
}
public void runCmdline (String[] args) {
if ( args.length < 2 ) {
System.out.println("Usage: TopicSubscriber <broker-url> <dest-name> [timeout=<msg-timeout>]");
throw new Error("invalid command-line arguments");
}
parseCmdlineArgs(args, 2);
this.engine = new ActiveMQEngineImpl();
this.engine.setConnectionFactory(new DefaultConnectionFactory());
this.engine.setSessionFactory(new DefaultSessionFactory(true));
this.engine.setMessagingClientFactory(new DefaultMessageConsumerFactory());
this.engine.setDestinationFactory(new DefaultTopicFactory());
final long fTimeout = this.timeout;
this.engine.setProcessorFactory(
new ProcessorFactory() {
public Processor createProcessor () {
ConsumeToStdout processor = new ConsumeToStdout();
if ( fTimeout > 0 ) {
FixedTimeoutStrategy timeoutStrategy = new FixedTimeoutStrategy();
timeoutStrategy.setTimeout(fTimeout);
timeoutStrategy.setDoesTerminate(true);
processor.setTimeoutStrategy(timeoutStrategy);
}
return processor;
}
});
try {
this.engine.execute(args[0], args[1]);
}
catch ( Exception exc ) {
exc.printStackTrace();
}
}
protected void parseCmdlineArgs (String[] args, int first) {
int cur = first;
try {
while ( cur < args.length ) {
if ( args[cur].startsWith("timeout=") ) {
this.timeout = Long.parseLong(args[cur].substring(8));
} else {
throw new Error("unrecognized command line argument " + args[cur]);
}
cur++;
}
} catch ( NumberFormatException numFmtExc ) {
throw new Error("invalid command-line argument " + args[cur], numFmtExc);
}
}
}
|
3e1cf97b6df3a3d7c9b1dbe77cbf97428da48cfa | 27,547 | java | Java | store/src/main/java/org/apache/rocketmq/store/MappedFile.java | whadmin/rocketmq | 2492e9e7ce38a2706f158992b1c5d65c095adc4e | [
"Apache-2.0"
] | 3 | 2019-07-31T03:20:25.000Z | 2020-12-22T06:50:43.000Z | store/src/main/java/org/apache/rocketmq/store/MappedFile.java | whadmin/rocketmq | 2492e9e7ce38a2706f158992b1c5d65c095adc4e | [
"Apache-2.0"
] | null | null | null | store/src/main/java/org/apache/rocketmq/store/MappedFile.java | whadmin/rocketmq | 2492e9e7ce38a2706f158992b1c5d65c095adc4e | [
"Apache-2.0"
] | 2 | 2018-07-28T08:30:49.000Z | 2018-12-11T14:19:11.000Z | 32.677343 | 154 | 0.594039 | 12,285 | /*
* 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.rocketmq.store;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageExtBatch;
import org.apache.rocketmq.store.config.FlushDiskType;
import org.apache.rocketmq.store.util.LibC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.nio.ch.DirectBuffer;
/**
* MappedFile 用来表示mq 文件系统中 文件对象
* MappedFile 可以用来操作commitlog目录下消息文件
* MappedFile 可以用来操作consumequeue目录下消费队列文件
* MappedFile 可以用来操作index 目录下索引文件
* <p>
* <p>
* MappedFile 存在2种构造方法,不同的构造方法在调用 appendMessagesInner 写入消息数据时会采用不同的策略
* public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb)
* <p>
* 不使用TransientStorePool
* <p>
* 1 消息文件会写入mappedByteBuffer内存映射字节缓冲区中 记录committedPosition
* 2 通过brokerFlush线程定时调用 flush 方法将mappedByteBuffer内存映射字节缓冲区中写入磁盘 记录flushedPosition
* <p>
* 使用TransientStorePool
* 1 初始化的时候会从TransientStorePool(堆外内存池) 获得一个writeBuffer(堆外内存缓存区)
* 2 消息文件会写入writeBuffer(堆外内存缓存区)
* 3 通过Commit线程定时调用 commit 方法将writeBuffer(堆外内存缓存区)数据写入fileChannel,记录committedPosition
* 4 通过brokerFlush线程定时调用 flush 方法将将fileChannel中数据写入磁盘,记录flushedPosition
*/
public class MappedFile extends ReferenceResource {
/**
* 日志文件
*/
protected static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);
/**
* 内存页大小,4KB
*/
public static final int OS_PAGE_SIZE = 1024 * 4;
/**
* 记录commitlog目录下所有MappedFile占用内存的总大小
*/
private static final AtomicLong TOTAL_MAPPED_VIRTUAL_MEMORY = new AtomicLong(0);
/**
* 记录commitlog目录下所有MappedFile总文件数
*/
private static final AtomicInteger TOTAL_MAPPED_FILES = new AtomicInteger(0);
/**
* MappedFile文件对应mappedByteBuffer(内存映射字节缓冲区)
*/
private MappedByteBuffer mappedByteBuffer;
/**
* MappedFile文件对应fileChannel
*/
protected FileChannel fileChannel;
/**
* 堆外内存池
*/
protected TransientStorePool transientStorePool = null;
/**
* 通过transientStorePool获取ByteBuffer(堆外内存字节缓冲区)
*/
protected ByteBuffer writeBuffer = null;
/**
* wrotePosition mappedByteBuffer/writeBuffer 字节缓冲区中pos写入位置
*/
protected final AtomicInteger wrotePosition = new AtomicInteger(0);
/**
* MappedFile使用TransientStorePool时
* broker commit 线程定时调用 commit 方法将writeBuffer(堆外内存缓存区)数据写入fileChannel
* committedPosition 表示fileChannel.commit后内存写入位置。理论上==wrotePosition
*/
protected final AtomicInteger committedPosition = new AtomicInteger(0);
/**
* broker flush 线程定时调用 flush 方法将mappedByteBuffer/fileChannel写入磁盘 记录flushedPosition
*/
private final AtomicInteger flushedPosition = new AtomicInteger(0);
/**
* MappedFile对应物理文件对象
*/
private File file;
/**
* mappedFile文件大小,参照MessageStoreConfig.mapedFileSizeCommitLog,默认1G
*/
protected int fileSize;
/**
* fileFromOffset 表示MappedFile文件名称是一个12位的数值,同时也表示文件存储的初始偏移
* 00000000000000000000 初始偏移是 0 存储 0~ fileSize
* 00000000001073741824 初始偏移是 1073741824 存储 fileSize~fileSize*2
*/
private long fileFromOffset;
/**
* MappedFile文件名 于fileFromOffset一致
*/
private String fileName;
/**
* 最后一次追加消息写入ByteBuffer的时间
*/
private volatile long storeTimestamp = 0;
/**
* 是否是MappedFileQueue队列中第一个MappedFile
*/
private boolean firstCreateInQueue = false;
/**
* 创建MappedFile
*/
public MappedFile() {
}
/**
* 创建MappedFile并设置文件名称,大小
* 使用当前方法创建的MappedFile并没有使用 TransientStorePool(堆外内存池)
* 1 消息文件会写入mappedByteBuffer内存映射字节缓冲区中 记录committedPosition
* 2 通过brokerFlush线程定时调用 flush 方法将mappedByteBuffer内存映射字节缓冲区中写入磁盘 记录flushedPosition
*/
public MappedFile(final String fileName, final int fileSize) throws IOException {
init(fileName, fileSize);
}
/**
* 创建MappedFile并设置文件名称,大小,同时设置TransientStorePool(堆外内存池)
* 1 初始化的时候会从TransientStorePool(堆外内存池) 获得一个writeBuffer(堆外内存缓存区)
* 2 消息文件会写入writeBuffer(堆外内存缓存区)
* 3 通过Commit线程定时调用 commit 方法将writeBuffer(堆外内存缓存区)数据写入fileChannel,记录committedPosition
* 4 通过brokerFlush线程定时调用 flush 方法将将fileChannel中数据写入磁盘,记录flushedPosition
*/
public MappedFile(final String fileName, final int fileSize,
final TransientStorePool transientStorePool) throws IOException {
init(fileName, fileSize, transientStorePool);
}
/*********************** 初始化 star ***********************/
/**
* 初始化MappedFile,使用transientStorePool(堆外内存池)
*/
public void init(final String fileName, final int fileSize,
final TransientStorePool transientStorePool) throws IOException {
init(fileName, fileSize);
this.writeBuffer = transientStorePool.borrowBuffer();
this.transientStorePool = transientStorePool;
}
/**
* 初始化MappedFile
* fileName 文件名,
* fileSize 大小
*/
private void init(final String fileName, final int fileSize) throws IOException {
//设置文件名称
this.fileName = fileName;
//设置文件大小
this.fileSize = fileSize;
//设置文件对象
this.file = new File(fileName);
//设置文件记录数据的偏移
this.fileFromOffset = Long.parseLong(this.file.getName());
//设置是否初始化成功
boolean ok = false;
//指定目录是否存在,不存在则创建一个
ensureDirOK(this.file.getParent());
try {
//设置fileChannel
this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
//设置mappedByteBuffer
this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
//累计当前broker MappedFile总大小
TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(fileSize);
//累计当前broker MappedFile个数
TOTAL_MAPPED_FILES.incrementAndGet();
ok = true;
} catch (FileNotFoundException e) {
log.error("create file channel " + this.fileName + " Failed. ", e);
throw e;
} catch (IOException e) {
log.error("map file " + this.fileName + " Failed. ", e);
throw e;
} finally {
if (!ok && this.fileChannel != null) {
this.fileChannel.close();
}
}
}
/**
* 指定目录是否存在,不存在则创建一个
*
* @param dirName
*/
public static void ensureDirOK(final String dirName) {
if (dirName != null) {
File f = new File(dirName);
if (!f.exists()) {
boolean result = f.mkdirs();
log.info(dirName + " mkdir " + (result ? "OK" : "Failed"));
}
}
}
/*********************** 初始化 end ***********************/
/*********************** 追加数据 star ***********************/
/**
* 向MapperFile追加消息,消息会写入ByteBuffer(堆外内存字节缓冲区)/mappedByteBuffer(内存映射字节缓冲区),等待异步刷盘
*
* @param msg
* @param cb
* @return
*/
public AppendMessageResult appendMessage(final MessageExtBrokerInner msg, final AppendMessageCallback cb) {
return appendMessagesInner(msg, cb);
}
/**
* 向MapperFile追加批量消息,,消息会写入ByteBuffer(堆外内存字节缓冲区)/mappedByteBuffer(内存映射字节缓冲区),等待异步刷盘
*
* @param messageExtBatch
* @param cb
* @return
*/
public AppendMessageResult appendMessages(final MessageExtBatch messageExtBatch, final AppendMessageCallback cb) {
return appendMessagesInner(messageExtBatch, cb);
}
/**
* 追加消息核心实现
*
* @param messageExt
* @param cb
* @return
*/
public AppendMessageResult appendMessagesInner(final MessageExt messageExt, final AppendMessageCallback cb) {
assert messageExt != null;
assert cb != null;
//获取文件写入的偏移位置
int currentPos = this.wrotePosition.get();
//文件还有剩余空间
if (currentPos < this.fileSize) {
//通过判断writeBuffer(推外内存字节缓冲区)来判断是否使用堆外内存池
ByteBuffer byteBuffer = writeBuffer != null ? writeBuffer.slice() : this.mappedByteBuffer.slice();
byteBuffer.position(currentPos);
//追加消息到byteBuffer中
AppendMessageResult result = null;
if (messageExt instanceof MessageExtBrokerInner) {
result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBrokerInner) messageExt);
} else if (messageExt instanceof MessageExtBatch) {
result = cb.doAppend(this.getFileFromOffset(), byteBuffer, this.fileSize - currentPos, (MessageExtBatch) messageExt);
} else {
return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
}
//更新wrotePosition
this.wrotePosition.addAndGet(result.getWroteBytes());
//更新storeTimestamp
this.storeTimestamp = result.getStoreTimestamp();
return result;
}
log.error("MappedFile.appendMessage return null, wrotePosition: {} fileSize: {}", currentPos, this.fileSize);
return new AppendMessageResult(AppendMessageStatus.UNKNOWN_ERROR);
}
/**
* MappedFile 文件尾部追加数据(直接写入文件)
*
* @param data
* @return
*/
public boolean appendMessage(final byte[] data) {
int currentPos = this.wrotePosition.get();
if ((currentPos + data.length) <= this.fileSize) {
try {
this.fileChannel.position(currentPos);
this.fileChannel.write(ByteBuffer.wrap(data));
} catch (Throwable e) {
log.error("Error occurred when append message to mappedFile.", e);
}
this.wrotePosition.addAndGet(data.length);
return true;
}
return false;
}
/**
* MappedFile 文件指定偏移位置追加数据(直接写入文件)
*
* @param data
* @param offset 偏移位置
* @param length 长度
* @return
*/
public boolean appendMessage(final byte[] data, final int offset, final int length) {
int currentPos = this.wrotePosition.get();
if ((currentPos + length) <= this.fileSize) {
try {
this.fileChannel.position(currentPos);
this.fileChannel.write(ByteBuffer.wrap(data, offset, length));
} catch (Throwable e) {
log.error("Error occurred when append message to mappedFile.", e);
}
this.wrotePosition.addAndGet(length);
return true;
}
return false;
}
/**
* 将mappedByteBuffer或fileChannel中数据写入磁盘,
*
* @param flushLeastPages 用来判断是否可以刷新最小页
* @return flushedPosition 刷新偏移
*/
public int flush(final int flushLeastPages) {
//判断是否可以进行刷盘
if (this.isAbleToFlush(flushLeastPages)) {
//引用计数+1
if (this.hold()) {
// 获取可以写入磁盘的偏移(mappedByteBuffer对应wrotePosition,也可能是writeBuffer对应committedPosition)
int value = getReadPosition();
try {
//我们只将数据附加到fileChannel或mappedByteBuffer,而不是两者。
if (writeBuffer != null || this.fileChannel.position() != 0) {
this.fileChannel.force(false);
} else {
//将此缓冲区内容的任何更改写入包含映射文件的存储设备
this.mappedByteBuffer.force();
}
} catch (Throwable e) {
log.error("Error occurred when force data to disk.", e);
}
//记录flushedPosition=getReadPosition()
this.flushedPosition.set(value);
//引用计数-1
this.release();
} else {
log.warn("in flush, hold failed, flush offset = " + this.flushedPosition.get());
this.flushedPosition.set(getReadPosition());
}
}
return this.getFlushedPosition();
}
/**
* 是否可以刷盘
*
* @param flushLeastPages flushLeastPages > 0 只有write-flush > flushLeastPages * 4K 才会刷盘
* @return
*/
private boolean isAbleToFlush(final int flushLeastPages) {
int flush = this.flushedPosition.get();
int write = getReadPosition();
if (this.isFull()) {
return true;
}
if (flushLeastPages > 0) {
return ((write / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE)) >= flushLeastPages;
}
return write > flush;
}
/**
* MappedFile使用transientStorePool追加数据时
* ByteBuffer字节缓冲区中的数据写入fileChannel
*
* @param commitLeastPages 用来判断是否可以刷新最小页
* @return flushedPosition 提交的偏移
*/
public int commit(final int commitLeastPages) {
//当writeBuffer为null,直接返回 wrotePosition
if (writeBuffer == null) {
return this.wrotePosition.get();
}
//是否可以提交
if (this.isAbleToCommit(commitLeastPages)) {
//引用计数+1
if (this.hold()) {
// 提交核心实现
commit0(commitLeastPages);
//引用计数-1
this.release();
} else {
log.warn("in commit, hold failed, commit offset = " + this.committedPosition.get());
}
}
//如果文件写满了将writeBuffer堆外内存字节缓冲区 归还给 对外内存池
if (writeBuffer != null && this.transientStorePool != null && this.fileSize == this.committedPosition.get()) {
//将writeBuffer堆外内存字节缓冲区 归还给 对外内存池
this.transientStorePool.returnBuffer(writeBuffer);
//设置writeBuffer堆外内存字节缓冲区为null
this.writeBuffer = null;
}
//返回提交的偏移
return this.committedPosition.get();
}
/**
* 将ByteBuffer字节缓冲区中的数据写入fileChannel
*
* @param commitLeastPages
*/
protected void commit0(final int commitLeastPages) {
int writePos = this.wrotePosition.get();
int lastCommittedPosition = this.committedPosition.get();
if (writePos - this.committedPosition.get() > 0) {
try {
/**
* writeBuffer 写入和mappedByteBuffer写入一样都是使用分片字节缓冲区。因为坐标指针都是延时的(数据已经写入),
* 需要手动坐标
*/
ByteBuffer byteBuffer = writeBuffer.slice();
byteBuffer.position(lastCommittedPosition);
byteBuffer.limit(writePos);
this.fileChannel.position(lastCommittedPosition);
this.fileChannel.write(byteBuffer);
//记录committedPosition
this.committedPosition.set(writePos);
} catch (Throwable e) {
log.error("Error occurred when commit data to FileChannel.", e);
}
}
}
/**
* 是否可以提交
*
* @param commitLeastPages
* @return
*/
protected boolean isAbleToCommit(final int commitLeastPages) {
int flush = this.committedPosition.get();
int write = this.wrotePosition.get();
if (this.isFull()) {
return true;
}
if (commitLeastPages > 0) {
return ((write / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE)) >= commitLeastPages;
}
return write > flush;
}
/*********************** 追加数据 end ***********************/
/*********************** 选择获取MappedFile数据 star ***********************/
/**
* 读取mappedFile文件 pos物理偏移坐标开始, size长度字节数据
*
* @param pos mappedFile文件数据初始偏移坐标
* @param size 长度
* @return
*/
public SelectMappedBufferResult selectMappedBuffer(int pos, int size) {
int readPosition = getReadPosition();
if ((pos + size) <= readPosition) {
if (this.hold()) {
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
byteBuffer.position(pos);
ByteBuffer byteBufferNew = byteBuffer.slice();
byteBufferNew.limit(size);
return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
} else {
log.warn("matched, but hold failed, request pos: " + pos + ", fileFromOffset: "
+ this.fileFromOffset);
}
} else {
log.warn("selectMappedBuffer request pos invalid, request pos: " + pos + ", size: " + size
+ ", fileFromOffset: " + this.fileFromOffset);
}
return null;
}
/**
* 读取mappedFile文件 pos物理偏移坐标开始所有字节数据
*
* @param pos mappedFile文件数据初始偏移坐标
* @return
*/
public SelectMappedBufferResult selectMappedBuffer(int pos) {
int readPosition = getReadPosition();
if (pos < readPosition && pos >= 0) {
if (this.hold()) {
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
byteBuffer.position(pos);
int size = readPosition - pos;
ByteBuffer byteBufferNew = byteBuffer.slice();
byteBufferNew.limit(size);
return new SelectMappedBufferResult(this.fileFromOffset + pos, byteBufferNew, size, this);
}
}
return null;
}
/**
* 获取文件内存映射
*
* @return
*/
public ByteBuffer sliceByteBuffer() {
return this.mappedByteBuffer.slice();
}
/*********************** 选择获取MappedFile数据 end ***********************/
public void warmMappedFile(FlushDiskType type, int pages) {
long beginTime = System.currentTimeMillis();
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
int flush = 0;
long time = System.currentTimeMillis();
for (int i = 0, j = 0; i < this.fileSize; i += MappedFile.OS_PAGE_SIZE, j++) {
byteBuffer.put(i, (byte) 0);
// force flush when flush disk type is sync
if (type == FlushDiskType.SYNC_FLUSH) {
if ((i / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE) >= pages) {
flush = i;
mappedByteBuffer.force();
}
}
// prevent gc
if (j % 1000 == 0) {
log.info("j={}, costTime={}", j, System.currentTimeMillis() - time);
time = System.currentTimeMillis();
try {
Thread.sleep(0);
} catch (InterruptedException e) {
log.error("Interrupted", e);
}
}
}
// force flush when prepare load finished
if (type == FlushDiskType.SYNC_FLUSH) {
log.info("mapped file warm-up done, force to disk, mappedFile={}, costTime={}",
this.getFileName(), System.currentTimeMillis() - beginTime);
mappedByteBuffer.force();
}
log.info("mapped file warm-up done. mappedFile={}, costTime={}", this.getFileName(),
System.currentTimeMillis() - beginTime);
this.mlock();
}
/*********************** 清理 star ***********************/
/**
* 清理mappedFile
*
* @return
*/
@Override
public boolean cleanup(final long currentRef) {
if (this.isAvailable()) {
log.error("this file[REF:" + currentRef + "] " + this.fileName
+ " have not shutdown, stop unmapping.");
return false;
}
if (this.isCleanupOver()) {
log.error("this file[REF:" + currentRef + "] " + this.fileName
+ " have cleanup, do not do it again.");
return true;
}
clean(this.mappedByteBuffer);
TOTAL_MAPPED_VIRTUAL_MEMORY.addAndGet(this.fileSize * (-1));
TOTAL_MAPPED_FILES.decrementAndGet();
log.info("unmap file[REF:" + currentRef + "] " + this.fileName + " OK");
return true;
}
public static void clean(final ByteBuffer buffer) {
if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
return;
/**
* 如果是directByteBuffer且容量不为0
* 则嵌套拿到directByteBuffer的最内部的attachment,强制转换成ByteBuffer对象(实际运行应该会是directByteBuffer),调用其clearner.clean方法进行深度的释放资源
*/
invoke(invoke(viewed(buffer), "cleaner"), "clean");
}
private static Object invoke(final Object target, final String methodName, final Class<?>... args) {
return AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
try {
Method method = method(target, methodName, args);
method.setAccessible(true);
return method.invoke(target);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
});
}
private static Method method(Object target, String methodName, Class<?>[] args)
throws NoSuchMethodException {
try {
return target.getClass().getMethod(methodName, args);
} catch (NoSuchMethodException e) {
return target.getClass().getDeclaredMethod(methodName, args);
}
}
/**
* 嵌套调用,获取最深层的attachment 或者 viewedBuffer方法
* 转化为ByteBuffer对象
*/
private static ByteBuffer viewed(ByteBuffer buffer) {
String methodName = "viewedBuffer";
Method[] methods = buffer.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("attachment")) {
methodName = "attachment";
break;
}
}
//执行DirectByteBuffer.attachment()方法
ByteBuffer viewedBuffer = (ByteBuffer) invoke(buffer, methodName);
if (viewedBuffer == null)
return buffer;
else
return viewed(viewedBuffer);
}
/**
* 销毁 MappedFile
*/
public boolean destroy(final long intervalForcibly) {
this.shutdown(intervalForcibly);
if (this.isCleanupOver()) {
try {
this.fileChannel.close();
log.info("close file channel " + this.fileName + " OK");
long beginTime = System.currentTimeMillis();
boolean result = this.file.delete();
log.info("delete file[REF:" + this.getRefCount() + "] " + this.fileName
+ (result ? " OK, " : " Failed, ") + "W:" + this.getWrotePosition() + " M:"
+ this.getFlushedPosition() + ", "
+ UtilAll.computeEclipseTimeMilliseconds(beginTime));
} catch (Exception e) {
log.warn("close file channel " + this.fileName + " Failed. ", e);
}
return true;
} else {
log.warn("destroy mapped file[REF:" + this.getRefCount() + "] " + this.fileName
+ " Failed. cleanupOver: " + this.cleanupOver);
}
return false;
}
/*********************** 清理 end ***********************/
public int getWrotePosition() {
return wrotePosition.get();
}
public void setWrotePosition(int pos) {
this.wrotePosition.set(pos);
}
File getFile() {
return this.file;
}
public static int getTotalMappedFiles() {
return TOTAL_MAPPED_FILES.get();
}
public static long getTotalMappedVirtualMemory() {
return TOTAL_MAPPED_VIRTUAL_MEMORY.get();
}
public long getLastModifiedTimestamp() {
return this.file.lastModified();
}
public int getFileSize() {
return fileSize;
}
public FileChannel getFileChannel() {
return fileChannel;
}
public String getFileName() {
return fileName;
}
public MappedByteBuffer getMappedByteBuffer() {
return mappedByteBuffer;
}
public long getStoreTimestamp() {
return storeTimestamp;
}
public long getFileFromOffset() {
return this.fileFromOffset;
}
public boolean isFirstCreateInQueue() {
return firstCreateInQueue;
}
public void setFirstCreateInQueue(boolean firstCreateInQueue) {
this.firstCreateInQueue = firstCreateInQueue;
}
public void setCommittedPosition(int pos) {
this.committedPosition.set(pos);
}
public int getFlushedPosition() {
return flushedPosition.get();
}
public void setFlushedPosition(int pos) {
this.flushedPosition.set(pos);
}
public boolean isFull() {
return this.fileSize == this.wrotePosition.get();
}
/**
* 返回MappedFile对应字节缓冲区区Pos偏移(可能是mappedByteBuffer对应wrotePosition,也可能是writeBuffer对应committedPosition)
*
* @return
*/
public int getReadPosition() {
return this.writeBuffer == null ? this.wrotePosition.get() : this.committedPosition.get();
}
public void mlock() {
final long beginTime = System.currentTimeMillis();
final long address = ((DirectBuffer) (this.mappedByteBuffer)).address();
Pointer pointer = new Pointer(address);
{
int ret = LibC.INSTANCE.mlock(pointer, new NativeLong(this.fileSize));
log.info("mlock {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime);
}
{
int ret = LibC.INSTANCE.madvise(pointer, new NativeLong(this.fileSize), LibC.MADV_WILLNEED);
log.info("madvise {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime);
}
}
public void munlock() {
final long beginTime = System.currentTimeMillis();
final long address = ((DirectBuffer) (this.mappedByteBuffer)).address();
Pointer pointer = new Pointer(address);
int ret = LibC.INSTANCE.munlock(pointer, new NativeLong(this.fileSize));
log.info("munlock {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime);
}
@Override
public String toString() {
return this.fileName;
}
}
|
3e1cfc22495583123c9dbf9c704974bcfe7ee4cc | 1,327 | java | Java | unityads/src/org/robovm/bindings/unityads/UnityAdsDelegate.java | BlueRiverInteractive/robovm-ios-bindings | 4fb9b4102d543f8529962334915a9b338a6231e6 | [
"Apache-2.0"
] | 90 | 2015-01-01T21:20:50.000Z | 2021-12-28T00:52:27.000Z | unityads/src/org/robovm/bindings/unityads/UnityAdsDelegate.java | BlueRiverInteractive/robovm-ios-bindings | 4fb9b4102d543f8529962334915a9b338a6231e6 | [
"Apache-2.0"
] | 68 | 2015-01-02T00:22:36.000Z | 2017-02-14T23:49:46.000Z | unityads/src/org/robovm/bindings/unityads/UnityAdsDelegate.java | BlueRiverInteractive/robovm-ios-bindings | 4fb9b4102d543f8529962334915a9b338a6231e6 | [
"Apache-2.0"
] | 65 | 2015-01-11T23:53:12.000Z | 2021-11-08T06:25:36.000Z | 27.645833 | 82 | 0.767898 | 12,286 | package org.robovm.bindings.unityads;
import org.robovm.apple.foundation.NSObjectProtocol;
import org.robovm.apple.foundation.NSString;
import org.robovm.objc.annotation.Method;
public interface UnityAdsDelegate extends NSObjectProtocol {
// @required
// - (void)unityAdsVideoCompleted:(NSString *)rewardItemKey skipped:(BOOL)skipped;
@Method(selector = "unityAdsVideoCompleted:skipped:")
void unityAdsVideoCompleted(NSString rewardItemKey, boolean skipped);
//
// @optional
// - (void)unityAdsWillShow;
@Method(selector = "unityAdsWillShow")
void unityAdsWillShow();
// - (void)unityAdsDidShow;
@Method(selector = "unityAdsDidShow")
void unityAdsDidShow();
// - (void)unityAdsWillHide;
@Method(selector = "unityAdsWillHide")
void unityAdsWillHide();
// - (void)unityAdsDidHide;
@Method(selector = "unityAdsDidHide")
void unityAdsDidHide();
// - (void)unityAdsWillLeaveApplication;
@Method(selector = "unityAdsWillLeaveApplication")
void unityAdsWillLeaveApplication();
// - (void)unityAdsVideoStarted;
@Method(selector = "unityAdsVideoStarted")
void unityAdsVideoStarted();
// - (void)unityAdsFetchCompleted;
@Method(selector = "unityAdsFetchCompleted")
void unityAdsFetchCompleted();
// - (void)unityAdsFetchFailed;
@Method(selector = "unityAdsFetchFailed")
void unityAdsFetchFailed();
}
|
3e1cfc94f9477e1098239ca61f7e50136025bc07 | 4,947 | java | Java | component/src/main/java/com/synopsys/integration/alert/component/scheduling/descriptor/SchedulingUIConfig.java | vberegov/blackduck-alert | f5597257fd19d11c1b8041b214d780d0255dcda5 | [
"Apache-2.0"
] | null | null | null | component/src/main/java/com/synopsys/integration/alert/component/scheduling/descriptor/SchedulingUIConfig.java | vberegov/blackduck-alert | f5597257fd19d11c1b8041b214d780d0255dcda5 | [
"Apache-2.0"
] | null | null | null | component/src/main/java/com/synopsys/integration/alert/component/scheduling/descriptor/SchedulingUIConfig.java | vberegov/blackduck-alert | f5597257fd19d11c1b8041b214d780d0255dcda5 | [
"Apache-2.0"
] | null | null | null | 58.2 | 282 | 0.725288 | 12,287 | /*
* component
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.alert.component.scheduling.descriptor;
import java.util.List;
import org.springframework.stereotype.Component;
import com.synopsys.integration.alert.common.descriptor.config.field.ConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.LabelValueSelectOption;
import com.synopsys.integration.alert.common.descriptor.config.field.ReadOnlyConfigField;
import com.synopsys.integration.alert.common.descriptor.config.field.SelectConfigField;
import com.synopsys.integration.alert.common.descriptor.config.ui.UIConfig;
@Component
public class SchedulingUIConfig extends UIConfig {
private static final String LABEL_DAILY_DIGEST_HOUR_OF_DAY = "Daily Digest Hour Of Day";
private static final String LABEL_DAILY_PROCESSOR_NEXT_RUN = "Daily Digest Cron Next Run";
private static final String LABEL_PURGE_DATA_FREQUENCY_IN_DAYS = "Purge Data Frequency In Days";
private static final String LABEL_PURGE_DATA_NEXT_RUN = "Purge Cron Next Run";
private static final String SCHEDULING_DIGEST_HOUR_DESCRIPTION = "Select the hour of the day to run the daily digest distribution jobs.";
private static final String DAILY_PROCESSOR_NEXT_RUN_DESCRIPTION = "This is the next time daily digest distribution jobs will run.";
private static final String SCHEDULING_PURGE_FREQUENCY_DESCRIPTION = "Choose a frequency for cleaning up provider data; the default value is three days. When the purge runs, it deletes all data that is older than the selected value. EX: data older than 3 days will be deleted.";
private static final String PURGE_DATA_NEXT_RUN_DESCRIPTION = "This is the next time Alert will purge provider data.";
public SchedulingUIConfig() {
super(SchedulingDescriptor.SCHEDULING_LABEL, SchedulingDescriptor.SCHEDULING_DESCRIPTION, SchedulingDescriptor.SCHEDULING_URL);
}
@Override
public List<ConfigField> createFields() {
ConfigField digestHour = new SelectConfigField(SchedulingDescriptor.KEY_DAILY_PROCESSOR_HOUR_OF_DAY, LABEL_DAILY_DIGEST_HOUR_OF_DAY, SCHEDULING_DIGEST_HOUR_DESCRIPTION, createDigestHours()).applyRequired(true);
ConfigField digestHourNextRun = new ReadOnlyConfigField(SchedulingDescriptor.KEY_DAILY_PROCESSOR_NEXT_RUN, LABEL_DAILY_PROCESSOR_NEXT_RUN, DAILY_PROCESSOR_NEXT_RUN_DESCRIPTION);
ConfigField purgeFrequency = new SelectConfigField(SchedulingDescriptor.KEY_PURGE_DATA_FREQUENCY_DAYS, LABEL_PURGE_DATA_FREQUENCY_IN_DAYS, SCHEDULING_PURGE_FREQUENCY_DESCRIPTION, createPurgeFrequency()).applyRequired(true);
ConfigField purgeNextRun = new ReadOnlyConfigField(SchedulingDescriptor.KEY_PURGE_DATA_NEXT_RUN, LABEL_PURGE_DATA_NEXT_RUN, PURGE_DATA_NEXT_RUN_DESCRIPTION);
return List.of(digestHour, digestHourNextRun, purgeFrequency, purgeNextRun);
}
private List<LabelValueSelectOption> createDigestHours() {
return List.of(
new LabelValueSelectOption("12 am", "0"),
new LabelValueSelectOption("1 am", "1"),
new LabelValueSelectOption("2 am", "2"),
new LabelValueSelectOption("3 am", "3"),
new LabelValueSelectOption("4 am", "4"),
new LabelValueSelectOption("5 am", "5"),
new LabelValueSelectOption("6 am", "6"),
new LabelValueSelectOption("7 am", "7"),
new LabelValueSelectOption("8 am", "8"),
new LabelValueSelectOption("9 am", "9"),
new LabelValueSelectOption("10 am", "10"),
new LabelValueSelectOption("11 am", "11"),
new LabelValueSelectOption("12 pm", "12"),
new LabelValueSelectOption("1 pm", "13"),
new LabelValueSelectOption("2 pm", "14"),
new LabelValueSelectOption("3 pm", "15"),
new LabelValueSelectOption("4 pm", "16"),
new LabelValueSelectOption("5 pm", "17"),
new LabelValueSelectOption("6 pm", "18"),
new LabelValueSelectOption("7 pm", "19"),
new LabelValueSelectOption("8 pm", "20"),
new LabelValueSelectOption("9 pm", "21"),
new LabelValueSelectOption("10 pm", "22"),
new LabelValueSelectOption("11 pm", "23"));
}
private List<LabelValueSelectOption> createPurgeFrequency() {
return List.of(
new LabelValueSelectOption("Every day", "1"),
new LabelValueSelectOption("Every 2 days", "2"),
new LabelValueSelectOption("Every 3 days", "3"),
new LabelValueSelectOption("Every 4 days", "4"),
new LabelValueSelectOption("Every 5 days", "5"),
new LabelValueSelectOption("Every 6 days", "6"),
new LabelValueSelectOption("Every 7 days", "7"));
}
}
|
3e1cfcb3e61042ebcd410f96705e6d7289899846 | 3,432 | java | Java | src/mazes/gui/MainWindow.java | QianchengLi2333/Maze | 94349af90c90cda56b64864fd94dca61e8d752b7 | [
"MIT"
] | null | null | null | src/mazes/gui/MainWindow.java | QianchengLi2333/Maze | 94349af90c90cda56b64864fd94dca61e8d752b7 | [
"MIT"
] | null | null | null | src/mazes/gui/MainWindow.java | QianchengLi2333/Maze | 94349af90c90cda56b64864fd94dca61e8d752b7 | [
"MIT"
] | null | null | null | 30.918919 | 83 | 0.630828 | 12,288 | package mazes.gui;
import mazes.logic.MazeSolver;
import mazes.logic.carvers.MazeCarver;
import mazes.logic.generators.MazeBaseGenerator;
import javax.swing.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Map;
/**
* The main entry point of the user interface.
*/
public class MainWindow extends JFrame {
public static final int DEFAULT_WIDTH = 800;
public static final int DEFAULT_HEIGHT = 600;
private final MazeSolver mazeSolver;
/**
* Responsible for configuring and launching the GUI.
*/
public static void launch(Map<String, MazeBaseGenerator> baseGenerators,
Map<String, MazeCarver> mazeCarvers,
MazeSolver mazeSolver) {
EventQueue.invokeLater(() -> {
MainWindow window = new MainWindow(
"MazeGenerator",
DEFAULT_WIDTH,
DEFAULT_HEIGHT,
baseGenerators,
mazeCarvers,
mazeSolver);
window.construct();
});
}
private final String title;
private final int width;
private final int height;
private ImageDrawer drawer;
private final Map<String, MazeBaseGenerator> baseGenerators;
private final Map<String, MazeCarver> baseCarvers;
public MainWindow(String title, int width, int height,
Map<String, MazeBaseGenerator> baseGenerators,
Map<String, MazeCarver> baseCarvers, MazeSolver mazeSolver) {
this.title = title;
this.width = width;
this.height = height;
this.baseGenerators = baseGenerators;
this.baseCarvers = baseCarvers;
this.mazeSolver = mazeSolver;
}
public void construct() {
this.setUpMainWindow();
ImagePanel imagePanel = this.makeDrawingPane();
ControlsPanel controlsPanel = new ControlsPanel(
this.drawer, this.baseGenerators, this.baseCarvers, this.mazeSolver);
imagePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
controlsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
// Set up pane
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.add(imagePanel);
pane.add(controlsPanel);
this.add(pane);
// Finish setting up geometry
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private void setUpMainWindow() {
this.setTitle(this.title);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
// Ignore
}
}
public ImagePanel makeDrawingPane() {
BufferedImage image = new BufferedImage(
this.width,
this.height, BufferedImage.TYPE_BYTE_INDEXED);
// Set up initial background color
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width + 1, this.height + 1);
this.drawer = new ImageDrawer(image, 5);
ImagePanel panel = new ImagePanel(image);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
return panel;
}
}
|
3e1cfcc8f2a5506a0eede1369a52c162bb43f716 | 1,232 | java | Java | src/main/java/hibernate/conventions/integrator/ConventionsIntegrator.java | andreluiznsilva/hibernate-conventions | 10da77e7ca0391f9a2e52b1dc935ee8ab76fb193 | [
"Apache-2.0"
] | 3 | 2015-01-21T18:25:41.000Z | 2018-03-11T05:58:24.000Z | src/main/java/hibernate/conventions/integrator/ConventionsIntegrator.java | andreluiznsilva/hibernate-conventions | 10da77e7ca0391f9a2e52b1dc935ee8ab76fb193 | [
"Apache-2.0"
] | 1 | 2015-04-21T11:49:09.000Z | 2015-04-21T11:49:09.000Z | src/main/java/hibernate/conventions/integrator/ConventionsIntegrator.java | andreluiznsilva/hibernate-conventions | 10da77e7ca0391f9a2e52b1dc935ee8ab76fb193 | [
"Apache-2.0"
] | null | null | null | 30.8 | 83 | 0.80763 | 12,289 | package hibernate.conventions.integrator;
import hibernate.conventions.ConfigConventions;
import hibernate.conventions.MappingConventions;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.metamodel.source.MetadataImplementor;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;
public class ConventionsIntegrator implements Integrator {
public void disintegrate(
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
}
public void integrate(
Configuration configuration,
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
ConfigConventions configConventions = ConfigConventions.create(configuration);
configConventions.validate();
MappingConventions mappingConventions = MappingConventions.create(configuration);
mappingConventions.normalize();
mappingConventions.validate();
}
public void integrate(
MetadataImplementor metadata,
SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {
}
} |
3e1cfdfb6561ee57965cc56c3c61efea828be482 | 2,338 | java | Java | Data/Juliet-Java/Juliet-Java-v103/000/148/057/CWE89_SQL_Injection__Property_executeQuery_68a.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/148/057/CWE89_SQL_Injection__Property_executeQuery_68a.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/148/057/CWE89_SQL_Injection__Property_executeQuery_68a.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | 31.173333 | 145 | 0.667237 | 12,290 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE89_SQL_Injection__Property_executeQuery_68a.java
Label Definition File: CWE89_SQL_Injection.label.xml
Template File: sources-sinks-68a.tmpl.java
*/
/*
* @description
* CWE: 89 SQL Injection
* BadSource: Property Read data from a system property
* GoodSource: A hardcoded string
* Sinks: executeQuery
* GoodSink: Use prepared statement and executeQuery (properly)
* BadSink : data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection
* Flow Variant: 68 Data flow: data passed as a member variable in the "a" class, which is used by a method in another class in the same package
*
* */
public class CWE89_SQL_Injection__Property_executeQuery_68a extends AbstractTestCase
{
public static String data;
public void bad() throws Throwable
{
/* get system property user.home */
/* POTENTIAL FLAW: Read data from a system property */
data = System.getProperty("user.home");
(new CWE89_SQL_Injection__Property_executeQuery_68b()).badSink();
}
public void good() throws Throwable
{
goodG2B();
goodB2G();
}
/* goodG2B() - use goodsource and badsink */
private void goodG2B() throws Throwable
{
/* FIX: Use a hardcoded string */
data = "foo";
(new CWE89_SQL_Injection__Property_executeQuery_68b()).goodG2BSink();
}
/* goodB2G() - use badsource and goodsink */
private void goodB2G() throws Throwable
{
/* get system property user.home */
/* POTENTIAL FLAW: Read data from a system property */
data = System.getProperty("user.home");
(new CWE89_SQL_Injection__Property_executeQuery_68b()).goodB2GSink();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
3e1cfe0b74f867ac738643db3071d268213153ca | 8,681 | java | Java | native/android/source/src/com/android2c/CCJNIWebJS.java | drdavient/multi | 2700c50ec15c1e1790f549e3d5a490df051e0ccb | [
"Apache-2.0"
] | 1 | 2015-06-03T21:54:51.000Z | 2015-06-03T21:54:51.000Z | native/android/source/src/com/android2c/CCJNIWebJS.java | drdavient/multi | 2700c50ec15c1e1790f549e3d5a490df051e0ccb | [
"Apache-2.0"
] | null | null | null | native/android/source/src/com/android2c/CCJNIWebJS.java | drdavient/multi | 2700c50ec15c1e1790f549e3d5a490df051e0ccb | [
"Apache-2.0"
] | null | null | null | 26.226586 | 121 | 0.595093 | 12,291 | /*-----------------------------------------------------------
* http://softwareispoetry.com
*-----------------------------------------------------------
* This software is distributed under the Apache 2.0 license.
*-----------------------------------------------------------
* File Name : CCJNIWebJS.java
* Description : Interfaces with ndk on web page load.
* JavaScript evaluation based on this tutorial
* http://www.gutterbling.com/blog/synchronous-javascript-evaluation-in-android-webview/
*
* Created : 09/10/11
* Author(s) : Ashraf Samy Hegab
*-----------------------------------------------------------
*/
package com.android2c;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.graphics.Bitmap;
import android.webkit.JsResult;
@SuppressLint("SetJavaScriptEnabled")
class CCJNIWebJS extends WebView
{
static CCJNIWebJS webView = null;
// Provides an interface for running JavaScript calls
public class JavaScriptInterface
{
// The JavaScript interface name for adding to web view.
private final String interfaceName = "CCJS";
private class JavaScriptCall
{
String script;
boolean returnResult;
boolean calledFromJava;
public JavaScriptCall(final String script, final boolean returnResult, final boolean calledFromJava)
{
this.script = script;
this.returnResult = returnResult;
this.calledFromJava = calledFromJava;
}
}
JavaScriptCall runningScript = null;
private ArrayList<JavaScriptCall> pendingScripts = new ArrayList<JavaScriptCall>();
// Evaluates the expression for Java (usually on pause/resume)
public synchronized void forceRunJavaScript(final String script)
{
if( webView != null && webView.loaded )
{
if( CCJNI.DEBUGJS )
{
String trimmed = script;
// trimmed = trimmed.replace( "\n", "" );
// trimmed = trimmed.replace( "\r", "" );
// if( trimmed.length() > 20 )
// {
// trimmed = trimmed.substring( 0, 20 );
// }
Log.d( "WebJS: Run", trimmed );
}
String code = "javascript: " + script;
webView.loadUrl( code );
}
}
// Evaluates the expression and returns the value.
public synchronized void runJavaScript(final String script, final boolean returnResult, final boolean calledFromJava)
{
if( webView != null && webView.loaded )
{
if( runningScript == null )
{
if( CCJNI.DEBUGJS )
{
String trimmed = script;
// trimmed = trimmed.replace( "\n", "" );
// trimmed = trimmed.replace( "\r", "" );
// if( trimmed.length() > 20 )
// {
// trimmed = trimmed.substring( 0, 20 );
// }
Log.d( "WebJS: Run", trimmed );
}
runningScript = new JavaScriptCall( script, returnResult, calledFromJava );
if( returnResult )
{
String code = "javascript: var result = " + script + ";\nwindow." + interfaceName + ".javaScriptResult( result );";
webView.loadUrl( code );
}
else
{
String code = "javascript: " + script;
webView.loadUrl( code );
javaScriptResult( "true" );
}
}
else
{
pendingScripts.add( new JavaScriptCall( script, returnResult, calledFromJava ) );
}
}
}
// Receives the value from the JavaScript.
public synchronized void javaScriptResult(final String result)
{
if( CCJNI.DEBUGJS )
{
String trimmed = result;
trimmed = trimmed.replace( "\n", "" );
trimmed = trimmed.replace( "\r", "" );
if( trimmed.length() > 20 )
{
trimmed = trimmed.substring( 0, 20 );
}
else if( trimmed.length() == 0 )
{
trimmed = " ";
}
Log.d( "WebJS: Result", trimmed );
}
if( !runningScript.calledFromJava )
{
final boolean returnResult = runningScript.returnResult;
CCJNIGLView.runOnGLThread(new Runnable()
{
public void run()
{
CCJNI.WebJSJavaScriptResultGLThread( result, returnResult );
}
});
}
runningScript = null;
if( pendingScripts.size() > 0 )
{
final JavaScriptCall script = pendingScripts.remove( 0 );
CCJNI.Activity.runOnUiThread(new Runnable()
{
public void run()
{
runJavaScript( script.script, script.returnResult, script.calledFromJava );
}
});
}
}
public String getInterfaceName()
{
return this.interfaceName;
}
}
JavaScriptInterface jsInterface;
boolean loading = false;
int errorCode = 0;
boolean loaded = false;
public CCJNIWebJS(Activity activity)
{
super( activity );
webView = this;
// Allow keyboard input
//requestFocus( View.FOCUS_DOWN );
{
WebSettings settings = getSettings();
settings.setJavaScriptEnabled( true );
// enable to use "window.localStorage['my']='hello1'", in webview js on >= android 2.0
settings.setDomStorageEnabled( true );
// if no set or wrong path, variables disappear on killed
settings.setDatabasePath( "/data/data/" + activity.getPackageName() + "/databases/" );
// No caching
//settings.setAppCacheEnabled( false );
settings.setCacheMode( WebSettings.LOAD_NO_CACHE );
}
jsInterface = new JavaScriptInterface();
addJavascriptInterface( jsInterface, jsInterface.getInterfaceName() );
if( CCJNI.DEBUGJS )
{
setWebChromeClient(new WebChromeClient()
{
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
Log.d( "WebJS", message + " -- line " + lineNumber + " " + sourceID );
}
public boolean onConsoleMessage(ConsoleMessage cm)
{
String message = cm.message();
Log.d( "WebJS", message + " -- line " + cm.lineNumber() + " " + cm.sourceId() );
return true;
}
public boolean onJsAlert(WebView view, String url, String message, JsResult result)
{
return false;
}
public boolean onJsTimeout()
{
return false;
}
});
}
setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, final String url)
{
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl( url );
CCJNIGLView.runOnGLThread(new Runnable()
{
public void run()
{
CCJNI.WebJSURLLoadedGLThread( url, "", false );
}
});
return false; // then it is not handled by default action
}
public void onLoadResource(WebView view, String url)
{
super.onLoadResource( view, url );
}
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted( view, url, favicon );
}
public void onPageFinished(WebView view, final String url)
{
if( loading )
{
loading = false;
final boolean success = errorCode == 0 ? true : false;
CCJNIGLView.runOnGLThread(new Runnable()
{
public void run()
{
if( success )
{
loaded = true;
}
CCJNI.WebJSURLLoadedGLThread( url, "", success );
}
});
}
}
public void onReceivedError(WebView view, int inErrorCode, String description, String failingUrl)
{
errorCode = inErrorCode;
onPageFinished( view, failingUrl );
}
});
}
public void open(final String url, final String htmlData)
{
loading = true;
if( htmlData != null )
{
loadDataWithBaseURL( url, htmlData, "text/html", "UTF-8", null );
}
else
{
loadUrl( url );
}
}
@Override
public void destroy()
{
webView = null;
super.destroy();
}
public void runJavaScript(final String script, final boolean returnResult, final boolean calledFromJava)
{
CCJNI.Activity.runOnUiThread(new Runnable()
{
public void run()
{
jsInterface.runJavaScript( script, returnResult, calledFromJava );
}
});
}
public void forceRunJavaScript(final String script)
{
CCJNI.Activity.runOnUiThread(new Runnable()
{
public void run()
{
jsInterface.forceRunJavaScript( script );
}
});
}
}
|
3e1cff7e25f92dc4f014936ca010c247bb95723b | 1,096 | java | Java | oceanus-all/oceanus-exchange/oceanus-exchange-sqlparser/src/main/java/com/bj58/sql/parser/SQLParserFeature.java | qinFamily/Oceanus | 62d8717f5f4f76a49d751fd8fbea9fe8250e3f5e | [
"Apache-2.0"
] | 617 | 2015-01-14T09:18:07.000Z | 2021-08-05T06:39:29.000Z | oceanus-all/oceanus-exchange/oceanus-exchange-sqlparser/src/main/java/com/bj58/sql/parser/SQLParserFeature.java | qinFamily/Oceanus | 62d8717f5f4f76a49d751fd8fbea9fe8250e3f5e | [
"Apache-2.0"
] | 5 | 2015-01-28T05:49:22.000Z | 2019-01-07T06:05:01.000Z | oceanus-all/oceanus-exchange/oceanus-exchange-sqlparser/src/main/java/com/bj58/sql/parser/SQLParserFeature.java | qinFamily/Oceanus | 62d8717f5f4f76a49d751fd8fbea9fe8250e3f5e | [
"Apache-2.0"
] | 348 | 2015-01-14T09:18:07.000Z | 2021-06-17T09:17:48.000Z | 28.102564 | 81 | 0.733577 | 12,292 | /**
* Copyright 2011-2013 FoundationDB, LLC
*
* 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.
*/
/** Features of the parser grammar.
* In particular, dialect-specific constructs that can be turned off for use with
* ordinary databases.
*/
package com.bj58.sql.parser;
public enum SQLParserFeature
{
GEO_INDEX_DEF_FUNC,
MYSQL_COLUMN_AS_FUNCS,
MYSQL_LEFT_RIGHT_FUNC,
DIV_OPERATOR, // integer division
GROUPING,
MYSQL_HINTS,
MYSQL_INTERVAL,
UNSIGNED,
INFIX_MOD,
INFIX_BIT_OPERATORS,
INFIX_LOGICAL_OPERATORS,
DOUBLE_QUOTED_STRING
}
|
3e1d009663414dacbade0ae6b7d66d0ccceab370 | 21,237 | java | Java | soot-reim-definite/bench/eclipsec/org/eclipse/jdt/internal/compiler/ast/ConditionalExpression.java | dongy6/type-inference | 90d002a1e2d0a3d160ab204084da9d5be5fdd971 | [
"Apache-2.0"
] | 1 | 2019-12-07T16:13:03.000Z | 2019-12-07T16:13:03.000Z | soot-reim-definite/bench/eclipsec/org/eclipse/jdt/internal/compiler/ast/ConditionalExpression.java | dongy6/type-inference | 90d002a1e2d0a3d160ab204084da9d5be5fdd971 | [
"Apache-2.0"
] | null | null | null | soot-reim-definite/bench/eclipsec/org/eclipse/jdt/internal/compiler/ast/ConditionalExpression.java | dongy6/type-inference | 90d002a1e2d0a3d160ab204084da9d5be5fdd971 | [
"Apache-2.0"
] | null | null | null | 44.615546 | 153 | 0.747704 | 12,293 | /*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;
//import checkers.inference.ownership.quals.*;
import org.eclipse.jdt.internal.compiler.ASTVisitor;
import org.eclipse.jdt.internal.compiler.impl.*;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.codegen.*;
import org.eclipse.jdt.internal.compiler.flow.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
public class ConditionalExpression extends OperatorExpression {
public Expression condition;
public /*@OwnOwn*/ Expression valueIfTrue, valueIfFalse;
public Constant optimizedBooleanConstant;
public Constant optimizedIfTrueConstant;
public Constant optimizedIfFalseConstant;
// for local variables table attributes
int trueInitStateIndex = -1;
int falseInitStateIndex = -1;
int mergedInitStateIndex = -1;
public ConditionalExpression(
Expression condition,
Expression valueIfTrue,
Expression valueIfFalse) {
this.condition = condition;
this.valueIfTrue = valueIfTrue;
this.valueIfFalse = valueIfFalse;
sourceStart = condition.sourceStart;
sourceEnd = valueIfFalse.sourceEnd;
}
public FlowInfo analyseCode(
BlockScope currentScope,
FlowContext flowContext,
FlowInfo flowInfo) {
Constant cst = this.condition.optimizedBooleanConstant();
boolean isConditionOptimizedTrue = cst != Constant.NotAConstant && cst.booleanValue() == true;
boolean isConditionOptimizedFalse = cst != Constant.NotAConstant && cst.booleanValue() == false;
int mode = flowInfo.reachMode();
flowInfo = condition.analyseCode(currentScope, flowContext, flowInfo, cst == Constant.NotAConstant);
// process the if-true part
FlowInfo trueFlowInfo = flowInfo.initsWhenTrue().copy();
if (isConditionOptimizedFalse) {
trueFlowInfo.setReachMode(FlowInfo.UNREACHABLE);
}
trueInitStateIndex = currentScope.methodScope().recordInitializationStates(trueFlowInfo);
trueFlowInfo = valueIfTrue.analyseCode(currentScope, flowContext, trueFlowInfo);
// process the if-false part
FlowInfo falseFlowInfo = flowInfo.initsWhenFalse().copy();
if (isConditionOptimizedTrue) {
falseFlowInfo.setReachMode(FlowInfo.UNREACHABLE);
}
falseInitStateIndex = currentScope.methodScope().recordInitializationStates(falseFlowInfo);
falseFlowInfo = valueIfFalse.analyseCode(currentScope, flowContext, falseFlowInfo);
// merge if-true & if-false initializations
FlowInfo mergedInfo;
if (isConditionOptimizedTrue){
mergedInfo = trueFlowInfo.addPotentialInitializationsFrom(falseFlowInfo);
} else if (isConditionOptimizedFalse) {
mergedInfo = falseFlowInfo.addPotentialInitializationsFrom(trueFlowInfo);
} else {
// if ((t && (v = t)) ? t : t && (v = f)) r = v; -- ok
cst = this.optimizedIfTrueConstant;
boolean isValueIfTrueOptimizedTrue = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == true;
boolean isValueIfTrueOptimizedFalse = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == false;
cst = this.optimizedIfFalseConstant;
boolean isValueIfFalseOptimizedTrue = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == true;
boolean isValueIfFalseOptimizedFalse = cst != null && cst != Constant.NotAConstant && cst.booleanValue() == false;
UnconditionalFlowInfo trueInfoWhenTrue = trueFlowInfo.initsWhenTrue().copy().unconditionalInits();
if (isValueIfTrueOptimizedFalse) trueInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE);
UnconditionalFlowInfo falseInfoWhenTrue = falseFlowInfo.initsWhenTrue().copy().unconditionalInits();
if (isValueIfFalseOptimizedFalse) falseInfoWhenTrue.setReachMode(FlowInfo.UNREACHABLE);
UnconditionalFlowInfo trueInfoWhenFalse = trueFlowInfo.initsWhenFalse().copy().unconditionalInits();
if (isValueIfTrueOptimizedTrue) trueInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE);
UnconditionalFlowInfo falseInfoWhenFalse = falseFlowInfo.initsWhenFalse().copy().unconditionalInits();
if (isValueIfFalseOptimizedTrue) falseInfoWhenFalse.setReachMode(FlowInfo.UNREACHABLE);
mergedInfo =
FlowInfo.conditional(
trueInfoWhenTrue.mergedWith(falseInfoWhenTrue),
trueInfoWhenFalse.mergedWith(falseInfoWhenFalse));
}
mergedInitStateIndex =
currentScope.methodScope().recordInitializationStates(mergedInfo);
mergedInfo.setReachMode(mode);
return mergedInfo;
}
/**
* Code generation for the conditional operator ?:
*
* @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
* @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
* @param valueRequired boolean
*/
public void generateCode(
BlockScope currentScope,
CodeStream codeStream,
boolean valueRequired) {
int pc = codeStream.position;
Label endifLabel, falseLabel;
if (constant != Constant.NotAConstant) {
if (valueRequired)
codeStream.generateConstant(constant, implicitConversion);
codeStream.recordPositionsFrom(pc, this.sourceStart);
return;
}
Constant cst = condition.constant;
Constant condCst = condition.optimizedBooleanConstant();
boolean needTruePart =
!(((cst != Constant.NotAConstant) && (cst.booleanValue() == false))
|| ((condCst != Constant.NotAConstant) && (condCst.booleanValue() == false)));
boolean needFalsePart =
!(((cst != Constant.NotAConstant) && (cst.booleanValue() == true))
|| ((condCst != Constant.NotAConstant) && (condCst.booleanValue() == true)));
endifLabel = new Label(codeStream);
// Generate code for the condition
boolean needConditionValue = (cst == Constant.NotAConstant) && (condCst == Constant.NotAConstant);
condition.generateOptimizedBoolean(
currentScope,
codeStream,
null,
(falseLabel = new Label(codeStream)),
needConditionValue);
if (trueInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(
currentScope,
trueInitStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, trueInitStateIndex);
}
// Then code generation
if (needTruePart) {
valueIfTrue.generateCode(currentScope, codeStream, valueRequired);
if (needFalsePart) {
// Jump over the else part
int position = codeStream.position;
codeStream.goto_(endifLabel);
codeStream.updateLastRecordedEndPC(currentScope, position);
// Tune codestream stack size
if (valueRequired) {
codeStream.decrStackSize(this.resolvedType == LongBinding || this.resolvedType == DoubleBinding ? 2 : 1);
}
}
}
if (needFalsePart) {
falseLabel.place();
if (falseInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(
currentScope,
falseInitStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, falseInitStateIndex);
}
valueIfFalse.generateCode(currentScope, codeStream, valueRequired);
// End of if statement
endifLabel.place();
}
// May loose some local variable initializations : affecting the local variable attributes
if (mergedInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(
currentScope,
mergedInitStateIndex);
}
// implicit conversion
if (valueRequired)
codeStream.generateImplicitConversion(implicitConversion);
codeStream.recordPositionsFrom(pc, this.sourceStart);
}
/**
* Optimized boolean code generation for the conditional operator ?:
*/
public void generateOptimizedBoolean(
BlockScope currentScope,
CodeStream codeStream,
Label trueLabel,
Label falseLabel,
boolean valueRequired) {
if ((constant != Constant.NotAConstant) && (constant.typeID() == T_boolean) // constant
|| ((valueIfTrue.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4) != T_boolean) { // non boolean values
super.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired);
return;
}
Constant cst = condition.constant;
Constant condCst = condition.optimizedBooleanConstant();
boolean needTruePart =
!(((cst != Constant.NotAConstant) && (cst.booleanValue() == false))
|| ((condCst != Constant.NotAConstant) && (condCst.booleanValue() == false)));
boolean needFalsePart =
!(((cst != Constant.NotAConstant) && (cst.booleanValue() == true))
|| ((condCst != Constant.NotAConstant) && (condCst.booleanValue() == true)));
Label internalFalseLabel, endifLabel = new Label(codeStream);
// Generate code for the condition
boolean needConditionValue = (cst == Constant.NotAConstant) && (condCst == Constant.NotAConstant);
condition.generateOptimizedBoolean(
currentScope,
codeStream,
null,
internalFalseLabel = new Label(codeStream),
needConditionValue);
if (trueInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(
currentScope,
trueInitStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, trueInitStateIndex);
}
// Then code generation
if (needTruePart) {
valueIfTrue.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired);
if (needFalsePart) {
// Jump over the else part
int position = codeStream.position;
codeStream.goto_(endifLabel);
codeStream.updateLastRecordedEndPC(currentScope, position);
// No need to decrement codestream stack size
// since valueIfTrue was already consumed by branch bytecode
}
}
if (needFalsePart) {
internalFalseLabel.place();
if (falseInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(currentScope, falseInitStateIndex);
codeStream.addDefinitelyAssignedVariables(currentScope, falseInitStateIndex);
}
valueIfFalse.generateOptimizedBoolean(currentScope, codeStream, trueLabel, falseLabel, valueRequired);
// End of if statement
endifLabel.place();
}
// May loose some local variable initializations : affecting the local variable attributes
if (mergedInitStateIndex != -1) {
codeStream.removeNotDefinitelyAssignedVariables(currentScope, mergedInitStateIndex);
}
// no implicit conversion for boolean values
codeStream.updateLastRecordedEndPC(currentScope, codeStream.position);
}
public Constant optimizedBooleanConstant() {
return this.optimizedBooleanConstant == null ? this.constant : this.optimizedBooleanConstant;
}
public StringBuffer printExpressionNoParenthesis(int indent, StringBuffer output) {
condition.printExpression(indent, output).append(" ? "); //$NON-NLS-1$
valueIfTrue.printExpression(0, output).append(" : "); //$NON-NLS-1$
return valueIfFalse.printExpression(0, output);
}
public TypeBinding resolveType(BlockScope scope) {
// JLS3 15.25
constant = Constant.NotAConstant;
LookupEnvironment env = scope.environment();
boolean use15specifics = scope.compilerOptions().sourceLevel >= ClassFileConstants.JDK1_5;
TypeBinding conditionType = condition.resolveTypeExpecting(scope, BooleanBinding);
condition.computeConversion(scope, BooleanBinding, conditionType);
if (valueIfTrue instanceof CastExpression) valueIfTrue.bits |= DisableUnnecessaryCastCheck; // will check later on
TypeBinding originalValueIfTrueType = valueIfTrue.resolveType(scope);
if (valueIfFalse instanceof CastExpression) valueIfFalse.bits |= DisableUnnecessaryCastCheck; // will check later on
TypeBinding originalValueIfFalseType = valueIfFalse.resolveType(scope);
if (conditionType == null || originalValueIfTrueType == null || originalValueIfFalseType == null)
return null;
TypeBinding valueIfTrueType = originalValueIfTrueType;
TypeBinding valueIfFalseType = originalValueIfFalseType;
if (use15specifics && valueIfTrueType != valueIfFalseType) {
if (valueIfTrueType.isBaseType()) {
if (valueIfFalseType.isBaseType()) {
// bool ? baseType : baseType
if (valueIfTrueType == NullBinding) { // bool ? null : 12 --> Integer
valueIfFalseType = env.computeBoxingType(valueIfFalseType); // boxing
} else if (valueIfFalseType == NullBinding) { // bool ? 12 : null --> Integer
valueIfTrueType = env.computeBoxingType(valueIfTrueType); // boxing
}
} else {
// bool ? baseType : nonBaseType
TypeBinding unboxedIfFalseType = valueIfFalseType.isBaseType() ? valueIfFalseType : env.computeBoxingType(valueIfFalseType);
if (valueIfTrueType.isNumericType() && unboxedIfFalseType.isNumericType()) {
valueIfFalseType = unboxedIfFalseType; // unboxing
} else if (valueIfTrueType != NullBinding) { // bool ? 12 : new Integer(12) --> int
valueIfFalseType = env.computeBoxingType(valueIfFalseType); // unboxing
}
}
} else if (valueIfFalseType.isBaseType()) {
// bool ? nonBaseType : baseType
TypeBinding unboxedIfTrueType = valueIfTrueType.isBaseType() ? valueIfTrueType : env.computeBoxingType(valueIfTrueType);
if (unboxedIfTrueType.isNumericType() && valueIfFalseType.isNumericType()) {
valueIfTrueType = unboxedIfTrueType; // unboxing
} else if (valueIfFalseType != NullBinding) { // bool ? new Integer(12) : 12 --> int
valueIfTrueType = env.computeBoxingType(valueIfTrueType); // unboxing
}
} else {
// bool ? nonBaseType : nonBaseType
TypeBinding unboxedIfTrueType = env.computeBoxingType(valueIfTrueType);
TypeBinding unboxedIfFalseType = env.computeBoxingType(valueIfFalseType);
if (unboxedIfTrueType.isNumericType() && unboxedIfFalseType.isNumericType()) {
valueIfTrueType = unboxedIfTrueType;
valueIfFalseType = unboxedIfFalseType;
}
}
}
// Propagate the constant value from the valueIfTrue and valueIFFalse expression if it is possible
Constant condConstant, trueConstant, falseConstant;
if ((condConstant = condition.constant) != Constant.NotAConstant
&& (trueConstant = valueIfTrue.constant) != Constant.NotAConstant
&& (falseConstant = valueIfFalse.constant) != Constant.NotAConstant) {
// all terms are constant expression so we can propagate the constant
// from valueIFTrue or valueIfFalse to the receiver constant
constant = condConstant.booleanValue() ? trueConstant : falseConstant;
}
if (valueIfTrueType == valueIfFalseType) { // harmed the implicit conversion
valueIfTrue.computeConversion(scope, valueIfTrueType, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, valueIfFalseType, originalValueIfFalseType);
if (valueIfTrueType == BooleanBinding) {
this.optimizedIfTrueConstant = valueIfTrue.optimizedBooleanConstant();
this.optimizedIfFalseConstant = valueIfFalse.optimizedBooleanConstant();
if (this.optimizedIfTrueConstant != Constant.NotAConstant
&& this.optimizedIfFalseConstant != Constant.NotAConstant
&& this.optimizedIfTrueConstant.booleanValue() == this.optimizedIfFalseConstant.booleanValue()) {
// a ? true : true / a ? false : false
this.optimizedBooleanConstant = optimizedIfTrueConstant;
} else if ((condConstant = condition.optimizedBooleanConstant()) != Constant.NotAConstant) { // Propagate the optimized boolean constant if possible
this.optimizedBooleanConstant = condConstant.booleanValue()
? this.optimizedIfTrueConstant
: this.optimizedIfFalseConstant;
}
}
return this.resolvedType = valueIfTrueType;
}
// Determine the return type depending on argument types
// Numeric types
if (valueIfTrueType.isNumericType() && valueIfFalseType.isNumericType()) {
// (Short x Byte) or (Byte x Short)"
if ((valueIfTrueType == ByteBinding && valueIfFalseType == ShortBinding)
|| (valueIfTrueType == ShortBinding && valueIfFalseType == ByteBinding)) {
valueIfTrue.computeConversion(scope, ShortBinding, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, ShortBinding, originalValueIfFalseType);
return this.resolvedType = ShortBinding;
}
// <Byte|Short|Char> x constant(Int) ---> <Byte|Short|Char> and reciprocally
if ((valueIfTrueType == ByteBinding || valueIfTrueType == ShortBinding || valueIfTrueType == CharBinding)
&& (valueIfFalseType == IntBinding
&& valueIfFalse.isConstantValueOfTypeAssignableToType(valueIfFalseType, valueIfTrueType))) {
valueIfTrue.computeConversion(scope, valueIfTrueType, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, valueIfTrueType, originalValueIfFalseType);
return this.resolvedType = valueIfTrueType;
}
if ((valueIfFalseType == ByteBinding
|| valueIfFalseType == ShortBinding
|| valueIfFalseType == CharBinding)
&& (valueIfTrueType == IntBinding
&& valueIfTrue.isConstantValueOfTypeAssignableToType(valueIfTrueType, valueIfFalseType))) {
valueIfTrue.computeConversion(scope, valueIfFalseType, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, valueIfFalseType, originalValueIfFalseType);
return this.resolvedType = valueIfFalseType;
}
// Manual binary numeric promotion
// int
if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_int)
&& BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_int)) {
valueIfTrue.computeConversion(scope, IntBinding, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, IntBinding, originalValueIfFalseType);
return this.resolvedType = IntBinding;
}
// long
if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_long)
&& BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_long)) {
valueIfTrue.computeConversion(scope, LongBinding, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, LongBinding, originalValueIfFalseType);
return this.resolvedType = LongBinding;
}
// float
if (BaseTypeBinding.isNarrowing(valueIfTrueType.id, T_float)
&& BaseTypeBinding.isNarrowing(valueIfFalseType.id, T_float)) {
valueIfTrue.computeConversion(scope, FloatBinding, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, FloatBinding, originalValueIfFalseType);
return this.resolvedType = FloatBinding;
}
// double
valueIfTrue.computeConversion(scope, DoubleBinding, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, DoubleBinding, originalValueIfFalseType);
return this.resolvedType = DoubleBinding;
}
// Type references (null null is already tested)
if (valueIfTrueType.isBaseType() && valueIfTrueType != NullBinding) {
if (use15specifics) {
valueIfTrueType = env.computeBoxingType(valueIfTrueType);
} else {
scope.problemReporter().conditionalArgumentsIncompatibleTypes((/*@OwnPar*/ /*@NoRep*/ ConditionalExpression)this, valueIfTrueType, valueIfFalseType);
return null;
}
} else if (valueIfFalseType.isBaseType() && valueIfFalseType != NullBinding) {
if (use15specifics) {
valueIfFalseType = env.computeBoxingType(valueIfFalseType);
} else {
scope.problemReporter().conditionalArgumentsIncompatibleTypes((/*@OwnPar*/ /*@NoRep*/ ConditionalExpression)this, valueIfTrueType, valueIfFalseType);
return null;
}
}
if (use15specifics) {
// >= 1.5 : LUB(operand types) must exist
TypeBinding commonType = null;
if (valueIfTrueType == NullBinding) {
commonType = valueIfFalseType;
} else if (valueIfFalseType == NullBinding) {
commonType = valueIfTrueType;
} else {
commonType = scope.lowerUpperBound(new TypeBinding[] { valueIfTrueType, valueIfFalseType });
}
if (commonType != null) {
valueIfTrue.computeConversion(scope, commonType, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, commonType, originalValueIfFalseType);
return this.resolvedType = commonType.capture(scope, this.sourceEnd);
}
} else {
// < 1.5 : one operand must be convertible to the other
if (valueIfFalseType.isCompatibleWith(valueIfTrueType)) {
valueIfTrue.computeConversion(scope, valueIfTrueType, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, valueIfTrueType, originalValueIfFalseType);
return this.resolvedType = valueIfTrueType;
} else if (valueIfTrueType.isCompatibleWith(valueIfFalseType)) {
valueIfTrue.computeConversion(scope, valueIfFalseType, originalValueIfTrueType);
valueIfFalse.computeConversion(scope, valueIfFalseType, originalValueIfFalseType);
return this.resolvedType = valueIfFalseType;
}
}
scope.problemReporter().conditionalArgumentsIncompatibleTypes(
(/*@OwnPar*/ /*@NoRep*/ ConditionalExpression)this,
valueIfTrueType,
valueIfFalseType);
return null;
}
public void traverse(ASTVisitor visitor, BlockScope scope) {
if (visitor.visit((/*@OwnPar*/ /*@NoRep*/ ConditionalExpression)this, scope)) {
condition.traverse(visitor, scope);
valueIfTrue.traverse(visitor, scope);
valueIfFalse.traverse(visitor, scope);
}
visitor.endVisit((/*@OwnPar*/ /*@NoRep*/ ConditionalExpression)this, scope);
}
}
|
3e1d016b23c6754ed2b9f487617723616618946a | 2,184 | java | Java | src/Program5.0/src/soars/application/simulator/main/Environment.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | null | null | null | src/Program5.0/src/soars/application/simulator/main/Environment.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | null | null | null | src/Program5.0/src/soars/application/simulator/main/Environment.java | degulab/SOARS | 2054c62f53a0027438b99ee26cc03510f04caa63 | [
"MIT"
] | 1 | 2019-03-18T06:22:49.000Z | 2019-03-18T06:22:49.000Z | 19.5 | 96 | 0.631868 | 12,294 | /*
* 2005/01/31
*/
package soars.application.simulator.main;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import soars.common.utility.tool.environment.EnvironmentBase;
/**
* @author kurata
*/
public class Environment extends EnvironmentBase {
/**
*
*/
static public final String _mainWindowRectangleKey = "MainWindow.window.rectangle.";
/**
*
*/
static public final String _logViewerWindowRectangleKey = "LogViewerWindow.window.rectangle.";
/**
*
*/
static public final String _openDirectoryKey = "Directory.open";
/**
*
*/
static public final String _saveAsDirectoryKey = "Directory.save.as";
/**
*
*/
static public final String _exportFilesDirectoryKey = "Directory.export.files";
/**
*
*/
static public final String _fileEditorWindowRectangleKey = "File.editor.rectangle.";
/**
* Key mapped to the position and size of the dialog box to show the warning messages.
*/
static public final String _warningDialog1RectangleKey = "Warning.dialog1.rectangle.";
/**
*
*/
static private Object _lock = new Object();
/**
*
*/
static private Environment _environment = null;
/**
*
*/
static {
try {
startup();
} catch (FileNotFoundException e) {
throw new RuntimeException( e);
} catch (IOException e) {
throw new RuntimeException( e);
}
}
/**
*
*/
private static void startup() throws FileNotFoundException, IOException {
synchronized( _lock) {
if ( null == _environment) {
_environment = new Environment();
if ( !_environment.initialize())
System.exit( 0);
}
}
}
/**
* @return
*/
public static Environment get_instance() {
if ( null == _environment) {
System.exit( 0);
}
return _environment;
}
/**
*
*/
public Environment() {
super(
System.getProperty( Constant._soarsProperty) + File.separator
+ "program" + File.separator
+ "simulator" + File.separator
+ "environment" + File.separator,
"environment.properties",
"SOARS Simulator properties");
}
}
|
3e1d03eb74137e87654c7a0d96688d0d49e0692c | 12,082 | java | Java | app/src/main/java/ch/yannick/display/activityPlay/Frag_PlayControl.java | YannickWidmer/SSE_app | aa34392621450822855668fe942acaac9414c512 | [
"CC0-1.0"
] | 1 | 2016-04-01T16:20:33.000Z | 2016-04-01T16:20:33.000Z | app/src/main/java/ch/yannick/display/activityPlay/Frag_PlayControl.java | YannickWidmer/SSE_app | aa34392621450822855668fe942acaac9414c512 | [
"CC0-1.0"
] | null | null | null | app/src/main/java/ch/yannick/display/activityPlay/Frag_PlayControl.java | YannickWidmer/SSE_app | aa34392621450822855668fe942acaac9414c512 | [
"CC0-1.0"
] | null | null | null | 41.662069 | 146 | 0.62829 | 12,295 | package ch.yannick.display.activityPlay;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import ch.yannick.context.R;
import ch.yannick.context.RootApplication;
import ch.yannick.display.activityMental.Act_Mental;
import ch.yannick.display.activityMental.Vector;
import ch.yannick.display.technical.AdapterColored;
import ch.yannick.display.technical.ColoredHolder;
import ch.yannick.display.views.JaugeView;
import ch.yannick.intern.action_talent.Action;
import ch.yannick.intern.personnage.HitZone;
import ch.yannick.intern.personnage.Limb;
import ch.yannick.intern.state.State;
import ch.yannick.intern.usables.UsableType;
import ch.yannick.intern.usables.Weapon;
public class Frag_PlayControl extends Fragment {
private static final String LOG = "frag:Control";
private static final int act_end = 0, new_round = 3, mental = 4, hit = 5;
private State st;
private JaugeView healthJauge, staminaJauge;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(LOG, "onCreateView");
st = ((RootApplication)getActivity().getApplication()).getCurrentState();
setHasOptionsMenu(true);
return inflater.inflate(R.layout.frag_play_control, container, false);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_play_control, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(LOG, "onActivityCreated");
getActivity().setTitle(st.getName());
View v = getView();
healthJauge = (JaugeView) v.findViewById(R.id.vie);
staminaJauge = (JaugeView) v.findViewById(R.id.endurance);
healthJauge.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplication(), Dialog_health.class);
intent.putExtra("id", st.getId());
startActivityForResult(intent, R.id.health);
}
});
staminaJauge.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity().getApplication(), Dialog_stamina.class);
intent.putExtra("id",st.getId());
startActivityForResult(intent, R.id.stamina);
}
});
v.findViewById(R.id.act).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
act();
}
});
v.findViewById(R.id.takehit).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
hit();
}
});
refresh();
}
// Accesed by the Button hit. This opens the Dialog where the player can enter the damage he got and where he was hit, such that
// the effective damage is calculated and then removed from the health bar.
private void hit() {
Intent intent = new Intent(getActivity().getApplication(), Dialog_hit.class);
startActivityForResult(intent,hit);
}
/* This is accesed via the act and react buttons, this is what the player will do every time when its his turn or he has the ocasion to react.
* The possible actions are displayed, those which from the State object should not be allowed are grayed out but still
* clickable if for some reason the master should still allow these actions.
* Once the action is chosen the method act(action,react) is called.
*/
private void act() {
if(st.canAct(0)){
List<ColoredHolder<Action>> actionsColored = new ArrayList<>();
for(Action action:st.getActions(Limb.ALL)){
actionsColored.add(new ColoredHolder<Action>(action, action.getStringId(),
st.canAct(action, Limb.ALL) ? R.color.white : R.color.grey));
Log.d(LOG,action.getName() +" canAct "+st.canAct(action, Limb.ALL));
}
final AdapterColored<Action> actionAdapter = new AdapterColored<Action>(getActivity(),actionsColored);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.act);
builder.setSingleChoiceItems(actionAdapter, 1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
Action action = actionAdapter.getItem(position).getObject();
act(action);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}else{
toTired();
}
}
/* This method is called when act(reaction) is called and an action is chosen. This method first check if the action can only
* be acomplished with one weapon or if there is a choice. In case there are multiple posiibilities it opens a list dialog with the different
* choices, the choices which should not be possible considering the State are greeyed out but still clickable in case the master should
* still allow these. Once the choice is made the method fatigue is called.
*/
private void act(final Action act){
final List<ColoredHolder<Limb>> coloredPossiblities = new ArrayList<>();
for(Limb limb:Limb.values()){
if(st.hasUsable(limb) && st.getActions(limb).contains(act)){
coloredPossiblities.add(new ColoredHolder<>(limb,limb.getStringId(),
st.canAct(act, limb)?R.color.white:R.color.grey));
}
}
if(coloredPossiblities.size()>1){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.act);
AdapterColored<Limb> adapterColored = new AdapterColored<Limb>(getActivity(),coloredPossiblities);
builder.setSingleChoiceItems(adapterColored, 1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
fatigue(coloredPossiblities.get(position).getObject(),act);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
refresh();
dialog.dismiss();
}
});
builder.create().show();
}else
fatigue(coloredPossiblities.get(0).getObject(),act);
}
/* This method is the last of the three methods when act is triggered. This method opens the fatigue dialog such that the player might
* adjust the fatigue for this action or reaction, most of the time he shoud just click ok. Further more this method also makes changes
* which might arrise from the action. This is change the load state of a range weapon,
*/
private void fatigue(Limb which, Action action){
if(st.getUsable(which).getTyp() == UsableType.CROSSBOW && action.is("Shoot"))
((Weapon)st.getUsable(which)).setLoad(false);
if(st.getUsable(which).getTyp() == UsableType.CROSSBOW && action == Action.valueOf("LOADING"))
((Weapon)st.getUsable(which)).setLoad(true);
Intent intent;
intent = new Intent(getActivity().getApplication(), Dialog_fatigue.class);
intent.putExtra("id",st.getId());
intent.putExtra("which",which.name());
intent.putExtra("action",action.getName());
startActivityForResult(intent,act_end);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.arsenal:
intent = new Intent(getActivity().getApplication(), Act_Equipement.class);
intent.putExtra("id", st.getId());
startActivityForResult(intent, R.id.arsenal);
return true;
case R.id.next_round:
intent = new Intent(getActivity().getApplication(), Act_Mental.class);
intent.putExtra("State", st.getId());
startActivityForResult(intent, mental);
return true;
case R.id.stamina:
intent = new Intent(getActivity().getApplication(), Dialog_stamina.class);
intent.putExtra("id",st.getId());
startActivityForResult(intent, R.id.stamina);
return true;
case R.id.health:
intent = new Intent(getActivity().getApplication(), Dialog_health.class);
intent.putExtra("id",st.getId());
startActivityForResult(intent, R.id.health);
return true;
case R.id.reset_mental:
st.setMentalState(new Vector(0,0));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Result from Dialogs
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
switch(requestCode) {
case hit:
Log.d(LOG, "bodyPart " + data.getIntExtra("bodyPart", -1)
+ " hit " + data.getIntExtra("hit", 0)
+ " direct " + data.getBooleanExtra("direct", false)
+ " pierce " + data.getIntExtra("pierce", 0));
HitZone hitZone = HitZone.valueOf(data.getStringExtra("bodyPart"));
int hit = data.getIntExtra("hit", 0);
int pierce = data.getIntExtra("pierce", 0);
boolean direct = data.getBooleanExtra("direct", false);
st.takeHit(hitZone, hit, pierce, direct);
break;
case act_end:
if (!st.act(data.getIntExtra("fatigue", 0)))
toTired();
break;
case mental:
Intent intent = new Intent(getActivity().getApplication(), Dialog_fatigue.class);
intent.putExtra("id", st.getId());
intent.putExtra("stamina",0);
startActivityForResult(intent, new_round);
break;
case new_round:
st.newRound();
if (!st.act(data.getIntExtra("fatigue", 0)))
toTired();
break;
}
}
refresh();
}
protected void refresh(){
healthJauge.setValues(st.getHealth(), 0, st.getHealthMax() - st.getHealth());
staminaJauge.setValues(st.getStaminaNow(), 0,
st.getStaminaMax() - st.getStaminaNow());
((TextView) getView().findViewById(R.id.mental_state)).setText(st.getMentalState().getStringId());
((TextView) getView().findViewById(R.id.race)).setText(st.getRace().getStringId());
}
private void toTired(){
Toast.makeText(getActivity(),R.string.to_tired,Toast.LENGTH_SHORT).show();
}
}
|
3e1d04bd296bd017bf3db3c9358b103d4c1d83e3 | 4,055 | java | Java | src/main/java/cn/yuan/blog/domain/BaseBlog.java | yuanjs2019/yn-manage-system | 390a585919ddcc56d5ac651060f977b59bcfc3be | [
"Apache-2.0"
] | 2 | 2020-11-28T01:50:02.000Z | 2021-06-24T07:32:54.000Z | src/main/java/cn/yuan/blog/domain/BaseBlog.java | yuanjs2019/yn-manage-system | 390a585919ddcc56d5ac651060f977b59bcfc3be | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/yuan/blog/domain/BaseBlog.java | yuanjs2019/yn-manage-system | 390a585919ddcc56d5ac651060f977b59bcfc3be | [
"Apache-2.0"
] | 1 | 2020-11-28T09:21:31.000Z | 2020-11-28T09:21:31.000Z | 18.515982 | 52 | 0.582244 | 12,296 | package cn.yuan.blog.domain;
import cn.yuan.common.annotation.ExportConfig;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 实体对象BLOG.
*
* @author yjs
* @since 2020-10-26
*/
@Table(name = "blog")
public class BaseBlog implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "JDBC")
@Column(name = "id")
@ExportConfig(value = "主键id")
private Long id;
/**
* 文章标题
*/
@Column(name = "title")
@ExportConfig(value = "文章标题")
private String title;
/**
* 文章描述
*/
@Column(name = "description")
@ExportConfig(value = "文章描述")
private String description;
/**
* 内容md格式
*/
@Column(name = "text_content")
@ExportConfig(value = "内容md格式")
private String textContent;
/**
* 内容(带有样式)
*/
@Column(name = "content")
@ExportConfig(value = "内容(带有样式)")
private String content;
/**
* 文章头图片
*/
@Column(name = "main_picture")
@ExportConfig(value = "文章头图片")
private String mainPicture;
/**
* 作者
*/
@Column(name = "author")
@ExportConfig(value = "作者")
private String author;
/**
* 系列code
*/
@Column(name = "series_code")
@ExportConfig(value = "系列code")
private String seriesCode;
/**
* 文章类型:1-转载,2-原创
*/
@Column(name = "type")
@ExportConfig(value = "文章类型:1-转载,2-原创")
private Integer type;
/**
* 年份
*/
@Column(name = "year")
@ExportConfig(value = "年份")
private Integer year;
/**
* 月份
*/
@Column(name = "month")
@ExportConfig(value = "月份")
private Integer month;
/**
* 创建时间
*/
@Column(name = "create_time")
@ExportConfig(value = "创建时间")
private Date createTime;
/**
* 更新时间
*/
@Column(name = "update_time")
@ExportConfig(value = "更新时间")
private Date updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getMainPicture() {
return mainPicture;
}
public void setMainPicture(String mainPicture) {
this.mainPicture = mainPicture;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSeriesCode() {
return seriesCode;
}
public void setSeriesCode(String seriesCode) {
this.seriesCode = seriesCode;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getMonth() {
return month;
}
public void setMonth(Integer month) {
this.month = month;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
|
3e1d052c7e5135aa1348adb3464bd09b976a08ce | 300 | java | Java | src/com/mobileread/ixtab/jbpatch/ui/kindlet/JBPatchJailbreak.java | kuthulux/jbpatcher | 15fe2a903f0d6030b610154e5ad6bffbf7394c4d | [
"WTFPL"
] | null | null | null | src/com/mobileread/ixtab/jbpatch/ui/kindlet/JBPatchJailbreak.java | kuthulux/jbpatcher | 15fe2a903f0d6030b610154e5ad6bffbf7394c4d | [
"WTFPL"
] | 1 | 2021-12-04T14:43:48.000Z | 2021-12-12T09:58:43.000Z | src/com/mobileread/ixtab/jbpatch/ui/kindlet/JBPatchJailbreak.java | kuthulux/jbpatcher | 15fe2a903f0d6030b610154e5ad6bffbf7394c4d | [
"WTFPL"
] | null | null | null | 20 | 68 | 0.783333 | 12,297 | package com.mobileread.ixtab.jbpatch.ui.kindlet;
import ixtab.jailbreak.Jailbreak;
import java.security.AllPermission;
public class JBPatchJailbreak extends Jailbreak {
public boolean requestPermissions() {
boolean ok = getContext().requestPermission(new AllPermission());
return ok;
}
}
|
3e1d05417e94a938bf251f1022870568c9ed3049 | 3,650 | java | Java | src/main/java/uk/co/claritysoftware/alexa/skills/kit/test/hamcrest/SsmlOutputSpeechMatcher.java | ClaritySoftwareSolutions/alexa-skills-kit-test | 8630d7e294a4487b38d7d62833b5477d71cefd09 | [
"MIT"
] | 1 | 2018-07-23T18:23:47.000Z | 2018-07-23T18:23:47.000Z | src/main/java/uk/co/claritysoftware/alexa/skills/kit/test/hamcrest/SsmlOutputSpeechMatcher.java | ClaritySoftwareSolutions/alexa-skills-kit-test | 8630d7e294a4487b38d7d62833b5477d71cefd09 | [
"MIT"
] | null | null | null | src/main/java/uk/co/claritysoftware/alexa/skills/kit/test/hamcrest/SsmlOutputSpeechMatcher.java | ClaritySoftwareSolutions/alexa-skills-kit-test | 8630d7e294a4487b38d7d62833b5477d71cefd09 | [
"MIT"
] | null | null | null | 32.300885 | 170 | 0.768493 | 12,298 | package uk.co.claritysoftware.alexa.skills.kit.test.hamcrest;
import static java.lang.String.format;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import com.amazon.speech.ui.SsmlOutputSpeech;
/**
* Hamcrest matchers for making assertions on a {@link SsmlOutputSpeech}
*/
public class SsmlOutputSpeechMatcher {
private SsmlOutputSpeechMatcher() {
}
/**
* Returns a {@link SsmlOutputSpeechSsmlMatcher} to assert the ssml content of the {@link SsmlOutputSpeech}
*
* @param expectedSpeechSsml the ssml that the {@link SsmlOutputSpeech} is expected to have
* @return the SsmlOutputSpeechSsmlMatcher
*/
public static SsmlOutputSpeechSsmlMatcher hasSsml(String expectedSpeechSsml) {
return new SsmlOutputSpeechSsmlMatcher(expectedSpeechSsml);
}
/**
* Returns a {@link SsmlOutputSpeechPatternMatcher} to assert that ssml content of the {@link SsmlOutputSpeech}
*
* @param expectedSpeechSsmlPattern the pattern that the {@link SsmlOutputSpeech}'s ssml is expected to match
* @return the SsmlOutputSpeechPatternMatcher
*/
public static SsmlOutputSpeechPatternMatcher hasSsml(Pattern expectedSpeechSsmlPattern) {
return new SsmlOutputSpeechPatternMatcher(expectedSpeechSsmlPattern);
}
/**
* Hamcrest matcher for asserting {@link SsmlOutputSpeech} has the specified speech ssml
*/
static class SsmlOutputSpeechSsmlMatcher extends TypeSafeDiagnosingMatcher<SsmlOutputSpeech> {
private final String expectedSpeechSsml;
private SsmlOutputSpeechSsmlMatcher(String expectedSpeechSsml) {
this.expectedSpeechSsml = expectedSpeechSsml;
}
@Override
protected boolean matchesSafely(SsmlOutputSpeech ssmlOutputSpeech, Description description) {
String actualSpeechSsml = ssmlOutputSpeech.getSsml();
if (actualSpeechSsml == null && expectedSpeechSsml == null) {
return true;
}
if (actualSpeechSsml == null && expectedSpeechSsml != null || !actualSpeechSsml.equals(expectedSpeechSsml)) {
description.appendText(format("was <%s>", actualSpeechSsml));
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText(format("Expected SsmlOutputSpeech to have ssml of <%s>", expectedSpeechSsml));
}
}
/**
* Hamcrest matcher for asserting the {@link SsmlOutputSpeech} ssml matches the specified pattern
*/
static class SsmlOutputSpeechPatternMatcher extends TypeSafeDiagnosingMatcher<SsmlOutputSpeech> {
private final Pattern expectedSpeechSsmlPattern;
private SsmlOutputSpeechPatternMatcher(Pattern expectedSpeechSsmlPattern) {
this.expectedSpeechSsmlPattern = expectedSpeechSsmlPattern;
}
@Override
protected boolean matchesSafely(SsmlOutputSpeech ssmlOutputSpeech, Description description) {
String actualSpeechSsml = ssmlOutputSpeech.getSsml();
if (actualSpeechSsml == null && expectedSpeechSsmlPattern == null) {
return true;
}
if (expectedSpeechSsmlPattern == null) {
description.appendText(format("was <%s>", actualSpeechSsml));
return false;
}
Matcher matcher = expectedSpeechSsmlPattern.matcher(actualSpeechSsml != null ? actualSpeechSsml : "");
if (actualSpeechSsml == null || !matcher.find()) {
description.appendText(format("was <%s>", actualSpeechSsml));
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText(format("Expected SsmlOutputSpeech to match ssml pattern <%s>", expectedSpeechSsmlPattern != null ? expectedSpeechSsmlPattern.pattern() : null));
}
}
}
|
3e1d05dba5ef7c01fa0b2ad5940c016d4dcfef3e | 24,986 | java | Java | de.fhdo.lemma.servicedsl/src-gen/de/fhdo/lemma/serializer/ServiceDslSemanticSequencer.java | SeelabFhdo/lemma | 080573ccc051defe591b76e64a4e7f940bf147d5 | [
"MIT"
] | 18 | 2019-08-28T13:16:01.000Z | 2022-02-09T01:17:09.000Z | de.fhdo.lemma.servicedsl/src-gen/de/fhdo/lemma/serializer/ServiceDslSemanticSequencer.java | SeelabFhdo/lemma | 080573ccc051defe591b76e64a4e7f940bf147d5 | [
"MIT"
] | 36 | 2019-08-27T12:34:49.000Z | 2022-03-07T19:02:50.000Z | de.fhdo.lemma.servicedsl/src-gen/de/fhdo/lemma/serializer/ServiceDslSemanticSequencer.java | SeelabFhdo/lemma | 080573ccc051defe591b76e64a4e7f940bf147d5 | [
"MIT"
] | 2 | 2019-09-26T12:30:22.000Z | 2019-12-13T03:17:39.000Z | 41.095395 | 175 | 0.781117 | 12,299 | /*
* generated by Xtext 2.25.0
*/
package de.fhdo.lemma.serializer;
import com.google.inject.Inject;
import de.fhdo.lemma.data.ComplexTypeImport;
import de.fhdo.lemma.data.Context;
import de.fhdo.lemma.data.DataField;
import de.fhdo.lemma.data.DataModel;
import de.fhdo.lemma.data.DataOperation;
import de.fhdo.lemma.data.DataOperationParameter;
import de.fhdo.lemma.data.DataPackage;
import de.fhdo.lemma.data.DataStructure;
import de.fhdo.lemma.data.Enumeration;
import de.fhdo.lemma.data.EnumerationField;
import de.fhdo.lemma.data.ImportedComplexType;
import de.fhdo.lemma.data.ListType;
import de.fhdo.lemma.data.PrimitiveBoolean;
import de.fhdo.lemma.data.PrimitiveByte;
import de.fhdo.lemma.data.PrimitiveCharacter;
import de.fhdo.lemma.data.PrimitiveDate;
import de.fhdo.lemma.data.PrimitiveDouble;
import de.fhdo.lemma.data.PrimitiveFloat;
import de.fhdo.lemma.data.PrimitiveInteger;
import de.fhdo.lemma.data.PrimitiveLong;
import de.fhdo.lemma.data.PrimitiveShort;
import de.fhdo.lemma.data.PrimitiveString;
import de.fhdo.lemma.data.PrimitiveUnspecified;
import de.fhdo.lemma.data.PrimitiveValue;
import de.fhdo.lemma.data.Version;
import de.fhdo.lemma.service.ApiOperationComment;
import de.fhdo.lemma.service.ApiParameterComment;
import de.fhdo.lemma.service.Endpoint;
import de.fhdo.lemma.service.Import;
import de.fhdo.lemma.service.ImportedProtocolAndDataFormat;
import de.fhdo.lemma.service.ImportedServiceAspect;
import de.fhdo.lemma.service.ImportedType;
import de.fhdo.lemma.service.Interface;
import de.fhdo.lemma.service.Microservice;
import de.fhdo.lemma.service.Operation;
import de.fhdo.lemma.service.PossiblyImportedInterface;
import de.fhdo.lemma.service.PossiblyImportedMicroservice;
import de.fhdo.lemma.service.PossiblyImportedOperation;
import de.fhdo.lemma.service.ProtocolSpecification;
import de.fhdo.lemma.service.ReferredOperation;
import de.fhdo.lemma.service.ServiceModel;
import de.fhdo.lemma.service.ServicePackage;
import de.fhdo.lemma.service.TechnologyReference;
import de.fhdo.lemma.services.ServiceDslGrammarAccess;
import de.fhdo.lemma.technology.CompatibilityMatrixEntry;
import de.fhdo.lemma.technology.DataFormat;
import de.fhdo.lemma.technology.DeploymentTechnology;
import de.fhdo.lemma.technology.InfrastructureTechnology;
import de.fhdo.lemma.technology.OperationAspect;
import de.fhdo.lemma.technology.OperationAspectPointcut;
import de.fhdo.lemma.technology.OperationAspectPointcutSelector;
import de.fhdo.lemma.technology.OperationEnvironment;
import de.fhdo.lemma.technology.PossiblyImportedTechnologySpecificType;
import de.fhdo.lemma.technology.Protocol;
import de.fhdo.lemma.technology.ServiceAspect;
import de.fhdo.lemma.technology.ServiceAspectPointcut;
import de.fhdo.lemma.technology.ServiceAspectPointcutSelector;
import de.fhdo.lemma.technology.Technology;
import de.fhdo.lemma.technology.TechnologyImport;
import de.fhdo.lemma.technology.TechnologyPackage;
import de.fhdo.lemma.technology.TechnologySpecificDataStructure;
import de.fhdo.lemma.technology.TechnologySpecificListType;
import de.fhdo.lemma.technology.TechnologySpecificPrimitiveType;
import de.fhdo.lemma.technology.TechnologySpecificProperty;
import de.fhdo.lemma.technology.TechnologySpecificPropertyValueAssignment;
import de.fhdo.lemma.technology.serializer.TechnologyDslSemanticSequencer;
import java.util.Set;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.xtext.Action;
import org.eclipse.xtext.Parameter;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.serializer.ISerializationContext;
import org.eclipse.xtext.serializer.acceptor.SequenceFeeder;
import org.eclipse.xtext.serializer.sequencer.ITransientValueService.ValueTransient;
@SuppressWarnings("all")
public class ServiceDslSemanticSequencer extends TechnologyDslSemanticSequencer {
@Inject
private ServiceDslGrammarAccess grammarAccess;
@Override
public void sequence(ISerializationContext context, EObject semanticObject) {
EPackage epackage = semanticObject.eClass().getEPackage();
ParserRule rule = context.getParserRule();
Action action = context.getAssignedAction();
Set<Parameter> parameters = context.getEnabledBooleanParameters();
if (epackage == DataPackage.eINSTANCE)
switch (semanticObject.eClass().getClassifierID()) {
case DataPackage.COMPLEX_TYPE_IMPORT:
sequence_ComplexTypeImport(context, (ComplexTypeImport) semanticObject);
return;
case DataPackage.CONTEXT:
sequence_Context(context, (Context) semanticObject);
return;
case DataPackage.DATA_FIELD:
sequence_DataField(context, (DataField) semanticObject);
return;
case DataPackage.DATA_MODEL:
sequence_DataModel(context, (DataModel) semanticObject);
return;
case DataPackage.DATA_OPERATION:
sequence_DataOperation(context, (DataOperation) semanticObject);
return;
case DataPackage.DATA_OPERATION_PARAMETER:
sequence_DataOperationParameter(context, (DataOperationParameter) semanticObject);
return;
case DataPackage.DATA_STRUCTURE:
sequence_DataStructure(context, (DataStructure) semanticObject);
return;
case DataPackage.ENUMERATION:
sequence_Enumeration(context, (Enumeration) semanticObject);
return;
case DataPackage.ENUMERATION_FIELD:
sequence_EnumerationField(context, (EnumerationField) semanticObject);
return;
case DataPackage.IMPORTED_COMPLEX_TYPE:
sequence_ImportedComplexType(context, (ImportedComplexType) semanticObject);
return;
case DataPackage.LIST_TYPE:
sequence_ListType(context, (ListType) semanticObject);
return;
case DataPackage.PRIMITIVE_BOOLEAN:
sequence_PrimitiveType(context, (PrimitiveBoolean) semanticObject);
return;
case DataPackage.PRIMITIVE_BYTE:
sequence_PrimitiveType(context, (PrimitiveByte) semanticObject);
return;
case DataPackage.PRIMITIVE_CHARACTER:
sequence_PrimitiveType(context, (PrimitiveCharacter) semanticObject);
return;
case DataPackage.PRIMITIVE_DATE:
sequence_PrimitiveType(context, (PrimitiveDate) semanticObject);
return;
case DataPackage.PRIMITIVE_DOUBLE:
sequence_PrimitiveType(context, (PrimitiveDouble) semanticObject);
return;
case DataPackage.PRIMITIVE_FLOAT:
sequence_PrimitiveType(context, (PrimitiveFloat) semanticObject);
return;
case DataPackage.PRIMITIVE_INTEGER:
sequence_PrimitiveType(context, (PrimitiveInteger) semanticObject);
return;
case DataPackage.PRIMITIVE_LONG:
sequence_PrimitiveType(context, (PrimitiveLong) semanticObject);
return;
case DataPackage.PRIMITIVE_SHORT:
sequence_PrimitiveType(context, (PrimitiveShort) semanticObject);
return;
case DataPackage.PRIMITIVE_STRING:
sequence_PrimitiveType(context, (PrimitiveString) semanticObject);
return;
case DataPackage.PRIMITIVE_UNSPECIFIED:
sequence_PrimitiveType(context, (PrimitiveUnspecified) semanticObject);
return;
case DataPackage.PRIMITIVE_VALUE:
sequence_PrimitiveValue(context, (PrimitiveValue) semanticObject);
return;
case DataPackage.VERSION:
sequence_Version(context, (Version) semanticObject);
return;
}
else if (epackage == ServicePackage.eINSTANCE)
switch (semanticObject.eClass().getClassifierID()) {
case ServicePackage.API_OPERATION_COMMENT:
sequence_ApiOperationComment(context, (ApiOperationComment) semanticObject);
return;
case ServicePackage.API_PARAMETER_COMMENT:
sequence_ApiParameterComment(context, (ApiParameterComment) semanticObject);
return;
case ServicePackage.ENDPOINT:
sequence_Endpoint(context, (Endpoint) semanticObject);
return;
case ServicePackage.IMPORT:
sequence_Import(context, (Import) semanticObject);
return;
case ServicePackage.IMPORTED_PROTOCOL_AND_DATA_FORMAT:
sequence_ImportedProtocolAndDataFormat(context, (ImportedProtocolAndDataFormat) semanticObject);
return;
case ServicePackage.IMPORTED_SERVICE_ASPECT:
sequence_ImportedServiceAspect(context, (ImportedServiceAspect) semanticObject);
return;
case ServicePackage.IMPORTED_TYPE:
sequence_ImportedType(context, (ImportedType) semanticObject);
return;
case ServicePackage.INTERFACE:
sequence_Interface(context, (Interface) semanticObject);
return;
case ServicePackage.MICROSERVICE:
sequence_Microservice(context, (Microservice) semanticObject);
return;
case ServicePackage.OPERATION:
sequence_Operation(context, (Operation) semanticObject);
return;
case ServicePackage.PARAMETER:
sequence_Parameter(context, (de.fhdo.lemma.service.Parameter) semanticObject);
return;
case ServicePackage.POSSIBLY_IMPORTED_INTERFACE:
sequence_PossiblyImportedInterface(context, (PossiblyImportedInterface) semanticObject);
return;
case ServicePackage.POSSIBLY_IMPORTED_MICROSERVICE:
sequence_PossiblyImportedMicroservice(context, (PossiblyImportedMicroservice) semanticObject);
return;
case ServicePackage.POSSIBLY_IMPORTED_OPERATION:
sequence_PossiblyImportedOperation(context, (PossiblyImportedOperation) semanticObject);
return;
case ServicePackage.PROTOCOL_SPECIFICATION:
sequence_ProtocolSpecification(context, (ProtocolSpecification) semanticObject);
return;
case ServicePackage.REFERRED_OPERATION:
sequence_ReferredOperation(context, (ReferredOperation) semanticObject);
return;
case ServicePackage.SERVICE_MODEL:
sequence_ServiceModel(context, (ServiceModel) semanticObject);
return;
case ServicePackage.TECHNOLOGY_REFERENCE:
sequence_TechnologyReference(context, (TechnologyReference) semanticObject);
return;
}
else if (epackage == TechnologyPackage.eINSTANCE)
switch (semanticObject.eClass().getClassifierID()) {
case TechnologyPackage.COMPATIBILITY_MATRIX_ENTRY:
sequence_CompatibilityMatrixEntry(context, (CompatibilityMatrixEntry) semanticObject);
return;
case TechnologyPackage.DATA_FORMAT:
sequence_DataFormat(context, (DataFormat) semanticObject);
return;
case TechnologyPackage.DEPLOYMENT_TECHNOLOGY:
sequence_DeploymentTechnology(context, (DeploymentTechnology) semanticObject);
return;
case TechnologyPackage.INFRASTRUCTURE_TECHNOLOGY:
sequence_InfrastructureTechnology(context, (InfrastructureTechnology) semanticObject);
return;
case TechnologyPackage.OPERATION_ASPECT:
sequence_OperationAspect(context, (OperationAspect) semanticObject);
return;
case TechnologyPackage.OPERATION_ASPECT_POINTCUT:
sequence_OperationAspectPointcut(context, (OperationAspectPointcut) semanticObject);
return;
case TechnologyPackage.OPERATION_ASPECT_POINTCUT_SELECTOR:
sequence_OperationAspectPointcutSelector(context, (OperationAspectPointcutSelector) semanticObject);
return;
case TechnologyPackage.OPERATION_ENVIRONMENT:
sequence_OperationEnvironment(context, (OperationEnvironment) semanticObject);
return;
case TechnologyPackage.POSSIBLY_IMPORTED_TECHNOLOGY_SPECIFIC_TYPE:
sequence_PossiblyImportedTechnologySpecificType(context, (PossiblyImportedTechnologySpecificType) semanticObject);
return;
case TechnologyPackage.PROTOCOL:
sequence_Protocol(context, (Protocol) semanticObject);
return;
case TechnologyPackage.SERVICE_ASPECT:
sequence_ServiceAspect(context, (ServiceAspect) semanticObject);
return;
case TechnologyPackage.SERVICE_ASPECT_POINTCUT:
sequence_ServiceAspectPointcut(context, (ServiceAspectPointcut) semanticObject);
return;
case TechnologyPackage.SERVICE_ASPECT_POINTCUT_SELECTOR:
sequence_ServiceAspectPointcutSelector(context, (ServiceAspectPointcutSelector) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY:
sequence_Technology(context, (Technology) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY_IMPORT:
sequence_TechnologyImport(context, (TechnologyImport) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY_SPECIFIC_DATA_STRUCTURE:
sequence_TechnologySpecificDataStructure(context, (TechnologySpecificDataStructure) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY_SPECIFIC_LIST_TYPE:
sequence_TechnologySpecificListType(context, (TechnologySpecificListType) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY_SPECIFIC_PRIMITIVE_TYPE:
sequence_TechnologySpecificPrimitiveType(context, (TechnologySpecificPrimitiveType) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY_SPECIFIC_PROPERTY:
sequence_TechnologySpecificProperty(context, (TechnologySpecificProperty) semanticObject);
return;
case TechnologyPackage.TECHNOLOGY_SPECIFIC_PROPERTY_VALUE_ASSIGNMENT:
sequence_PropertyValueAssignment(context, (TechnologySpecificPropertyValueAssignment) semanticObject);
return;
}
if (errorAcceptor != null)
errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context));
}
/**
* Contexts:
* ApiOperationComment returns ApiOperationComment
*
* Constraint:
* (comment=Anything parameterComments+=ApiParameterComment*)
*/
protected void sequence_ApiOperationComment(ISerializationContext context, ApiOperationComment semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* ApiParameterComment returns ApiParameterComment
*
* Constraint:
* (required?='@required'? parameter=[Parameter|ID] comment=Anything)
*/
protected void sequence_ApiParameterComment(ISerializationContext context, ApiParameterComment semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* Endpoint returns Endpoint
*
* Constraint:
* (protocols+=ImportedProtocolAndDataFormat protocols+=ImportedProtocolAndDataFormat* addresses+=STRING addresses+=STRING*)
*/
protected void sequence_Endpoint(ISerializationContext context, Endpoint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* Import returns Import
*
* Constraint:
* (importType=ImportType importURI=STRING name=ID)
*/
protected void sequence_Import(ISerializationContext context, Import semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.IMPORT__IMPORT_TYPE) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.IMPORT__IMPORT_TYPE));
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.IMPORT__IMPORT_URI) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.IMPORT__IMPORT_URI));
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.IMPORT__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.IMPORT__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getImportAccess().getImportTypeImportTypeEnumRuleCall_1_0(), semanticObject.getImportType());
feeder.accept(grammarAccess.getImportAccess().getImportURISTRINGTerminalRuleCall_3_0(), semanticObject.getImportURI());
feeder.accept(grammarAccess.getImportAccess().getNameIDTerminalRuleCall_5_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* ImportedProtocolAndDataFormat returns ImportedProtocolAndDataFormat
*
* Constraint:
* (import=[Import|ID] importedProtocol=[Protocol|QualifiedName] dataFormat=[DataFormat|STRING]?)
*/
protected void sequence_ImportedProtocolAndDataFormat(ISerializationContext context, ImportedProtocolAndDataFormat semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* ImportedServiceAspect returns ImportedServiceAspect
*
* Constraint:
* (
* import=[Import|ID]
* importedAspect=[ServiceAspect|QualifiedName]
* (singlePropertyValue=PrimitiveValue | (values+=PropertyValueAssignment values+=PropertyValueAssignment*))?
* )
*/
protected void sequence_ImportedServiceAspect(ISerializationContext context, ImportedServiceAspect semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* ImportedType returns ImportedType
*
* Constraint:
* (import=[Import|ID] type=[Type|QualifiedName])
*/
protected void sequence_ImportedType(ISerializationContext context, ImportedType semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.IMPORTED_TYPE__IMPORT) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.IMPORTED_TYPE__IMPORT));
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.IMPORTED_TYPE__TYPE) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.IMPORTED_TYPE__TYPE));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getImportedTypeAccess().getImportImportIDTerminalRuleCall_0_0_1(), semanticObject.eGet(ServicePackage.Literals.IMPORTED_TYPE__IMPORT, false));
feeder.accept(grammarAccess.getImportedTypeAccess().getTypeTypeQualifiedNameParserRuleCall_2_0_1(), semanticObject.eGet(ServicePackage.Literals.IMPORTED_TYPE__TYPE, false));
feeder.finish();
}
/**
* Contexts:
* Interface returns Interface
*
* Constraint:
* (
* (protocols+=ProtocolSpecification protocols+=ProtocolSpecification?)?
* endpoints+=Endpoint*
* endpoints+=Endpoint*
* aspects+=ImportedServiceAspect*
* notImplemented?='noimpl'?
* visibility=Visibility?
* name=ID
* version=ID?
* referredOperations+=ReferredOperation*
* operations+=Operation*
* )
*/
protected void sequence_Interface(ISerializationContext context, Interface semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* Microservice returns Microservice
*
* Constraint:
* (
* technologyReferences+=TechnologyReference*
* (protocols+=ProtocolSpecification protocols+=ProtocolSpecification?)?
* endpoints+=Endpoint*
* endpoints+=Endpoint*
* aspects+=ImportedServiceAspect*
* visibility=Visibility?
* type=MicroserviceType
* name=QualifiedNameWithAtLeastOneLevel
* version=ID?
* (requiredMicroservices+=PossiblyImportedMicroservice requiredMicroservices+=PossiblyImportedMicroservice*)?
* (requiredInterfaces+=PossiblyImportedInterface requiredInterfaces+=PossiblyImportedInterface*)?
* (requiredOperations+=PossiblyImportedOperation requiredOperations+=PossiblyImportedOperation*)?
* interfaces+=Interface+
* )
*/
protected void sequence_Microservice(ISerializationContext context, Microservice semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* Operation returns Operation
*
* Constraint:
* (
* apiOperationComment=ApiOperationComment?
* (protocols+=ProtocolSpecification protocols+=ProtocolSpecification?)?
* endpoints+=Endpoint*
* endpoints+=Endpoint*
* aspects+=ImportedServiceAspect*
* notImplemented?='noimpl'?
* visibility=Visibility?
* name=ID
* parameters+=Parameter?
* parameters+=Parameter*
* )
*/
protected void sequence_Operation(ISerializationContext context, Operation semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* Parameter returns Parameter
*
* Constraint:
* (
* aspects+=ImportedServiceAspect*
* communicationType=CommunicationType
* exchangePattern=ExchangePattern?
* communicatesFault?='fault'?
* name=ID
* optional?='?'?
* (primitiveType=PrimitiveType | importedType=ImportedType)
* initializedByOperation=PossiblyImportedOperation?
* )
*/
protected void sequence_Parameter(ISerializationContext context, de.fhdo.lemma.service.Parameter semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* PossiblyImportedInterface returns PossiblyImportedInterface
*
* Constraint:
* (import=[Import|ID]? interface=[Interface|QualifiedName])
*/
protected void sequence_PossiblyImportedInterface(ISerializationContext context, PossiblyImportedInterface semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* PossiblyImportedMicroservice returns PossiblyImportedMicroservice
*
* Constraint:
* (import=[Import|ID]? microservice=[Microservice|QualifiedName])
*/
protected void sequence_PossiblyImportedMicroservice(ISerializationContext context, PossiblyImportedMicroservice semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* PossiblyImportedOperation returns PossiblyImportedOperation
*
* Constraint:
* (import=[Import|ID]? operation=[Operation|QualifiedName])
*/
protected void sequence_PossiblyImportedOperation(ISerializationContext context, PossiblyImportedOperation semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* PropertyValueAssignment returns TechnologySpecificPropertyValueAssignment
*
* Constraint:
* ((property=[TechnologySpecificProperty|ID] value=PrimitiveValue) | (property=[TechnologySpecificProperty|ID] value=PrimitiveValue))
*/
protected void sequence_PropertyValueAssignment(ISerializationContext context, TechnologySpecificPropertyValueAssignment semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* ProtocolSpecification returns ProtocolSpecification
*
* Constraint:
* (communicationType=CommunicationType protocol=ImportedProtocolAndDataFormat)
*/
protected void sequence_ProtocolSpecification(ISerializationContext context, ProtocolSpecification semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.PROTOCOL_SPECIFICATION__COMMUNICATION_TYPE) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.PROTOCOL_SPECIFICATION__COMMUNICATION_TYPE));
if (transientValues.isValueTransient(semanticObject, ServicePackage.Literals.PROTOCOL_SPECIFICATION__PROTOCOL) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, ServicePackage.Literals.PROTOCOL_SPECIFICATION__PROTOCOL));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getProtocolSpecificationAccess().getCommunicationTypeCommunicationTypeEnumRuleCall_1_0(), semanticObject.getCommunicationType());
feeder.accept(grammarAccess.getProtocolSpecificationAccess().getProtocolImportedProtocolAndDataFormatParserRuleCall_3_0(), semanticObject.getProtocol());
feeder.finish();
}
/**
* Contexts:
* ReferredOperation returns ReferredOperation
*
* Constraint:
* (
* (protocols+=ProtocolSpecification protocols+=ProtocolSpecification?)?
* endpoints+=Endpoint*
* endpoints+=Endpoint*
* aspects+=ImportedServiceAspect*
* operation=[Operation|QualifiedName]
* )
*/
protected void sequence_ReferredOperation(ISerializationContext context, ReferredOperation semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* ServiceModel returns ServiceModel
*
* Constraint:
* (imports+=Import* microservices+=Microservice+)
*/
protected void sequence_ServiceModel(ISerializationContext context, ServiceModel semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* TechnologyReference returns TechnologyReference
*
* Constraint:
* (technology=[Import|ID] isTypeDefinitionTechnology=BOOLEAN?)
*/
protected void sequence_TechnologyReference(ISerializationContext context, TechnologyReference semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
}
|
3e1d0639d75adf6738c70ce8a83419cd8e419861 | 1,915 | java | Java | java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/CountAggregateDefinition.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | 282 | 2015-01-06T02:30:11.000Z | 2022-03-23T06:40:17.000Z | java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/CountAggregateDefinition.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | null | null | null | java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/CountAggregateDefinition.java | Sudeepa14/derby | d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88 | [
"Apache-2.0"
] | 163 | 2015-01-07T00:07:53.000Z | 2022-03-07T08:35:03.000Z | 31.393443 | 88 | 0.745692 | 12,300 | /*
Derby - Class org.apache.derby.impl.sql.compile.CountAggregateDefinition
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.derby.impl.sql.compile;
import org.apache.derby.shared.common.reference.ClassName;
import org.apache.derby.iapi.types.DataTypeDescriptor;
/**
* Definition for the COUNT()/COUNT(*) aggregates.
*
*/
class CountAggregateDefinition
implements AggregateDefinition
{
/**
* Niladic constructor. Does nothing. For ease
* Of use, only.
*/
public CountAggregateDefinition() { super(); }
/**
* Determines the result datatype. We can run
* count() on anything, and it always returns a
* INTEGER (java.lang.Integer).
*
* @param inputType the input type, either a user type or a java.lang object
*
* @return the output Class (null if cannot operate on
* value expression of this type.
*/
public final DataTypeDescriptor getAggregator(DataTypeDescriptor inputType,
StringBuffer aggregatorClass)
{
aggregatorClass.append( ClassName.CountAggregator);
/*
** COUNT never returns NULL
*/
return DataTypeDescriptor.getBuiltInDataTypeDescriptor(java.sql.Types.INTEGER, false);
}
}
|
3e1d06fff1455ca4544aa577b149745c5c5f6598 | 1,591 | java | Java | src/main/java/net/floodlightcontroller/blackbox/Action_MAC_Unblock.java | vincentxx/Blackbox | 85f03141c3066532cd929dd4ca3708c24ae5e67c | [
"Apache-2.0"
] | 1 | 2019-01-26T19:51:52.000Z | 2019-01-26T19:51:52.000Z | src/main/java/net/floodlightcontroller/blackbox/Action_MAC_Unblock.java | vincentxx/Blackbox | 85f03141c3066532cd929dd4ca3708c24ae5e67c | [
"Apache-2.0"
] | null | null | null | src/main/java/net/floodlightcontroller/blackbox/Action_MAC_Unblock.java | vincentxx/Blackbox | 85f03141c3066532cd929dd4ca3708c24ae5e67c | [
"Apache-2.0"
] | null | null | null | 31.82 | 110 | 0.754243 | 12,301 | /* SDN DDOS Mitigation Security Project @ CSUF Computing Lab
* by Vincent Tran @vuqt1.uci.edu | Ver: 1.0 | July 18th, 2017
*
* Purpose: One of Actions implementation is to unblock the attacking hosts,
* please refer to my paper for more detail
*/
package net.floodlightcontroller.blackbox;
import net.floodlightcontroller.core.IOFSwitch;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.OFFlowDelete;
import org.projectfloodlight.openflow.protocol.match.Match;
import org.projectfloodlight.openflow.protocol.match.MatchField;
import org.projectfloodlight.openflow.types.MacAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Action_MAC_Unblock implements Actions {
protected MacAddress MAC_Unblocked = null;
protected static Logger logger;
protected OFFlowDelete flowDel;
@Override
public void execute(IOFSwitch sw) {
logger = LoggerFactory.getLogger(Action_MAC_Unblock.class);
if (MAC_Unblocked != null)
{
logger.warn("");
logger.warn("BLACKBOX: $$$$$$$$$$$$$$ UNBLOCKED of ATTACKER's: " + MAC_Unblocked + " $$$$$$$$$$$$$$$$$\n");
//Remove a flow of denial attacker host
OFFactory myFactoryDel = sw.getOFFactory(); //get the factory version of current running switch
Match myMatchDel = myFactoryDel.buildMatch().setExact(MatchField.ETH_SRC, MAC_Unblocked).build();
flowDel = myFactoryDel.buildFlowDelete().setMatch(myMatchDel).build();
sw.write(flowDel);
}
}
Action_MAC_Unblock(MacAddress MAC_Address)
{
MAC_Unblocked = MAC_Address;
}
}
|
3e1d070f120101e241cb63544e21a71c401d3a5f | 3,413 | java | Java | officefloor/web/officeweb_template/src/main/impl/net/officefloor/web/template/section/WebTemplateFunction.java | officefloor/OfficeFloor | 16c73ac87019d27de6df16c54c976a295db184ea | [
"Apache-2.0"
] | 17 | 2019-09-30T08:23:01.000Z | 2021-12-20T04:51:03.000Z | officefloor/web/officeweb_template/src/main/impl/net/officefloor/web/template/section/WebTemplateFunction.java | officefloor/OfficeFloor | 16c73ac87019d27de6df16c54c976a295db184ea | [
"Apache-2.0"
] | 880 | 2019-07-08T04:31:14.000Z | 2022-03-16T20:16:03.000Z | officefloor/web/officeweb_template/src/main/impl/net/officefloor/web/template/section/WebTemplateFunction.java | officefloor/OfficeFloor | 16c73ac87019d27de6df16c54c976a295db184ea | [
"Apache-2.0"
] | 3 | 2019-09-30T08:22:37.000Z | 2021-10-13T10:05:24.000Z | 28.680672 | 112 | 0.713156 | 12,302 | /*-
* #%L
* Web Template
* %%
* Copyright (C) 2005 - 2020 Daniel Sagenschneider
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package net.officefloor.web.template.section;
import java.io.IOException;
import java.nio.charset.Charset;
import net.officefloor.frame.api.build.Indexed;
import net.officefloor.frame.api.build.None;
import net.officefloor.frame.api.function.ManagedFunction;
import net.officefloor.frame.api.function.ManagedFunctionContext;
import net.officefloor.frame.api.function.StaticManagedFunction;
import net.officefloor.server.http.HttpResponse;
import net.officefloor.server.http.ServerHttpConnection;
import net.officefloor.server.stream.ServerWriter;
import net.officefloor.web.template.parse.ParsedTemplateSection;
/**
* {@link ManagedFunction} to write the {@link ParsedTemplateSection}.
*
* @author Daniel Sagenschneider
*/
public class WebTemplateFunction extends StaticManagedFunction<Indexed, None> {
/**
* {@link WebTemplateWriter} instances to write the content.
*/
private final WebTemplateWriter[] contentWriters;
/**
* Flag indicating if a bean.
*/
private final boolean isBean;
/**
* Default {@link Charset} for the template.
*/
private final Charset defaultCharset;
/**
* Initiate.
*
* @param contentWriters {@link WebTemplateWriter} instances to write the
* content.
* @param isBean Flag indicating if a bean.
* @param charset Default {@link Charset} for the template.
*/
public WebTemplateFunction(WebTemplateWriter[] contentWriters, boolean isBean, Charset charset) {
this.contentWriters = contentWriters;
this.isBean = isBean;
this.defaultCharset = charset;
}
/*
* ======================= ManagedFunction ================================
*/
@Override
public void execute(ManagedFunctionContext<Indexed, None> context) throws IOException {
// Obtain the bean dependency
Object bean;
if (this.isBean) {
// Obtain the bean
bean = context.getObject(1);
// No bean, no content
if (bean == null) {
return;
}
} else {
// No bean
bean = null;
}
// Obtain the dependencies
ServerHttpConnection connection = (ServerHttpConnection) context.getObject(0);
// Obtain the writer
HttpResponse response = connection.getResponse();
ServerWriter writer = response.getEntityWriter();
// Determine if using default char set
boolean isDefaultCharset = (this.defaultCharset.name().equalsIgnoreCase(response.getContentCharset().name()));
// Determine the template path
String path = connection.getRequest().getUri();
int endPathIndex = path.indexOf('?');
if (endPathIndex >= 0) {
path = path.substring(0, endPathIndex);
}
// Write the contents
for (WebTemplateWriter contentWriter : this.contentWriters) {
contentWriter.write(writer, isDefaultCharset, bean, connection, path);
}
}
}
|
3e1d0832ab72281ebbad8d3691787d65b20d7e4b | 761 | java | Java | core/src/main/java/com/andedit/dungeon/input/KeyListener.java | AndEditor7/dungeon-chamber | 2ac6ae0e271477907cdc7f4ceae6bd32a5668879 | [
"MIT"
] | null | null | null | core/src/main/java/com/andedit/dungeon/input/KeyListener.java | AndEditor7/dungeon-chamber | 2ac6ae0e271477907cdc7f4ceae6bd32a5668879 | [
"MIT"
] | null | null | null | core/src/main/java/com/andedit/dungeon/input/KeyListener.java | AndEditor7/dungeon-chamber | 2ac6ae0e271477907cdc7f4ceae6bd32a5668879 | [
"MIT"
] | null | null | null | 20.026316 | 60 | 0.689882 | 12,303 | package com.andedit.dungeon.input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.IntMap;
public class KeyListener extends InputAdapter {
private final IntMap<Array<Runnable>> map = new IntMap<>();
public KeyListener() {
}
public KeyListener(int key, Runnable runnable) {
put(key, runnable);
}
public void put(int key, Runnable runnable) {
Array<Runnable> array = map.get(key);
if (array == null) {
array = new Array<Runnable>(8);
map.put(key, array);
}
array.add(runnable);
}
@Override
public boolean keyDown(int keycode) {
Array<Runnable> array = map.get(keycode);
if (array != null) {
array.forEach(Runnable::run);
return true;
}
return false;
}
}
|
3e1d084e328fee11c3ad673b91286b21f8c379e1 | 6,829 | java | Java | backend/src/main/java/org/seng302/datagenerator/UserGenerator.java | shengyKai/Wasteless-SENG302-Group-Project | f31a4ccac75fdec1bd411ca8e9c10ccebbaa1ce7 | [
"Unlicense"
] | null | null | null | backend/src/main/java/org/seng302/datagenerator/UserGenerator.java | shengyKai/Wasteless-SENG302-Group-Project | f31a4ccac75fdec1bd411ca8e9c10ccebbaa1ce7 | [
"Unlicense"
] | null | null | null | backend/src/main/java/org/seng302/datagenerator/UserGenerator.java | shengyKai/Wasteless-SENG302-Group-Project | f31a4ccac75fdec1bd411ca8e9c10ccebbaa1ce7 | [
"Unlicense"
] | null | null | null | 38.544944 | 133 | 0.626585 | 12,304 | package org.seng302.datagenerator;
/**
* If you are running this function from gradle generate then it will not
*/
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.seng302.datagenerator.LocationGenerator.Location;
import org.seng302.leftovers.dto.user.UserRole;
import java.sql.*;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.seng302.datagenerator.Main.randomDate;
public class UserGenerator {
private Random random = new Random();
private Connection conn;
private LocationGenerator locationGenerator = LocationGenerator.getInstance();
private PersonNameGenerator personNameGenerator = PersonNameGenerator.getInstance();
private final DescriptionGenerator descriptionGenerator = DescriptionGenerator.getInstance();
private final Logger logger = LogManager.getLogger(UserGenerator.class.getName());
public UserGenerator(Connection conn) {
this.conn = conn;
}
/**
* Randomly generates the hashed password
* @return
*/
private String generatePassword() {
return "vqbpgud2ghvjgm1n5hdgjnn5818fzsf2";
}
/**
* Randomly generates the email of the user. Appends an number representing
* the current user being generate to keep each individual email unique
* @return the user's email
*/
private String generateEmail(int counter, PersonNameGenerator.FullName fullName) {
String[] suffixes = {"@gmail.com", "@hotmail.com", "@yahoo.com", "@uclive.ac.nz", "@xtra.co.nz"};
String emailStart = fullName.getFirstName() + fullName.getLastName();
String counterStr = String.valueOf(counter);
String suffix = suffixes[random.nextInt(suffixes.length)];
return emailStart + counterStr + suffix;
}
/**
* Generates the users
* @param userCount Number of users to generate
* @return List of generated user ids
*/
public List<Long> generateUsers(int userCount) {
Instant startTime = Instant.now();
List<PersonNameGenerator.FullName> names = new ArrayList<>();
for (int i = 0; i < userCount; i++) names.add(personNameGenerator.generateName());
try {
logger.info("Adding addresses");
List<Location> addresses = new ArrayList<>();
for (int i = 0; i < userCount; i++) addresses.add(locationGenerator.generateAddress(random));
List<Long> addressIds = locationGenerator.createInsertAddressSQL(addresses, conn);
logger.info("Adding accounts");
AccountBatch accountBatch = new AccountBatch(conn);
for (int i = 0; i<userCount; i++) {
String email = generateEmail(i, names.get(i));
String password = generatePassword();
accountBatch.addAccount(email, password);
}
List<Long> generatedUserIds = accountBatch.execute();
logger.info("Adding users");
UserBatch userBatch = new UserBatch(conn);
for (int i = 0; i<userCount; i++) userBatch.addUser(generatedUserIds.get(i), addressIds.get(i), names.get(i));
userBatch.execute();
Instant endTime = Instant.now();
logger.info("Added {} users in {} ms", userCount, ChronoUnit.MILLIS.between(startTime, endTime));
return generatedUserIds;
} catch (Exception e) {
logger.error(e.getStackTrace());
return List.of();
}
}
public class AccountBatch {
private final PreparedStatement statement;
public AccountBatch(Connection connection) throws SQLException {
statement = connection.prepareStatement(
"INSERT INTO account (email, role, authentication_code) "
+ "VALUES (?, ?, ?);",
Statement.RETURN_GENERATED_KEYS
);
}
public void addAccount(String email, String password) throws SQLException {
UserRole role = UserRole.USER;
statement.setObject(1, email);
statement.setObject(2, role.ordinal());
statement.setObject(3, password);
statement.addBatch();
}
public List<Long> execute() throws SQLException {
statement.executeBatch();
List<Long> keys = new ArrayList<>();
ResultSet keyResults = statement.getGeneratedKeys();
while (keyResults.next()) keys.add(keyResults.getLong(1));
return keys;
}
}
public class UserBatch {
private final PreparedStatement statement;
/**
* Randomly generates the date of birth of the user
* @return the user's date of birth
*/
private LocalDate generateDOB() {
return randomDate(LocalDate.of(1900, 1, 1), LocalDate.of(2006, 1, 1));
}
/**
* Randomly generates an account creation date for the user.
* @return the account's creation date.
*/
private LocalDate generateCreated() {
return randomDate(LocalDate.of(2021, 1, 1), LocalDate.now());
}
/**
* Randomly generates the phone number of the user
* @return the user's phone number
*/
private String generatePhNum() {
return "027 " + (random.nextInt(8999999) + 1000000);
}
public UserBatch(Connection connection) throws SQLException {
statement = connection.prepareStatement(
"INSERT INTO user (first_name, middle_name, last_name, nickname, ph_num, dob, bio, created, userid, address_id) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
}
public void addUser(long userId, long addressId, PersonNameGenerator.FullName fullName) throws SQLException {
statement.setObject(1, fullName.getFirstName()); //first name
statement.setObject(2, fullName.getMiddleName()); //middle name
statement.setObject(3, fullName.getLastName()); //last name
statement.setObject(4, fullName.getNickname()); //nickname
statement.setObject(5, generatePhNum()); //phone number
statement.setObject(6, generateDOB()); //date of birth
statement.setObject(7, descriptionGenerator.randomDescription()); //bio
statement.setObject(8, generateCreated()); //date created
statement.setObject(9, userId);
statement.setObject(10, addressId);
statement.addBatch();
}
public void execute() throws SQLException {
statement.executeBatch();
}
}
} |
3e1d0930988ad69b848eb2314513b84a22ea8212 | 3,436 | java | Java | oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/standby/codec/GetHeadResponseEncoder.java | sho25/jackrabbit-oak | 1bb8a341fdf907578298f9ed52a48458e4f6efdc | [
"Apache-2.0"
] | null | null | null | oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/standby/codec/GetHeadResponseEncoder.java | sho25/jackrabbit-oak | 1bb8a341fdf907578298f9ed52a48458e4f6efdc | [
"Apache-2.0"
] | 2 | 2020-06-15T19:48:29.000Z | 2021-02-08T21:25:54.000Z | oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/standby/codec/GetHeadResponseEncoder.java | sho25/jackrabbit-oak | 1bb8a341fdf907578298f9ed52a48458e4f6efdc | [
"Apache-2.0"
] | null | null | null | 16.599034 | 810 | 0.796566 | 12,305 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|segment
operator|.
name|standby
operator|.
name|codec
package|;
end_package
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|buffer
operator|.
name|ByteBuf
import|;
end_import
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|channel
operator|.
name|ChannelHandlerContext
import|;
end_import
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|handler
operator|.
name|codec
operator|.
name|MessageToByteEncoder
import|;
end_import
begin_import
import|import
name|io
operator|.
name|netty
operator|.
name|util
operator|.
name|CharsetUtil
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_comment
comment|/** * Encodes a 'get head' response. */
end_comment
begin_class
specifier|public
class|class
name|GetHeadResponseEncoder
extends|extends
name|MessageToByteEncoder
argument_list|<
name|GetHeadResponse
argument_list|>
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|log
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|GetHeadResponseEncoder
operator|.
name|class
argument_list|)
decl_stmt|;
annotation|@
name|Override
specifier|protected
name|void
name|encode
parameter_list|(
name|ChannelHandlerContext
name|ctx
parameter_list|,
name|GetHeadResponse
name|msg
parameter_list|,
name|ByteBuf
name|out
parameter_list|)
throws|throws
name|Exception
block|{
name|log
operator|.
name|debug
argument_list|(
literal|"Sending head {} to client {}"
argument_list|,
name|msg
operator|.
name|getHeadRecordId
argument_list|()
argument_list|,
name|msg
operator|.
name|getClientId
argument_list|()
argument_list|)
expr_stmt|;
name|byte
index|[]
name|body
init|=
name|msg
operator|.
name|getHeadRecordId
argument_list|()
operator|.
name|getBytes
argument_list|(
name|CharsetUtil
operator|.
name|UTF_8
argument_list|)
decl_stmt|;
name|out
operator|.
name|writeInt
argument_list|(
name|body
operator|.
name|length
operator|+
literal|1
argument_list|)
expr_stmt|;
name|out
operator|.
name|writeByte
argument_list|(
name|Messages
operator|.
name|HEADER_RECORD
argument_list|)
expr_stmt|;
name|out
operator|.
name|writeBytes
argument_list|(
name|body
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
3e1d0943c1a9d3ac1204d5933733a0390b22a5d3 | 3,237 | java | Java | generate_workspace/src/main/java/com/google/devtools/build/workspace/maven/GraphSerializer.java | meteorcloudy/migration-tooling | 066edcb2d30d898ac70a4ce34ceb1ee59f3ae702 | [
"Apache-2.0"
] | 51 | 2017-06-12T17:12:24.000Z | 2022-01-24T10:09:55.000Z | generate_workspace/src/main/java/com/google/devtools/build/workspace/maven/GraphSerializer.java | meteorcloudy/migration-tooling | 066edcb2d30d898ac70a4ce34ceb1ee59f3ae702 | [
"Apache-2.0"
] | 87 | 2017-06-12T18:36:56.000Z | 2019-01-31T23:39:09.000Z | generate_workspace/src/main/java/com/google/devtools/build/workspace/maven/GraphSerializer.java | meteorcloudy/migration-tooling | 066edcb2d30d898ac70a4ce34ceb1ee59f3ae702 | [
"Apache-2.0"
] | 33 | 2017-06-12T17:15:45.000Z | 2021-12-12T01:42:26.000Z | 33.371134 | 94 | 0.734322 | 12,306 | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.workspace.maven;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.graph.DependencyVisitor;
import java.util.Map;
import java.util.Set;
/**
* Serializes a resolved dependency graph into a set of Bazel Build Rules.
*/
public class GraphSerializer {
public static Set<MavenJarRule> generateBuildRules(DependencyNode root) {
MutableGraph<MavenJarRule> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
DependencyVisitor visitor = new AetherGraphTraverser(graph);
root.getChildren().forEach(c -> c.accept(visitor));
return graph.nodes();
}
}
/**
* Performs a depth first traversal of aether's dependency node graph, and
* constructs a guava graph representation of the aether graph, with each
* node being a Rule object.
*/
class AetherGraphTraverser implements DependencyVisitor {
private final Set<MavenJarRule> visited;
private final MutableGraph<MavenJarRule> ruleGraph;
private final Map<DependencyNode, MavenJarRule> nodeRuleMap;
AetherGraphTraverser(MutableGraph<MavenJarRule> ruleGraph) {
this.visited = Sets.newHashSet();
this.ruleGraph = ruleGraph;
this.nodeRuleMap = Maps.newHashMap();
}
@Override
public boolean visitEnter(DependencyNode dependencyNode) {
if (dependencyNode == null || dependencyNode.getDependency().isOptional()) {
return false;
}
MavenJarRule rule = getRule(dependencyNode);
boolean isFirstVisit = visited.add(rule);
if (!isFirstVisit) {
return false;
}
for (DependencyNode child : dependencyNode.getChildren()) {
MavenJarRule childRule = getRule(child);
ruleGraph.putEdge(rule, childRule);
}
return true;
}
@Override
/* Adds parent and child pointers to nodes for later use by serializer. */
public boolean visitLeave(DependencyNode dependencyNode) {
MavenJarRule rule = getRule(dependencyNode);
ruleGraph.successors(rule).forEach(r -> r.addParent(rule));
ruleGraph.successors(rule).forEach(rule::addDependency);
return true;
}
/**
* Given a dependency node, either fetches a cached Rule object or
* constructs a new one.
*/
private MavenJarRule getRule(DependencyNode node) {
MavenJarRule rule = nodeRuleMap.get(node);
if (rule != null) {
return rule;
}
rule = new MavenJarRule(node);
nodeRuleMap.put(node, rule);
ruleGraph.addNode(rule);
return rule;
}
}
|
3e1d09fe3cdfb0bacd05a6036cdd806faec95860 | 1,602 | java | Java | src/main/java/fr/imag/adele/cadse/core/CadseError.java | chomats/cadse.as-cu | f18a18ba31c5828d201b70aaabe93950d9381daa | [
"Apache-2.0"
] | null | null | null | src/main/java/fr/imag/adele/cadse/core/CadseError.java | chomats/cadse.as-cu | f18a18ba31c5828d201b70aaabe93950d9381daa | [
"Apache-2.0"
] | null | null | null | src/main/java/fr/imag/adele/cadse/core/CadseError.java | chomats/cadse.as-cu | f18a18ba31c5828d201b70aaabe93950d9381daa | [
"Apache-2.0"
] | null | null | null | 24.646154 | 71 | 0.694757 | 12,307 | /*
* 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.
*
* Copyright (C) 2006-2010 Adele Team/LIG/Grenoble University, France
*/
package fr.imag.adele.cadse.core;
import fr.imag.adele.cadse.util.NLS;
/**
* Represents an exception thrown by CADSE runtime.
*
* @author Thomas
*
*/
public class CadseError {
private String _msg;
private Object[] _args;
/*
* type : warning (can commit) error (can commit) fail (cannot commit)
*/
/**
* Creates a CADSE error.
*
* @param message
* error message
* @param args
* arguments used to format error message
*/
public CadseError(String msg, Object... args) {
_msg = msg;
_args = args;
}
public Object[] getArgs() {
return _args;
}
public String getMsg() {
return _msg;
}
public String getMessage() {
return NLS.bind(_msg, _args);
}
}
|
3e1d0a34e8dc6a3ff2f996ede315d84537cc04fc | 2,992 | java | Java | src/main/java/com/solvd/carina/gui/common/component/base/BaseBasketProduct.java | DimaGrinevich/socket.by | 24c8393109944cd7a360d88e5cb8084373feb04a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/solvd/carina/gui/common/component/base/BaseBasketProduct.java | DimaGrinevich/socket.by | 24c8393109944cd7a360d88e5cb8084373feb04a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/solvd/carina/gui/common/component/base/BaseBasketProduct.java | DimaGrinevich/socket.by | 24c8393109944cd7a360d88e5cb8084373feb04a | [
"Apache-2.0"
] | null | null | null | 33.244444 | 92 | 0.67881 | 12,308 | package com.solvd.carina.gui.common.component.base;
import com.qaprosoft.carina.core.foundation.webdriver.decorator.ExtendedWebElement;
import com.qaprosoft.carina.core.gui.AbstractUIObject;
import com.solvd.carina.gui.common.component.IBasketProduct;
import com.solvd.carina.util.Parser;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedCondition;
import java.util.List;
public abstract class BaseBasketProduct extends AbstractUIObject implements IBasketProduct {
@FindBy(xpath = "//a[@class='plus-minus plus']")
protected List<ExtendedWebElement> productsPlus;
@FindBy(xpath = "//a[@class='plus-minus minus']")
protected List<ExtendedWebElement> productsMinuses;
@FindBy(xpath = "//a[@class='del']")
protected List<ExtendedWebElement> delProduct;
@FindBy(xpath = "//div[@class='bt-price-wrap']/div")
protected List<ExtendedWebElement> priceOfAProduct;
@FindBy(xpath = "//div[contains(@class,'cell_4')]/div[@class='bt-price']")
protected List<ExtendedWebElement> totalPriceOfAProductRow;
@FindBy(xpath = "//div[@class='basket-summary']/div[@class='bt-price']")
protected ExtendedWebElement totalPriceOfAllProductRows;
public BaseBasketProduct(WebDriver driver, SearchContext searchContext) {
super(driver, searchContext);
}
public void increaseQuantity(int product, int howMuch) {
ExpectedCondition ex = new ExpectedCondition<Boolean>() {
@NullableDecl
@Override
public Boolean apply(@NullableDecl WebDriver driver) {
return productsPlus.size()>0;
}
};
waitUntil(ex,5);
while(howMuch>0){
productsPlus.get(product).click();
howMuch--;
}
}
public void decreaseQuantity(int product, int howMuch) {
ExpectedCondition ex = new ExpectedCondition<Boolean>() {
@NullableDecl
@Override
public Boolean apply(@NullableDecl WebDriver driver) {
return productsMinuses.size()>0;
}
};
waitUntil(ex,5);
while(howMuch>0){
productsMinuses.get(product).click();
howMuch--;
}
}
public void deleteProduct(int product){
delProduct.get(product).click();
}
public double getTotalRowPrice(int product){
String tmp = totalPriceOfAProductRow.get(product).getText();
return Parser.parsePriceToDouble(tmp);
}
public double getProductPrice(int product){
String tmp = priceOfAProduct.get(product).getText();
return Parser.parsePriceToDouble(tmp);
}
public double getTotalPriceOfAllProductRows(){
String tmp = totalPriceOfAllProductRows.getText();
return Parser.parsePriceToDouble(tmp);
}
}
|
3e1d0a56b89dedd53b7f7d7668c5006ee49c434b | 1,282 | java | Java | app/models/SecurityRole.java | JiboStore/play-authenticate-mongodb | 8fd2409ac7624f452000b304862669346e36e613 | [
"Apache-2.0"
] | 12 | 2015-07-17T20:21:56.000Z | 2015-11-24T04:25:50.000Z | app/models/SecurityRole.java | JiboStore/play-authenticate-mongodb | 8fd2409ac7624f452000b304862669346e36e613 | [
"Apache-2.0"
] | 14 | 2015-04-27T06:22:42.000Z | 2015-09-06T08:36:15.000Z | app/models/SecurityRole.java | JiboStore/play-authenticate-mongodb | 8fd2409ac7624f452000b304862669346e36e613 | [
"Apache-2.0"
] | 2 | 2015-06-06T06:35:10.000Z | 2016-01-30T21:25:20.000Z | 26.729167 | 102 | 0.749805 | 12,309 | /*
* Copyright 2012 Steve Chaloner
*
* 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 models;
import be.objectify.deadbolt.core.models.Role;
import helper.datasources.MorphiaObject;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
/**
* @author Steve Chaloner (upchh@example.com)
*/
@Entity
public class SecurityRole implements Role {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
public ObjectId id;
public String roleName;
@Override
public String getName() {
return roleName;
}
public static SecurityRole findByRoleName(String roleName) {
return MorphiaObject.datastore.createQuery(SecurityRole.class).filter("roleName =", roleName).get();
}
}
|
3e1d0ac29eabe833fab0faece1940336837866e0 | 439 | java | Java | src/main/java/com/maybe/live/kit/Mail.java | x-pengg/LeTV | 6ebcec8a103fce291599b4da4633c4786f144831 | [
"MIT"
] | null | null | null | src/main/java/com/maybe/live/kit/Mail.java | x-pengg/LeTV | 6ebcec8a103fce291599b4da4633c4786f144831 | [
"MIT"
] | null | null | null | src/main/java/com/maybe/live/kit/Mail.java | x-pengg/LeTV | 6ebcec8a103fce291599b4da4633c4786f144831 | [
"MIT"
] | null | null | null | 13.30303 | 43 | 0.687927 | 12,310 | package com.maybe.live.kit;
import lombok.Data;
import java.io.Serializable;
/**
* @author: Tate
* @date: 2016/5/20 14:57
*/
@Data
public class Mail implements Serializable {
private String host;
private String sender;
private String receiver;
private String name;
private String username;
private String password;
private String subject;
private String message;
private int smtpPort;
}
|
3e1d0b706ffd3d256c3e83ecd807c77199ace786 | 166 | java | Java | Android/ControlMain/gen/com/dannixon/rgblighting/BuildConfig.java | r0kdu5t/ArduinoRGBLighting | e39fe74ec224fc960a3f1fe9b573a72cfc47f6b8 | [
"Apache-2.0"
] | 7 | 2015-04-16T09:13:55.000Z | 2018-11-27T05:50:28.000Z | Android/ControlMain/gen/com/dannixon/rgblighting/BuildConfig.java | r0kdu5t/ArduinoRGBLighting | e39fe74ec224fc960a3f1fe9b573a72cfc47f6b8 | [
"Apache-2.0"
] | null | null | null | Android/ControlMain/gen/com/dannixon/rgblighting/BuildConfig.java | r0kdu5t/ArduinoRGBLighting | e39fe74ec224fc960a3f1fe9b573a72cfc47f6b8 | [
"Apache-2.0"
] | 7 | 2015-07-13T10:50:09.000Z | 2021-08-19T03:36:20.000Z | 27.666667 | 50 | 0.759036 | 12,311 | /** Automatically generated file. DO NOT MODIFY */
package com.dannixon.rgblighting;
public final class BuildConfig {
public final static boolean DEBUG = true;
} |
3e1d0c20204dfecfb950162dcdeca8c095f77c27 | 80 | java | Java | alexandria-forms/javaee/gen/src/main/java/applications/HairType.java | abstratt/cloudfier-sustainable-jersey | 30f171ac95a5b49091d3d540c3b0699bd2a7483c | [
"Apache-2.0"
] | 1 | 2020-01-14T20:31:19.000Z | 2020-01-14T20:31:19.000Z | alexandria-forms/javaee/gen/src/main/java/applications/HairType.java | abstratt/cloudfier-sustainable-jersey | 30f171ac95a5b49091d3d540c3b0699bd2a7483c | [
"Apache-2.0"
] | 1 | 2017-02-21T14:07:39.000Z | 2017-03-29T14:43:57.000Z | alexandria-forms/javaee/gen/src/main/java/applications/HairType.java | abstratt/cloudfier-sustainable-jersey | 30f171ac95a5b49091d3d540c3b0699bd2a7483c | [
"Apache-2.0"
] | null | null | null | 10 | 22 | 0.65 | 12,312 | package applications;
public enum HairType {
Short,
Medium,
Long
}
|
3e1d0ce69640114f644a8acba343df4dc4d5169f | 16,344 | java | Java | gobblin-utility/src/main/java/gobblin/util/HadoopUtils.java | Hanmourang/Gobblin | d597970a92e1d6c4a24deebaa0b175a679eb3c1f | [
"Apache-2.0"
] | 3 | 2017-06-26T04:42:17.000Z | 2019-09-25T01:15:23.000Z | gobblin-utility/src/main/java/gobblin/util/HadoopUtils.java | Hanmourang/Gobblin | d597970a92e1d6c4a24deebaa0b175a679eb3c1f | [
"Apache-2.0"
] | null | null | null | gobblin-utility/src/main/java/gobblin/util/HadoopUtils.java | Hanmourang/Gobblin | d597970a92e1d6c4a24deebaa0b175a679eb3c1f | [
"Apache-2.0"
] | 4 | 2017-01-19T08:12:01.000Z | 2020-11-10T11:56:03.000Z | 41.800512 | 141 | 0.718123 | 12,313 | /*
* Copyright (C) 2014-2015 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package gobblin.util;
import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.State;
import gobblin.writer.DataWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map.Entry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileAlreadyExistsException;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.ReflectionUtils;
import com.google.common.collect.Lists;
import com.google.common.io.BaseEncoding;
import com.google.common.io.Closer;
/**
* A utility class for working with Hadoop.
*/
@Slf4j
public class HadoopUtils {
public static Configuration newConfiguration() {
Configuration conf = new Configuration();
// Explicitly check for S3 environment variables, so that Hadoop can access s3 and s3n URLs.
// h/t https://github.com/apache/spark/blob/master/core/src/main/scala/org/apache/spark/deploy/SparkHadoopUtil.scala
String awsAccessKeyId = System.getenv("AWS_ACCESS_KEY_ID");
String awsSecretAccessKey = System.getenv("AWS_SECRET_ACCESS_KEY");
if (awsAccessKeyId != null && awsSecretAccessKey != null) {
conf.set("fs.s3.awsAccessKeyId", awsAccessKeyId);
conf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey);
conf.set("fs.s3n.awsAccessKeyId", awsAccessKeyId);
conf.set("fs.s3n.awsSecretAccessKey", awsSecretAccessKey);
}
// Add a new custom filesystem mapping
conf.set("fs.sftp.impl", "gobblin.source.extractor.extract.sftp.SftpLightWeightFileSystem");
return conf;
}
/**
* @deprecated Use {@link FileListUtils#listFilesRecursively(FileSystem, Path)}.
*/
@Deprecated
public static List<FileStatus> listStatusRecursive(FileSystem fileSystem, Path path) throws IOException {
List<FileStatus> results = Lists.newArrayList();
walk(results, fileSystem, path);
return results;
}
/**
* A wrapper around {@link FileSystem#delete(Path, boolean)} which throws {@link IOException} if the given
* {@link Path} exists, and {@link FileSystem#delete(Path, boolean)} returns False.
*/
public static void deletePath(FileSystem fs, Path f, boolean recursive) throws IOException {
if (fs.exists(f) && !fs.delete(f, recursive)) {
throw new IOException("Failed to delete: " + f);
}
}
public static void deletePathAndEmptyAncestors(FileSystem fs, Path f, boolean recursive) throws IOException {
deletePath(fs, f, recursive);
Path parent = f.getParent();
while (parent != null) {
if (fs.exists(parent) && fs.listStatus(parent).length == 0) {
deletePath(fs, parent, true);
parent = parent.getParent();
} else {
break;
}
}
}
/**
* A wrapper around {@link FileSystem#rename(Path, Path)} which throws {@link IOException} if
* {@link FileSystem#rename(Path, Path)} returns False.
*/
public static void renamePath(FileSystem fs, Path oldName, Path newName) throws IOException {
if (!fs.exists(oldName)) {
throw new FileNotFoundException(String.format("Failed to rename %s to %s: src not found", oldName, newName));
}
if (fs.exists(newName)) {
throw new FileAlreadyExistsException(
String.format("Failed to rename %s to %s: dst already exists", oldName, newName));
}
if (!fs.rename(oldName, newName)) {
throw new IOException(String.format("Failed to rename %s to %s", oldName, newName));
}
}
/**
* A wrapper around {@link FileUtil#copy(FileSystem, Path, FileSystem, Path, boolean, Configuration)}
* which throws {@link IOException}
* if {@link FileUtil#copy(FileSystem, Path, FileSystem, Path, boolean, Configuration)} returns false.
*/
public static void copyPath(FileSystem fs, Path src, Path dst) throws IOException {
if (!FileUtil.copy(fs, src, fs, dst, false, fs.getConf())) {
throw new IOException(String.format("Failed to copy %s to %s", src, dst));
}
}
@SuppressWarnings("deprecation")
private static void walk(List<FileStatus> results, FileSystem fileSystem, Path path) throws IOException {
for (FileStatus status : fileSystem.listStatus(path)) {
if (!status.isDir()) {
results.add(status);
} else {
walk(results, fileSystem, status.getPath());
}
}
}
/**
* This method is an additive implementation of the {@link FileSystem#rename(Path, Path)} method. It moves all the
* files/directories under 'from' path to the 'to' path without overwriting existing directories in the 'to' path.
*
* <p>
* The rename operation happens at the first non-existent sub-directory. If a directory at destination path already
* exists, it recursively tries to move for sub-directories. If all the sub-directories also exist at the destination,
* a file level copy is done
* </p>
*
* <p>
* If the contents of destination 'to' path is expected to be modified concurrently, use
* {@link #safeRenameRecursively(FileSystem, Path, Path)}
* </p>
*
* @param fileSystem on which the data needs to be moved
* @param from path of the data to be moved
* @param to path of the data to be moved
*/
public static void renameRecursively(FileSystem fileSystem, Path from, Path to) throws IOException {
for (FileStatus fromFile : fileSystem.listStatus(from)) {
Path relativeFilePath =
new Path(StringUtils.substringAfter(fromFile.getPath().toString(), from.toString() + Path.SEPARATOR));
Path toFilePath = new Path(to, relativeFilePath);
if (!fileSystem.exists(toFilePath)) {
if (!fileSystem.rename(fromFile.getPath(), toFilePath)) {
throw new IOException(String.format("Failed to rename %s to %s.", fromFile.getPath(), toFilePath));
} else {
log.info(String.format("Renamed %s to %s", fromFile.getPath(), toFilePath));
}
} else if (fromFile.isDir()) {
renameRecursively(fileSystem, fromFile.getPath(), toFilePath);
} else {
log.info(String.format("File already exists %s. Will not rewrite", toFilePath));
}
}
}
/**
* A thread safe variation of {@link #renamePath(FileSystem, Path, Path)} which can be used in
* multi-threaded/multi-mapper environment. The rename operation always happens at file level hence directories are
* not overwritten under the 'to' path.
*
* <p>
* If the contents of destination 'to' path is not expected to be modified concurrently, use
* {@link #renamePath(FileSystem, Path, Path)} which is faster and more optimized
* </p>
*
* @param fileSystem on which the data needs to be moved
* @param from path of the data to be moved
* @param to path of the data to be moved
*/
public static void safeRenameRecursively(FileSystem fileSystem, Path from, Path to) throws IOException {
for (FileStatus fromFile : FileListUtils.listFilesRecursively(fileSystem, from)) {
Path relativeFilePath =
new Path(StringUtils.substringAfter(fromFile.getPath().toString(), from.toString() + Path.SEPARATOR));
Path toFilePath = new Path(to, relativeFilePath);
if (!fileSystem.exists(toFilePath)) {
if (!fileSystem.rename(fromFile.getPath(), toFilePath)) {
throw new IOException(String.format("Failed to rename %s to %s.", fromFile.getPath(), toFilePath));
} else {
log.info(String.format("Renamed %s to %s", fromFile.getPath(), toFilePath));
}
} else {
log.info(String.format("File already exists %s. Will not rewrite", toFilePath));
}
}
}
public static Configuration getConfFromState(State state) {
Configuration conf = newConfiguration();
for (String propName : state.getPropertyNames()) {
conf.set(propName, state.getProp(propName));
}
return conf;
}
public static State getStateFromConf(Configuration conf) {
State state = new State();
for (Entry<String, String> entry : conf) {
state.setProp(entry.getKey(), entry.getValue());
}
return state;
}
/**
* Set the group associated with a given path.
*
* @param fs the {@link FileSystem} instance used to perform the file operation
* @param path the given path
* @param group the group associated with the path
* @throws IOException
*/
public static void setGroup(FileSystem fs, Path path, String group) throws IOException {
fs.setOwner(path, fs.getFileStatus(path).getOwner(), group);
}
/**
* Serialize a {@link Writable} object into a string.
*
* @param writable the {@link Writable} object to be serialized
* @return a string serialized from the {@link Writable} object
* @throws IOException if there's something wrong with the serialization
*/
public static String serializeToString(Writable writable) throws IOException {
Closer closer = Closer.create();
try {
ByteArrayOutputStream byteArrayOutputStream = closer.register(new ByteArrayOutputStream());
DataOutputStream dataOutputStream = closer.register(new DataOutputStream(byteArrayOutputStream));
writable.write(dataOutputStream);
return BaseEncoding.base64().encode(byteArrayOutputStream.toByteArray());
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
/**
* Deserialize a {@link Writable} object from a string.
*
* @param writableClass the {@link Writable} implementation class
* @param serializedWritableStr the string containing a serialized {@link Writable} object
* @return a {@link Writable} deserialized from the string
* @throws IOException if there's something wrong with the deserialization
*/
public static Writable deserializeFromString(Class<? extends Writable> writableClass, String serializedWritableStr)
throws IOException {
return deserializeFromString(writableClass, serializedWritableStr, new Configuration());
}
/**
* Deserialize a {@link Writable} object from a string.
*
* @param writableClass the {@link Writable} implementation class
* @param serializedWritableStr the string containing a serialized {@link Writable} object
* @param configuration a {@link Configuration} object containing Hadoop configuration properties
* @return a {@link Writable} deserialized from the string
* @throws IOException if there's something wrong with the deserialization
*/
public static Writable deserializeFromString(Class<? extends Writable> writableClass, String serializedWritableStr,
Configuration configuration) throws IOException {
Closer closer = Closer.create();
try {
byte[] writableBytes = BaseEncoding.base64().decode(serializedWritableStr);
ByteArrayInputStream byteArrayInputStream = closer.register(new ByteArrayInputStream(writableBytes));
DataInputStream dataInputStream = closer.register(new DataInputStream(byteArrayInputStream));
Writable writable = ReflectionUtils.newInstance(writableClass, configuration);
writable.readFields(dataInputStream);
return writable;
} catch (Throwable t) {
throw closer.rethrow(t);
} finally {
closer.close();
}
}
/**
* Given a {@link FsPermission} objects, set a key, value pair in the given {@link State} for the writer to
* use when creating files. This method should be used in conjunction with {@link #deserializeWriterFilePermissions(State, int, int)}.
*/
public static void serializeWriterFilePermissions(State state, int numBranches, int branchId,
FsPermission fsPermissions) {
serializeFsPermissions(state,
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PERMISSIONS, numBranches, branchId),
fsPermissions);
}
/**
* Given a {@link FsPermission} objects, set a key, value pair in the given {@link State} for the writer to
* use when creating files. This method should be used in conjunction with {@link #deserializeWriterDirPermissions(State, int, int)}.
*/
public static void serializeWriterDirPermissions(State state, int numBranches, int branchId,
FsPermission fsPermissions) {
serializeFsPermissions(state,
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
fsPermissions);
}
/**
* Helper method that serializes a {@link FsPermission} object.
*/
private static void serializeFsPermissions(State state, String key, FsPermission fsPermissions) {
state.setProp(key, String.format("%04o", fsPermissions.toShort()));
}
/**
* Given a {@link String} in octal notation, set a key, value pair in the given {@link State} for the writer to
* use when creating files. This method should be used in conjunction with {@link #deserializeWriterFilePermissions(State, int, int)}.
*/
public static void setWriterFileOctalPermissions(State state, int numBranches, int branchId,
String octalPermissions) {
state.setProp(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PERMISSIONS, numBranches, branchId),
octalPermissions);
}
/**
* Given a {@link String} in octal notation, set a key, value pair in the given {@link State} for the writer to
* use when creating directories. This method should be used in conjunction with {@link #deserializeWriterDirPermissions(State, int, int)}.
*/
public static void setWriterDirOctalPermissions(State state, int numBranches, int branchId, String octalPermissions) {
state.setProp(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
octalPermissions);
}
/**
* Deserializes a {@link FsPermission}s object that should be used when a {@link DataWriter} is writing a file.
*/
public static FsPermission deserializeWriterFilePermissions(State state, int numBranches, int branchId) {
return new FsPermission(state.getPropAsShortWithRadix(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_PERMISSIONS, numBranches, branchId),
FsPermission.getDefault().toShort(), ConfigurationKeys.PERMISSION_PARSING_RADIX));
}
/**
* Deserializes a {@link FsPermission}s object that should be used when a {@link DataWriter} is creating directories.
*/
public static FsPermission deserializeWriterDirPermissions(State state, int numBranches, int branchId) {
return new FsPermission(state.getPropAsShortWithRadix(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
FsPermission.getDefault().toShort(), ConfigurationKeys.PERMISSION_PARSING_RADIX));
}
/**
* Get {@link FsPermission} from a {@link State} object.
*
* @param props A {@link State} containing properties.
* @param propName The property name for the permission. If not contained in the given state,
* defaultPermission will be used.
* @param defaultPermission default permission if propName is not contained in props.
* @return An {@link FsPermission} object.
*/
public static FsPermission deserializeFsPermission(State props, String propName, FsPermission defaultPermission) {
short mode = props.getPropAsShortWithRadix(propName, defaultPermission.toShort(),
ConfigurationKeys.PERMISSION_PARSING_RADIX);
return new FsPermission(mode);
}
}
|
3e1d0f13d1d61f1379a1cfc045d879ded308791a | 2,023 | java | Java | aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/transform/InsightImpactGraphEdgeMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/transform/InsightImpactGraphEdgeMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-xray/src/main/java/com/amazonaws/services/xray/model/transform/InsightImpactGraphEdgeMarshaller.java | ericvincent83/aws-sdk-java | c491416f3ea9411a04d9bafedee6c6874a79e48d | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 36.125 | 120 | 0.739496 | 12,314 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.xray.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.xray.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* InsightImpactGraphEdgeMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class InsightImpactGraphEdgeMarshaller {
private static final MarshallingInfo<Integer> REFERENCEID_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ReferenceId").build();
private static final InsightImpactGraphEdgeMarshaller instance = new InsightImpactGraphEdgeMarshaller();
public static InsightImpactGraphEdgeMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(InsightImpactGraphEdge insightImpactGraphEdge, ProtocolMarshaller protocolMarshaller) {
if (insightImpactGraphEdge == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(insightImpactGraphEdge.getReferenceId(), REFERENCEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
3e1d0f2c43e5220593ab45d6ff91e3814433bc95 | 559 | java | Java | src/main/java/org/singularitylab/infakt/client/model/SaleType.java | jakub-dzon/infakt-client | 69111e00fed136e7c8014519e0b945691d7b1876 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/singularitylab/infakt/client/model/SaleType.java | jakub-dzon/infakt-client | 69111e00fed136e7c8014519e0b945691d7b1876 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/singularitylab/infakt/client/model/SaleType.java | jakub-dzon/infakt-client | 69111e00fed136e7c8014519e0b945691d7b1876 | [
"Apache-2.0"
] | null | null | null | 20.703704 | 53 | 0.649374 | 12,315 | package org.singularitylab.infakt.client.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* @author Jakub Dzon
*/
public enum SaleType {
SERVICE,
MERCHANDISE;
@JsonValue
@Override
public String toString() {
return name().toLowerCase();
}
@JsonCreator
public static SaleType forValue(String value) {
if (value == null || value.isEmpty()) {
return SERVICE;
}
return SaleType.valueOf(value.toUpperCase());
}
}
|
3e1d10220d703aafd0b87127a9161c2654225b25 | 691 | java | Java | app/src/main/java/com/gurug/education/data/model/response/Response.java | SunbirdEd/teacher-aid-prep-app | 6d70de48862845c369e3e5ecb6dbd82d653884cb | [
"MIT"
] | null | null | null | app/src/main/java/com/gurug/education/data/model/response/Response.java | SunbirdEd/teacher-aid-prep-app | 6d70de48862845c369e3e5ecb6dbd82d653884cb | [
"MIT"
] | null | null | null | app/src/main/java/com/gurug/education/data/model/response/Response.java | SunbirdEd/teacher-aid-prep-app | 6d70de48862845c369e3e5ecb6dbd82d653884cb | [
"MIT"
] | 1 | 2020-11-21T17:55:26.000Z | 2020-11-21T17:55:26.000Z | 18.675676 | 59 | 0.66136 | 12,316 | package com.gurug.education.data.model.response;
import android.os.Parcel;
import android.os.Parcelable;
public class Response implements Parcelable {
private Throwable httpError;
public Throwable getHttpError() {
return httpError;
}
public void setHttpError(Throwable httpError) {
this.httpError = httpError;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(this.httpError);
}
public Response() {
}
protected Response(Parcel in) {
this.httpError = (Throwable) in.readSerializable();
}
}
|
3e1d10bc59905e4bc7871a78b3f75cb69780c5ee | 2,128 | java | Java | java/testingapps/restlisticator/src/main/java/uk/co/compendiumdev/restlisticator/api/action/SetFeatureTogglesApiAction.java | Shail06/TestingApp | 53c1ee35178af21f56c4eea8677b033dd592543c | [
"Apache-2.0"
] | 39 | 2018-04-26T11:48:12.000Z | 2022-01-27T22:57:08.000Z | java/testingapps/restlisticator/src/main/java/uk/co/compendiumdev/restlisticator/api/action/SetFeatureTogglesApiAction.java | Shail06/TestingApp | 53c1ee35178af21f56c4eea8677b033dd592543c | [
"Apache-2.0"
] | 2 | 2018-08-06T06:02:19.000Z | 2020-01-25T04:50:34.000Z | java/testingapps/restlisticator/src/main/java/uk/co/compendiumdev/restlisticator/api/action/SetFeatureTogglesApiAction.java | Shail06/TestingApp | 53c1ee35178af21f56c4eea8677b033dd592543c | [
"Apache-2.0"
] | 24 | 2018-04-27T07:39:29.000Z | 2021-12-27T01:29:07.000Z | 39.407407 | 171 | 0.742011 | 12,317 | package uk.co.compendiumdev.restlisticator.api.action;
import uk.co.compendiumdev.restlisticator.api.ApiRequest;
import uk.co.compendiumdev.restlisticator.api.ApiResponse;
import uk.co.compendiumdev.restlisticator.api.payloads.FeatureTogglePayload;
import uk.co.compendiumdev.restlisticator.api.payloads.ListOfFeatureTogglesPayload;
import uk.co.compendiumdev.restlisticator.api.payloads.convertor.PayloadConvertor;
import uk.co.compendiumdev.restlisticator.api.payloads.convertor.SimplePayloadConvertor;
import uk.co.compendiumdev.restlisticator.testappconfig.FeatureToggles;
/**
* Created by Alan on 18/07/2017.
*/
public class SetFeatureTogglesApiAction {
private final ApiResponse response;
private final ApiRequest request;
private PayloadConvertor payloadConvertor;
public SetFeatureTogglesApiAction(ApiRequest apiRequest, ApiResponse apiResponse) {
this.request = apiRequest;
this.response = apiResponse;
}
public SetFeatureTogglesApiAction setConvertor(PayloadConvertor convertor) {
this.payloadConvertor = convertor;
return this;
}
public ApiResponse perform() {
ListOfFeatureTogglesPayload toggles = payloadConvertor.convertFromPayloadStringToPatchPayloadForListOfFeatureTogglesPayload(
request.getBody(), request.getRequestFormat());
ListOfFeatureTogglesPayload responseToggles = new ListOfFeatureTogglesPayload();
for(FeatureTogglePayload toggle : toggles.toggles){
if(toggle.key!=null) {
FeatureToggles thistoggle = FeatureToggles.valueOf(toggle.key);
if (thistoggle != null) {
thistoggle.setState(Boolean.valueOf(toggle.value));
responseToggles.toggles.add(new FeatureTogglePayload(thistoggle.name(), thistoggle.getState()));
}
}
}
response.setAsSuccessful_OK();
response.setBody(new SimplePayloadConvertor<ListOfFeatureTogglesPayload>(ListOfFeatureTogglesPayload.class).convert(responseToggles, request.getResponseFormat()));
return response;
}
}
|
3e1d111224cad6228a441f361301f98791aae4f0 | 4,681 | java | Java | Corpus/birt/6514.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | 1 | 2022-01-15T02:47:45.000Z | 2022-01-15T02:47:45.000Z | Corpus/birt/6514.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | Corpus/birt/6514.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | 23.641414 | 179 | 0.64687 | 12,318 | /*
*************************************************************************
* Copyright (c) 2004, 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.aggregation.impl;
import java.util.LinkedList;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.aggregation.api.IBuildInAggregation;
import org.eclipse.birt.data.aggregation.calculator.CalculatorFactory;
import org.eclipse.birt.data.aggregation.i18n.Messages;
import org.eclipse.birt.data.aggregation.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.api.aggregation.Accumulator;
import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
* Implements the built-in Total.movingAva aggregation
*/
public class TotalMovingAve extends AggrFunction
{
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.Aggregation#getName()
*/
public String getName( )
{
return IBuildInAggregation.TOTAL_MOVINGAVE_FUNC;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.Aggregation#getType()
*/
public int getType( )
{
return RUNNING_AGGR;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IAggregation#getDateType()
*/
public int getDataType( )
{
return DataType.DOUBLE_TYPE;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.Aggregation#getParameterDefn()
*/
public IParameterDefn[] getParameterDefn( )
{
return new IParameterDefn[]{
new ParameterDefn( Constants.EXPRESSION_NAME,
Constants.EXPRESSION_DISPLAY_NAME,
false,
true,
SupportedDataTypes.CALCULATABLE,
"" ),//$NON-NLS-1$
new ParameterDefn( "window", Messages.getString( "TotalMovingAve.param.window" ), false, false, SupportedDataTypes.CALCULATABLE, "" ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
};
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.Aggregation#newAccumulator()
*/
public Accumulator newAccumulator( )
{
return new MyAccumulator( );
}
private static class MyAccumulator extends RunningAccumulator
{
private LinkedList list;
private int window = 1;
private Number sum = 0D;
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.RunningAccumulator#start()
*/
public void start( ) throws DataException
{
super.start( );
sum = 0D;
list = new LinkedList( );
window = 1;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.Accumulator#onRow(java.lang.Object[])
*/
public void onRow( Object[] args ) throws DataException
{
assert ( args.length > 1 );
if ( args[0] != null && args[1] != null )
{
if ( calculator == null )
{
calculator = CalculatorFactory.getCalculator( args[0].getClass( ) );
}
try
{
if ( list.size( ) == 0 )
{
window = DataTypeUtil.toInteger( args[1] ).intValue( );
assert ( window > 0 );
}
list.addLast( args[0] );
sum = calculator.add( sum, args[0] );
if ( list.size( ) > window )
{
sum = calculator.subtract( sum, list.get( 0 ) );
list.remove( 0 );
}
}
catch ( BirtException e )
{
throw DataException.wrap( new AggrException( ResourceConstants.DATATYPEUTIL_ERROR,
e ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.aggregation.Accumulator#getValue()
*/
public Object getValue( )
{
if ( list.size( ) == 0 )
{
return null;
}
try
{
return calculator.divide( sum, list.size( ) );
}
catch ( DataException e )
{
return null;
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IAggrFunction#getDescription()
*/
public String getDescription( )
{
return Messages.getString( "TotalMovingAve.description" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.api.aggregation.IAggrFunction#getDisplayName()
*/
public String getDisplayName( )
{
return Messages.getString( "TotalMovingAve.displayName" ); //$NON-NLS-1$
}
} |
3e1d11802bc394dec284a3a9c4e77783e6075e0c | 1,601 | java | Java | runescape-client/src/main/java/DualNodeDeque.java | Sharpienero/unethicalite | 6901bdba9e8079619acd9601c1deb44ee9b5b219 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/DualNodeDeque.java | Sharpienero/unethicalite | 6901bdba9e8079619acd9601c1deb44ee9b5b219 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/DualNodeDeque.java | Sharpienero/unethicalite | 6901bdba9e8079619acd9601c1deb44ee9b5b219 | [
"BSD-2-Clause"
] | null | null | null | 30.788462 | 55 | 0.646471 | 12,319 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("lo")
@Implements("DualNodeDeque")
public final class DualNodeDeque {
@ObfuscatedName("c")
@ObfuscatedSignature(descriptor = "Lnd;")
@Export("sentinel")
DualNode sentinel;
public DualNodeDeque() {
this.sentinel = new DualNode();
this.sentinel.previousDual = this.sentinel;
this.sentinel.nextDual = this.sentinel;
}
@ObfuscatedName("c")
@ObfuscatedSignature(descriptor = "(Lnd;)V")
@Export("addFirst")
public void addFirst(DualNode var1) {
if (var1.nextDual != null) {
var1.removeDual();
}
var1.nextDual = this.sentinel.nextDual;
var1.previousDual = this.sentinel;
var1.nextDual.previousDual = var1;
var1.previousDual.nextDual = var1;
}
@ObfuscatedName("l")
@ObfuscatedSignature(descriptor = "(Lnd;)V")
@Export("addLast")
public void addLast(DualNode var1) {
if (var1.nextDual != null) {
var1.removeDual();
}
var1.nextDual = this.sentinel;
var1.previousDual = this.sentinel.previousDual;
var1.nextDual.previousDual = var1;
var1.previousDual.nextDual = var1;
}
@ObfuscatedName("s")
@ObfuscatedSignature(descriptor = "()Lnd;")
@Export("removeLast")
public DualNode removeLast() {
DualNode var1 = this.sentinel.previousDual;
return var1 == this.sentinel ? null : var1;
}
} |
3e1d11e3f880e3161e409e488fe8e47a11f604a7 | 2,855 | java | Java | app/src/main/java/com/example/tina/openstackclient/ConnectedActivity.java | tinsk/OpenStackAndroidApp | 5c34465102e01d91ea06764691a435faf29b7696 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/tina/openstackclient/ConnectedActivity.java | tinsk/OpenStackAndroidApp | 5c34465102e01d91ea06764691a435faf29b7696 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/tina/openstackclient/ConnectedActivity.java | tinsk/OpenStackAndroidApp | 5c34465102e01d91ea06764691a435faf29b7696 | [
"Apache-2.0"
] | null | null | null | 35.6875 | 106 | 0.681261 | 12,320 | package com.example.tina.openstackclient;
import android.content.Intent;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
/*
* Klasa koju nasljedjuju aktivnosti koje se pokrecu
* nakon sto je korisnik autenticiran na OpenStack API
*/
public abstract class ConnectedActivity extends AppCompatActivity {
/*
* Inicijalizira UI elemenate koji su zajednicki svim aktivnostima
*/
public void initializeCommonUI() {
// Pronadjemo element toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// Zadamo toolbar kao ActionBar {android.support.v7.app.ActionBar} za ovu aktivnost
setSupportActionBar(toolbar);
// Pronadjemo element drawer_layout
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Zadajemo funkcionalnosti za drawer_layout
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
/*
* Prelazi na Login ekran i brise povijest navigiranja
*/
public void returnToLogin() {
// Ako smo kliknuli na Login, kreiramo Intent za
// prijelaz na Login aktivnost
Intent i = new Intent(this, LoginActivity.class);
// U slucaju povratka na Login zelimo izbrisati "povijest" navigiranja,
// tako da nas "Back" gumb ne vrati prethodnu aktivnost
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Prelazimo na Login aktivnost
startActivity(i);
// Zavrsavamo trenutnu aktivnost i oslobadjamo resurse
finish();
}
@Override
// Poziva se kad korisnik pritisne Back tipku
public void onBackPressed() {
// Drawer izbornik ce se zatvoriti ako pritisnemo "Back" tipku
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
// Poziva se kad korisnik odabere element
// iz gornjeg desnog "options" izbornika
public boolean onOptionsItemSelected(MenuItem item) {
// Dohvatimo id elementa koji smo kliknuli
int id = item.getItemId();
// Ako je kliknut "Sign Out" element, vracamo se
// na pocetni Login ekran
if (id == R.id.action_settings) {
returnToLogin();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
3e1d1229ecc610a6b3b0bc542930f26a688b5942 | 8,327 | java | Java | s2-dao/src/main/java/org/seasar/dao/impl/ResultSetHandlerFactoryImpl.java | seasarorg/s2dao | a05c9a26a0575e85053c4c7781865f71d07d91d9 | [
"Apache-2.0"
] | 2 | 2020-12-17T08:25:38.000Z | 2021-03-31T09:01:40.000Z | s2-dao/src/main/java/org/seasar/dao/impl/ResultSetHandlerFactoryImpl.java | seasarorg/s2dao | a05c9a26a0575e85053c4c7781865f71d07d91d9 | [
"Apache-2.0"
] | null | null | null | s2-dao/src/main/java/org/seasar/dao/impl/ResultSetHandlerFactoryImpl.java | seasarorg/s2dao | a05c9a26a0575e85053c4c7781865f71d07d91d9 | [
"Apache-2.0"
] | 6 | 2015-10-10T11:00:43.000Z | 2020-09-18T03:07:45.000Z | 40.033654 | 94 | 0.672271 | 12,321 | /*
* Copyright 2004-2011 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.dao.impl;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.seasar.dao.BeanMetaData;
import org.seasar.dao.DaoAnnotationReader;
import org.seasar.dao.DtoMetaData;
import org.seasar.dao.DtoMetaDataFactory;
import org.seasar.dao.RelationRowCreator;
import org.seasar.dao.ResultSetHandlerFactory;
import org.seasar.dao.RowCreator;
import org.seasar.dao.impl.BeanMetaDataResultSetHandler.RestrictBeanMetaDataResultSetHandler;
import org.seasar.dao.impl.DtoMetaDataResultSetHandler.RestrictDtoMetaDataResultSetHandler;
import org.seasar.dao.impl.MapResultSetHandler.RestrictMapResultSetHandler;
import org.seasar.dao.impl.ObjectResultSetHandler.RestrictObjectResultSetHandler;
import org.seasar.dao.util.TypeUtil;
import org.seasar.extension.jdbc.ResultSetHandler;
/**
* @author manhole
* @author jflute
*/
public class ResultSetHandlerFactoryImpl implements ResultSetHandlerFactory {
public static final String dtoMetaDataFactory_BINDING = "bindingType=must";
protected DtoMetaDataFactory dtoMetaDataFactory;
/**
* プロパティrestrictNotSingleResultに対するBINDINGアノテーションです。
*/
public static final String restrictNotSingleResult_BINDING = "bindingType=may";
/**
* 返り値がBean、DTOやMapのメソッドで、結果が2件以上の時に例外を投げるかを設定します。
*/
protected boolean restrictNotSingleResult = false;
public ResultSetHandler getResultSetHandler(
final DaoAnnotationReader daoAnnotationReader,
final BeanMetaData beanMetaData, final Method method) {
final Class beanClass = daoAnnotationReader.getBeanClass();
final Class clazz = daoAnnotationReader.getBeanClass(method);
if ((clazz != null) && !clazz.isAssignableFrom(beanClass)) {
if (TypeUtil.isSimpleType(clazz)) {
if (List.class.isAssignableFrom(method.getReturnType())) {
return createObjectListResultSetHandler(clazz);
} else if (method.getReturnType().isArray()
&& !TypeUtil.isSimpleType(method.getReturnType())) {
return createObjectArrayResultSetHandler(clazz);
} else {
return createObjectResultSetHandler(clazz);
}
}
if (Map.class.isAssignableFrom(clazz)) {
if (List.class.isAssignableFrom(method.getReturnType())) {
return createMapListResultSetHandler();
} else if (method.getReturnType().isArray()) {
return createMapArrayResultSetHandler();
} else {
return createMapResultSetHandler();
}
}
final DtoMetaData dtoMetaData = dtoMetaDataFactory
.getDtoMetaData(clazz);
if (List.class.isAssignableFrom(method.getReturnType())) {
return createDtoListMetaDataResultSetHandler(dtoMetaData);
} else if (method.getReturnType() == clazz) {
return createDtoMetaDataResultSetHandler(dtoMetaData);
} else if (method.getReturnType().isArray()) {
return createDtoArrayMetaDataResultSetHandler(dtoMetaData);
}
} else {
if (List.class.isAssignableFrom(method.getReturnType())) {
return createBeanListMetaDataResultSetHandler(beanMetaData);
} else if (isBeanClassAssignable(beanClass, method.getReturnType())) {
return createBeanMetaDataResultSetHandler(beanMetaData);
} else if (method.getReturnType().isAssignableFrom(
Array.newInstance(beanClass, 0).getClass())) {
return createBeanArrayMetaDataResultSetHandler(beanMetaData);
}
}
return createObjectResultSetHandler(null);
}
protected ResultSetHandler createDtoListMetaDataResultSetHandler(
final DtoMetaData dtoMetaData) {
return new DtoListMetaDataResultSetHandler(dtoMetaData,
createRowCreator());
}
protected ResultSetHandler createDtoMetaDataResultSetHandler(
final DtoMetaData dtoMetaData) {
if (restrictNotSingleResult) {
return new RestrictDtoMetaDataResultSetHandler(dtoMetaData,
createRowCreator());
}
return new DtoMetaDataResultSetHandler(dtoMetaData, createRowCreator());
}
protected ResultSetHandler createDtoArrayMetaDataResultSetHandler(
final DtoMetaData dtoMetaData) {
return new DtoArrayMetaDataResultSetHandler(dtoMetaData,
createRowCreator());
}
protected ResultSetHandler createMapListResultSetHandler() {
return new MapListResultSetHandler();
}
protected ResultSetHandler createMapResultSetHandler() {
if (restrictNotSingleResult) {
return new RestrictMapResultSetHandler();
}
return new MapResultSetHandler();
}
protected ResultSetHandler createMapArrayResultSetHandler() {
return new MapArrayResultSetHandler();
}
protected ResultSetHandler createBeanListMetaDataResultSetHandler(
final BeanMetaData beanMetaData) {
return new BeanListMetaDataResultSetHandler(beanMetaData,
createRowCreator(), createRelationRowCreator());
}
protected ResultSetHandler createBeanMetaDataResultSetHandler(
final BeanMetaData beanMetaData) {
if (restrictNotSingleResult) {
return new RestrictBeanMetaDataResultSetHandler(beanMetaData,
createRowCreator(), createRelationRowCreator());
}
return new BeanMetaDataResultSetHandler(beanMetaData,
createRowCreator(), createRelationRowCreator());
}
protected ResultSetHandler createBeanArrayMetaDataResultSetHandler(
final BeanMetaData beanMetaData) {
return new BeanArrayMetaDataResultSetHandler(beanMetaData,
createRowCreator(), createRelationRowCreator());
}
protected ResultSetHandler createObjectListResultSetHandler(Class clazz) {
return new ObjectListResultSetHandler(clazz);
}
protected ResultSetHandler createObjectResultSetHandler(Class clazz) {
if (restrictNotSingleResult) {
return new RestrictObjectResultSetHandler(clazz);
}
return new ObjectResultSetHandler(clazz);
}
protected ResultSetHandler createObjectArrayResultSetHandler(Class clazz) {
return new ObjectArrayResultSetHandler(clazz);
}
protected RowCreator createRowCreator() {// [DAO-118] (2007/08/25)
return new RowCreatorImpl();
}
protected RelationRowCreator createRelationRowCreator() {
return new RelationRowCreatorImpl();
}
protected boolean isBeanClassAssignable(final Class beanClass,
final Class clazz) {
return beanClass.isAssignableFrom(clazz)
|| clazz.isAssignableFrom(beanClass);
}
public void setDtoMetaDataFactory(
final DtoMetaDataFactory dtoMetaDataFactory) {
this.dtoMetaDataFactory = dtoMetaDataFactory;
}
/**
* 返り値がBean、DTOやMapのメソッドで、結果が2件以上の時に例外を投げるかを設定します。
*
* @param 例外を投げるときに
* <code>true</code>
*/
public void setRestrictNotSingleResult(boolean restrictNotSingleResult) {
this.restrictNotSingleResult = restrictNotSingleResult;
}
}
|
3e1d141bd39942226a7544b42549028ffed82206 | 1,421 | java | Java | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncTriggerResponse.java | raghuvaran/azure-sdk-for-java | fc1a28fa1e8d34e7e17d4df02ec5ee65b4af37a9 | [
"MIT"
] | null | null | null | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncTriggerResponse.java | raghuvaran/azure-sdk-for-java | fc1a28fa1e8d34e7e17d4df02ec5ee65b4af37a9 | [
"MIT"
] | null | null | null | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosAsyncTriggerResponse.java | raghuvaran/azure-sdk-for-java | fc1a28fa1e8d34e7e17d4df02ec5ee65b4af37a9 | [
"MIT"
] | null | null | null | 32.295455 | 100 | 0.710767 | 12,322 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos;
import com.azure.cosmos.implementation.ResourceResponse;
import com.azure.cosmos.implementation.Trigger;
import org.apache.commons.lang3.StringUtils;
public class CosmosAsyncTriggerResponse extends CosmosResponse<CosmosTriggerProperties> {
private final CosmosTriggerProperties cosmosTriggerProperties;
private final CosmosAsyncTrigger cosmosTrigger;
CosmosAsyncTriggerResponse(ResourceResponse<Trigger> response, CosmosAsyncContainer container) {
super(response);
String bodyAsString = response.getBodyAsString();
if (StringUtils.isEmpty(bodyAsString)) {
cosmosTriggerProperties = null;
cosmosTrigger = null;
} else {
cosmosTriggerProperties = new CosmosTriggerProperties(bodyAsString);
cosmosTrigger = new CosmosAsyncTrigger(cosmosTriggerProperties.getId(), container);
}
}
/**
* Gets the cosmos trigger properties or null
*
* @return {@link CosmosTriggerProperties}
*/
public CosmosTriggerProperties getProperties() {
return cosmosTriggerProperties;
}
/**
* Gets the cosmos trigger object or null
*
* @return {@link CosmosAsyncTrigger}
*/
public CosmosAsyncTrigger getTrigger() {
return cosmosTrigger;
}
}
|
3e1d14c4ee86f0899417649fb8dfa8af82d2e290 | 580 | java | Java | Problem Solving/Extra Long Factorials.java | AtosNeves/HackerRank | f1957ce5d1e2538eccec5892257c9d7b925f5083 | [
"MIT"
] | null | null | null | Problem Solving/Extra Long Factorials.java | AtosNeves/HackerRank | f1957ce5d1e2538eccec5892257c9d7b925f5083 | [
"MIT"
] | null | null | null | Problem Solving/Extra Long Factorials.java | AtosNeves/HackerRank | f1957ce5d1e2538eccec5892257c9d7b925f5083 | [
"MIT"
] | null | null | null | 22.307692 | 63 | 0.582759 | 12,323 | import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
BigInteger fac = BigInteger.valueOf(1);
// x = x - 1;
while (x > 1) {
fac = fac.multiply(BigInteger.valueOf(x));
x = x - 1;
}
System.out.println(fac);
System.exit(0);
input.close();
}
}
|
3e1d15695bd8def3c7ef5c09f52c2b0c8e33ced7 | 10,162 | java | Java | projects/OG-LiveData/src/main/java/com/opengamma/livedata/cogda/server/CogdaLiveDataServer.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 12 | 2017-03-10T13:56:52.000Z | 2021-10-03T01:21:20.000Z | projects/OG-LiveData/src/main/java/com/opengamma/livedata/cogda/server/CogdaLiveDataServer.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 1 | 2021-08-02T17:20:43.000Z | 2021-08-02T17:20:43.000Z | projects/OG-LiveData/src/main/java/com/opengamma/livedata/cogda/server/CogdaLiveDataServer.java | emcleod/OG-Platform | dbd4e1c64907f6a2dd27a62d252e9c61e609f779 | [
"Apache-2.0"
] | 16 | 2017-01-12T10:31:58.000Z | 2019-04-19T08:17:33.000Z | 35.16263 | 128 | 0.743161 | 12,324 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.livedata.cogda.server;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.fudgemsg.FudgeContext;
import org.fudgemsg.FudgeMsg;
import org.fudgemsg.FudgeMsgEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.Lifecycle;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.opengamma.core.user.UserAccount;
import com.opengamma.core.user.UserSource;
import com.opengamma.core.user.impl.SimpleUserAccount;
import com.opengamma.id.ExternalId;
import com.opengamma.livedata.LiveDataSpecification;
import com.opengamma.livedata.LiveDataValueUpdate;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.livedata.server.LastKnownValueStore;
import com.opengamma.livedata.server.LastKnownValueStoreProvider;
import com.opengamma.livedata.server.LiveDataServer;
import com.opengamma.transport.FudgeConnection;
import com.opengamma.transport.FudgeConnectionReceiver;
import com.opengamma.transport.socket.ServerSocketFudgeConnectionReceiver;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.metric.MetricProducer;
/**
* The base server process for any Cogda Live Data Server.
* <p/>
* By default, it will operate in a completely unauthenticated mode. User names and passwords
* in connection requests will be ignored, and all fields will be accessible by any connection.
* However, in combination with an injected {@link UserSource} (see {@link #setUserSource(UserSource)}),
* the server will authenticate users and authorize access.
* If the server has a {@link UserSource} provided, but the {@code checkPassword} parameter
* is set to false (see {@link #setCheckPassword(boolean)}) then only authorization will be provided and it is assumed
* that authentication is handled elsewhere in the overall application and so user credentials
* can be assumed to be valid without a password being provided.
* <p/>
* Because the {@link UserSource} will be hit for every authorization question, it is <strong>critical</strong>
* that the source caches requests in some form.
*/
public class CogdaLiveDataServer implements LiveDataServer, FudgeConnectionReceiver, Lifecycle, MetricProducer {
/** Logger. */
private static final Logger s_logger = LoggerFactory.getLogger(CogdaLiveDataServer.class);
/**
* The default port on which the server will listen for inbound connections.
*/
public static final int DEFAULT_LISTEN_PORT = 11876;
private int _portNumber = DEFAULT_LISTEN_PORT;
private final ServerSocketFudgeConnectionReceiver _connectionReceiver;
private final LastKnownValueStoreProvider _lastKnownValueStoreProvider;
private final ConcurrentMap<LiveDataSpecification, LastKnownValueStore> _lastKnownValueStores =
new ConcurrentHashMap<LiveDataSpecification, LastKnownValueStore>();
private final Set<CogdaClientConnection> _clients = new CopyOnWriteArraySet<CogdaClientConnection>();
// TODO kirk 2012-07-23 -- This is absolutely the wrong executor here.
private final Executor _valueUpdateSendingExecutor = Executors.newFixedThreadPool(5);
private UserSource _userSource;
private boolean _checkPassword = true;
// Metrics:
private Meter _tickMeter = new Meter();
public CogdaLiveDataServer(LastKnownValueStoreProvider lkvStoreProvider) {
this(lkvStoreProvider, OpenGammaFudgeContext.getInstance());
}
public CogdaLiveDataServer(LastKnownValueStoreProvider lkvStoreProvider, FudgeContext fudgeContext) {
ArgumentChecker.notNull(lkvStoreProvider, "lkvStoreProvider");
ArgumentChecker.notNull(fudgeContext, "fudgeContext");
_lastKnownValueStoreProvider = lkvStoreProvider;
_connectionReceiver = new ServerSocketFudgeConnectionReceiver(fudgeContext, this);
_connectionReceiver.setLazyFudgeMsgReads(false);
}
@Override
public synchronized void registerMetrics(MetricRegistry summaryRegistry, MetricRegistry detailedRegistry, String namePrefix) {
_tickMeter = summaryRegistry.meter(namePrefix + ".ticks");
}
/**
* Gets the portNumber.
* @return the portNumber
*/
public int getPortNumber() {
return _portNumber;
}
/**
* Sets the portNumber. Defaults to {@link #DEFAULT_LISTEN_PORT}.
* This <b>must</b> be set <b>before</b> {@link #start()} is called.
* @param portNumber the portNumber
*/
public void setPortNumber(int portNumber) {
_portNumber = portNumber;
}
/**
* Gets the lastKnownValueStoreProvider.
* @return the lastKnownValueStoreProvider
*/
public LastKnownValueStoreProvider getLastKnownValueStoreProvider() {
return _lastKnownValueStoreProvider;
}
/**
* Gets the userSource.
* @return the userSource
*/
public UserSource getUserSource() {
return _userSource;
}
/**
* Sets the userSource.
* @param userSource the userSource
*/
public void setUserSource(UserSource userSource) {
_userSource = userSource;
}
/**
* Whether passwords will be checked.
* @return true if passwords will be checked.
*/
public boolean isCheckPassword() {
return _checkPassword;
}
/**
* Sets whether passwords will be checked.
* Setting to false means that only authorization will be performed
* rather than authentication.
* @param checkPassword false to turn off password checking on connections.
*/
public void setCheckPassword(boolean checkPassword) {
_checkPassword = checkPassword;
}
@Override
public void connectionReceived(FudgeContext fudgeContext, FudgeMsgEnvelope message, FudgeConnection connection) {
CogdaClientConnection clientConnection = new CogdaClientConnection(fudgeContext, this, connection);
// We're blocked on connection acceptance. Therefore it's entirely fine
// to do the handshake here as we won't get any more messages until
// it's done.
clientConnection.handshakeMessage(fudgeContext, message);
_clients.add(clientConnection);
}
@Override
public void start() {
_connectionReceiver.setPortNumber(getPortNumber());
_connectionReceiver.start();
}
@Override
public void stop() {
_connectionReceiver.stop();
}
@Override
public boolean isRunning() {
return _connectionReceiver.isRunning();
}
public void liveDataReceived(LiveDataValueUpdate valueUpdate) {
_tickMeter.mark();
// REVIEW kirk 2013-03-27 -- Does this loop need to be done in an executor
// task or something? If nothing else, connection.liveDataReceived() can
// block.
// This could probably be much much faster, but we're designed initially for low-frequency
// updates. Someone smarter should optimize the data structures here.
for (CogdaClientConnection connection : _clients) {
boolean needsPump = connection.liveDataReceived(valueUpdate);
if (needsPump) {
final CogdaClientConnection finalConnection = connection;
_valueUpdateSendingExecutor.execute(new Runnable() {
@Override
public void run() {
finalConnection.sendAllUpdates();
}
});
}
}
}
protected UserAccount getUserAccount(String userName) {
if (getUserSource() == null) {
// Nothing will work without a UserAccount. So we return a mock one.
SimpleUserAccount simpleUser = new SimpleUserAccount(userName);
simpleUser.getPermissions().add("*");
return simpleUser;
}
try {
return getUserSource().getAccount(userName);
} catch (RuntimeException ex) {
s_logger.warn("Authentication could not find user {}", userName);
return null;
}
}
// Callbacks from the client.
public UserPrincipal authenticate(String userId, String password) {
if (getUserSource() == null) {
// No user source. Allow all connections.
return UserPrincipal.getLocalUser(userId);
}
UserAccount user = getUserAccount(userId);
if (user == null) {
s_logger.info("Not allowing login for {} because no user in UserSource", userId);
return null;
}
// password check not supported
return UserPrincipal.getLocalUser(userId);
}
public List<String> getAvailableServers() {
return Collections.emptyList();
}
public FudgeMsg getCapabilities() {
return OpenGammaFudgeContext.getInstance().newMessage();
}
public boolean isValidLiveData(ExternalId subscriptionId, String normalizationScheme) {
return getLastKnownValueStoreProvider().isAvailable(subscriptionId, normalizationScheme);
}
public LastKnownValueStore getLastKnownValueStore(ExternalId subscriptionId, String normalizationScheme) {
LiveDataSpecification ldspec = new LiveDataSpecification(normalizationScheme, subscriptionId);
// TODO kirk 2012-07-23 -- Check to see if valid.
LastKnownValueStore store = _lastKnownValueStores.get(ldspec);
if (store == null) {
LastKnownValueStore fresh = getLastKnownValueStoreProvider().newInstance(subscriptionId, normalizationScheme);
LastKnownValueStore fromMap = _lastKnownValueStores.putIfAbsent(ldspec, fresh);
if (fromMap == null) {
store = fresh;
} else {
store = fromMap;
}
}
return store;
}
public void removeClient(CogdaClientConnection connection) {
_clients.remove(connection);
}
public int getNumClients() {
return _clients.size();
}
public Set<String> getActiveUsers() {
Set<String> result = new TreeSet<String>();
synchronized (_clients) {
for (CogdaClientConnection connection : _clients) {
result.add(connection.getUserPrincipal().toString());
}
}
return result;
}
}
|
3e1d156b7bc2a9d5e62a4875b94ed64ca24c1ac1 | 8,331 | java | Java | src/main/java/net/rcarz/jiraclient/Version.java | yevgenykuz/qpack-to-jira-with-xray-migrator | ab04b93bcee09fc821ab24cdd8c20bd92e7b9b7f | [
"MIT"
] | null | null | null | src/main/java/net/rcarz/jiraclient/Version.java | yevgenykuz/qpack-to-jira-with-xray-migrator | ab04b93bcee09fc821ab24cdd8c20bd92e7b9b7f | [
"MIT"
] | 3 | 2020-04-10T23:13:39.000Z | 2022-01-04T16:37:14.000Z | src/main/java/net/rcarz/jiraclient/Version.java | yevgenykuz/qpack-to-jira-with-xray-migrator | ab04b93bcee09fc821ab24cdd8c20bd92e7b9b7f | [
"MIT"
] | null | null | null | 29.359155 | 96 | 0.585512 | 12,325 | /**
* jira-client - a simple JIRA REST client
* Copyright (c) 2013 Bob Carroll (kenaa@example.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.rcarz.jiraclient;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* Represents a product version.
*/
public class Version extends Resource {
/**
* Used to chain fields to a create action.
*/
public static final class FluentCreate {
/**
* The Jira rest client.
*/
RestClient restclient = null;
/**
* The JSON request that will be built incrementally as fluent methods
* are invoked.
*/
JSONObject req = new JSONObject();
/**
* Creates a new fluent.
* @param restclient the REST client
* @param project the project key
*/
private FluentCreate(RestClient restclient, String project) {
this.restclient = restclient;
req.put("project", project);
}
/**
* Sets the name of the version.
* @param name the name
* @return <code>this</code>
*/
public FluentCreate name(String name) {
req.put("name", name);
return this;
}
/**
* Sets the description of the version.
* @param description the description
* @return <code>this</code>
*/
public FluentCreate description(String description) {
req.put("description", description);
return this;
}
/**
* Sets the archived status of the version.
* @param isArchived archived status
* @return <code>this</code>
*/
public FluentCreate archived(boolean isArchived) {
req.put("archived", isArchived);
return this;
}
/**
* Sets the released status of the version.
* @param isReleased released status
* @return <code>this</code>
*/
public FluentCreate released(boolean isReleased) {
req.put("released", isReleased);
return this;
}
/**
* Sets the release date of the version.
* @param releaseDate release Date
* @return <code>this</code>
*/
public FluentCreate releaseDate(Date releaseDate) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
req.put("releaseDate", df.format(releaseDate));
return this;
}
/**
* Executes the create action.
* @return the created Version
*
* @throws JiraException when the create fails
*/
public Version execute() throws JiraException {
JSON result = null;
try {
result = restclient.post(getRestUri(null), req);
} catch (Exception ex) {
throw new JiraException("Failed to create version", ex);
}
if (!(result instanceof JSONObject) || !((JSONObject) result).containsKey("id")
|| !(((JSONObject) result).get("id") instanceof String)) {
throw new JiraException("Unexpected result on create version");
}
return new Version(restclient, (JSONObject) result);
}
}
private String name = null;
private boolean archived = false;
private boolean released = false;
private String releaseDate;
private String description = null;
/**
* Creates a version from a JSON payload.
*
* @param restclient REST client instance
* @param json JSON payload
*/
protected Version(RestClient restclient, JSONObject json) {
super(restclient);
if (json != null)
deserialise(json);
}
/**
* Merges the given version with current version
*
* @param version
* The version to merge
*/
public void mergeWith(Version version) throws JiraException {
JSONObject req = new JSONObject();
req.put("description", version.getDescription());
req.put("name", version.getName());
req.put("archived", version.isArchived());
req.put("released", version.isReleased());
req.put("releaseDate", version.getReleaseDate());
try {
restclient.put(Resource.getBaseUri() + "version/" + id, req);
} catch (Exception ex) {
throw new JiraException("Failed to merge", ex);
}
}
/**
* Copies the version to the given project
*
* @param project
* The project the version will be copied to
*/
public void copyTo(Project project) throws JiraException {
JSONObject req = new JSONObject();
req.put("description", getDescription());
req.put("name", getName());
req.put("archived", isArchived());
req.put("released", isReleased());
req.put("releaseDate", getReleaseDate());
req.put("project", project.getKey());
req.put("projectId", project.getId());
try {
restclient.post(Resource.getBaseUri() + "version/", req);
} catch (Exception ex) {
throw new JiraException("Failed to copy to project '" + project.getKey() + "'", ex);
}
}
/**
* Retrieves the given version record.
*
* @param restclient REST client instance
* @param id Internal JIRA ID of the version
* @return a version instance
* @throws JiraException when the retrieval fails
*/
public static Version get(RestClient restclient, String id)
throws JiraException {
JSON result = null;
try {
result = restclient.get(getBaseUri() + "version/" + id);
} catch (Exception ex) {
throw new JiraException("Failed to retrieve version " + id, ex);
}
if (!(result instanceof JSONObject))
throw new JiraException("JSON payload is malformed");
return new Version(restclient, (JSONObject) result);
}
private void deserialise(JSONObject json) {
Map map = json;
self = Field.getString(map.get("self"));
id = Field.getString(map.get("id"));
name = Field.getString(map.get("name"));
archived = Field.getBoolean(map.get("archived"));
released = Field.getBoolean(map.get("released"));
releaseDate = Field.getString(map.get("releaseDate"));
description = Field.getString(map.get("description"));
}
@Override
public String toString() {
return getName();
}
public String getName() {
return name;
}
public boolean isArchived() {
return archived;
}
public boolean isReleased() {
return released;
}
public String getReleaseDate() {
return releaseDate;
}
public String getDescription() {
return description;
}
private static String getRestUri(String id) {
return getBaseUri() + "version/" + (id != null ? id : "");
}
/**
* Creates a new JIRA Version.
*
* @param restclient REST client instance
* @param project Key of the project to create the version in
*
* @return a fluent create instance
*/
public static FluentCreate create(RestClient restclient, String project) {
FluentCreate fc = new FluentCreate(restclient, project);
return fc;
}
}
|
3e1d15b90a6030f3f26ea6dddaba15ecde97328b | 2,373 | java | Java | AL-Game/src/com/aionemu/gameserver/model/templates/portal/PortalReq.java | karllgiovany/Aion-Lightning-4.9-SRC | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2019-09-24T23:26:34.000Z | 2019-09-24T23:26:34.000Z | AL-Game/src/com/aionemu/gameserver/model/templates/portal/PortalReq.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | null | null | null | AL-Game/src/com/aionemu/gameserver/model/templates/portal/PortalReq.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2017-12-28T16:59:47.000Z | 2017-12-28T16:59:47.000Z | 25.793478 | 74 | 0.671302 | 12,326 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.templates.portal;
import com.aionemu.gameserver.configs.main.GSConfig;
import javax.xml.bind.annotation.*;
import java.util.List;
/**
* @author xTz
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PortalReq")
public class PortalReq {
@XmlElement(name = "quest_req")
protected List<QuestReq> questReq;
@XmlElement(name = "item_req")
protected List<ItemReq> itemReq;
@XmlAttribute(name = "min_level")
protected int minLevel;
@XmlAttribute(name = "max_level")
protected int maxLevel = GSConfig.PLAYER_MAX_LEVEL;
@XmlAttribute(name = "kinah_req")
protected int kinahReq;
@XmlAttribute(name = "title_id")
protected int titleId;
@XmlAttribute(name = "err_level")
protected int errLevel;
@XmlAttribute(name = "legion_req")
protected boolean legionReq;
public List<QuestReq> getQuestReq() {
return this.questReq;
}
public List<ItemReq> getItemReq() {
return this.itemReq;
}
public int getMinLevel() {
return minLevel;
}
public void setMinLevel(int value) {
this.minLevel = value;
}
public int getMaxLevel() {
return maxLevel;
}
public void setMaxLevel(int value) {
this.maxLevel = value;
}
public int getKinahReq() {
return kinahReq;
}
public void setKinahReq(int value) {
this.kinahReq = value;
}
public int getTitleId() {
return titleId;
}
public int getErrLevel() {
return errLevel;
}
public boolean getLegionReq() {
return legionReq;
}
}
|
3e1d16b88d9c8607d8b6c537c0810eb6388c9b5f | 965 | java | Java | spring-amqp/src/main/java/org/springframework/amqp/core/CorrelationAwareMessagePostProcessor.java | tqrg-bot/spring-amqp | dde0ad39669e38a7fb5707c1d3783fac5f556ec1 | [
"Apache-2.0"
] | null | null | null | spring-amqp/src/main/java/org/springframework/amqp/core/CorrelationAwareMessagePostProcessor.java | tqrg-bot/spring-amqp | dde0ad39669e38a7fb5707c1d3783fac5f556ec1 | [
"Apache-2.0"
] | null | null | null | spring-amqp/src/main/java/org/springframework/amqp/core/CorrelationAwareMessagePostProcessor.java | tqrg-bot/spring-amqp | dde0ad39669e38a7fb5707c1d3783fac5f556ec1 | [
"Apache-2.0"
] | null | null | null | 32.166667 | 84 | 0.748187 | 12,327 | /*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.amqp.core;
/**
* A message post processor that can also use/manipulate correlation data.
*
* @author Gary Russell
* @since 1.6.7
* @deprecated in 2.0, the method has been moved to {@link MessagePostProcessor}.
*/
@Deprecated
public interface CorrelationAwareMessagePostProcessor extends MessagePostProcessor {
}
|
3e1d17f93d8b2753f86cdb92b38bd15513d2aa63 | 1,144 | java | Java | [Array]-30-substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.java | JingGe/leetcode | a6538515c6dad27dcb2190850e04e5f8abe63dc3 | [
"Apache-2.0"
] | 1 | 2021-07-19T16:13:06.000Z | 2021-07-19T16:13:06.000Z | [Array]-30-substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.java | JingGe/leetcode | a6538515c6dad27dcb2190850e04e5f8abe63dc3 | [
"Apache-2.0"
] | null | null | null | [Array]-30-substring-with-concatenation-of-all-words/substring-with-concatenation-of-all-words.java | JingGe/leetcode | a6538515c6dad27dcb2190850e04e5f8abe63dc3 | [
"Apache-2.0"
] | null | null | null | 29.333333 | 85 | 0.48514 | 12,328 | /**
* https://www.cnblogs.com/grandyang/p/4521224.html
*/
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
int wordsNumber = words.length;
int wordLength = words[0].length();
List<Integer> result = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
map.put(word, map.getOrDefault(word, 0)+1);
}
//System.out.println(map);
for(int i=0; i<=s.length()-wordLength*wordsNumber;i++) {
Map<String, Integer> current = new HashMap<>();
int j=0;
for(j=0;j<wordsNumber;j++) {
String word = s.substring(i+j*wordLength, i+j*wordLength+wordLength);
if (!map.containsKey(word)) break;
current.put(word, current.getOrDefault(word, 0)+1);
if (current.get(word) > map.get(word)) break;
}
if (j==wordsNumber) result.add(i);
}
return result;
}
}
|
3e1d180f0a22b680fe573626e1f05efcc999a58f | 12,375 | java | Java | foxtrot-core/src/test/java/com/flipkart/foxtrot/core/querystore/impl/ElasticsearchQueryStoreTest.java | grasskode/foxtrot | 31d3d0d32846bff3984673809515809a139b1f98 | [
"Apache-2.0"
] | null | null | null | foxtrot-core/src/test/java/com/flipkart/foxtrot/core/querystore/impl/ElasticsearchQueryStoreTest.java | grasskode/foxtrot | 31d3d0d32846bff3984673809515809a139b1f98 | [
"Apache-2.0"
] | 3 | 2021-07-02T18:43:16.000Z | 2022-03-08T21:11:25.000Z | foxtrot-core/src/test/java/com/flipkart/foxtrot/core/querystore/impl/ElasticsearchQueryStoreTest.java | grasskode/foxtrot | 31d3d0d32846bff3984673809515809a139b1f98 | [
"Apache-2.0"
] | null | null | null | 44.836957 | 145 | 0.686949 | 12,329 | /**
* Copyright 2014 Flipkart Internet Pvt. 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.flipkart.foxtrot.core.querystore.impl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.foxtrot.common.Document;
import com.flipkart.foxtrot.common.FieldType;
import com.flipkart.foxtrot.common.FieldTypeMapping;
import com.flipkart.foxtrot.common.TableFieldMapping;
import com.flipkart.foxtrot.core.MockElasticsearchServer;
import com.flipkart.foxtrot.core.TestUtils;
import com.flipkart.foxtrot.core.datastore.DataStore;
import com.flipkart.foxtrot.core.datastore.DataStoreException;
import com.flipkart.foxtrot.core.querystore.QueryExecutor;
import com.flipkart.foxtrot.core.querystore.QueryStoreException;
import com.flipkart.foxtrot.core.querystore.TableMetadataManager;
import com.flipkart.foxtrot.core.querystore.actions.spi.AnalyticsLoader;
import org.elasticsearch.action.get.GetResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
/**
* Created by rishabh.goyal on 16/04/14.
*/
public class ElasticsearchQueryStoreTest {
private MockElasticsearchServer elasticsearchServer;
private DataStore dataStore;
private ElasticsearchQueryStore queryStore;
private ObjectMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new ObjectMapper();
ElasticsearchUtils.setMapper(mapper);
dataStore = TestUtils.getDataStore();
elasticsearchServer = new MockElasticsearchServer(UUID.randomUUID().toString());
ElasticsearchConnection elasticsearchConnection = Mockito.mock(ElasticsearchConnection.class);
when(elasticsearchConnection.getClient()).thenReturn(elasticsearchServer.getClient());
ElasticsearchUtils.initializeMappings(elasticsearchConnection.getClient());
AnalyticsLoader analyticsLoader = new AnalyticsLoader(dataStore, elasticsearchConnection);
ExecutorService executorService = Executors.newFixedThreadPool(1);
QueryExecutor queryExecutor = new QueryExecutor(analyticsLoader, executorService);
TableMetadataManager tableMetadataManager = Mockito.mock(TableMetadataManager.class);
when(tableMetadataManager.exists(TestUtils.TEST_TABLE)).thenReturn(true);
queryStore = new ElasticsearchQueryStore(tableMetadataManager, elasticsearchConnection, dataStore, queryExecutor);
}
@After
public void tearDown() throws Exception {
elasticsearchServer.shutdown();
}
@Test
public void testSaveSingle() throws Exception {
Document expectedDocument = new Document();
expectedDocument.setId(UUID.randomUUID().toString());
expectedDocument.setTimestamp(System.currentTimeMillis());
JsonNode data = mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"));
expectedDocument.setData(data);
queryStore.save(TestUtils.TEST_TABLE, expectedDocument);
GetResponse getResponse = elasticsearchServer
.getClient()
.prepareGet(ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE, expectedDocument.getTimestamp()),
ElasticsearchUtils.TYPE_NAME,
expectedDocument.getId())
.setFields("_timestamp").execute().actionGet();
assertTrue("Id should exist in ES", getResponse.isExists());
assertEquals("Id should match requestId", expectedDocument.getId(), getResponse.getId());
assertEquals("Timestamp should match request timestamp", expectedDocument.getTimestamp(), getResponse.getField("_timestamp").getValue());
}
@Test
public void testSaveSingleInvalidTable() throws Exception {
Document expectedDocument = new Document();
expectedDocument.setId(UUID.randomUUID().toString());
expectedDocument.setTimestamp(System.currentTimeMillis());
JsonNode data = mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"));
expectedDocument.setData(data);
try {
queryStore.save(TestUtils.TEST_TABLE + "-missing", expectedDocument);
fail();
} catch (QueryStoreException qse) {
assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, qse.getErrorCode());
}
}
@Test
public void testSaveBulk() throws Exception {
List<Document> documents = new Vector<Document>();
for (int i = 0; i < 10; i++) {
documents.add(new Document(UUID.randomUUID().toString(),
System.currentTimeMillis(),
mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"))));
}
queryStore.save(TestUtils.TEST_TABLE, documents);
for (Document document : documents) {
GetResponse getResponse = elasticsearchServer
.getClient()
.prepareGet(ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE, document.getTimestamp()),
ElasticsearchUtils.TYPE_NAME,
document.getId())
.setFields("_timestamp").execute().actionGet();
assertTrue("Id should exist in ES", getResponse.isExists());
assertEquals("Id should match requestId", document.getId(), getResponse.getId());
assertEquals("Timestamp should match request timestamp", document.getTimestamp(), getResponse.getField("_timestamp").getValue());
}
}
@Test
public void testSaveBulkNullList() throws Exception {
List<Document> list = null;
try{
queryStore.save(TestUtils.TEST_TABLE, list);
fail();
}catch (QueryStoreException ex){
assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getErrorCode());
}
}
@Test
public void testSaveBulkEmptyList() throws Exception {
List<Document> list = new Vector<Document>();
try{
queryStore.save(TestUtils.TEST_TABLE, list);
fail();
}catch (QueryStoreException ex){
assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, ex.getErrorCode());
}
}
@Test
public void testSaveBulkInvalidTable() throws Exception {
List<Document> documents = new Vector<Document>();
for (int i = 0; i < 10; i++) {
documents.add(new Document(UUID.randomUUID().toString(),
System.currentTimeMillis(),
mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"))));
}
try {
queryStore.save(TestUtils.TEST_TABLE + "-missing", documents);
fail();
} catch (QueryStoreException qse) {
assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, qse.getErrorCode());
}
}
@Test
public void testGetSingle() throws Exception {
String id = UUID.randomUUID().toString();
long timestamp = System.currentTimeMillis();
JsonNode data = mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"));
Document document = new Document(id, System.currentTimeMillis(), data);
document.setTimestamp(timestamp);
dataStore.save(TestUtils.TEST_TABLE, document);
Document responseDocument = queryStore.get(TestUtils.TEST_TABLE, id);
assertNotNull(responseDocument);
assertEquals(id, responseDocument.getId());
assertEquals("Timestamp should match request timestamp", document.getTimestamp(), responseDocument.getTimestamp());
}
@Test
public void testGetSingleInvalidId() throws Exception {
try {
queryStore.get(TestUtils.TEST_TABLE, UUID.randomUUID().toString());
} catch (QueryStoreException qse) {
assertEquals(QueryStoreException.ErrorCode.DOCUMENT_NOT_FOUND, qse.getErrorCode());
}
}
@Test
public void testGetBulk() throws Exception {
Map<String, Document> idValues = new HashMap<String, Document>();
List<String> ids = new Vector<String>();
for (int i = 0; i < 10; i++) {
String id = UUID.randomUUID().toString();
ids.add(id);
idValues.put(id,
new Document(id,
System.currentTimeMillis(),
mapper.valueToTree(Collections.singletonMap("TEST_NAME", "SINGLE_SAVE_TEST"))));
idValues.get(id).setTimestamp(System.currentTimeMillis());
}
for (Document document : idValues.values()) {
dataStore.save(TestUtils.TEST_TABLE, document);
}
List<Document> responseDocuments = queryStore.get(TestUtils.TEST_TABLE, ids);
HashMap<String, Document> responseIdValues = new HashMap<String, Document>();
for (Document doc : responseDocuments) {
responseIdValues.put(doc.getId(), doc);
}
assertNotNull("List of returned Documents should not be null", responseDocuments);
for (String id : ids) {
assertTrue("Requested Id should be present in response", responseIdValues.containsKey(id));
assertNotNull(responseIdValues.get(id));
assertEquals(id, responseIdValues.get(id).getId());
assertEquals("Timestamp should match request timestamp", idValues.get(id).getTimestamp(), responseIdValues.get(id).getTimestamp());
}
}
@Test
public void testGetBulkInvalidIds() throws Exception {
try {
queryStore.get(TestUtils.TEST_TABLE, Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString()));
fail();
} catch (QueryStoreException qse) {
assertEquals(QueryStoreException.ErrorCode.DOCUMENT_NOT_FOUND, qse.getErrorCode());
}
}
@Test
public void testGetFieldMappings() throws QueryStoreException, InterruptedException {
queryStore.save(TestUtils.TEST_TABLE, TestUtils.getMappingDocuments(mapper));
Thread.sleep(500);
Set<FieldTypeMapping> mappings = new HashSet<FieldTypeMapping>();
mappings.add(new FieldTypeMapping("word", FieldType.STRING));
mappings.add(new FieldTypeMapping("data.data", FieldType.STRING));
mappings.add(new FieldTypeMapping("header.hello", FieldType.STRING));
mappings.add(new FieldTypeMapping("head.hello", FieldType.LONG));
TableFieldMapping tableFieldMapping = new TableFieldMapping(TestUtils.TEST_TABLE, mappings);
TableFieldMapping responseMapping = queryStore.getFieldMappings(TestUtils.TEST_TABLE);
assertEquals(tableFieldMapping.getTable(), responseMapping.getTable());
assertTrue(tableFieldMapping.getMappings().equals(responseMapping.getMappings()));
}
@Test
public void testGetFieldMappingsNonExistingTable() throws QueryStoreException {
try {
queryStore.getFieldMappings(TestUtils.TEST_TABLE + "-test");
fail();
} catch (QueryStoreException qse) {
assertEquals(QueryStoreException.ErrorCode.NO_SUCH_TABLE, qse.getErrorCode());
}
}
@Test
public void testGetFieldMappingsNoDocumentsInTable() throws QueryStoreException {
TableFieldMapping request = new TableFieldMapping(TestUtils.TEST_TABLE, new HashSet<FieldTypeMapping>());
TableFieldMapping response = queryStore.getFieldMappings(TestUtils.TEST_TABLE);
assertEquals(request.getTable(), response.getTable());
assertTrue(request.getMappings().equals(response.getMappings()));
}
}
|
3e1d18ad22da81a2614a911ea85a38da038093de | 830 | java | Java | src/main/java/com/mahogano/core/presta/mapper/SmartyLazyCacheMapper.java | mahogano/mahogano | e4e8db4659946cd997b5aa34660c19749312e2a0 | [
"MIT"
] | null | null | null | src/main/java/com/mahogano/core/presta/mapper/SmartyLazyCacheMapper.java | mahogano/mahogano | e4e8db4659946cd997b5aa34660c19749312e2a0 | [
"MIT"
] | null | null | null | src/main/java/com/mahogano/core/presta/mapper/SmartyLazyCacheMapper.java | mahogano/mahogano | e4e8db4659946cd997b5aa34660c19749312e2a0 | [
"MIT"
] | null | null | null | 36.086957 | 88 | 0.761446 | 12,330 | package com.mahogano.core.presta.mapper;
import com.mahogano.core.presta.entity.SmartyLazyCache;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SmartyLazyCacheMapper implements RowMapper<SmartyLazyCache> {
@Override
public SmartyLazyCache mapRow(ResultSet rs, int i) throws SQLException {
SmartyLazyCache smartyLazyCache = new SmartyLazyCache();
smartyLazyCache.setTemplateHash(rs.getString("template_hash"));
smartyLazyCache.setCacheId(rs.getString("cache_id"));
smartyLazyCache.setCompileId(rs.getString("compile_id"));
smartyLazyCache.setFilepath(rs.getString("filepath"));
smartyLazyCache.setLastUpdate(rs.getTimestamp("last_update").toLocalDateTime());
return smartyLazyCache;
}
}
|
3e1d1b733f06d2852bfc14c1a039af67bd226a91 | 741 | java | Java | src/com/my/designpatterns/behavior/chainofresponsibility/RequestorClientTest.java | tunlinnaung/designpatternjava | ef128359d813f0a0ebf451f26b3ca456b95dacf4 | [
"Apache-2.0"
] | null | null | null | src/com/my/designpatterns/behavior/chainofresponsibility/RequestorClientTest.java | tunlinnaung/designpatternjava | ef128359d813f0a0ebf451f26b3ca456b95dacf4 | [
"Apache-2.0"
] | null | null | null | src/com/my/designpatterns/behavior/chainofresponsibility/RequestorClientTest.java | tunlinnaung/designpatternjava | ef128359d813f0a0ebf451f26b3ca456b95dacf4 | [
"Apache-2.0"
] | null | null | null | 46.3125 | 106 | 0.593792 | 12,331 | package com.my.designpatterns.behavior.chainofresponsibility;
public class RequestorClientTest {
public static void main(String[] args) {
AbstractSupportHandler handler = RequestorClient.getHandlerChain();
handler.receiveRequest(AbstractSupportHandler.TECHNICAL, "please resolve for technical problem.");
System.out.println("............................................");
handler.receiveRequest(AbstractSupportHandler.BILLING, "billing have problem.");
System.out.println("............................................");
handler.receiveRequest(AbstractSupportHandler.GENERAL, "why loading so long.");
System.out.println("............................................");
}
}
|
3e1d1bcef1ebc3677524e6bd4944646b84d52f77 | 1,251 | java | Java | chapter5/src/main/java/com/manning/pulsar/chapter5/source/DirectorySource.java | AlexRogalskiy/pulsar-in-action | 83d5fdc82ecf54eda652aeddb4974e509ad08e49 | [
"Apache-2.0"
] | 37 | 2019-09-14T08:58:14.000Z | 2022-02-24T14:28:07.000Z | chapter5/src/main/java/com/manning/pulsar/chapter5/source/DirectorySource.java | david-streamlio/pulsar-in-action | 83d5fdc82ecf54eda652aeddb4974e509ad08e49 | [
"Apache-2.0"
] | 3 | 2020-01-04T02:27:23.000Z | 2021-05-01T00:22:40.000Z | chapter5/src/main/java/com/manning/pulsar/chapter5/source/DirectorySource.java | AlexRogalskiy/pulsar-in-action | 83d5fdc82ecf54eda652aeddb4974e509ad08e49 | [
"Apache-2.0"
] | 15 | 2019-08-22T18:39:32.000Z | 2022-02-15T08:41:03.000Z | 32.076923 | 89 | 0.766587 | 12,332 | package com.manning.pulsar.chapter5.source;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.pulsar.io.core.PushSource;
import org.apache.pulsar.io.core.SourceContext;
import org.slf4j.Logger;
public class DirectorySource extends PushSource<String> {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
private DirectoryConsumerThread scanner;
private Logger log;
@Override
public void open(Map<String, Object> config, SourceContext context) throws Exception {
log = context.getLogger();
String inputDir = (String) config.getOrDefault("inputDir", ".");
String processedDir = (String) config.getOrDefault("processedDir", ".");
String frequency = (String) config.getOrDefault("frequency", "10");
scanner = new DirectoryConsumerThread(this, inputDir, processedDir, log);
scheduler.scheduleAtFixedRate(scanner, 0, Long.parseLong(frequency), TimeUnit.MINUTES);
log.info(String.format("Scheduled to run every %s minutes", frequency));
}
@Override
public void close() throws Exception {
log.info("Closing connector");
scheduler.shutdownNow();
}
}
|
3e1d1d0e734a61789bf92d7cc4ec2a451b3b70ec | 224 | java | Java | shared/src/main/java/org/diskproject/shared/classes/vocabulary/Individual.java | reginawang99/DISKNeuro | 88c7b8cdd2aac0d62e012b9c87992ab707981051 | [
"Apache-2.0"
] | null | null | null | shared/src/main/java/org/diskproject/shared/classes/vocabulary/Individual.java | reginawang99/DISKNeuro | 88c7b8cdd2aac0d62e012b9c87992ab707981051 | [
"Apache-2.0"
] | 3 | 2022-01-19T20:16:53.000Z | 2022-03-22T00:51:44.000Z | shared/src/main/java/org/diskproject/shared/classes/vocabulary/Individual.java | KnowledgeCaptureAndDiscovery/DISK-WEB | 291334cf10f6ed3b5e4d248ebcfdb1eea577c479 | [
"Apache-2.0"
] | null | null | null | 16 | 50 | 0.696429 | 12,333 | package org.diskproject.shared.classes.vocabulary;
public class Individual extends Entity {
String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
3e1d1d1e549c73f7203eb3a48b621b22d251fbc2 | 1,188 | java | Java | odps-sdk/odps-sdk-graph/src/main/java/com/aliyun/odps/graph/job/JobRunner.java | fetchadd/aliyun-odps-java-sdk | 86dc24289f95a595cff7066ff567148dc8d3f08e | [
"Apache-2.0"
] | 80 | 2015-07-08T09:33:25.000Z | 2022-03-12T16:58:28.000Z | odps-sdk/odps-sdk-graph/src/main/java/com/aliyun/odps/graph/job/JobRunner.java | fetchadd/aliyun-odps-java-sdk | 86dc24289f95a595cff7066ff567148dc8d3f08e | [
"Apache-2.0"
] | 43 | 2016-03-29T06:40:44.000Z | 2022-02-28T10:32:10.000Z | odps-sdk/odps-sdk-graph/src/main/java/com/aliyun/odps/graph/job/JobRunner.java | fetchadd/aliyun-odps-java-sdk | 86dc24289f95a595cff7066ff567148dc8d3f08e | [
"Apache-2.0"
] | 55 | 2015-09-02T14:27:29.000Z | 2022-01-12T02:33:22.000Z | 30.461538 | 63 | 0.744108 | 12,334 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.aliyun.odps.graph.job;
import com.aliyun.odps.OdpsException;
import com.aliyun.odps.conf.Configurable;
import com.aliyun.odps.mapred.RunningJob;
/**
* 该接口用于执行作业提交
*/
public interface JobRunner extends Configurable {
/**
* 提交一个Graph作业,返回一个正在运行作业的实例
*
* @return 正在运行作业的实例
* @throws OdpsException
*/
RunningJob submit() throws OdpsException;
}
|
3e1d1de2985c867083a66b50931feccc5d89f16f | 1,024 | java | Java | src/main/java/com/emc/documentum/rest/client/sample/model/json/JsonAvailableAuditEvents.java | octanner/documentum-rest-client-java | 0f5b03ebb4686fc3eeea4166be75be8195edd166 | [
"Apache-2.0"
] | 40 | 2016-03-23T08:31:01.000Z | 2021-07-28T03:15:34.000Z | src/main/java/com/emc/documentum/rest/client/sample/model/json/JsonAvailableAuditEvents.java | djole87/documentum-rest-client-java | 0f5b03ebb4686fc3eeea4166be75be8195edd166 | [
"Apache-2.0"
] | 10 | 2016-03-29T06:35:57.000Z | 2021-12-09T20:21:34.000Z | src/main/java/com/emc/documentum/rest/client/sample/model/json/JsonAvailableAuditEvents.java | djole87/documentum-rest-client-java | 0f5b03ebb4686fc3eeea4166be75be8195edd166 | [
"Apache-2.0"
] | 29 | 2016-03-24T02:30:11.000Z | 2020-09-11T11:19:22.000Z | 27.675676 | 96 | 0.713867 | 12,335 | /*
* Copyright (c) 2018. Open Text Corporation. All Rights Reserved.
*/
package com.emc.documentum.rest.client.sample.model.json;
import java.util.List;
import java.util.Objects;
import com.emc.documentum.rest.client.sample.client.util.Equals;
import com.emc.documentum.rest.client.sample.model.AvailableAuditEvents;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class JsonAvailableAuditEvents extends JsonLinkableBase implements AvailableAuditEvents {
private List<String> events;
public List<String> getEvents() {
return events;
}
public void setEvents(List<String> events) {
this.events = events;
}
@Override
public boolean equals(Object obj) {
JsonAvailableAuditEvents that = (JsonAvailableAuditEvents) obj;
return Equals.equal(events, that.events)
&& super.equals(obj);
}
@Override
public int hashCode() {
return Objects.hash(events);
}
}
|
3e1d1e0616c7994f0351fb10c84a1e2ffd4b1ced | 1,319 | java | Java | src/main/java/com/github/cive/core/shogi/Pieces/Gin.java | cive/shogicore | d5ce8013cccb3f037c8aab3bafe72296d8121c66 | [
"MIT"
] | 3 | 2018-03-18T08:13:16.000Z | 2020-10-16T01:48:45.000Z | src/main/java/com/github/cive/core/shogi/Pieces/Gin.java | cive/shogicore | d5ce8013cccb3f037c8aab3bafe72296d8121c66 | [
"MIT"
] | 5 | 2018-03-18T15:15:44.000Z | 2018-07-08T02:36:13.000Z | src/main/java/com/github/cive/core/shogi/Pieces/Gin.java | cive/shogicore | d5ce8013cccb3f037c8aab3bafe72296d8121c66 | [
"MIT"
] | null | null | null | 23.553571 | 73 | 0.536012 | 12,336 | package com.github.cive.core.shogi.Pieces;
import com.github.cive.core.shogi.Players.PlayerBase;
import java.awt.*;
import java.util.HashSet;
import java.util.Set;
public class Gin extends PieceBase {
public Gin(Point p) {
super(p);
}
@Override
public String getName() {
return "銀";
}
@Override
public String getName(Boolean in_English) {
if (in_English) {
return "GI";
} else {
return getName();
}
}
@Override
public Set<Point> getRuleOfPiece(PlayerBase.PlayerType player_type) {
Set<Point> set = new HashSet<>();
if(player_type == PlayerBase.PlayerType.Ahead) {
set.add(new Point(-1, -1));
set.add(new Point(0, -1));
set.add(new Point(1, -1));
set.add(new Point(-1, 1));
set.add(new Point(1, 1));
} else {
set.add(new Point(-1, 1));
set.add(new Point(0, 1));
set.add(new Point(1, 1));
set.add(new Point(-1, -1));
set.add(new Point(1, -1));
}
return set;
}
@Override
public Integer getTypeOfPiece() {
return PieceBase.GIN;
}
@Override
public Integer getBacksideType()
{
return PieceBase.NARIGIN;
}
}
|
3e1d1efccfec3613f7f1e5dbc81a4aa5b3c01a3d | 862 | java | Java | blackduck-artifactory-common/src/main/java/com/synopsys/integration/blackduck/artifactory/modules/inspection/externalid/composer/model/FileNamePieces.java | blackducksoftware/blackduck-artifactory | 1571e2d21cb39d7ed45d431d517f843f6e94e97b | [
"Apache-2.0"
] | 7 | 2018-11-19T02:55:52.000Z | 2021-08-18T14:41:31.000Z | blackduck-artifactory-common/src/main/java/com/synopsys/integration/blackduck/artifactory/modules/inspection/externalid/composer/model/FileNamePieces.java | blackducksoftware/blackduck-artifactory | 1571e2d21cb39d7ed45d431d517f843f6e94e97b | [
"Apache-2.0"
] | 28 | 2019-04-19T08:04:45.000Z | 2022-01-31T08:33:58.000Z | blackduck-artifactory-common/src/main/java/com/synopsys/integration/blackduck/artifactory/modules/inspection/externalid/composer/model/FileNamePieces.java | blackducksoftware/blackduck-artifactory | 1571e2d21cb39d7ed45d431d517f843f6e94e97b | [
"Apache-2.0"
] | 8 | 2019-01-17T21:48:10.000Z | 2021-07-12T22:19:17.000Z | 26.121212 | 142 | 0.701856 | 12,337 | /*
* blackduck-artifactory-common
*
* Copyright (c) 2021 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.blackduck.artifactory.modules.inspection.externalid.composer.model;
public class FileNamePieces {
private final String componentName;
private final String hash;
private final String extension;
public FileNamePieces(String componentName, String hash, String extension) {
this.componentName = componentName;
this.hash = hash;
this.extension = extension;
}
public String getComponentName() {
return componentName;
}
public String getHash() {
return hash;
}
public String getExtension() {
return extension;
}
}
|
3e1d1f63b4f74042459637ec389672b517583a37 | 1,032 | java | Java | Slrtce/app/src/main/java/com/palette/PaletteTarget.java | Eklavya-EIPAR/eklavya | 36d8c11f8224477aa4463f319d1303256ab2094d | [
"Unlicense"
] | 75 | 2017-08-18T08:22:02.000Z | 2022-03-23T11:54:01.000Z | Slrtce/app/src/main/java/com/palette/PaletteTarget.java | Eklavya-EIPAR/eklavya | 36d8c11f8224477aa4463f319d1303256ab2094d | [
"Unlicense"
] | 7 | 2017-10-02T13:11:46.000Z | 2020-04-13T13:16:03.000Z | Slrtce/app/src/main/java/com/palette/PaletteTarget.java | Eklavya-EIPAR/eklavya | 36d8c11f8224477aa4463f319d1303256ab2094d | [
"Unlicense"
] | 72 | 2017-07-15T21:25:50.000Z | 2022-03-23T10:31:24.000Z | 26.461538 | 83 | 0.718992 | 12,338 | package com.palette;
import android.support.v4.util.Pair;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Coolalien on 1/3/2017.
*/
public class PaletteTarget {
@BitmapPalette.Profile
protected int paletteProfile = GlidePalette.Profile.VIBRANT;
protected ArrayList<Pair<View, Integer>> targetsBackground = new ArrayList<>();
protected ArrayList<Pair<TextView, Integer>> targetsText = new ArrayList<>();
protected boolean targetCrossfade = false;
protected int targetCrossfadeSpeed = DEFAULT_CROSSFADE_SPEED;
protected static final int DEFAULT_CROSSFADE_SPEED = 300;
public PaletteTarget(@BitmapPalette.Profile int paletteProfile) {
this.paletteProfile = paletteProfile;
}
public void clear() {
targetsBackground.clear();
targetsText.clear();
targetsBackground = null;
targetsText = null;
targetCrossfade = false;
targetCrossfadeSpeed = DEFAULT_CROSSFADE_SPEED;
}
} |
3e1d1f77cffbbc1ab7f5388bc39285622ea5a49a | 4,891 | java | Java | plugins/com.google.cloud.tools.eclipse.integration.appengine/src/com/google/cloud/tools/eclipse/integration/appengine/NewNativeAppEngineStandardProjectTest.java | chanseokoh/google-cloud-eclipse | 418b4bc88c446afe31eb87e6d54d475ebfc3a931 | [
"Apache-2.0"
] | 80 | 2016-10-09T10:28:00.000Z | 2022-01-21T15:43:22.000Z | plugins/com.google.cloud.tools.eclipse.integration.appengine/src/com/google/cloud/tools/eclipse/integration/appengine/NewNativeAppEngineStandardProjectTest.java | chanseokoh/google-cloud-eclipse | 418b4bc88c446afe31eb87e6d54d475ebfc3a931 | [
"Apache-2.0"
] | 2,802 | 2016-09-26T16:44:53.000Z | 2022-03-16T03:50:13.000Z | plugins/com.google.cloud.tools.eclipse.integration.appengine/src/com/google/cloud/tools/eclipse/integration/appengine/NewNativeAppEngineStandardProjectTest.java | isabella232/google-cloud-eclipse | 4d213f59421f7d28aab17e336a248713fc97f1fa | [
"Apache-2.0"
] | 63 | 2016-10-09T17:59:29.000Z | 2022-03-29T15:01:44.000Z | 45.287037 | 99 | 0.754651 | 12,339 | /*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.tools.eclipse.integration.appengine;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.cloud.tools.eclipse.appengine.facets.AppEngineStandardFacet;
import com.google.cloud.tools.eclipse.appengine.ui.AppEngineRuntime;
import com.google.cloud.tools.eclipse.test.util.ThreadDumpingWatchdog;
import com.google.cloud.tools.eclipse.test.util.project.ProjectUtils;
import java.util.concurrent.TimeUnit;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jst.common.project.facet.core.JavaFacet;
import org.eclipse.jst.j2ee.web.project.facet.WebFacetUtils;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.junit.Rule;
import org.junit.Test;
/**
* Test creation of a new standard App Engine project.
*/
public class NewNativeAppEngineStandardProjectTest extends BaseProjectTest {
@Rule
public ThreadDumpingWatchdog timer = new ThreadDumpingWatchdog(2, TimeUnit.MINUTES);
@Test
public void testWithDefaults() throws Exception {
String[] projectFiles = {"src/main/java/HelloAppEngine.java",
"src/main/webapp/META-INF/MANIFEST.MF", "src/main/webapp/WEB-INF/appengine-web.xml",
"src/main/webapp/WEB-INF/web.xml", "src/main/webapp/index.html"};
createAndCheck("appWithDefault_java8", null /* packageName */, null /* runtime */,
projectFiles);
}
@Test
public void testWithDefaults_java8Servlet25() throws Exception {
String[] projectFiles = {"src/main/java/HelloAppEngine.java",
"src/main/webapp/META-INF/MANIFEST.MF", "src/main/webapp/WEB-INF/appengine-web.xml",
"src/main/webapp/WEB-INF/web.xml", "src/main/webapp/index.html"};
createAndCheck("appWithDefault_java8Servlet25", null /* packageName */,
AppEngineRuntime.STANDARD_JAVA_8_SERVLET_25, projectFiles);
}
@Test
public void testWithPackage() throws Exception {
String[] projectFiles = {"src/main/java/app/engine/test/HelloAppEngine.java",
"src/main/webapp/META-INF/MANIFEST.MF", "src/main/webapp/WEB-INF/appengine-web.xml",
"src/main/webapp/WEB-INF/web.xml", "src/main/webapp/index.html",};
createAndCheck("appWithPackage_java8", "app.engine.test", null /* runtime */, projectFiles);
}
/** Create a project with the given parameters. */
private void createAndCheck(String projectName, String packageName, AppEngineRuntime runtime,
String[] projectFiles) throws CoreException {
assertFalse(projectExists(projectName));
project = SwtBotAppEngineActions.createNativeWebAppProject(bot, projectName, null, packageName,
runtime);
assertTrue(project.exists());
IFacetedProject facetedProject = ProjectFacetsManager.create(project);
assertNotNull("Native App Engine projects should be faceted", facetedProject);
// we don't currently export a JRE8 facet version
assertNotNull("Project does not have standard facet",
facetedProject.getProjectFacetVersion(AppEngineStandardFacet.FACET));
assertEquals("Project does not have standard facet", "JRE8",
facetedProject.getProjectFacetVersion(AppEngineStandardFacet.FACET).getVersionString());
assertEquals(JavaFacet.VERSION_1_8, facetedProject.getProjectFacetVersion(JavaFacet.FACET));
if (runtime == null || runtime == AppEngineRuntime.STANDARD_JAVA_8) {
assertEquals(WebFacetUtils.WEB_31,
facetedProject.getProjectFacetVersion(WebFacetUtils.WEB_FACET));
} else if (runtime == AppEngineRuntime.STANDARD_JAVA_8_SERVLET_25) {
assertEquals(WebFacetUtils.WEB_25,
facetedProject.getProjectFacetVersion(WebFacetUtils.WEB_FACET));
} else {
fail("Runtime not handled: " + runtime);
}
for (String projectFile : projectFiles) {
Path projectFilePath = new Path(projectFile);
assertTrue(project.exists(projectFilePath));
}
ProjectUtils.waitForProjects(project); // App Engine runtime is added via a Job, so wait.
ProjectUtils.failIfBuildErrors("New native project has errors", project);
}
}
|
3e1d200f2d2f5a788337c9600ab1f75c103a2b69 | 1,303 | java | Java | src/main/java/core/cli/TraceGenerator.java | AppLoidx/bcomp-extended | ad556afaefa69a87ed976b8869d0fa07b93a0c6f | [
"MIT"
] | 28 | 2019-05-02T11:44:05.000Z | 2022-02-17T14:54:08.000Z | src/main/java/core/cli/TraceGenerator.java | AppLoidx/bcomp-extended | ad556afaefa69a87ed976b8869d0fa07b93a0c6f | [
"MIT"
] | 3 | 2019-08-21T13:37:01.000Z | 2021-11-18T12:37:05.000Z | src/main/java/core/cli/TraceGenerator.java | AppLoidx/bcomp-extended | ad556afaefa69a87ed976b8869d0fa07b93a0c6f | [
"MIT"
] | null | null | null | 28.326087 | 66 | 0.46815 | 12,340 | package core.cli;
/**
* @author Arthur Kupriyanov
*/
public class TraceGenerator {
// public File generate(String traceCommands, String fileName){
// Workbook book = new HSSFWorkbook();
// Sheet sheet = book.createSheet();
// int rowCount = 0;
// for(String line : traceCommands.split("\n")){
// int columnCount = 0;
// Row newRow = sheet.createRow(rowCount++);
// for (String column : line.split(" +")){
// Cell newCell = newRow.createCell(columnCount++);
// newCell.setCellValue(column);
// }
// }
// sheet.autoSizeColumn(1);
//
// try {
// String path = "files";
// File folder = new File(path);
// if (!folder.exists()){
// folder.mkdir();
// }
// String filePath = path + "/" + fileName + ".xls";
// File file = new File(filePath);
// if (file.exists()){
// file.delete();
// }
// file.createNewFile();
//
// book.write(new FileOutputStream(file));
// book.close();
// return file;
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// }
//
// }
}
|
3e1d20cb02f10816a78e8080448b1f7eb35891bc | 2,491 | java | Java | src/main/java/com/github/shredder121/asyncaudio/jda/AsyncPacketProviderFactory.java | MinnDevelopment/jda-async-packetprovider | ef9cedd3136bbc31ee751511586351c21042b291 | [
"Apache-2.0"
] | 4 | 2017-08-05T20:05:43.000Z | 2020-03-18T10:16:12.000Z | src/main/java/com/github/shredder121/asyncaudio/jda/AsyncPacketProviderFactory.java | MinnDevelopment/jda-async-packetprovider | ef9cedd3136bbc31ee751511586351c21042b291 | [
"Apache-2.0"
] | 2 | 2017-08-07T08:43:14.000Z | 2019-07-06T13:07:10.000Z | src/main/java/com/github/shredder121/asyncaudio/jda/AsyncPacketProviderFactory.java | MinnDevelopment/jda-async-packetprovider | ef9cedd3136bbc31ee751511586351c21042b291 | [
"Apache-2.0"
] | 2 | 2019-07-06T12:37:23.000Z | 2020-03-18T10:21:29.000Z | 32.776316 | 105 | 0.765556 | 12,341 | /*
* Copyright 2017 Shredder121.
*
* 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.shredder121.asyncaudio.jda;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import com.github.shredder121.asyncaudio.common.CommonAsync;
import lombok.RequiredArgsConstructor;
import net.dv8tion.jda.core.audio.factory.IAudioSendFactory;
import net.dv8tion.jda.core.audio.factory.IAudioSendSystem;
import net.dv8tion.jda.core.audio.factory.IPacketProvider;
/**
* An audio send factory that wraps an existing audio send factory, but keeps a backlog of packets ready.
* <p>
*
* The backlog is customizable, default backlog is {@value CommonAsync#DEFAULT_BACKLOG}.
* <p>
*
* Keep in mind that having a bigger backlog means that when you do seeking, skipping, etc.
* the previous packets in the backlog still need to be run through.
*
* @author Shredder121
*/
@RequiredArgsConstructor(staticName = "adapt")
public class AsyncPacketProviderFactory implements IAudioSendFactory {
/**
* Wrap the given factory with the default backlog. ({@value CommonAsync#DEFAULT_BACKLOG})
*
* @param factory the factory to be wrapped
* @return
*/
public static AsyncPacketProviderFactory adapt(IAudioSendFactory factory) {
return AsyncPacketProviderFactory.adapt(factory, CommonAsync.DEFAULT_BACKLOG);
}
/**
* The wrapped audio send factory.
*/
IAudioSendFactory factory;
/**
* How many packets to keep a backlog of per PacketProvider.
*/
int backlog;
@Override
public IAudioSendSystem createSendSystem(IPacketProvider packetProvider) {
// to be able to introduce the taskRef to both parties
AtomicReference<Future<?>> taskRef = new AtomicReference<>();
AsyncPacketProvider provider = AsyncPacketProvider.wrap(packetProvider, backlog, taskRef);
AsyncAudioSendSystemWrapper system = AsyncAudioSendSystemWrapper.wrap(
this.factory.createSendSystem(provider),
taskRef
);
return system;
}
}
|
3e1d210893368cf469dc226f81365d0a6ef99877 | 655 | java | Java | netty/NettyDemo2/src/main/java/com/netty/server/session/Group.java | victoryckl/w3cschool | 4d1c4efef7188325f7f551764acec8bcfcdd493e | [
"Apache-2.0"
] | null | null | null | netty/NettyDemo2/src/main/java/com/netty/server/session/Group.java | victoryckl/w3cschool | 4d1c4efef7188325f7f551764acec8bcfcdd493e | [
"Apache-2.0"
] | null | null | null | netty/NettyDemo2/src/main/java/com/netty/server/session/Group.java | victoryckl/w3cschool | 4d1c4efef7188325f7f551764acec8bcfcdd493e | [
"Apache-2.0"
] | null | null | null | 19.264706 | 87 | 0.630534 | 12,342 | package com.netty.server.session;
import java.util.Collections;
import java.util.Set;
/**
* 聊天组,即聊天室
*/
public class Group {
// 聊天室名称
private String name;
// 聊天室成员
private Set<String> members;
public static final Group EMPTY_GROUP = new Group("empty", Collections.emptySet());
public Group(String name, Set<String> members) {
this.name = name;
this.members = members;
}
public void addMember(String member) {
members.add(member);
}
public void removeMember(String member) {
members.remove(member);
}
public Set<String> getMembers() {
return members;
}
}
|
3e1d21273637bb8c215a62531f02e24a6bad7cd0 | 172 | java | Java | java/warmup1/delDel/Solution.java | sanjay-3129/codingbat.com | 198b6129d8d68182eb19fbe10233d4388ae9b1bf | [
"MIT"
] | null | null | null | java/warmup1/delDel/Solution.java | sanjay-3129/codingbat.com | 198b6129d8d68182eb19fbe10233d4388ae9b1bf | [
"MIT"
] | null | null | null | java/warmup1/delDel/Solution.java | sanjay-3129/codingbat.com | 198b6129d8d68182eb19fbe10233d4388ae9b1bf | [
"MIT"
] | null | null | null | 24.571429 | 58 | 0.633721 | 12,343 | public String delDel(String str) {
if(str.length()>=4 && str.substring(1,4).equals("del")){
return str.charAt(0) + str.substring(4,str.length());
}
return str;
}
|
3e1d220f77626386bfa14bf194172ec432dc411b | 468 | java | Java | src/main/java/dev/jmpalazzolo/springblog/services/PostService.java | jmpala/spring-blog | 12ec82ae01b5668a27f6c32892da4eb6ac2cdff8 | [
"MIT"
] | null | null | null | src/main/java/dev/jmpalazzolo/springblog/services/PostService.java | jmpala/spring-blog | 12ec82ae01b5668a27f6c32892da4eb6ac2cdff8 | [
"MIT"
] | 36 | 2020-04-14T11:03:14.000Z | 2020-05-01T12:59:33.000Z | src/main/java/dev/jmpalazzolo/springblog/services/PostService.java | jmpala/spring-blog | 12ec82ae01b5668a27f6c32892da4eb6ac2cdff8 | [
"MIT"
] | null | null | null | 20.347826 | 68 | 0.775641 | 12,344 | package dev.jmpalazzolo.springblog.services;
import java.util.Optional;
import org.springframework.data.domain.Page;
import dev.jmpalazzolo.springblog.models.Post;
import dev.jmpalazzolo.springblog.models.User;
public interface PostService {
Optional<Post> findForId(Long id);
Post save(Post post);
Page<Post> findByUserOrderedByDatePageable(User user, int page);
Page<Post> findAllOrderedByDatePageable(int page);
void delete(Post post);
}
|
3e1d229323557f2e051f86e09c085df49901d377 | 2,548 | java | Java | core/src/main/java/org/jeeventstore/store/EventsIterator.java | tkocjan/JEEventStore_es_JEEventStore | 66d5926f18966636c3d39edb9ac3e011eb145eac | [
"MIT"
] | 28 | 2015-03-19T15:47:42.000Z | 2021-07-30T22:27:25.000Z | core/src/main/java/org/jeeventstore/store/EventsIterator.java | tkocjan/JEEventStore_es_JEEventStore | 66d5926f18966636c3d39edb9ac3e011eb145eac | [
"MIT"
] | 1 | 2015-08-17T09:26:27.000Z | 2015-08-17T12:30:44.000Z | core/src/main/java/org/jeeventstore/store/EventsIterator.java | tkocjan/JEEventStore_es_JEEventStore | 66d5926f18966636c3d39edb9ac3e011eb145eac | [
"MIT"
] | 7 | 2015-07-17T15:22:58.000Z | 2018-03-13T19:22:52.000Z | 32.253165 | 84 | 0.654239 | 12,345 | /*
* Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany
*
* 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.jeeventstore.store;
import java.io.Serializable;
import java.util.Iterator;
import org.jeeventstore.ChangeSet;
/**
* An iterator that iterates over all events for multiple {@link ChangeSet}s
* in a proper sequence.
*/
public class EventsIterator<T extends ChangeSet> implements Iterator<Serializable> {
private Iterator<T> cit;
private Iterator<Serializable> it = null;
public EventsIterator(Iterator<T> cit) {
this.cit = cit;
advance();
}
private void advance() {
if (it != null && it.hasNext())
return;
// now either it == null or it has no next
do {
// already reached the last change set?
if (!cit.hasNext()) {
it = null;
return;
}
// no, another changeset is available. Grab it.
ChangeSet nextcs = cit.next();
it = nextcs.events();
} while (!it.hasNext()); // protect against ChangeSets w/o events
}
@Override
public boolean hasNext() {
return it != null;
}
@Override
public Serializable next() {
Serializable n = it.next();
advance();
return n;
}
/**
* {@link #remove()} is not supported.
*/
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
|
3e1d22d39e9f843355103cc06cabbeffaf671772 | 1,995 | java | Java | app/src/main/java/me/arkadiy/geronplayer/loader/ArtistAlbumLoader.java | Arkadzi/geron-player | 8269c7c60fe48a8a42a8b6a4efaa4a49e2611a38 | [
"Apache-2.0"
] | 1 | 2015-11-07T11:23:32.000Z | 2015-11-07T11:23:32.000Z | app/src/main/java/me/arkadiy/geronplayer/loader/ArtistAlbumLoader.java | Arkadzi/geron-player | 8269c7c60fe48a8a42a8b6a4efaa4a49e2611a38 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/me/arkadiy/geronplayer/loader/ArtistAlbumLoader.java | Arkadzi/geron-player | 8269c7c60fe48a8a42a8b6a4efaa4a49e2611a38 | [
"Apache-2.0"
] | null | null | null | 29.776119 | 94 | 0.6401 | 12,346 | package me.arkadiy.geronplayer.loader;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import me.arkadiy.geronplayer.R;
import me.arkadiy.geronplayer.plain.Category;
import me.arkadiy.geronplayer.plain.Song;
import me.arkadiy.geronplayer.statics.MusicRetriever;
/**
* Created by Arkadiy on 10.11.2015.
*/
public class ArtistAlbumLoader extends AbstractLoader<Category> {
private final long artistId;
public ArtistAlbumLoader(Context context, String param, long id) {
super(context, param);
this.artistId = id;
}
@Override
protected Uri getUri() {
return MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
@Override
protected List<Category> getList() {
ArrayList<Category> albums = new ArrayList<>();
String[] projection = {MediaStore.Audio.Albums._ID, //0
MediaStore.Audio.Artists.Albums.ALBUM,//1
MediaStore.Audio.Artists.Albums.NUMBER_OF_SONGS // 2
};
Uri uri = MediaStore.Audio.Artists.Albums.getContentUri("external", artistId);
final Cursor musicCursor = musicResolver.query(
uri,
projection, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
do {
Category newAlbum = new Category(musicCursor.getLong(0),
musicCursor.getString(1),
musicCursor.getInt(2));
long length = MusicRetriever.getLengthByAlbum(getContext(), newAlbum.getID());
newAlbum.setLength(length);
albums.add(newAlbum);
} while (musicCursor.moveToNext());
}
if (musicCursor != null) {
musicCursor.close();
}
return albums;
}
} |
3e1d233fa3e682027f95682395bf0e2cd7ae03ac | 1,672 | java | Java | core/src/main/java/org/apache/druid/data/input/InputSourceReader.java | richardstartin/druid | 790e9482ea18d87d59eeeeab4ceec14e4b1e192d | [
"Apache-2.0"
] | 5,813 | 2015-01-01T14:14:54.000Z | 2018-07-06T11:13:03.000Z | core/src/main/java/org/apache/druid/data/input/InputSourceReader.java | richardstartin/druid | 790e9482ea18d87d59eeeeab4ceec14e4b1e192d | [
"Apache-2.0"
] | 4,320 | 2015-01-02T18:37:24.000Z | 2018-07-06T14:51:01.000Z | core/src/main/java/org/apache/druid/data/input/InputSourceReader.java | richardstartin/druid | 790e9482ea18d87d59eeeeab4ceec14e4b1e192d | [
"Apache-2.0"
] | 1,601 | 2015-01-05T05:37:05.000Z | 2018-07-06T11:13:04.000Z | 38 | 111 | 0.770335 | 12,347 | /*
* 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.druid.data.input;
import org.apache.druid.data.input.impl.InputEntityIteratingReader;
import org.apache.druid.guice.annotations.UnstableApi;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import java.io.IOException;
/**
* InputSourceReader reads data from {@link InputSource} and returns a {@link CloseableIterator} of
* {@link InputRow}s. See {@link InputSource} for an example usage.
*
* Implementations of this class can use {@link InputEntity} and {@link InputEntityReader}. {@link InputFormat}
* can be useful to understand how to create an InputEntityReader.
*
* See {@link InputEntityIteratingReader} as an example.
*/
@UnstableApi
public interface InputSourceReader
{
CloseableIterator<InputRow> read() throws IOException;
CloseableIterator<InputRowListPlusRawValues> sample() throws IOException;
}
|
3e1d2369ec08abaaaa3321a41c85ad492ea9272d | 771 | java | Java | Client/src/main/java/popups/SaveGameRejectedPopupController.java | MahaAmin/TicTacToe | b69acbb2a18bc90e288a814e46621ba403de3aca | [
"MIT"
] | 5 | 2020-02-04T17:28:44.000Z | 2022-01-23T13:26:09.000Z | Client/src/main/java/popups/SaveGameRejectedPopupController.java | mo7amedsalah/TicTacToe | b69acbb2a18bc90e288a814e46621ba403de3aca | [
"MIT"
] | null | null | null | Client/src/main/java/popups/SaveGameRejectedPopupController.java | mo7amedsalah/TicTacToe | b69acbb2a18bc90e288a814e46621ba403de3aca | [
"MIT"
] | 9 | 2020-01-27T14:45:19.000Z | 2022-02-27T18:13:26.000Z | 22.676471 | 69 | 0.744488 | 12,348 | package popups;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import actions.App;
import actions.GameConfig;
import actions.PlayRequest;
import com.tictactoe.tictactoefx.SwitchTo;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import org.json.simple.JSONObject;
public class SaveGameRejectedPopupController implements Initializable
{
private JSONObject jsonData;
@FXML private void okButtonClicked(ActionEvent event)
{
App.getPopUpWindow().close();
}
@Override
public void initialize(URL url, ResourceBundle rb)
{
// String name = jsonData.get("from_name").toString();
jsonData=GameConfig.getSaveGameRejectedPobUp();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.