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
64833ad475dd72b27d7886b69833d3b59a477a37
3,506
package core; import core.interfaces.ManagerController; import models.battleFields.BattleFieldImpl; import models.battleFields.interfaces.Battlefield; import models.cards.MagicCard; import models.cards.TrapCard; import models.cards.interfaces.Card; import models.players.Advanced; import models.players.Beginner; import models.players.interfaces.Player; import repositories.CardRepositoryImpl; import repositories.PlayerRepositoryImpl; import repositories.interfaces.CardRepository; import repositories.interfaces.PlayerRepository; import static common.ConstantMessages.*; public class ManagerControllerImpl implements ManagerController { private PlayerRepository playerRepository; private CardRepository cardRepository; private Battlefield battlefield; public ManagerControllerImpl() { playerRepository = new PlayerRepositoryImpl(); cardRepository = new CardRepositoryImpl(); battlefield = new BattleFieldImpl(); } @Override public String addPlayer(String type, String username) { Player playerToAdd = null; switch (type) { case "Beginner": playerToAdd = new Beginner(new CardRepositoryImpl(), username); break; case "Advanced": playerToAdd = new Advanced(new CardRepositoryImpl(), username); break; } if (playerToAdd != null) { if (playerRepository.find(username) == null) { playerRepository.add(playerToAdd); } else { throw new IllegalArgumentException(String.format("Player %s already exists!", username)); } } return String.format(SUCCESSFULLY_ADDED_PLAYER, type, username); } @Override public String addCard(String type, String name) { Card cardToAdd = null; switch (type) { case "Trap": cardToAdd = new TrapCard(name); break; case "Magic": cardToAdd = new MagicCard(name); break; } if (cardToAdd != null) { if (cardRepository.find(name) == null) { cardRepository.add(cardToAdd); } else { throw new IllegalArgumentException(String.format("Card %s already exists!", name)); } } return String.format(SUCCESSFULLY_ADDED_CARD, type, name); } @Override public String addPlayerCard(String username, String cardName) { Player player = playerRepository.find(username); Card card = cardRepository.find(cardName); player.getCardRepository().add(card); return String.format(SUCCESSFULLY_ADDED_PLAYER_WITH_CARDS, cardName, username); } @Override public String fight(String attackUser, String enemyUser) { Player attacker = playerRepository.find(attackUser); Player enemy = playerRepository.find(enemyUser); battlefield.fight(attacker, enemy); return String.format(FIGHT_INFO, attacker.getHealth(), enemy.getHealth()); } @Override public String report() { StringBuilder res = new StringBuilder(); for (Player player : playerRepository.getPlayers()) { res.append(player.toString()).append(System.lineSeparator()); res.append(DEFAULT_REPORT_SEPARATOR).append(System.lineSeparator()); } return res.toString().trim(); } }
31.872727
99
0.641187
23fce64a977c520cc25735f3696db0bb2350b73f
229
package com.github.spriet2000.vertx.httprouter; import io.vertx.core.http.HttpServerRequest; import java.util.Map; public interface RouteHandler { void handle(HttpServerRequest request, Map<String, String> parameters); }
20.818182
75
0.79476
61d5ed1bff96bc9572ceb4a13acd81ed9f5bdc28
2,590
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.controller.persistence; import javax.xml.stream.XMLStreamException; import org.jboss.as.controller.parsing.Element; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLExtendedStreamWriter; /** * Context passed to {@link org.jboss.staxmapper.XMLElementWriter}s that marshal a subsystem. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ public class SubsystemMarshallingContext { private final ModelNode modelNode; private final XMLExtendedStreamWriter writer; public SubsystemMarshallingContext(final ModelNode modelNode, final XMLExtendedStreamWriter writer) { this.modelNode = modelNode; this.writer = writer; } public ModelNode getModelNode() { return modelNode; } public void startSubsystemElement(String namespaceURI, boolean empty) throws XMLStreamException { if (writer.getNamespaceContext().getPrefix(namespaceURI) == null) { // Unknown namespace; it becomes default writer.setDefaultNamespace(namespaceURI); if (empty) { writer.writeEmptyElement(Element.SUBSYSTEM.getLocalName()); } else { writer.writeStartElement(Element.SUBSYSTEM.getLocalName()); } writer.writeNamespace(null, namespaceURI); } else { if (empty) { writer.writeEmptyElement(namespaceURI, Element.SUBSYSTEM.getLocalName()); } else { writer.writeStartElement(namespaceURI, Element.SUBSYSTEM.getLocalName()); } } } }
37
105
0.696525
444d258763adf6b9980caa2f966524f23feeb97a
7,339
private void createHomeTab() { Tabpanel homeTab = new Tabpanel(); windowContainer.addWindow(homeTab, Msg.getMsg(EnvWeb.getCtx(), "Home").replaceAll("&", ""), false); Portallayout portalLayout = new Portallayout(); portalLayout.setWidth("100%"); portalLayout.setHeight("100%"); portalLayout.setStyle("position: absolute; overflow: auto"); homeTab.appendChild(portalLayout); Portalchildren portalchildren = null; int currentColumnNo = 0; String sql = "SELECT COUNT(DISTINCT COLUMNNO) " + "FROM PA_DASHBOARDCONTENT " + "WHERE (AD_CLIENT_ID=0 OR AD_CLIENT_ID=?) AND ISACTIVE='Y'"; int noOfCols = DB.getSQLValue(null, sql, EnvWeb.getCtx().getAD_Client_ID()); int width = noOfCols <= 0 ? 100 : 100 / noOfCols; sql = "SELECT x.*, m.AD_MENU_ID " + "FROM PA_DASHBOARDCONTENT x " + "LEFT OUTER JOIN AD_MENU m ON x.AD_WINDOW_ID=m.AD_WINDOW_ID " + "WHERE (x.AD_CLIENT_ID=0 OR x.AD_CLIENT_ID=?) AND x.ISACTIVE='Y' " + "AND x.zulfilepath not in (?, ?, ?) " + "ORDER BY x.COLUMNNO, x.AD_CLIENT_ID, x.LINE "; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, null); pstmt.setInt(1, EnvWeb.getCtx().getAD_Client_ID()); pstmt.setString(2, ACTIVITIES_PATH); pstmt.setString(3, FAVOURITES_PATH); pstmt.setString(4, VIEWS_PATH); rs = pstmt.executeQuery(); while (rs.next()) { int columnNo = rs.getInt("ColumnNo"); if (portalchildren == null || currentColumnNo != columnNo) { portalchildren = new Portalchildren(); portalLayout.appendChild(portalchildren); portalchildren.setWidth(width + "%"); portalchildren.setStyle("padding: 5px"); currentColumnNo = columnNo; } Panel panel = new Panel(); panel.setStyle("margin-bottom:10px"); panel.setTitle(rs.getString("Name")); String description = rs.getString("Description"); if (description != null) panel.setTooltiptext(description); String collapsible = rs.getString("IsCollapsible"); panel.setCollapsible(collapsible.equals("Y")); panel.setBorder("normal"); portalchildren.appendChild(panel); Panelchildren content = new Panelchildren(); panel.appendChild(content); boolean panelEmpty = true; String htmlContent = rs.getString("HTML"); if (htmlContent != null) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(stripHtml(htmlContent, false) + "<br>\n"); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } int AD_Window_ID = rs.getInt("AD_Window_ID"); if (AD_Window_ID > 0) { int AD_Menu_ID = rs.getInt("AD_Menu_ID"); ToolBarButton btn = new ToolBarButton(String.valueOf(AD_Menu_ID)); MMenu menu = new MMenu(EnvWeb.getCtx(), AD_Menu_ID, null); btn.setLabel(menu.getName()); btn.addEventListener(Events.ON_CLICK, this); content.appendChild(btn); panelEmpty = false; } int PA_Goal_ID = rs.getInt("PA_Goal_ID"); if (PA_Goal_ID > 0) { StringBuffer result = new StringBuffer("<html><head>"); URL url = getClass().getClassLoader().getResource("org/compiere/images/PAPanel.css"); InputStreamReader ins; try { ins = new InputStreamReader(url.openStream()); BufferedReader bufferedReader = new BufferedReader(ins); String cssLine; while ((cssLine = bufferedReader.readLine()) != null) result.append(cssLine + "\n"); } catch (IOException e1) { logger.log(Level.SEVERE, e1.getLocalizedMessage(), e1); } result.append("</head><body><div class=\"content\">\n"); result.append(renderGoals(PA_Goal_ID, content)); result.append("</div>\n</body>\n</html>\n</html>"); Html html = new Html(); html.setContent(result.toString()); content.appendChild(html); panelEmpty = false; } String url = rs.getString("ZulFilePath"); if (url != null) { try { Component component = Executions.createComponents(url, content, null); if (component != null) { if (component instanceof DashboardPanel) { DashboardPanel dashboardPanel = (DashboardPanel) component; if (!dashboardPanel.getChildren().isEmpty()) { content.appendChild(dashboardPanel); dashboardRunnable.add(dashboardPanel); panelEmpty = false; } } else { content.appendChild(component); panelEmpty = false; } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create components. zul=" + url, e); } } if (panelEmpty) panel.detach(); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to create dashboard content", e); } finally { Util.closeCursor(pstmt, rs); } registerWindow(homeTab); if (!portalLayout.getDesktop().isServerPushEnabled()) portalLayout.getDesktop().enableServerPush(true); dashboardRunnable.refreshDashboard(); dashboardThread = new Thread(dashboardRunnable, "UpdateInfo"); dashboardThread.setDaemon(true); dashboardThread.start(); }
55.598485
296
0.512059
3cb47a634458eccff6b054f643f5c461ca6fee49
6,576
package com.github.focus.util; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import javax.xml.bind.DatatypeConverter; import java.io.IOException; import java.lang.reflect.Array; import java.net.URLEncoder; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 阿里POP的签名算法工具类 * * @Author 袁旭云【[email protected]】 * Created by rain on 2018/8/6. * @Date 2018/8/6 14:55 */ public class SignaUtil { /*** * specialUrlEncode * @param value * @return * @throws Exception */ public static String specialUrlEncode(String value) throws Exception { // return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); return value != null ? URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null; } /*** * sign * @param accessSecret * @param stringToSign * @return * @throws Exception */ public static String sign(String accessSecret, String stringToSign) throws Exception { javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1"); mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); return DatatypeConverter.printBase64Binary(signData);//new sun.misc.BASE64Encoder().encode(signData); } /*** * 解析阿里接口返回的 Message 短信邮件使用 * @param str * @param nodesKey * @return * @throws DocumentException */ public static String getMessage(String str, String nodesKey) throws DocumentException { if (!isEmpty(str)) { Document doc = DocumentHelper.parseText(str); List<Element> tplList = doc.selectNodes(nodesKey); if (isEmpty(tplList)) { //兼容发送异常时获取的数据 tplList = doc.selectNodes("/Error"); } String message = null; Element tpl = tplList.get(0); Iterator msgIt = tpl.elementIterator("Message"); if (msgIt.hasNext()) { message = ((Element) msgIt.next()).getTextTrim(); } else { //发送成功 没有返回值 自定义一个 message = "OK"; } return message; } else { return ""; } } /*** * 解析阿里接口返回的 Message 人机验证接口返回的数据 * @param str * @param nodesKey * @return * @throws DocumentException */ public static String getCode(String str, String nodesKey) throws DocumentException { if (!isEmpty(str)) { Document doc = DocumentHelper.parseText(str); List<Element> tplList = doc.selectNodes(nodesKey); if (isEmpty(tplList)) { //兼容发送异常时获取的数据 tplList = doc.selectNodes("/Error"); } String message = null; Element tpl = tplList.get(0); Iterator msgIt = tpl.elementIterator("Code"); if (msgIt.hasNext()) { message = ((Element) msgIt.next()).getTextTrim(); } else { //发送成功 没有返回值 自定义一个 message = "OK"; } return message; } else { return ""; } } /*** * 发送get请求 * @param url * @param encode * @return * @throws IOException */ public static String doGet(String url, String encode) throws IOException { String result = ""; System.setProperty("sun.net.client.defaultConnectTimeout", "7000"); System.setProperty("sun.net.client.defaultReadTimeout", "7000"); HttpGet get = new HttpGet(url); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpResponse response = httpclient.execute(get); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, encode); } } return result; } /*** * 发送get请求 * @param url * @param encode * @return * @throws IOException */ public static String doPost(String url, String encode) throws IOException { String result = ""; System.setProperty("sun.net.client.defaultConnectTimeout", "7000"); System.setProperty("sun.net.client.defaultReadTimeout", "7000"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setHeader("Content-type", "application/x-www-form-urlencoded"); /*post.setHeader("Accept-Encoding","identity"); post.setHeader("x-sdk-invoke-type","normal"); post.setHeader("Accept","JSON"); post.setHeader("x-sdk-client","Java/2.0.0"); post.setHeader("User-Agent","AlibabaCloud (Windows 10; amd64) Java/1.8.0_65-b17 Core/4.4.8 HTTPClient/ApacheHttpClient"); post.setHeader("Content-MD5","yNv2dAjWtmyG76JwCHMcaA=="); */ CloseableHttpResponse response1 = httpclient.execute(post); if (response1 != null) { HttpEntity resEntity = response1.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, encode); } } return result; } /** * 判断参数是否非NULL,空字符串,空数组,空的Collection或Map(只有空格的字符串也认为是空串) * * @param obj * @return */ @SuppressWarnings("rawtypes") public static boolean isEmpty(Object obj) { if (obj == null) { return true; } if (obj instanceof String && obj.toString().trim().length() == 0) { return true; } if (obj.getClass().isArray() && Array.getLength(obj) == 0) { return true; } if (obj instanceof Collection && ((Collection) obj).isEmpty()) { return true; } if (obj instanceof Map && ((Map) obj).isEmpty()) { return true; } return false; } }
32.88
132
0.588808
a4e852d9b534eede71679e5e383a3c8898bc57f8
10,819
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.passes; import com.google.common.base.Equivalence; import com.google.common.base.Preconditions; import com.google.template.soy.base.internal.SanitizedContentKind; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.shared.internal.DelTemplateSelector; import com.google.template.soy.soytree.AbstractSoyNodeVisitor; import com.google.template.soy.soytree.CallBasicNode; import com.google.template.soy.soytree.CallDelegateNode; import com.google.template.soy.soytree.SoyFileSetNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.ParentSoyNode; import com.google.template.soy.soytree.TemplateBasicNode; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.TemplateRegistry; import com.google.template.soy.soytree.defn.TemplateParam; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * Checks various rules regarding the use of delegates (including delegate packages, delegate * templates, and delegate calls). * * <p>Important: Do not use outside of Soy code (treat as superpackage-private). * * <p>{@link #exec} should be called on a full parse tree. There is no return value. A {@code * SoySyntaxException} is thrown if an error is found. * */ final class CheckDelegatesVisitor extends AbstractSoyNodeVisitor<Void> { private static final SoyErrorKind CALL_TO_DELTEMPLATE = SoyErrorKind.of("''call'' to delegate template ''{0}'' (expected ''delcall'')."); private static final SoyErrorKind CROSS_PACKAGE_DELCALL = SoyErrorKind.of( "Found illegal call from ''{0}'' to ''{1}'', which is in a different delegate package."); private static final SoyErrorKind DELCALL_TO_BASIC_TEMPLATE = SoyErrorKind.of("''delcall'' to basic template ''{0}'' (expected ''call'')."); private static final SoyErrorKind DELTEMPLATES_WITH_DIFFERENT_PARAM_DECLARATIONS = SoyErrorKind.of( "Found delegate template with same name ''{0}'' but different param declarations " + "compared to the definition at {1}."); private static final SoyErrorKind STRICT_DELTEMPLATES_WITH_DIFFERENT_CONTENT_KIND = SoyErrorKind.of( "If one deltemplate has strict autoescaping, all its peers must also be strictly" + " autoescaped with the same content kind: {0} != {1}. Conflicting definition at" + " {2}."); private static final SoyErrorKind DELTEMPLATES_WITH_DIFFERENT_STRICT_HTML_MODE = SoyErrorKind.of( "Found delegate template with same name ''{0}'' but different strict html mode " + "compared to the definition at {1}."); /** A template registry built from the Soy tree. */ private final TemplateRegistry templateRegistry; /** The current enclosing template's name, as suitable for user messages (during pass). */ private String currTemplateNameForUserMsgs; /** Current delegate package name, or null if none (during pass). */ private String currDelPackageName; private final ErrorReporter errorReporter; CheckDelegatesVisitor(TemplateRegistry templateRegistry, ErrorReporter errorReporter) { this.templateRegistry = templateRegistry; this.errorReporter = errorReporter; } @Override public Void exec(SoyNode soyNode) { Preconditions.checkArgument(soyNode instanceof SoyFileSetNode); // Perform checks that only involve templates (uses templateRegistry only, no traversal). checkTemplates(); // Perform checks that involve calls (uses traversal). super.exec(soyNode); return null; } /** Performs checks that only involve templates (uses templateRegistry only). */ private void checkTemplates() { DelTemplateSelector<TemplateDelegateNode> selector = templateRegistry.getDelTemplateSelector(); // Check that all delegate templates with the same name have the same declared params, // content kind, and strict html mode. for (Collection<TemplateDelegateNode> delTemplateGroup : selector.delTemplateNameToValues().asMap().values()) { TemplateDelegateNode firstDelTemplate = null; Set<Equivalence.Wrapper<TemplateParam>> firstRequiredParamSet = null; SanitizedContentKind firstContentKind = null; boolean firstStrictHtml = false; // loop over all members of the deltemplate group. for (TemplateDelegateNode delTemplate : delTemplateGroup) { if (firstDelTemplate == null) { // First template encountered. firstDelTemplate = delTemplate; firstRequiredParamSet = getRequiredParamSet(delTemplate); firstContentKind = delTemplate.getContentKind(); firstStrictHtml = delTemplate.isStrictHtml() && firstContentKind == SanitizedContentKind.HTML; } else { // Not first template encountered. Set<Equivalence.Wrapper<TemplateParam>> currRequiredParamSet = getRequiredParamSet(delTemplate); if (!currRequiredParamSet.equals(firstRequiredParamSet)) { errorReporter.report( delTemplate.getSourceLocation(), DELTEMPLATES_WITH_DIFFERENT_PARAM_DECLARATIONS, firstDelTemplate.getDelTemplateName(), firstDelTemplate.getSourceLocation().toString()); } if (delTemplate.getContentKind() != firstContentKind) { // TODO: This is only *truly* a requirement if the strict mode deltemplates are // being called by contextual templates. For a strict-to-strict call, everything // is escaped at runtime at the call sites. You could imagine delegating between // either a plain-text or rich-html template. However, most developers will write // their deltemplates in a parallel manner, and will want to know when the // templates differ. Plus, requiring them all to be the same early-on will allow // future optimizations to avoid the run-time checks, so it's better to start out // as strict as possible and only open up if needed. errorReporter.report( delTemplate.getSourceLocation(), STRICT_DELTEMPLATES_WITH_DIFFERENT_CONTENT_KIND, String.valueOf(firstContentKind), String.valueOf(delTemplate.getContentKind()), firstDelTemplate.getSourceLocation().toString()); } // Check if all del templates have the same settings of strict HTML mode. // We do not need to check {@code ContentKind} again since we already did that earlier // in this pass. if (delTemplate.isStrictHtml() != firstStrictHtml) { errorReporter.report( delTemplate.getSourceLocation(), DELTEMPLATES_WITH_DIFFERENT_STRICT_HTML_MODE, firstDelTemplate.getDelTemplateName(), firstDelTemplate.getSourceLocation().toString()); } } } } } // A specific equivalence relation for seeing if the params of 2 difference templates are // effectively the same. private static final class ParamEquivalence extends Equivalence<TemplateParam> { static final ParamEquivalence INSTANCE = new ParamEquivalence(); @Override protected boolean doEquivalent(TemplateParam a, TemplateParam b) { return a.name().equals(b.name()) && a.isRequired() == b.isRequired() && a.isInjected() == b.isInjected() && a.type().equals(b.type()); } @Override protected int doHash(TemplateParam t) { return Objects.hash(t.name(), t.isInjected(), t.isRequired(), t.type()); } } private static Set<Equivalence.Wrapper<TemplateParam>> getRequiredParamSet( TemplateDelegateNode delTemplate) { Set<Equivalence.Wrapper<TemplateParam>> paramSet = new HashSet<>(); for (TemplateParam param : delTemplate.getParams()) { if (param.isRequired()) { paramSet.add(ParamEquivalence.INSTANCE.wrap(param)); } } return paramSet; } // ----------------------------------------------------------------------------------------------- // Implementations for specific nodes. @Override protected void visitTemplateNode(TemplateNode node) { this.currTemplateNameForUserMsgs = node.getTemplateNameForUserMsgs(); this.currDelPackageName = node.getDelPackageName(); visitChildren(node); } @Override protected void visitCallBasicNode(CallBasicNode node) { String calleeName = node.getCalleeName(); // Check that the callee name is not a delegate template name. if (templateRegistry.getDelTemplateSelector().hasDelTemplateNamed(calleeName)) { errorReporter.report(node.getSourceLocation(), CALL_TO_DELTEMPLATE, calleeName); } // Check that the callee is either not in a delegate package or in the same delegate package. TemplateBasicNode callee = templateRegistry.getBasicTemplate(calleeName); if (callee != null) { String calleeDelPackageName = callee.getDelPackageName(); if (calleeDelPackageName != null && !calleeDelPackageName.equals(currDelPackageName)) { errorReporter.report( node.getSourceLocation(), CROSS_PACKAGE_DELCALL, currTemplateNameForUserMsgs, callee.getTemplateName()); } } } @Override protected void visitCallDelegateNode(CallDelegateNode node) { String delCalleeName = node.getDelCalleeName(); // Check that the callee name is not a basic template name. if (templateRegistry.getBasicTemplate(delCalleeName) != null) { errorReporter.report(node.getSourceLocation(), DELCALL_TO_BASIC_TEMPLATE, delCalleeName); } } // ----------------------------------------------------------------------------------------------- // Fallback implementation. @Override protected void visitSoyNode(SoyNode node) { if (node instanceof ParentSoyNode<?>) { visitChildren((ParentSoyNode<?>) node); } } }
42.594488
100
0.694796
a3e3c32b92f38d7b1268dffa253310d7abc5386c
1,157
package com.condition.umzzal.activity; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MyRetrofit2 { public static final String URL = "http:///"; static Retrofit mRetrofit; public static Retrofit getRetrofit2(){ if(mRetrofit == null){ HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.connectTimeout(5, TimeUnit.MINUTES) .writeTimeout(5,TimeUnit.MINUTES) .readTimeout(5,TimeUnit.MINUTES) .addInterceptor(logging) .build(); mRetrofit = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient.build()) .build(); } return mRetrofit; } }
27.547619
74
0.622299
bd66f267d9c75e131af2bd65f20a0107404280de
1,056
package com.ybsystem.tweethub.models.entities; import com.ybsystem.tweethub.utils.ToastUtils; public class AccountArray<T extends Account> extends EntityArray<T> { public Account getCurrentAccount() { int index = getCurrentAccountNum(); if (index == -1) { return null; } else { return this.get(index); } } public int getCurrentAccountNum() { for (int i = 0; i < size(); i++) { if (get(i).isCurrentAccount()) { return i; } } return -1; } public void setCurrentAccount(int i) { // Clear for (Account account: this) { account.setCurrentAccount(false); } // Set get(i).setCurrentAccount(true); pcs.firePropertyChange(); } @Override public T remove(int index) { if(index == getCurrentAccountNum()) { ToastUtils.showShortToast("使用中のアカウントです。"); return null; } return super.remove(index); } }
23.466667
69
0.541667
ff37d009ef36691adea7c550ec6b33258af9a74f
1,065
package carry.ilearn.dao; import carry.ilearn.dataobject.CommentDO; import carry.ilearn.dataobject.CommentFirstLevelDO; import org.apache.ibatis.annotations.Param; import java.util.List; public interface CommentDao { int deleteByPrimaryKey(Integer id); int insert(CommentDO record); int insertSelective(CommentDO record); CommentDO selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(CommentDO record); int updateByPrimaryKey(CommentDO record); List<CommentFirstLevelDO> selectFirstLevelByPostIdPaged(@Param("postId") Integer postId, @Param("offset") Integer offset, @Param("limit") Integer limit, @Param("secondOffset") Integer secondOffset, @Param("secondLimit") Integer secondLimit); List<CommentDO> selectSecondLevelByCommentIdPaged(@Param("commentId") Integer commentId, @Param("offset") Integer offset, @Param("limit") Integer limit); long selectSecondLevelCountByCommentId(Integer commentId); }
33.28125
121
0.707981
c944fc8df1660a8e79835073a11341ff38feb957
1,288
package visualization.componentIcons; import javafx.scene.Group; import javafx.scene.shape.Shape; public class BreakerIcon extends DeviceIcon { // shapes that are energized when both nodes are energized and the device is closed private final Group backFedOffNodeEnergyOutline = new Group(); public BreakerIcon() { addEnergyOutlineNode(backFedOffNodeEnergyOutline); } public void addBackfedOffNodeShapes(Shape... shapes) { addNodesToIconNode(shapes); addShapesToEnergyOutlineNode(backFedOffNodeEnergyOutline, shapes); } public void setBreakerEnergyStates(boolean inNodeEnergized, boolean outNodeEnergized, boolean isClosed) { setInNodeEnergyState(inNodeEnergized); setOutNodeEnergyState(outNodeEnergized); if (!getMidNodeEnergyOutline().getChildren().isEmpty()) { setMidNodeEnergyState(inNodeEnergized && outNodeEnergized); } if (!backFedOffNodeEnergyOutline.getChildren().isEmpty()) { setBackfedOffNodeEnergyState(isClosed && inNodeEnergized && outNodeEnergized); } } private void setBackfedOffNodeEnergyState(boolean energized) { backFedOffNodeEnergyOutline.getChildren().forEach(element -> element.setOpacity(energized ? 1 : 0)); } }
35.777778
109
0.731366
7448027e7da394020ad4fc683432fb9e447580c8
431
import java.util.Scanner; public class book { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the monthly saving amount:"); double m = input.nextDouble(); double sum = 0.0; for(int i=0;i<6;i++) sum = (m+sum)*(1+0.00417); System.out.println("After the sixth month, the account value is $"+sum+"."); } }
30.785714
84
0.577726
6326daa164e031d0e89dfde0c85e871bb12581b3
1,945
package com.Da_Technomancer.essentials.blocks.redstone; import com.Da_Technomancer.essentials.blocks.ESProperties; import com.Da_Technomancer.essentials.tileentities.CircuitTileEntity; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IWorldReader; import net.minecraft.world.World; public class ReaderCircuit extends AbstractCircuit{ public ReaderCircuit(){ super("reader_circuit"); } @Override public boolean useInput(CircuitTileEntity.Orient or){ return false; } @Override public boolean getWeakChanges(BlockState state, IWorldReader world, BlockPos pos){ return true; } @Override public void onNeighborChange(BlockState state, IWorldReader world, BlockPos pos, BlockPos neighbor){ if(world instanceof World){ neighborChanged(state, (World) world, pos, this, neighbor, false); } } @Override public float getOutput(float in0, float in1, float in2, CircuitTileEntity te){ World world = te.getWorld(); BlockPos pos = te.getPos(); Direction back = CircuitTileEntity.Orient.BACK.getFacing(te.getBlockState().get(ESProperties.HORIZ_FACING)); float output; pos = pos.offset(back); BlockState state = world.getBlockState(pos); Block block = state.getBlock(); if(block instanceof IReadable){ output = ((IReadable) block).read(world, pos, state); }else if(state.hasComparatorInputOverride()){ output = state.getComparatorInputOverride(world, pos); }else if(state.isNormalCube(world, pos)){ pos = pos.offset(back); state = world.getBlockState(pos); block = state.getBlock(); if(block instanceof IReadable){ output = ((IReadable) block).read(world, pos, state); }else if(state.hasComparatorInputOverride()){ output = state.getComparatorInputOverride(world, pos); }else{ output = 0; } }else{ output = 0; } return output; } }
29.923077
110
0.7491
e09732338b6a7259f1d0ca6f5ede4b1e31556576
1,596
package com.auth.config; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import tk.mybatis.spring.annotation.MapperScan; import javax.sql.DataSource; /** * @author: Gu danpeng * @date: 2019-1-2 * @version:1.0 */ @Configuration @MapperScan(basePackages = "com.auth.mapper") public class MySQLDataSourceConfiguration { // @Autowired // DataSource dataSource; //将properties中以mysql为前缀的参数值,写入方法返回的对象中 //默认数据源 @Bean // @Qualifier("mysql") @Primary // @ConfigurationProperties(prefix="mysql.datasource") public DataSource mysqDataSource() { //通过DataSourceBuilder构建数据源 // DataSource dataSource = DataSourceBuilder.create().type(HikariDataSource.class).build(); DataSource dataSource = DruidDataSourceBuilder.create().build(); System.out.println("MySQL Datasource: " + dataSource); return dataSource; } @Bean(name = "sqlSessionFactory") @Primary public SqlSessionFactory mysqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } }
32.571429
98
0.753759
001321961fcd1938edc43d86893dcc0a243d3df8
4,359
/* * Copyright 2003-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.mps.typesystem.inference.util; import gnu.trove.THashMap; import gnu.trove.THashSet; import jetbrains.mps.lang.pattern.util.MatchingUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.model.SNode; import java.util.Collection; import java.util.Map; import java.util.Set; public class StructuralNodeMap<T> implements Map<SNode, T> { private Map<SNode, SNode> myRepresentatorsMap = new THashMap<>(); private Map<SNode, T> myMap = new THashMap<>(); private Set<SNode> myAbsentNodes = new THashSet<>(); public SNode getKeyRepresentator(SNode node) { return myRepresentatorsMap.get(node); } @Override public int size() { return myMap.size(); } @Override public boolean isEmpty() { return myMap.isEmpty(); } @Override public boolean containsValue(Object value) { return myMap.containsValue(value); } @Override public void putAll(@NotNull Map<? extends SNode, ? extends T> t) { throw new UnsupportedOperationException(); } @NotNull @Override public Set<SNode> keySet() { return myMap.keySet(); } @Override public void clear() { myRepresentatorsMap.clear(); myMap.clear(); myAbsentNodes.clear(); } @NotNull @Override public Collection<T> values() { return myMap.values(); } @NotNull @Override public Set<Entry<SNode, T>> entrySet() { return myMap.entrySet(); } @Override public T get(Object key) { if (!(key instanceof SNode)) return null; SNode keyNode = (SNode) key; SNode representator = getKeyRepresentator(keyNode); if (representator == null) { if (myAbsentNodes.contains(keyNode)) return null; for (SNode node : myMap.keySet()) { if (MatchingUtil.matchNodes(node, keyNode)) { myRepresentatorsMap.put(keyNode, node); return myMap.get(node); } } } if (representator == null) { myAbsentNodes.add(keyNode); return null; } return myMap.get(representator); } @Override public T put(SNode keyNode, T value) { SNode representator = getKeyRepresentator(keyNode); if (representator == null) { for (SNode node : myMap.keySet()) { if (MatchingUtil.matchNodes(node, keyNode)) { myRepresentatorsMap.put(keyNode, node); return myMap.put(node, value); } } } if (representator == null) { myRepresentatorsMap.put(keyNode, keyNode); myAbsentNodes.remove(keyNode); representator = keyNode; } return myMap.put(representator, value); } @Override public T remove(Object key) { if (!(key instanceof SNode)) return null; SNode keyNode = (SNode) key; myAbsentNodes.add(keyNode); SNode representator = getKeyRepresentator(keyNode); if (representator == null) { for (SNode node : myMap.keySet()) { if (MatchingUtil.matchNodes(node, keyNode)) { myRepresentatorsMap.put(keyNode, node); return myMap.remove(node); } } } if (representator == null) return null; return myMap.remove(representator); } @Override public boolean containsKey(Object key) { if (!(key instanceof SNode)) return false; SNode keyNode = (SNode) key; SNode representator = getKeyRepresentator(keyNode); if (representator == null) { if (myAbsentNodes.contains(keyNode)) return false; for (SNode node : myMap.keySet()) { if (MatchingUtil.matchNodes(node, keyNode)) { myRepresentatorsMap.put(keyNode, node); return myMap.containsKey(node); } } } if (representator == null) { myAbsentNodes.add(keyNode); return false; } return myMap.containsKey(representator); } }
27.074534
75
0.663455
32e232f0a21525fe89c04b4a70df3f823ceac164
4,214
package com.oa.common.tool.page; import java.util.List; import org.apache.commons.lang.StringUtils; /** * @className:Page.java * @classDescription:分页参数对象 * @author:linjiekai * @createTime:2010-7-12 */ public class PageQueryResult<T> { private PageSettings pageSetting; // -- 分页参数 --// protected int pageNo = 1;// 页数 protected int pageSize = 20;// 显示条数 protected int leftCount = 3;// 左边显示的条数 protected int rigthCount = 3;// 右边显示的条数 private String forwordName;// 跳转页面 protected List<T> result;// 取得页内的记录列表. // -- 返回结果 --// protected long totalCount = -1;// 总条数 protected int pageMaxNo;// 总共有几页 //构造 public PageQueryResult(PageSettings pageSetting) { this.pageSetting = pageSetting; this.pageNo = pageSetting.getPageNo(); this.pageSize = pageSetting.getPageSize(); } // -- 访问查询参数函数 --// /** * 取得最大页码数 * * @param size * @param totalRows * @return */ public int getPageMaxNo(int size, int totalRows) { // 最大页数 int pageMaxNo; // 实际每页数据条数 int actualSize; // 总记录数 // int totalRows = this.getTotalRows(); // 计算实际每页的条数,如果请求的每页数据条数大于总条数, 则等于总条数 actualSize = (size > totalRows) ? totalRows : size; if (totalRows > 0) { pageMaxNo = (totalRows % size == 0) ? (totalRows / actualSize) : (totalRows / actualSize + 1); } else { pageMaxNo = 0; } this.pageMaxNo = pageMaxNo; return pageMaxNo; } /** * 获得当前页的页号,序号如果大于总条数,则当前页定位到总页数 */ public int getPageNo() { if (this.getTotalPages() > -1 && this.pageNo > this.getTotalPages()) { this.pageNo = (int) this.getTotalPages(); } return pageNo; } /** * 设置当前页的页号,序号从1开始,低于1时自动调整为1. */ public void setPageNo(final int pageNo) { this.pageNo = pageNo; if (pageNo < 1) { this.pageNo = 1; } } public PageQueryResult<T> pageNo(final int thePageNo) { setPageNo(thePageNo); return this; } /** * 获得每页的记录数量,默认为1. */ public int getPageSize() { return pageSize; } /** * 设置每页的记录数量,低于1时自动调整为1. */ public void setPageSize(final int pageSize) { this.pageSize = pageSize; if (pageSize < 1) { this.pageSize = 1; } } public PageQueryResult<T> pageSize(final int thePageSize) { setPageSize(thePageSize); return this; } /** * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始. */ public int getFirst() { return ((pageNo - 1) * pageSize) + 1; } // -- 访问查询结果函数 --// /** * 取得页内的记录列表. */ public List<T> getResult() { return result; } /** * 设置页内的记录列表. */ public void setResult(final List<T> result) { this.result = result; } /** * 取得总记录数, 默认值为-1. */ public long getTotalCount() { return totalCount; } /** * 设置总记录数. */ public void setTotalCount(final long totalCount) { this.totalCount = totalCount; } /** * 根据pageSize与totalCount计算总页数, 默认值为-1. */ public long getTotalPages() { if (totalCount < 0) { return -1; } long count = totalCount / pageSize; if (totalCount % pageSize > 0) { count++; } return count; } /** * 是否还有下一页. */ public boolean isHasNext() { return (pageNo + 1 <= getTotalPages()); } /** * 取得下页的页号, 序号从1开始. 当前页为尾页时仍返回尾页序号. */ public int getNextPage() { if (isHasNext()) { return pageNo + 1; } else { return pageNo; } } /** * 是否还有上一页. */ public boolean isHasPre() { return (pageNo - 1 >= 1); } /** * 取得上页的页号, 序号从1开始. 当前页为首页时返回首页序号. */ public int getPrePage() { if (isHasPre()) { return pageNo - 1; } else { return pageNo; } } /** * @return the leftCount */ public int getLeftCount() { return leftCount; } /** * @param leftCount * the leftCount to set */ public void setLeftCount(int leftCount) { this.leftCount = leftCount; } /** * @return the rigthCount */ public int getRigthCount() { return rigthCount; } /** * @param rigthCount * the rigthCount to set */ public void setRigthCount(int rigthCount) { this.rigthCount = rigthCount; } /** * @return the forwordName */ public String getForwordName() { return forwordName; } /** * @param forwordName * the forwordName to set */ public void setForwordName(String forwordName) { this.forwordName = forwordName; } }
14.890459
70
0.620788
5bd3cea3be3f574af14ea31e491a384bff22b2ea
69
package software.engineering.upm.es.objetos; class Registro { }
13.8
45
0.73913
55c4a27d16ccfcaa304abcc1c9fe6e7aa6f9e23c
482
package dk.kea.trash_api.controllers; import dk.kea.trash_api.SuperMarioCharacters; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SuperMarioController { static SuperMarioCharacters superMarioCharacters = new SuperMarioCharacters(); @GetMapping("/supermario/characters") public SuperMarioCharacters getCharacters() { return superMarioCharacters; } }
28.352941
82
0.802905
ccb5f149d04e31ef6c0a7be72cf1118cd4c2976c
953
package org.lintx.plugins.modules.command_helper.annotation; /** * 参数绑定的类型 */ public enum CommandVariableType { /** * 默认类型,会尝试自动解析参数的类型和名称来绑定对应的参数,如: * 参数类型为CommandSender时会绑定执行的CommandSender * 参数类型为Command时会绑定执行的Command * 参数类型为Plugin或插件主类时会绑定插件主类 * 参数类型为String且name为label且命令中没有绑定label变量时会绑定label变量(插件名) * 参数类型为String[]且name为args且命令中没有绑定args时会绑定原生命令的args参数(即所有参数) * 参数类型为String且name为permission且命令中没有绑定permission变量时会绑定permission变量(所需权限) * 参数类型为boolean且name为hasPermission且命令中没有绑定hasPermission变量时会绑定hasPermission变量(是否具有所需权限) * 不在上述列表中的,将尝试绑定命令中的同名变量,支持的数据类型有: * String,Integer,Boolean,Float,int,boolean,float,Player(bukkit),String[],List<String> */ DEFAULT, //将绑定CommandSender SENDER, //将绑定Command COMMAND, //将绑定label LABEL, //将绑定插件主类 PLUGIN, //将绑定注解中所写的权限 PERMISSION, //将绑定该角色是否具有所需的权限 HAS_PERMISSION, //将绑定命令中的同名变量 VARIABLE }
22.690476
90
0.729276
f70f16c9c3a2ac9c56fb0716baebb1cb26917e11
9,669
/* * Copyright (c) 2019 PonySDK * Owners: * Luciano Broussal <luciano.broussal AT gmail.com> * Mathieu Barbier <mathieu.barbier AT gmail.com> * Nicolas Ciaravola <nicolas.ciaravola.pro AT gmail.com> * * WebSite: * http://code.google.com/p/pony-sdk/ * * 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.ponysdk.core.ui.eventbus; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.ponysdk.test.PSuite; public class EventBusTest extends PSuite { private static final Event.Type CLICK_EVENT_TYPE = new Event.Type(); private static final Event.Type HOVER_EVENT_TYPE = new Event.Type(); @Test public void testGlobalHandler() { final EventBus eventBus = new EventBus(); final TestEventHandler clickEventHandler = new TestEventHandler(); eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler); final Event<TestEventHandler> hoverEvent = new HoverTestEvent(null); eventBus.fireEvent(hoverEvent); assertFalse("Click handler should NOT have been invoked", clickEventHandler.invoked); final Event<TestEventHandler> clickEvent = new ClickTestEvent(null); eventBus.fireEvent(clickEvent); assertTrue("Click handler should have been invoked", clickEventHandler.invoked); eventBus.removeHandler(CLICK_EVENT_TYPE, clickEventHandler); clickEventHandler.invoked = false; eventBus.fireEvent(clickEvent); assertFalse("Click handler should NOT have been invoked", clickEventHandler.invoked); } @Test public void testSourceHandler() { final EventBus eventBus = new EventBus(); final EventSource eventSource = new EventSource(); final TestEventHandler clickEventHandler = new TestEventHandler(); eventSource.addHandler(CLICK_EVENT_TYPE, clickEventHandler); final Event<TestEventHandler> hoverEvent = new HoverTestEvent(eventSource); eventBus.fireEventFromSource(hoverEvent, eventSource); assertFalse("Click handler should NOT have been invoked", clickEventHandler.invoked); final Event<TestEventHandler> clickEvent = new ClickTestEvent(eventSource); eventBus.fireEventFromSource(clickEvent, eventSource); assertTrue("Click handler should have been invoked", clickEventHandler.invoked); eventSource.removeHandler(CLICK_EVENT_TYPE, clickEventHandler); clickEventHandler.invoked = false; eventBus.fireEventFromSource(clickEvent, eventSource); assertFalse("Click handler should NOT have been invoked", clickEventHandler.invoked); } @Test public void testBroadcastHandler() { final EventBus eventBus = new EventBus(); final TestBroadcastHandler broadcastHandler = new TestBroadcastHandler(); eventBus.addHandler(broadcastHandler); assertFalse("Broadcast handler should NOT have been invoked", broadcastHandler.invoked); final Event<TestEventHandler> clickEvent = new ClickTestEvent(null); eventBus.fireEvent(clickEvent); assertTrue("Broadcast handler should have been invoked", broadcastHandler.invoked); eventBus.removeHandler(broadcastHandler); broadcastHandler.invoked = false; eventBus.fireEvent(clickEvent); assertFalse("Broadcast handler should NOT have been invoked", broadcastHandler.invoked); } @Test public void testSingleHandlerPerEventType() { final EventBus eventBus = new EventBus(); final EventSource eventSource = new EventSource(); final TestEventHandler clickEventHandler = new TestEventHandler(); final TestEventHandler hoverEventHandler = new TestEventHandler(); eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler); eventBus.addHandler(HOVER_EVENT_TYPE, hoverEventHandler); final Event<TestEventHandler> clickEvent = new ClickTestEvent(eventSource); assertFalse("Click handler should NOT have been invoked", clickEventHandler.invoked); assertFalse("Hover handler should NOT have been invoked", hoverEventHandler.invoked); eventBus.fireEventFromSource(clickEvent, eventSource); assertTrue("Click handler should have been invoked", clickEventHandler.invoked); assertFalse("Hover handler should NOT have been invoked", hoverEventHandler.invoked); } @Test public void testMultipleHandlersOfSingleEventType() { final EventBus eventBus = new EventBus(); final EventSource eventSource = new EventSource(); final TestEventHandler clickEventHandler = new TestEventHandler(); final TestEventHandler clickEventHandler2 = new TestEventHandler(); eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler); eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler2); final Event<TestEventHandler> clickEvent = new ClickTestEvent(eventSource); assertFalse("Click handler 1 should NOT have been invoked", clickEventHandler.invoked); assertFalse("Click handler 2 should NOT have been invoked", clickEventHandler2.invoked); eventBus.fireEventFromSource(clickEvent, eventSource); assertTrue("Click handler 1 should have been invoked", clickEventHandler.invoked); assertTrue("Click handler 2 should have been invoked", clickEventHandler2.invoked); } @Test public void testAddHandlerFromAnotherHandler() { final EventBus eventBus = new EventBus(); final EventSource eventSource = new EventSource(); final TestEventHandler clickEventHandler2 = new TestEventHandler(); final TestEventHandler clickEventHandler = new TestEventHandler() { @Override void invoke() { super.invoke(); eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler2); } }; eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler); final Event<TestEventHandler> clickEvent = new ClickTestEvent(eventSource); assertFalse("Click handler 1 should NOT have been invoked", clickEventHandler.invoked); assertFalse("Click handler 2 should NOT have been invoked", clickEventHandler2.invoked); eventBus.fireEventFromSource(clickEvent, eventSource); assertTrue("Click handler 1 should have been invoked", clickEventHandler.invoked); assertFalse("Click handler 2 should NOT have been invoked", clickEventHandler2.invoked); } @Test public void testRemoveHandlerFromAnotherHandler() { final EventBus eventBus = new EventBus(); final EventSource eventSource = new EventSource(); final TestEventHandler clickEventHandler2 = new TestEventHandler(); final TestEventHandler clickEventHandler = new TestEventHandler() { @Override void invoke() { super.invoke(); eventBus.removeHandler(CLICK_EVENT_TYPE, clickEventHandler2); } }; eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler); eventBus.addHandler(CLICK_EVENT_TYPE, clickEventHandler2); final Event<TestEventHandler> clickEvent = new ClickTestEvent(eventSource); assertFalse("Click handler 1 should NOT have been invoked", clickEventHandler.invoked); assertFalse("Click handler 2 should NOT have been invoked", clickEventHandler2.invoked); eventBus.fireEventFromSource(clickEvent, eventSource); assertTrue("Click handler 1 should have been invoked", clickEventHandler.invoked); assertTrue("Click handler 2 should have been invoked", clickEventHandler2.invoked); } private static class TestEventHandler implements EventHandler { private boolean invoked = false; void invoke() { invoked = true; } } private static class TestBroadcastHandler implements BroadcastEventHandler { private boolean invoked = false; @Override public void onEvent(final Event<?> event) { invoked = true; } } private static abstract class TestEvent extends Event<TestEventHandler> { protected TestEvent(final Object source) { super(source); } @Override protected void dispatch(final TestEventHandler handler) { handler.invoke(); } } private static class ClickTestEvent extends TestEvent { protected ClickTestEvent(final Object source) { super(source); } @Override public Type getAssociatedType() { return CLICK_EVENT_TYPE; } } private static class HoverTestEvent extends TestEvent { protected HoverTestEvent(final Object source) { super(source); } @Override public Type getAssociatedType() { return HOVER_EVENT_TYPE; } } }
43.358744
97
0.69004
d2d37369e41b1766169fd05035c082cb15f2c6a8
2,054
package com.smartsheet.api.models; /* * #[license] * Smartsheet SDK for Java * %% * Copyright (C) 2019 Smartsheet * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * %[license] */ import com.smartsheet.api.models.enums.WidgetType; public class TitleRichTextWidgetContent implements WidgetContent { /** * The hex color, for instance #E6F5FE */ private String backgroundColor; /** * HTML snippet to render title or rich text */ private String htmlContent; /** * Returns the type for this widget content object * * @return TITLE */ @Override public WidgetType getWidgetType() { return WidgetType.TITLE; } /** * Gets the hex color for the background * * @return the hex color */ public String getBackgroundColor() { return backgroundColor; } /** * Sets the hex color for the background * * @param backgroundColor */ public TitleRichTextWidgetContent setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; return this; } /** * Gets the HTML snippet to render title or rich text * * @return the HTML snippet */ public String getHtmlContent() { return htmlContent; } /** * Sets the HTML snippet to render title or rich text * * @param htmlContent */ public TitleRichTextWidgetContent setHtmlContent(String htmlContent) { this.htmlContent = htmlContent; return this; } }
25.675
82
0.659202
9b9c619cc80a7b3daf1a8eec45419a31c61ddc31
631
package br.edu.usf; import org.bson.Document; import java.text.MessageFormat; import java.util.List; public class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { DBConnection.gi().insert(Randomizes.name(), Randomizes.address()); } final List<Document> all = DBConnection.gi().findAll(); for (Document document : all) { final Object name = document.get("name"); final Object address = document.get("address"); System.out.println(MessageFormat.format("Name: {0}, Address: {1}", name, address)); } } }
27.434783
95
0.597464
a293cee007a28f74fdb8516725071c3321ca6ebc
8,191
package net.swofty.lobby.util.signgui; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; import com.comphenix.protocol.events.PacketAdapter; import com.comphenix.protocol.events.PacketEvent; import com.comphenix.protocol.wrappers.BlockPosition; import com.comphenix.protocol.wrappers.WrappedBlockData; import com.comphenix.protocol.wrappers.WrappedChatComponent; import net.swofty.lobby.Loader; import net.swofty.lobby.util.protocol.WrapperPlayClientUpdateSign; import net.swofty.lobby.util.protocol.WrapperPlayServerBlockChange; import net.swofty.lobby.util.protocol.WrapperPlayServerOpenSignEntity; import net.swofty.lobby.util.protocol.WrapperPlayServerUpdateSign; import org.apache.commons.lang.StringEscapeUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import java.util.Hashtable; import java.util.UUID; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import java.lang.reflect.Field; public class SignGUI { private PacketAdapter packetListener; private final Player player; private Sign sign; private final LeaveListener listener = new LeaveListener(); public SignGUI(Player player, String[] lines, UpdateHandler uh) { this.player = player; int x_start = player.getLocation().getBlockX(); int y_start = 255; int z_start = player.getLocation().getBlockZ(); while (!player.getWorld().getBlockAt(x_start, y_start, z_start).getType().equals(Material.AIR)) { y_start--; if (y_start == 1) return; } Material material = Material.getMaterial("OAK_WALL_SIGN"); if (material == null) material = Material.getMaterial("WALL_SIGN"); player.getWorld().getBlockAt(x_start, y_start, z_start).setType(material); sign = (Sign) player.getWorld().getBlockAt(x_start, y_start, z_start).getState(); sign.setLine(1, lines[0]); sign.setLine(2, lines[1]); sign.setLine(3, lines[2]); sign.update(false, false); Bukkit.getScheduler().runTaskLater(Loader.getInstance(), () -> { try { openSignEditor(player, sign); } catch (Exception ignored) { } }, 2); Bukkit.getPluginManager().registerEvents(listener, Loader.getInstance()); registerSignUpdateListener(uh); //if(!auxiliar.equals(upperVersion?Material.OAK_WALL_SIGN:Material.getMaterial("WALL_SIGN"))) // Bukkit.getScheduler().runTaskLater(plugin, () -> p.getWorld().getBlockAt(x_start, y_start, z_start).setType(auxiliar), 40); } private static void openSignEditor(Player player, Sign sign) throws Exception { Object entityPlayer = getEntityPlayer(player); attachEntityPlayerToSign(entityPlayer, sign); Object position = getBlockPosition(sign.getBlock()); Object packet = createPositionalPacket(position, "PacketPlayOutOpenSignEditor"); sendPacketToEntityPlayer(packet, entityPlayer); } private static Object getEntityPlayer(Player player) throws Exception { Field entityPlayerField = getFirstFieldOfType(player, MinecraftReflector.getMinecraftServerClass("Entity")); return entityPlayerField.get(player); } private static void sendPacketToEntityPlayer(Object packet, Object entityPlayer) throws Exception { Object connection = entityPlayer.getClass().getField("playerConnection").get(entityPlayer); connection .getClass() .getDeclaredMethod("sendPacket", MinecraftReflector.getMinecraftServerClass("Packet")) .invoke(connection, packet); } private static Object createPositionalPacket(Object position, String typeOfPacket) throws Exception { return createPositionalPacket(position, MinecraftReflector.getMinecraftServerClass(typeOfPacket)); } private static Object createPositionalPacket(Object position, Class<?> typeOfPacket) throws Exception { return typeOfPacket .getConstructor(MinecraftReflector.getMinecraftServerClass("BlockPosition")) .newInstance(position); } private static Object getBlockPosition(Block block) throws Exception { return MinecraftReflector.getMinecraftServerClass("BlockPosition") .getConstructor(int.class, int.class, int.class) .newInstance(block.getX(), block.getY(), block.getZ()); } private static void attachEntityPlayerToSign(Object entityPlayer, Sign sign) throws Exception { Object tileEntitySign = getTileEntitySign(sign); maketileEntitySignEditable(tileEntitySign); Field signEntityHumanField = getFirstFieldOfType(tileEntitySign, MinecraftReflector.getMinecraftServerClass("EntityHuman")); signEntityHumanField.set(tileEntitySign, entityPlayer); } private static Object getTileEntitySign(Sign sign) throws Exception { Field tileEntityField = getFirstFieldOfType(sign, MinecraftReflector.getMinecraftServerClass("TileEntity")); return tileEntityField.get(sign); } private static void maketileEntitySignEditable(Object tileEntitySign) throws Exception { Field signIsEditable = tileEntitySign.getClass().getDeclaredField("isEditable"); signIsEditable.setAccessible(true); signIsEditable.set(tileEntitySign, true); } private static Field getFirstFieldOfType(Object source, Class<?> desiredType) throws NoSuchFieldException { return getFirstFieldOfType(source.getClass(), desiredType); } private static Field getFirstFieldOfType(Class<?> source, Class<?> desiredType) throws NoSuchFieldException { Class<?> ancestor = source; while (ancestor != null) { Field[] fields = ancestor.getDeclaredFields(); for (Field field : fields) { Class<?> candidateType = field.getType(); if (desiredType.isAssignableFrom(candidateType)) { field.setAccessible(true); return field; } } ancestor = ancestor.getSuperclass(); } throw new NoSuchFieldException("Cannot match " + desiredType.getName() + " in ancestry of " + source.getName()); } private class LeaveListener implements Listener { @EventHandler public void onLeave(PlayerQuitEvent e) { if (e.getPlayer().equals(player)) { sign.getBlock().setType(Material.AIR); ProtocolLibrary.getProtocolManager().removePacketListener(packetListener); HandlerList.unregisterAll(this); } } } private void registerSignUpdateListener(UpdateHandler uh) { ProtocolManager manager = ProtocolLibrary.getProtocolManager(); packetListener = new PacketAdapter(Loader.getInstance(), PacketType.Play.Client.UPDATE_SIGN) { @Override public void onPacketReceiving(PacketEvent event) { if (event.getPlayer().equals(player)) { String input; if (Bukkit.getVersion().contains("1.8")) input = event.getPacket().getChatComponentArrays().read(0)[0].getJson().replaceAll("\"", ""); else input = event.getPacket().getStringArrays().read(0)[0]; uh.onUpdate(input); Bukkit.getScheduler().runTask(Loader.getInstance(), () -> sign.getBlock().setType(Material.AIR)); manager.removePacketListener(this); HandlerList.unregisterAll(listener); } } }; manager.addPacketListener(packetListener); } public interface UpdateHandler { void onUpdate(String input); } }
41.790816
137
0.677085
322f4a32a798533e333abe76a6c3a821630e6f39
875
package com.nuix.superutilities.reporting; /*** * Encapsulates a Nuix query string and an associated name. * @author Jason Wells * */ public class NamedQuery { private String name = "Name"; private String query = "Query"; public NamedQuery() {} public NamedQuery(String name, String query) { this.name = name; this.query = query; } /*** * Gets the associated name * @return The associated name */ public String getName() { return name; } /*** * Sets the associated name * @param name The name to associate */ public void setName(String name) { this.name = name; } /*** * Gets the associated query * @return The associated query */ public String getQuery() { return query; } /*** * Sets the associated query * @param query The query to associate */ public void setQuery(String query) { this.query = query; } }
17.156863
59
0.657143
c500036bd2a19a313c46fda27d6fe47f04cc7ab2
172
package com.designpattern.cases.structure.decorator.drinks; public class HouseBlend implements Drink { @Override public double cost() { return 3; } }
17.2
59
0.69186
ed6edfeb86bd84745485063db64bc75e451bd5fe
4,856
package edu.psu.compbio.seqcode.gse.tools.chipchip; import java.util.*; import edu.psu.compbio.seqcode.gse.datasets.binding.*; import edu.psu.compbio.seqcode.gse.datasets.chipchip.*; import edu.psu.compbio.seqcode.gse.datasets.general.*; import edu.psu.compbio.seqcode.gse.datasets.species.*; import edu.psu.compbio.seqcode.gse.ewok.verbs.*; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.gse.utils.*; /** * Scans for binding (using JBD output) around genes. * * GeneJBDCalls --species "$SC;SGDv1" --genes sgdGene --jbd "analysis;version" --upstream 500 --downstream 100 * * --peaks: passes the peaks option to BayesBindingGenerator (tries to get the whole peak region?) * --includeORF: by default GeneJBDCalls only looks at the specified region upstream and downstream of the start site. * This option makes GeneJBDCalls look n bases upstream of the ORF through m bases downstream (ie, it * looks for binding in the ORF too). * --noorfoverlap: don't allow the region you get from expanding upstream and downstream to overlap another ORF. * */ public class GeneJBDCalls { private BayesBindingGenerator bayes; private RefGeneGenerator genes; private Genome genome; private int upstream, downstream; private boolean includeORF, dontOverlapORFs; public static void main(String args[]) throws NotFoundException { GeneJBDCalls caller = new GeneJBDCalls(); caller.parseArgs(args); caller.run(); } public GeneJBDCalls() {} public void parseArgs(String args[]) throws NotFoundException { genome = Args.parseGenome(args).cdr(); genes = Args.parseGenes(args).get(0); String exptname = Args.parseString(args,"jbd",null); String exptparts[] = exptname.split(";"); ChipChipDataset dataset = new ChipChipDataset(genome); ChipChipBayes b = dataset.getBayes(exptparts[0], exptparts[1]); bayes = new BayesBindingGenerator(b, Args.parseDouble(args,"probthresh",.2), Args.parseDouble(args,"sizethresh",1), Args.parseFlags(args).contains("peaks")); upstream = Args.parseInteger(args,"upstream",500); downstream = Args.parseInteger(args,"downstream",100); includeORF = Args.parseFlags(args).contains("includeORF"); // include the coding region of the gene in question dontOverlapORFs = Args.parseFlags(args).contains("noorfoverlap"); // don't allow the upstream or downstream values to cause overlap with another orf } public void run() { ChromRegionIterator chroms = new ChromRegionIterator(genome); while (chroms.hasNext()) { Region chrom = chroms.next(); Iterator<Gene> geneiter = genes.execute(chrom); while (geneiter.hasNext()) { StringBuffer buffer = new StringBuffer(); Gene g = geneiter.next(); Region r = null; if (includeORF) { r = g.expand(upstream,downstream); } else { r = g.expand(upstream,downstream - g.getWidth()); } if (dontOverlapORFs) { ArrayList<Integer> positions = new ArrayList<Integer>(); int tss = g.getStrand() == '+' ? g.getStart() : g.getEnd(); positions.add(tss); positions.add(r.getStart()); positions.add(r.getEnd()); Iterator<Gene> otherGenes = genes.execute(r); while (otherGenes.hasNext()) { Gene o = otherGenes.next(); if (o.getID().equals(g.getID()) || o.overlaps(g)) { continue; } positions.add(o.getStart()); positions.add(o.getEnd()); } Collections.sort(positions); int i = positions.indexOf(tss); if (i == 0) { i = 1;} int start = positions.get(i-1); int end = positions.get(i+1); // System.err.println(" " + r + " -> " + start + "," + end); r = new Region(r.getGenome(), r.getChrom(), start,end); } buffer.append(g.toString()); Iterator<BindingExtent> bindingiter = bayes.execute(r); while (bindingiter.hasNext()) { buffer.append("\t" + bindingiter.next().toString()); } System.out.println(buffer.toString()); } } } }
46.692308
156
0.562191
8f01665ba6c1f24a34bab5a5161f97f422ec60db
784
package com.ccffee.NotifyRobot.controller; import com.ccffee.NotifyRobot.service.CqMessageEntryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; @RestController public class CoolQHttpServerController { @Autowired private CqMessageEntryService cqMessageEntryService; @RequestMapping(value = "/coolQHttpServer", method = RequestMethod.POST) public HashMap coolQHttpServer(@RequestBody HashMap param){ return cqMessageEntryService.coolQhttpServer(param); } }
35.636364
76
0.82398
80c47e5061deb6af5ebdb66b5955ca79460b2e2f
6,212
/* * The MIT License * * Copyright: Copyright (C) 2014 T2Ti.COM * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * The author may be contacted at: [email protected] * * @author Claudio de Barros (T2Ti.com) * @version 2.0 */ package com.t2tierp.esocial.servidor; import com.t2tierp.cadastros.java.EmpresaEnderecoVO; import com.t2tierp.cadastros.java.EmpresaVO; import com.t2tierp.ged.java.ArquivoVO; import com.t2tierp.nfe.java.NfeConfiguracaoVO; import com.t2tierp.padrao.java.Biblioteca; import com.t2tierp.padrao.servidor.HibernateUtil; import java.io.File; import java.io.FileInputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyStore; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.hibernate.Criteria; import org.hibernate.Session; import org.openswing.swing.message.receive.java.ErrorResponse; import org.openswing.swing.message.receive.java.Response; import org.openswing.swing.message.receive.java.VOListResponse; import org.openswing.swing.message.send.java.GridParams; import org.openswing.swing.server.Action; import org.openswing.swing.server.UserSessionParameters; public class ESocialGridAction implements Action { @Override public String getRequestName() { return "eSocialGridAction"; } @Override public Response executeCommand(Object inputPar, UserSessionParameters userSessionPars, HttpServletRequest request, HttpServletResponse response, HttpSession userSession, ServletContext context) { Session session = null; try { GridParams pars = (GridParams) inputPar; Date dataInicial = (Date) pars.getOtherGridParams().get("dataInicial"); Date dataFinal = (Date) pars.getOtherGridParams().get("dataFinal"); EmpresaVO empresa = (EmpresaVO) pars.getOtherGridParams().get("empresa"); EmpresaEnderecoVO enderecoEmpresa = (EmpresaEnderecoVO) pars.getOtherGridParams().get("enderecoPrincipalEmpresa"); Map<String, Boolean> arquivosGerar = (HashMap) pars.getOtherGridParams().get("arquivosGerar");; session = HibernateUtil.getSessionFactory().openSession(); Criteria criteria = session.createCriteria(NfeConfiguracaoVO.class); NfeConfiguracaoVO nfeConfiguracao = (NfeConfiguracaoVO) criteria.uniqueResult(); if (nfeConfiguracao == null) { throw new Exception("Configuração NF-e não definida."); } KeyStore ks = KeyStore.getInstance("PKCS12"); char[] senha = nfeConfiguracao.getCertificadoDigitalSenha().toCharArray(); ks.load(new FileInputStream(new File(nfeConfiguracao.getCertificadoDigitalCaminho())), senha); String alias = ks.aliases().nextElement(); GeraXmlESocial geraXmlESocial = new GeraXmlESocial(alias, ks, senha); ValidaXmlESocial validaXmleSocial = new ValidaXmlESocial(); File file = File.createTempFile("eSocial", ".xml"); file.deleteOnExit(); List<ArquivoVO> arquivos = new ArrayList<>(); ArquivoVO arquivo; String xml; if (arquivosGerar.get("S1000")) { xml = geraXmlESocial.gerarESocial1000(empresa, enderecoEmpresa, dataInicial, dataFinal); try { validaXmleSocial.validaXmlESocial1000(xml, context); } catch (Exception e) { throw new Exception("Erro na validação do XML (S-1000)\n" + e.getMessage()); } Files.write(Paths.get(file.toURI()), xml.getBytes("UTF-8")); arquivo = new ArquivoVO(); arquivo.setFile(Biblioteca.getBytesFromFile(file)); arquivo.setNome("eSocial_S1000"); arquivo.setExtensao(".xml"); arquivos.add(arquivo); } if (arquivosGerar.get("S1010")) { xml = geraXmlESocial.gerarESocial1010(empresa, enderecoEmpresa, dataInicial, dataFinal); try { validaXmleSocial.validaXmlESocial1010(xml, context); } catch (Exception e) { throw new Exception("Erro na validação do XML (S-1010)\n" + e.getMessage()); } Files.write(Paths.get(file.toURI()), xml.getBytes("UTF-8")); arquivo = new ArquivoVO(); arquivo.setFile(Biblioteca.getBytesFromFile(file)); arquivo.setNome("eSocial_S1010"); arquivo.setExtensao(".xml"); arquivos.add(arquivo); } return new VOListResponse(arquivos, false, arquivos.size()); } catch (Exception ex) { ex.printStackTrace(); return new ErrorResponse(ex.getMessage()); } finally { if (session != null) { session.close(); } } } }
41.413333
199
0.670637
4bf0fd15d7aa8227d51f40817e54a84e7c152381
626
package com.github.tifezh.kchart.model; import com.github.tifezh.kchartlib.chart.rate.base.IRate; import com.github.tifezh.kchartlib.chart.rate.base.IRateDraw; import java.util.Date; public class RateModel implements IRate { public Date date; public float value; public String change; public String percent; @Override public Date getDate() { return date; } @Override public float getValue() { return value; } @Override public String getChange() { return change; } @Override public String getPercent() { return percent; } }
18.411765
61
0.654952
b5f57e9f7787498af925378fd577b3fd2952b3dc
1,856
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.vendorsoftwareproduct.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.zip.ZipOutputStream; /** * @author Avrahamg * @since November 08, 2016 */ public class ZipFileUtils { public InputStream getZipInputStream(String name) { URL url = getClass().getResource(name); File templateDir = new File(url.getFile()); try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos)) { VSPCommon.zipDir(templateDir, "", zos, true); return new ByteArrayInputStream(baos.toByteArray()); } catch (IOException exception) { throw new RuntimeException("Failed to read from Zip file: " + name, exception); } } }
35.018868
85
0.61153
553d9d90cfbc224ab8c64bc0605cc3ae90eb36a0
2,349
package dev.dhbw.testproject.vaadintest; import javax.servlet.annotation.WebServlet; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; import com.vaadin.server.VaadinRequest; import com.vaadin.server.VaadinServlet; import com.vaadin.ui.Button; import com.vaadin.ui.Label; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; /** * This is a more elaborated example of building a web-page with different * Vaadin components. */ @Theme("mytheme") public class SimpleExampleUI extends UI { private static final long serialVersionUID = 4161167027744554330L; @Override protected void init(VaadinRequest request) { /* * A Layout is a container, where different components can be placed. This is * comparable to an HTML div element. */ VerticalLayout layout = new VerticalLayout(); // A simple text field (like the input tag from HTML). TextField nameField = new TextField(); nameField.setCaption("Type your name here:"); // Simple button. Button button = new Button("Click Me"); Label buttonLabel = new Label(""); /* * Adds an action listener to the button and makes the button to an action when * it gets pressed. */ button.addClickListener(e -> { buttonLabel.setValue("Hi " + nameField.getValue() + "!"); }); // Adds the components to our layout container. layout.addComponents(nameField, button, buttonLabel); /* * Sets the site content to our layout container. We can only set our site * content to one component so we need to use these layouts if we want more than * one component in our page. */ setContent(layout); } /** * This is a basic Servlet which configures the URL where this page is available * and actually deploys it to there. */ @WebServlet("/simple/*") @VaadinServletConfiguration(ui = SimpleExampleUI.class, productionMode = false) public static class SimpleExampleServlet extends VaadinServlet { private static final long serialVersionUID = 184279586288058600L; } }
30.907895
89
0.649212
dd5a1893d351e7e1fb55232b215dc11742b6b21c
3,981
package org.nesc.ecbd.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * @author:Truman.P.Du * @createDate: 2018年3月21日 下午4:23:44 * @version:1.0 * @description: */ @Configuration @ConfigurationProperties("rct") public class InitConfig { @Value("${rct.elasticsearch.rest.urls:''}") private String esUrls; @Value("${rct.elasticsearch.slowlog.index:''}") private String slowlogIndexName; @Value("${rct.elasticsearch.slowlog.indexSuffix:''}") private String slowlogIndexNameSuffix; @Value("${rct.elasticsearch.client-list.index:''}") private String clientIndex; @Value("${rct.elasticsearch.enable:false}") private boolean elasticsearchEnable; @Value("${rct.rdb.generate.enable:false}") private boolean rdbGenerateEnable; @Value("${rct.dev.enable:false}") private boolean devEnable; @Value("${rct.dev.rdb.port:9002}") private String devRDBPort; private Email email; private User user; public String getClientIndex() { return clientIndex; } public void setClientIndex(String clientIndex) { this.clientIndex = clientIndex; } public String getEsUrls() { return esUrls; } public void setEsUrls(String esUrls) { this.esUrls = esUrls; } public String getSlowlogIndexName() { return slowlogIndexName; } public void setSlowlogIndexName(String slowlogIndexName) { this.slowlogIndexName = slowlogIndexName; } public String getSlowlogIndexNameSuffix() { return slowlogIndexNameSuffix; } public void setSlowlogIndexNameSuffix(String slowlogIndexNameSuffix) { this.slowlogIndexNameSuffix = slowlogIndexNameSuffix; } public boolean isElasticsearchEnable() { return elasticsearchEnable; } public void setElasticsearchEnable(boolean elasticsearchEnable) { this.elasticsearchEnable = elasticsearchEnable; } public boolean isRdbGenerateEnable() { return rdbGenerateEnable; } public void setRdbGenerateEnable(boolean rdbGenerateEnable) { this.rdbGenerateEnable = rdbGenerateEnable; } public boolean isDevEnable() { return devEnable; } public void setDevEnable(boolean devEnable) { this.devEnable = devEnable; } public String getDevRDBPort() { return devRDBPort; } public void setDevRDBPort(String devRDBPort) { this.devRDBPort = devRDBPort; } public Email getEmail() { return email; } public void setEmail(Email email) { this.email = email; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public static class Email { private String smtp; private String fromName; private String userName; private String password; private String subject; public String getSmtp() { return smtp; } public void setSmtp(String smtp) { this.smtp = smtp; } public String getFromName() { return fromName; } public void setFromName(String fromName) { this.fromName = fromName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } } public static class User { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } }
20.208122
76
0.693544
f6a64929a62d27ffd264502fe4c91da537a6e6ee
5,528
// *************************************************************************************************************************** // * 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.juneau.annotation; import static org.apache.juneau.BeanContext.*; import static java.util.Arrays.*; import java.util.*; import org.apache.juneau.*; import org.apache.juneau.http.header.*; import org.apache.juneau.reflect.*; import org.apache.juneau.svl.*; /** * Utility classes and methods for the {@link BeanConfig @BeanConfig} annotation. */ public class BeanConfigAnnotation { /** * Applies {@link BeanConfig} annotations to a {@link BeanContextBuilder}. */ public static class Applier extends AnnotationApplier<BeanConfig,BeanContextBuilder> { /** * Constructor. * * @param vr The resolver for resolving values in annotations. */ public Applier(VarResolverSession vr) { super(BeanConfig.class, BeanContextBuilder.class, vr); } @Override public void apply(AnnotationInfo<BeanConfig> ai, BeanContextBuilder b) { BeanConfig a = ai.getAnnotation(); visibility(a.beanClassVisibility(), "beanClassVisibility").ifPresent(x -> b.beanClassVisibility(x)); visibility(a.beanConstructorVisibility(), "beanConstructorVisibility").ifPresent(x -> b.beanConstructorVisibility(x)); visibility(a.beanFieldVisibility(), "beanFieldVisibility").ifPresent(x -> b.beanFieldVisibility(x)); visibility(a.beanMethodVisibility(), "beanMethodVisibility").ifPresent(x -> b.beanMethodVisibility(x)); bool(a.beanMapPutReturnsOldValue()).ifPresent(x -> b.beanMapPutReturnsOldValue(x)); bool(a.beansRequireDefaultConstructor()).ifPresent(x -> b.beansRequireDefaultConstructor(x)); bool(a.beansRequireSerializable()).ifPresent(x -> b.beansRequireSerializable(x)); bool(a.beansRequireSettersForGetters()).ifPresent(x -> b.beansRequireSettersForGetters(x)); bool(a.disableBeansRequireSomeProperties()).ifPresent(x -> b.disableBeansRequireSomeProperties(x)); bool(a.debug()).ifPresent(x -> b.set(CONTEXT_debug, x)); bool(a.findFluentSetters()).ifPresent(x -> b.findFluentSetters(x)); bool(a.ignoreInvocationExceptionsOnGetters()).ifPresent(x -> b.ignoreInvocationExceptionsOnGetters(x)); bool(a.ignoreInvocationExceptionsOnSetters()).ifPresent(x -> b.ignoreInvocationExceptionsOnSetters(x)); bool(a.disableIgnoreMissingSetters()).ifPresent(x -> b.disableIgnoreMissingSetters(x)); bool(a.disableIgnoreTransientFields()).ifPresent(x -> b.disableIgnoreTransientFields(x)); bool(a.ignoreUnknownBeanProperties()).ifPresent(x -> b.ignoreUnknownBeanProperties(x)); bool(a.disableIgnoreUnknownNullBeanProperties()).ifPresent(x -> b.disableIgnoreUnknownNullBeanProperties(x)); bool(a.sortProperties()).ifPresent(x -> b.sortProperties(x)); bool(a.useEnumNames()).ifPresent(x -> b.useEnumNames(x)); bool(a.disableInterfaceProxies()).ifPresent(x -> b.disableInterfaceProxies(x)); bool(a.useJavaBeanIntrospector()).ifPresent(x -> b.useJavaBeanIntrospector(x)); string(a.typePropertyName()).ifPresent(x -> b.typePropertyName(x)); string(a.locale()).map(Locale::forLanguageTag).ifPresent(x -> b.locale(x)); string(a.mediaType()).map(MediaType::of).ifPresent(x -> b.mediaType(x)); string(a.timeZone()).map(TimeZone::getTimeZone).ifPresent(x -> b.timeZone(x)); classes(a.dictionary()).ifPresent(x -> b.beanDictionary(x)); classes(a.dictionary_replace()).ifPresent(x -> { b.beanDictionary().clear(); b.beanDictionary(x);}); classes(a.swaps()).ifPresent(x -> b.swaps(x)); classes(a.swaps_replace()).ifPresent(x -> { b.swaps().clear(); b.swaps(x);}); classes(a.notBeanClasses()).ifPresent(x -> b.notBeanClasses(x)); classes(a.notBeanClasses_replace()).ifPresent(x -> { b.notBeanClasses().clear(); b.notBeanClasses(x);}); type(a.propertyNamer()).ifPresent(x -> b.propertyNamer(x)); asList(a.interfaces()).stream().map(x -> BeanAnnotation.create(x).interfaceClass(x).build()).forEach(x -> b.annotations(x)); strings(a.notBeanPackages()).ifPresent(x -> b.notBeanPackages(x)); strings(a.notBeanPackages_replace()).ifPresent(x -> {b.notBeanPackages().clear(); b.notBeanPackages(x);}); } } }
64.27907
127
0.644899
6e76bfa768aff4e2bae40a0044bde6cbc0780b1f
13,451
package taskmgt; /** * * @author Ray */ import taskmgt.Models.*; import java.util.LinkedList; import java.io.PrintWriter; import java.io.File; import java.io.IOException; import java.awt.Desktop; import java.util.Collections; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TaskSystem { public static void main(String[] args) { try { // Set System L&F UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { } TaskSystem.Initialize(); InitializeDefaultUsers(); LoginGUI loginForm=new LoginGUI(); loginForm.setVisible(true); loginForm.setLocationRelativeTo(null); } //Properties private static User CurrentUser; //Lists private static LinkedList<User> userList = new LinkedList(); private static LinkedList<Project> projectList = new LinkedList(); //Serializer private final static Serializer<User> userSerializer=new Serializer(".//Data","User.ser"); private final static Serializer<Project> projectSerializer=new Serializer(".//Data","Project.ser"); //Data Manipulation //Pull List from File public static void pullUser(){ userList=userSerializer.readObject();} public static void pullProject(){ projectList=projectSerializer.readObject();} //Push List to File public static void pushUser(){ userSerializer.writeObject(userList);} public static void pushProject(){ projectSerializer.writeObject(projectList);} //Initialize and Finalize public static void Initialize(){ pullUser(); pullProject(); } public static void checkforEmptyLists(){ if(userList == null) { userList = new LinkedList<>(); } if(projectList == null) { projectList = new LinkedList<>(); } } public static void Finalize(){ pushUser(); pushProject(); } public static void InitializeDefaultUsers(){ if(userList==null){ userList= new LinkedList(); projectList= new LinkedList(); Administrator admin=new Administrator("admin","[email protected]","123456"); TeamLeader leader=new TeamLeader("leader","[email protected]","123456"); TeamMember member=new TeamMember("member","[email protected]","123456"); //If these users are not already in the list, then add. Else do nothing if (!userList.contains(admin)) userList.add(admin); if (!userList.contains(leader)) userList.add(leader); if (!userList.contains(member)) userList.add(member); Finalize(); } } // public static void InitializeProject(String title, String owner, Date start, Date end) { // Project project = new Project(title, owner, start, end); // projectList.add(project); // Finalize(); // } // public static void InitializeMember(String name,String email,boolean leader) { // User member; // if(leader){ // member = new TeamLeader(name,email); // } // else{ // member = new TeamMember(name,email); // } // userList.add(member); // Finalize(); // } //Methods public static void setCurrentUser(User user) { CurrentUser = user; } public static User getCurrentUser() { return CurrentUser; } //Get List public static LinkedList<Project> getProjectList() { return projectList;} public static LinkedList<User> getUserList() { return userList;} //Set List public static void setProjectList(Project project) { projectList.add(project);} public static void setUserList(User user) { userList.add(user);} public static LinkedList<TeamLeader> getLeaders(){ LinkedList<TeamLeader> leaders=new LinkedList(); for(User user:userList){ if(user instanceof TeamLeader) leaders.add((TeamLeader)user); } return leaders; } public static LinkedList<TeamMember> getMembers(){ LinkedList<TeamMember> members=new LinkedList(); for(User user:userList){ if(user instanceof TeamMember) members.add((TeamMember)user); } return members; } //Get Object public static User getUser(String email, String password){ for(User user:userList){ if (user != null) { if (user.getEmail() != null && user.getPassword() != null) { if(user.getEmail().equalsIgnoreCase(email) && user.getPassword().equals(password)){ return user; } } else if (user.getEmail() != null) { if (user.getEmail().equalsIgnoreCase(email)) { user.setPassword(null); return user; } } } } return null; } public static User getUserByEmail(String email){ for(User user:userList){ if(user.getEmail().toLowerCase().equals(email.toLowerCase())){ return user; } } return null; } public static LinkedList<Project> refreshProjectList(){ LinkedList<Project> projList=new LinkedList(); if (!TaskSystem.getProjectList().isEmpty()) { for (Project project : TaskSystem.getProjectList()) { if (TaskSystem.getCurrentUser().getEmail().equalsIgnoreCase(project.getOwner())) { projList.add(project); } else{ for (User member : project.getMembers()) { if (TaskSystem.getCurrentUser().equals(member)) { projList.add(project); break; } } } } } return projList; } public static Project getProjectByTitle(String projectTitle) { for(Project project:projectList){ if(project.getTitle().equalsIgnoreCase(projectTitle)){ return project; } } return null; } public static Project getProjectByID(int id) { for(Project project:projectList){ if(project.getID() == id){ return project; } } return null; } public static void clearAllLists() { projectList = new LinkedList<>(); userList = new LinkedList<>(); } public static void printMemberRpt(TeamMember[] memberList) throws IOException { PrintWriter output ; try { File file = new File ("reports/memberReport.txt"); file.getParentFile().mkdirs(); output = new PrintWriter("reports/memberReport.txt"); output.println("\nMEMBER REPORT\n-------------"); String taskHeader = String.format("%-30s%-15s%-15s%-15s%-4s", "TASK", "OWNER", "START DATE","END DATE", "DONE"); String line = String.format("------------------------------------------------------------------------------------------------------------"); //TOTAL COUNT ARRAYS (INDEX = SELECTEDMEMBER) int[] totalProjectCount = new int[memberList.length]; int[] totalTaskCount = new int[memberList.length]; int[] totalTaskCompletedCount = new int[memberList.length]; //PRINTS .TOSTRING OF EVERY MEMBER SELECTED for (TeamMember member: memberList){output.println(member.toString());} output.println(); //CONSOLIDATES UNIQUE PROJECTS OF EACH MEMBER INTO CONSOLIDATED UNIQUE PROJECT LIST LinkedList<Project> uniqueProjectList = new LinkedList(); LinkedList<Project> ProjectList = null; for (TeamMember member: memberList){ ProjectList = member.getProjects(); int i = 0; for (Project p : ProjectList){ totalProjectCount[i]++; if(!uniqueProjectList.contains(p)){uniqueProjectList.add(p);} } i++; } //SORT PROJECT LIST (BY START DATE) Collections.sort(uniqueProjectList); //FOR EACH PROJECT... for( Project p : uniqueProjectList){ int[] taskCount = new int[memberList.length]; int[] taskCompletedCount = new int[memberList.length]; // PRINT THE PROJECT .TOSTRING output.println(p.toString()); // PRINT THE HEADER output.println(line); output.println(taskHeader); output.println(line); // GET THE PROJECT'S TASKS (ALL) LinkedList<Task> taskList = p.getTasks(); LinkedList<Task> projectTaskList = new LinkedList(); for( Task t : taskList) { for(int j=0; j < memberList.length; j++){ if(TaskSystem.getUserByEmail(t.getOwner()) == memberList[j]) { projectTaskList.add(t); if(t.getStatus() == State.Completed){ taskCompletedCount[j]++;} taskCount[j]++; } } } Collections.sort(projectTaskList); // Collections.sort(projectTaskList, Comparator<Task> c); for (Task pt : projectTaskList) { output.println(pt.toString()); } output.println(); int k=0; for (User m : memberList){ float percent = 0; if(taskCount[k]!=0){ percent = (float)taskCompletedCount[k]/(float)taskCount[k]*100; String mem = String.format("%s completed %d out of %d tasks (%.1f%%)", m.getName(), taskCompletedCount[k],taskCount[k],percent); output.println(mem); totalTaskCount[k] += taskCount[k]; totalTaskCompletedCount[k] += taskCompletedCount[k]; } k++; } output.println(); } output.println("\nTOTALS"); output.println(line); output.printf("%-30s%-15s%-15s%-15s%-10s", "MEMBER", "PROJECTS", "TASKS","COMPLETED", "(%)"); output.println(line); //PRINT MEMBER TOTALS for(int i=0;i<memberList.length;i++){ float percent = 0; if(totalTaskCount[i]!=0){percent = (float)totalTaskCompletedCount[i]/(float)totalTaskCount[i]*100;} String mem = String.format("%-30s%-15d%-15d%-15d%-10.1f", memberList[i].getName(), totalProjectCount[i], totalTaskCount[i], totalTaskCompletedCount[i], percent); output.println(mem); } //PRINT GRAND TOTAL (IF MULTIPLE) if(memberList.length > 1){ int grandTotalProjects = 0; int grandTotalTasks = 0; int grandTotalCompleted = 0; for(int i=0;i<memberList.length;i++){ grandTotalProjects += totalProjectCount[i]; grandTotalTasks += totalTaskCount[i]; grandTotalCompleted += totalTaskCompletedCount[i]; } float percent = 0; if(grandTotalTasks!=0){percent = (float)grandTotalCompleted/(float)grandTotalTasks*100;} output.println(line); String grand = String.format("%-30s%-15d%-15d%-15d%-10.1f", "GRAND TOTAL",grandTotalProjects, grandTotalTasks, grandTotalCompleted, percent); output.println(grand); } output.flush(); } catch(IOException ioe) { System.out.println(ioe.toString()); } Desktop desktop = Desktop.getDesktop(); File dirToOpen = null; try { dirToOpen = new File("reports/memberReport.txt"); desktop.open(dirToOpen); } catch (IllegalArgumentException iae) { System.out.println("File Not Found"); } } }
35.304462
177
0.510371
c72a7a1bf862b6ddc15912f6702b36211f5adddc
1,333
/** * Copyright 2005-2019 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.rice.kew.engine; import org.kuali.rice.kew.routeheader.DocumentRouteHeaderValue; /** * Defines the contract to the core workflow engine. The standard unit of work of the engine * is the process method. Document must also be initialized by the WorkflowEngine when they * are initially created. * * @author Kuali Rice Team ([email protected]) * */ public interface WorkflowEngine { public void process(String documentId, String nodeInstanceId) throws Exception; /** * @throws IllegalDocumentTypeException if the given document could not be initialized successfully */ public void initializeDocument(DocumentRouteHeaderValue document); }
34.179487
103
0.747187
14595925c3354a0730a64ed175f4a939d10bbd60
11,758
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query.materializedview; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.NamedType; import com.fasterxml.jackson.dataformat.smile.SmileFactory; import com.fasterxml.jackson.dataformat.smile.SmileGenerator; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import io.druid.client.BatchServerInventoryView; import io.druid.client.BrokerSegmentWatcherConfig; import io.druid.client.BrokerServerView; import io.druid.client.DruidServer; import io.druid.client.selector.HighestPriorityTierSelectorStrategy; import io.druid.client.selector.RandomServerSelectorStrategy; import io.druid.curator.CuratorTestBase; import io.druid.indexing.materializedview.DerivativeDataSourceMetadata; import io.druid.jackson.DefaultObjectMapper; import io.druid.java.util.common.Intervals; import io.druid.java.util.http.client.HttpClient; import io.druid.metadata.IndexerSQLMetadataStorageCoordinator; import io.druid.metadata.TestDerbyConnector; import io.druid.query.Query; import static io.druid.query.QueryRunnerTestHelper.allGran; import io.druid.query.QueryToolChestWarehouse; import io.druid.query.QueryWatcher; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.LongSumAggregatorFactory; import io.druid.query.spec.MultipleIntervalSegmentSpec; import io.druid.query.topn.TopNQuery; import io.druid.query.topn.TopNQueryBuilder; import io.druid.segment.TestHelper; import io.druid.server.coordination.DruidServerMetadata; import io.druid.server.coordination.ServerType; import io.druid.server.initialization.ZkPathsConfig; import io.druid.server.metrics.NoopServiceEmitter; import io.druid.timeline.DataSegment; import io.druid.timeline.partition.NoneShardSpec; import org.easymock.EasyMock; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; public class DatasourceOptimizerTest extends CuratorTestBase { @Rule public final TestDerbyConnector.DerbyConnectorRule derbyConnectorRule = new TestDerbyConnector.DerbyConnectorRule(); private TestDerbyConnector derbyConnector; private DerivativeDataSourceManager derivativesManager; private DruidServer druidServer; private ObjectMapper jsonMapper; private ZkPathsConfig zkPathsConfig; private DataSourceOptimizer optimizer; private MaterializedViewConfig viewConfig; private IndexerSQLMetadataStorageCoordinator metadataStorageCoordinator; private BatchServerInventoryView baseView; private BrokerServerView brokerServerView; @Before public void setUp() throws Exception { derbyConnector = derbyConnectorRule.getConnector(); derbyConnector.createDataSourceTable(); derbyConnector.createSegmentTable(); viewConfig = new MaterializedViewConfig(); jsonMapper = TestHelper.makeJsonMapper(); jsonMapper.registerSubtypes(new NamedType(DerivativeDataSourceMetadata.class, "view")); metadataStorageCoordinator = EasyMock.createMock(IndexerSQLMetadataStorageCoordinator.class); derivativesManager = new DerivativeDataSourceManager( viewConfig, derbyConnectorRule.metadataTablesConfigSupplier(), jsonMapper, derbyConnector ); metadataStorageCoordinator = new IndexerSQLMetadataStorageCoordinator( jsonMapper, derbyConnectorRule.metadataTablesConfigSupplier().get(), derbyConnector ); setupServerAndCurator(); curator.start(); curator.blockUntilConnected(); zkPathsConfig = new ZkPathsConfig(); setupViews(); druidServer = new DruidServer( "localhost:1234", "localhost:1234", null, 10000000L, ServerType.HISTORICAL, "default_tier", 0 ); setupZNodeForServer(druidServer, new ZkPathsConfig(), jsonMapper); optimizer = new DataSourceOptimizer(brokerServerView); } @After public void tearDown() throws IOException { baseView.stop(); tearDownServerAndCurator(); } @Test(timeout = 60_000L) public void testOptimize() throws InterruptedException { // insert datasource metadata String dataSource = "derivative"; String baseDataSource = "base"; Set<String> dims = Sets.newHashSet("dim1", "dim2", "dim3"); Set<String> metrics = Sets.newHashSet("cost"); DerivativeDataSourceMetadata metadata = new DerivativeDataSourceMetadata(baseDataSource, dims, metrics); metadataStorageCoordinator.insertDataSourceMetadata(dataSource, metadata); // insert base datasource segments List<Boolean> baseResult = Lists.transform( ImmutableList.<String>of( "2011-04-01/2011-04-02", "2011-04-02/2011-04-03", "2011-04-03/2011-04-04", "2011-04-04/2011-04-05", "2011-04-05/2011-04-06" ), interval -> { final DataSegment segment = createDataSegment( "base", interval, "v1", Lists.newArrayList("dim1", "dim2", "dim3", "dim4"), 1024 * 1024 ); try { metadataStorageCoordinator.announceHistoricalSegments(Sets.newHashSet(segment)); announceSegmentForServer(druidServer, segment, zkPathsConfig, jsonMapper); } catch (IOException e) { return false; } return true; } ); // insert derivative segments List<Boolean> derivativeResult = Lists.transform( ImmutableList.<String>of( "2011-04-01/2011-04-02", "2011-04-02/2011-04-03", "2011-04-03/2011-04-04" ), interval -> { final DataSegment segment = createDataSegment("derivative", interval, "v1", Lists.newArrayList("dim1", "dim2", "dim3"), 1024); try { metadataStorageCoordinator.announceHistoricalSegments(Sets.newHashSet(segment)); announceSegmentForServer(druidServer, segment, zkPathsConfig, jsonMapper); } catch (IOException e) { return false; } return true; } ); Assert.assertFalse(baseResult.contains(false)); Assert.assertFalse(derivativeResult.contains(false)); derivativesManager.start(); while (DerivativeDataSourceManager.getAllDerivatives().isEmpty()) { TimeUnit.SECONDS.sleep(1L); } // build user query TopNQuery userQuery = new TopNQueryBuilder() .dataSource("base") .granularity(allGran) .dimension("dim1") .metric("cost") .threshold(4) .intervals("2011-04-01/2011-04-06") .aggregators( Lists.<AggregatorFactory>newArrayList( new LongSumAggregatorFactory("cost", "cost") ) ) .build(); List<Query> expectedQueryAfterOptimizing = Lists.newArrayList( new TopNQueryBuilder() .dataSource("derivative") .granularity(allGran) .dimension("dim1") .metric("cost") .threshold(4) .intervals(new MultipleIntervalSegmentSpec(Lists.newArrayList(Intervals.of("2011-04-01/2011-04-04")))) .aggregators( Lists.<AggregatorFactory>newArrayList( new LongSumAggregatorFactory("cost", "cost") ) ) .build(), new TopNQueryBuilder() .dataSource("base") .granularity(allGran) .dimension("dim1") .metric("cost") .threshold(4) .intervals(new MultipleIntervalSegmentSpec(Lists.newArrayList(Intervals.of("2011-04-04/2011-04-06")))) .aggregators( Lists.<AggregatorFactory>newArrayList( new LongSumAggregatorFactory("cost", "cost") ) ) .build() ); Assert.assertEquals(expectedQueryAfterOptimizing, optimizer.optimize(userQuery)); derivativesManager.stop(); } private DataSegment createDataSegment(String name, String intervalStr, String version, List<String> dims, long size) { return DataSegment.builder() .dataSource(name) .interval(Intervals.of(intervalStr)) .loadSpec( ImmutableMap.<String, Object>of( "type", "local", "path", "somewhere" ) ) .version(version) .dimensions(dims) .metrics(ImmutableList.<String>of("cost")) .shardSpec(NoneShardSpec.instance()) .binaryVersion(9) .size(size) .build(); } private void setupViews() throws Exception { baseView = new BatchServerInventoryView( zkPathsConfig, curator, jsonMapper, Predicates.alwaysTrue() ) { @Override public void registerSegmentCallback(Executor exec, final SegmentCallback callback) { super.registerSegmentCallback( exec, new SegmentCallback() { @Override public CallbackAction segmentAdded(DruidServerMetadata server, DataSegment segment) { CallbackAction res = callback.segmentAdded(server, segment); return res; } @Override public CallbackAction segmentRemoved(DruidServerMetadata server, DataSegment segment) { CallbackAction res = callback.segmentRemoved(server, segment); return res; } @Override public CallbackAction segmentViewInitialized() { CallbackAction res = callback.segmentViewInitialized(); return res; } } ); } }; brokerServerView = new BrokerServerView( EasyMock.createMock(QueryToolChestWarehouse.class), EasyMock.createMock(QueryWatcher.class), getSmileMapper(), EasyMock.createMock(HttpClient.class), baseView, new HighestPriorityTierSelectorStrategy(new RandomServerSelectorStrategy()), new NoopServiceEmitter(), new BrokerSegmentWatcherConfig() ); baseView.start(); } private ObjectMapper getSmileMapper() { final SmileFactory smileFactory = new SmileFactory(); smileFactory.configure(SmileGenerator.Feature.ENCODE_BINARY_AS_7BIT, false); smileFactory.delegateToTextual(true); final ObjectMapper retVal = new DefaultObjectMapper(smileFactory); retVal.getFactory().setCodec(retVal); return retVal; } }
35.522659
136
0.675965
6756a944a0a6c3b675fef7aa7a7be4951e028663
234
package net.woggle; public class ApiUrl { String mUrl; boolean mIsV2; public ApiUrl(String url, boolean isV2) { mUrl = url; mIsV2 = isV2; } public String getUrl () { return mUrl; } public boolean isV2() { return mIsV2; } }
18
41
0.679487
e3defb22a63f6da3253438f0140ee30b39bba6cc
3,724
/* * Copyright 2013-2019 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.cloud.sleuth.instrument.messaging; import java.util.function.BiConsumer; import brave.Span; import brave.Tracer; import brave.Tracing; import brave.propagation.Propagation; import brave.propagation.TraceContext; import brave.propagation.TraceContextOrSamplingFlags; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.support.MessageHeaderAccessor; import static brave.Span.Kind.CONSUMER; /** * Adds tracing extraction to an instance of * {@link org.springframework.messaging.handler.invocation.AbstractMethodMessageHandler} * in a reusable way. When sub-classing a provider specific class of that type you would * wrap the <pre>super.handleMessage(...)</pre> call with a call to this. See * {@link org.springframework.cloud.sleuth.instrument.messaging.SqsQueueMessageHandler} * for an example. * * This implementation also allows for supplying a {@link java.util.function.BiConsumer} * instance that can be used to add queue specific tags and modifications to the span. * * @author Brian Devins-Suresh */ class TracingMethodMessageHandlerAdapter { private Tracing tracing; private Tracer tracer; private TraceContext.Extractor<MessageHeaderAccessor> extractor; TracingMethodMessageHandlerAdapter(Tracing tracing, Propagation.Getter<MessageHeaderAccessor, String> traceMessagePropagationGetter) { this.tracing = tracing; this.tracer = tracing.tracer(); this.extractor = tracing.propagation().extractor(traceMessagePropagationGetter); } void wrapMethodMessageHandler(Message<?> message, MessageHandler messageHandler, BiConsumer<Span, Message<?>> messageSpanTagger) { TraceContextOrSamplingFlags extracted = extractAndClearHeaders(message); Span consumerSpan = tracer.nextSpan(extracted); Span listenerSpan = tracer.newChild(consumerSpan.context()); if (!consumerSpan.isNoop()) { consumerSpan.name("next-message").kind(CONSUMER); if (messageSpanTagger != null) { messageSpanTagger.accept(consumerSpan, message); } // incur timestamp overhead only once long timestamp = tracing.clock(consumerSpan.context()) .currentTimeMicroseconds(); consumerSpan.start(timestamp); long consumerFinish = timestamp + 1L; // save a clock reading consumerSpan.finish(consumerFinish); // not using scoped span as we want to start with a pre-configured time listenerSpan.name("on-message").start(consumerFinish); } try (Tracer.SpanInScope ws = tracer.withSpanInScope(listenerSpan)) { messageHandler.handleMessage(message); } catch (Throwable t) { listenerSpan.error(t); throw t; } finally { listenerSpan.finish(); } } private TraceContextOrSamplingFlags extractAndClearHeaders(Message<?> message) { MessageHeaderAccessor headers = MessageHeaderAccessor.getMutableAccessor(message); TraceContextOrSamplingFlags extracted = extractor.extract(headers); for (String propagationKey : tracing.propagation().keys()) { headers.removeHeader(propagationKey); } return extracted; } }
33.854545
88
0.772556
9824c57339670f22edf94b82dbef86492296447e
711
package com.parkinfo.entity.informationTotal; import com.parkinfo.entity.base.BaseEntity; import io.swagger.annotations.ApiModel; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.Index; import javax.persistence.Table; @Data @EqualsAndHashCode(callSuper = true) @Entity @Table(name = "c_info_template") @EntityListeners(AuditingEntityListener.class) @ApiModel(value = "InfoTotalTemplate", description = "信息统计-文件模板") public class InfoTotalTemplate extends BaseEntity { private String type; private String templateUrl; }
26.333333
74
0.818565
3ead1918781305d5eaaa84ed0dfcc037738f4621
32,116
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.ws.security.wss4j.policyhandlers; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.xml.namespace.QName; import javax.xml.soap.SOAPException; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.util.StringUtils; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.message.MessageUtils; import org.apache.cxf.rt.security.utils.SecurityUtils; import org.apache.cxf.ws.policy.AssertionInfoMap; import org.apache.cxf.ws.security.SecurityConstants; import org.apache.cxf.ws.security.tokenstore.SecurityToken; import org.apache.cxf.ws.security.tokenstore.TokenStoreException; import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils; import org.apache.cxf.ws.security.wss4j.TokenStoreCallbackHandler; import org.apache.cxf.ws.security.wss4j.WSS4JUtils; import org.apache.wss4j.common.ConfigurationConstants; import org.apache.wss4j.common.ext.WSSecurityException; import org.apache.wss4j.common.util.KeyUtils; import org.apache.wss4j.common.util.XMLUtils; import org.apache.wss4j.policy.SPConstants; import org.apache.wss4j.policy.model.AbstractSymmetricAsymmetricBinding; import org.apache.wss4j.policy.model.AbstractToken; import org.apache.wss4j.policy.model.AbstractToken.DerivedKeys; import org.apache.wss4j.policy.model.AbstractTokenWrapper; import org.apache.wss4j.policy.model.AlgorithmSuite; import org.apache.wss4j.policy.model.AlgorithmSuite.AlgorithmSuiteType; import org.apache.wss4j.policy.model.IssuedToken; import org.apache.wss4j.policy.model.KerberosToken; import org.apache.wss4j.policy.model.SecureConversationToken; import org.apache.wss4j.policy.model.SecurityContextToken; import org.apache.wss4j.policy.model.SpnegoContextToken; import org.apache.wss4j.policy.model.SymmetricBinding; import org.apache.wss4j.policy.model.UsernameToken; import org.apache.wss4j.policy.model.X509Token; import org.apache.wss4j.stax.ext.WSSConstants; import org.apache.wss4j.stax.ext.WSSSecurityProperties; import org.apache.wss4j.stax.securityEvent.WSSecurityEventConstants; import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants; import org.apache.xml.security.exceptions.XMLSecurityException; import org.apache.xml.security.stax.ext.OutboundSecurityContext; import org.apache.xml.security.stax.ext.SecurePart; import org.apache.xml.security.stax.ext.SecurePart.Modifier; import org.apache.xml.security.stax.ext.XMLSecurityConstants; import org.apache.xml.security.stax.impl.util.IDGenerator; import org.apache.xml.security.stax.securityEvent.AbstractSecuredElementSecurityEvent; import org.apache.xml.security.stax.securityEvent.SecurityEvent; /** * */ public class StaxSymmetricBindingHandler extends AbstractStaxBindingHandler { private static final Logger LOG = LogUtils.getL7dLogger(StaxSymmetricBindingHandler.class); private SymmetricBinding sbinding; private SoapMessage message; public StaxSymmetricBindingHandler( WSSSecurityProperties properties, SoapMessage msg, SymmetricBinding sbinding, OutboundSecurityContext outboundSecurityContext ) { super(properties, msg, sbinding, outboundSecurityContext); this.message = msg; this.sbinding = sbinding; } private AbstractTokenWrapper getSignatureToken() { if (sbinding.getProtectionToken() != null) { return sbinding.getProtectionToken(); } return sbinding.getSignatureToken(); } private AbstractTokenWrapper getEncryptionToken() { if (sbinding.getProtectionToken() != null) { return sbinding.getProtectionToken(); } return sbinding.getEncryptionToken(); } public void handleBinding() { AssertionInfoMap aim = getMessage().get(AssertionInfoMap.class); configureTimestamp(aim); assertPolicy(sbinding.getName()); String asymSignatureAlgorithm = (String)getMessage().getContextualProperty(SecurityConstants.ASYMMETRIC_SIGNATURE_ALGORITHM); if (asymSignatureAlgorithm != null && sbinding.getAlgorithmSuite() != null) { sbinding.getAlgorithmSuite().getAlgorithmSuiteType().setAsymmetricSignature(asymSignatureAlgorithm); } String symSignatureAlgorithm = (String)getMessage().getContextualProperty(SecurityConstants.SYMMETRIC_SIGNATURE_ALGORITHM); if (symSignatureAlgorithm != null && sbinding.getAlgorithmSuite() != null) { sbinding.getAlgorithmSuite().getAlgorithmSuiteType().setSymmetricSignature(symSignatureAlgorithm); } // Set up CallbackHandler which wraps the configured Handler WSSSecurityProperties properties = getProperties(); try { TokenStoreCallbackHandler callbackHandler = new TokenStoreCallbackHandler( properties.getCallbackHandler(), TokenStoreUtils.getTokenStore(message) ); properties.setCallbackHandler(callbackHandler); } catch (TokenStoreException e) { LOG.log(Level.FINE, e.getMessage(), e); throw new Fault(e); } if (sbinding.getProtectionOrder() == AbstractSymmetricAsymmetricBinding.ProtectionOrder.EncryptBeforeSigning) { doEncryptBeforeSign(); assertPolicy( new QName(sbinding.getName().getNamespaceURI(), SPConstants.ENCRYPT_BEFORE_SIGNING)); } else { doSignBeforeEncrypt(); assertPolicy( new QName(sbinding.getName().getNamespaceURI(), SPConstants.SIGN_BEFORE_ENCRYPTING)); } if (!isRequestor()) { properties.setEncryptSymmetricEncryptionKey(false); } configureLayout(aim); assertAlgorithmSuite(sbinding.getAlgorithmSuite()); assertWSSProperties(sbinding.getName().getNamespaceURI()); assertTrustProperties(sbinding.getName().getNamespaceURI()); assertPolicy( new QName(sbinding.getName().getNamespaceURI(), SPConstants.ONLY_SIGN_ENTIRE_HEADERS_AND_BODY)); if (sbinding.isProtectTokens()) { assertPolicy( new QName(sbinding.getName().getNamespaceURI(), SPConstants.PROTECT_TOKENS)); } } private void doEncryptBeforeSign() { try { AbstractTokenWrapper encryptionWrapper = getEncryptionToken(); assertTokenWrapper(encryptionWrapper); AbstractToken encryptionToken = encryptionWrapper.getToken(); String tokenId = null; SecurityToken tok = null; if (encryptionToken instanceof KerberosToken) { tok = getSecurityToken(); if (MessageUtils.isRequestor(message)) { addKerberosToken((KerberosToken)encryptionToken, false, true, true); } } else if (encryptionToken instanceof IssuedToken) { tok = getSecurityToken(); addIssuedToken(encryptionToken, tok, false, true); if (tok == null && !isRequestor()) { org.apache.xml.security.stax.securityToken.SecurityToken securityToken = findInboundSecurityToken(WSSecurityEventConstants.SAML_TOKEN); tokenId = WSS4JUtils.parseAndStoreStreamingSecurityToken(securityToken, message); } } else if (encryptionToken instanceof SecureConversationToken || encryptionToken instanceof SecurityContextToken || encryptionToken instanceof SpnegoContextToken) { tok = getSecurityToken(); if (tok != null && isRequestor()) { WSSSecurityProperties properties = getProperties(); WSSConstants.Action actionToPerform = WSSConstants.CUSTOM_TOKEN; properties.addAction(actionToPerform); } else if (tok == null && !isRequestor()) { org.apache.xml.security.stax.securityToken.SecurityToken securityToken = findInboundSecurityToken(WSSecurityEventConstants.SECURITY_CONTEXT_TOKEN); tokenId = WSS4JUtils.parseAndStoreStreamingSecurityToken(securityToken, message); } } else if (encryptionToken instanceof X509Token) { if (isRequestor()) { tokenId = setupEncryptedKey(); } else { org.apache.xml.security.stax.securityToken.SecurityToken securityToken = findEncryptedKeyToken(); tokenId = WSS4JUtils.parseAndStoreStreamingSecurityToken(securityToken, message); } } else if (encryptionToken instanceof UsernameToken) { unassertPolicy(sbinding, "UsernameTokens not supported with Symmetric binding"); return; } assertToken(encryptionToken); if (tok == null) { tokenId = XMLUtils.getIDFromReference(tokenId); // Get hold of the token from the token storage tok = TokenStoreUtils.getTokenStore(message).getToken(tokenId); } // Store key if (!(MessageUtils.isRequestor(message) && encryptionToken instanceof KerberosToken)) { storeSecurityToken(encryptionToken, tok); } final List<SecurePart> encrParts; final List<SecurePart> sigParts; try { encrParts = getEncryptedParts(); //Signed parts are determined before encryption because encrypted signed headers //will not be included otherwise sigParts = getSignedParts(); } catch (SOAPException ex) { throw new Fault(ex); } addSupportingTokens(); if (encryptionToken != null && !encrParts.isEmpty()) { if (isRequestor()) { encrParts.addAll(encryptedTokensList); } //Check for signature protection if (sbinding.isEncryptSignature()) { SecurePart part = new SecurePart(new QName(XMLSecurityConstants.NS_DSIG, "Signature"), Modifier.Element); encrParts.add(part); if (signatureConfirmationAdded) { part = new SecurePart(WSSConstants.TAG_WSSE11_SIG_CONF, Modifier.Element); encrParts.add(part); } assertPolicy( new QName(sbinding.getName().getNamespaceURI(), SPConstants.ENCRYPT_SIGNATURE)); } doEncryption(encryptionWrapper, encrParts); } if (timestampAdded) { SecurePart part = new SecurePart(new QName(WSSConstants.NS_WSU10, "Timestamp"), Modifier.Element); sigParts.add(part); } sigParts.addAll(this.getSignedParts()); if (!sigParts.isEmpty()) { AbstractTokenWrapper sigAbstractTokenWrapper = getSignatureToken(); if (sigAbstractTokenWrapper != null) { AbstractToken sigToken = sigAbstractTokenWrapper.getToken(); if (isRequestor()) { doSignature(sigAbstractTokenWrapper, sigToken, sigParts); } else { addSignatureConfirmation(sigParts); doSignature(sigAbstractTokenWrapper, sigToken, sigParts); } } } removeSignatureIfSignedSAML(); enforceEncryptBeforeSigningWithSignedSAML(); prependSignatureToSC(); putCustomTokenAfterSignature(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new Fault(ex); } } private void doSignBeforeEncrypt() { AbstractTokenWrapper sigAbstractTokenWrapper = getSignatureToken(); assertTokenWrapper(sigAbstractTokenWrapper); AbstractToken sigToken = sigAbstractTokenWrapper.getToken(); String sigTokId = null; try { SecurityToken sigTok = null; if (sigToken != null) { if (sigToken instanceof KerberosToken) { sigTok = getSecurityToken(); if (isRequestor()) { addKerberosToken((KerberosToken)sigToken, false, true, true); } } else if (sigToken instanceof IssuedToken) { sigTok = getSecurityToken(); addIssuedToken(sigToken, sigTok, false, true); if (sigTok == null && !isRequestor()) { org.apache.xml.security.stax.securityToken.SecurityToken securityToken = findInboundSecurityToken(WSSecurityEventConstants.SAML_TOKEN); sigTokId = WSS4JUtils.parseAndStoreStreamingSecurityToken(securityToken, message); } } else if (sigToken instanceof SecureConversationToken || sigToken instanceof SecurityContextToken || sigToken instanceof SpnegoContextToken) { sigTok = getSecurityToken(); if (sigTok != null && isRequestor()) { WSSSecurityProperties properties = getProperties(); WSSConstants.Action actionToPerform = WSSConstants.CUSTOM_TOKEN; properties.addAction(actionToPerform); } else if (sigTok == null && !isRequestor()) { org.apache.xml.security.stax.securityToken.SecurityToken securityToken = findInboundSecurityToken(WSSecurityEventConstants.SECURITY_CONTEXT_TOKEN); sigTokId = WSS4JUtils.parseAndStoreStreamingSecurityToken(securityToken, message); } } else if (sigToken instanceof X509Token) { if (isRequestor()) { sigTokId = setupEncryptedKey(); } else { org.apache.xml.security.stax.securityToken.SecurityToken securityToken = findEncryptedKeyToken(); sigTokId = WSS4JUtils.parseAndStoreStreamingSecurityToken(securityToken, message); } } else if (sigToken instanceof UsernameToken) { unassertPolicy(sbinding, "UsernameTokens not supported with Symmetric binding"); return; } assertToken(sigToken); } else { unassertPolicy(sbinding, "No signature token"); return; } if (sigTok == null && StringUtils.isEmpty(sigTokId)) { unassertPolicy(sigAbstractTokenWrapper, "No signature token id"); return; } if (sigTok == null) { sigTok = TokenStoreUtils.getTokenStore(message).getToken(sigTokId); } // Store key if (!(MessageUtils.isRequestor(message) && sigToken instanceof KerberosToken)) { storeSecurityToken(sigToken, sigTok); } // Add timestamp List<SecurePart> sigs = new ArrayList<>(); if (timestampAdded) { SecurePart part = new SecurePart(new QName(WSSConstants.NS_WSU10, "Timestamp"), Modifier.Element); sigs.add(part); } sigs.addAll(this.getSignedParts()); if (!isRequestor()) { addSignatureConfirmation(sigs); } if (!sigs.isEmpty()) { doSignature(sigAbstractTokenWrapper, sigToken, sigs); } addSupportingTokens(); removeSignatureIfSignedSAML(); prependSignatureToSC(); //Encryption List<SecurePart> enc = getEncryptedParts(); //Check for signature protection if (sbinding.isEncryptSignature()) { SecurePart part = new SecurePart(new QName(XMLSecurityConstants.NS_DSIG, "Signature"), Modifier.Element); enc.add(part); if (signatureConfirmationAdded) { part = new SecurePart(WSSConstants.TAG_WSSE11_SIG_CONF, Modifier.Element); enc.add(part); } assertPolicy( new QName(sbinding.getName().getNamespaceURI(), SPConstants.ENCRYPT_SIGNATURE)); } //Do encryption if (isRequestor()) { enc.addAll(encryptedTokensList); } AbstractTokenWrapper encrAbstractTokenWrapper = getEncryptionToken(); doEncryption(encrAbstractTokenWrapper, enc); putCustomTokenAfterSignature(); } catch (Exception e) { throw new Fault(e); } } private void doEncryption(AbstractTokenWrapper recToken, List<SecurePart> encrParts) throws SOAPException { //Do encryption if (recToken != null && recToken.getToken() != null) { AbstractToken encrToken = recToken.getToken(); AlgorithmSuite algorithmSuite = sbinding.getAlgorithmSuite(); // Action WSSSecurityProperties properties = getProperties(); WSSConstants.Action actionToPerform = XMLSecurityConstants.ENCRYPTION; if (recToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { actionToPerform = WSSConstants.ENCRYPTION_WITH_DERIVED_KEY; if (MessageUtils.isRequestor(message) && recToken.getToken() instanceof X509Token) { properties.setDerivedKeyTokenReference( WSSConstants.DerivedKeyTokenReference.EncryptedKey); } else { properties.setDerivedKeyTokenReference( WSSConstants.DerivedKeyTokenReference.DirectReference); } AlgorithmSuiteType algSuiteType = sbinding.getAlgorithmSuite().getAlgorithmSuiteType(); properties.setDerivedEncryptionKeyLength( algSuiteType.getEncryptionDerivedKeyLength() / 8); } if (recToken.getVersion() == SPConstants.SPVersion.SP12) { properties.setUse200512Namespace(true); } properties.getEncryptionSecureParts().addAll(encrParts); properties.addAction(actionToPerform); if (isRequestor()) { properties.setEncryptionKeyIdentifier(getKeyIdentifierType(encrToken)); properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } else if (recToken.getToken() instanceof KerberosToken && !isRequestor()) { properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_KERBEROS_SHA1_IDENTIFIER); properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_KERBEROS_SHA1_IDENTIFIER); if (recToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } } else if ((recToken.getToken() instanceof IssuedToken || recToken.getToken() instanceof SecureConversationToken || recToken.getToken() instanceof SpnegoContextToken) && !isRequestor()) { properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } else { properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_ENCRYPTED_KEY_SHA1_IDENTIFIER); if (recToken.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_ENCRYPTED_KEY_SHA1_IDENTIFIER); properties.setEncryptionKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); properties.setEncryptSymmetricEncryptionKey(false); } } // Find out do we also need to include the token as per the Inclusion requirement WSSecurityTokenConstants.KeyIdentifier keyIdentifier = properties.getEncryptionKeyIdentifier(); if (encrToken instanceof X509Token && isTokenRequired(encrToken.getIncludeTokenType()) && (WSSecurityTokenConstants.KeyIdentifier_IssuerSerial.equals(keyIdentifier) || WSSecurityTokenConstants.KEYIDENTIFIER_THUMBPRINT_IDENTIFIER.equals(keyIdentifier) || WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE.equals( keyIdentifier))) { properties.setIncludeEncryptionToken(true); } else { properties.setIncludeEncryptionToken(false); } properties.setEncryptionKeyTransportAlgorithm( algorithmSuite.getAlgorithmSuiteType().getAsymmetricKeyWrap()); properties.setEncryptionSymAlgorithm( algorithmSuite.getAlgorithmSuiteType().getEncryption()); properties.setEncryptionKeyTransportDigestAlgorithm( algorithmSuite.getAlgorithmSuiteType().getEncryptionDigest()); properties.setEncryptionKeyTransportMGFAlgorithm( algorithmSuite.getAlgorithmSuiteType().getMGFAlgo()); String encUser = (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENCRYPT_USERNAME, message); if (encUser == null) { encUser = (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.USERNAME, message); } if (encUser != null && properties.getEncryptionUser() == null) { properties.setEncryptionUser(encUser); } if (ConfigurationConstants.USE_REQ_SIG_CERT.equals(encUser)) { properties.setUseReqSigCertForEncryption(true); } if (encrToken instanceof KerberosToken || encrToken instanceof IssuedToken || encrToken instanceof SpnegoContextToken || encrToken instanceof SecurityContextToken) { properties.setEncryptSymmetricEncryptionKey(false); } } } private void doSignature(AbstractTokenWrapper wrapper, AbstractToken policyToken, List<SecurePart> sigParts) throws WSSecurityException, SOAPException { // Action WSSSecurityProperties properties = getProperties(); WSSConstants.Action actionToPerform = XMLSecurityConstants.SIGNATURE; if (wrapper.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { actionToPerform = WSSConstants.SIGNATURE_WITH_DERIVED_KEY; if (MessageUtils.isRequestor(message) && policyToken instanceof X509Token) { properties.setDerivedKeyTokenReference( WSSConstants.DerivedKeyTokenReference.EncryptedKey); } else { properties.setDerivedKeyTokenReference( WSSConstants.DerivedKeyTokenReference.DirectReference); } AlgorithmSuiteType algSuiteType = sbinding.getAlgorithmSuite().getAlgorithmSuiteType(); properties.setDerivedSignatureKeyLength( algSuiteType.getSignatureDerivedKeyLength() / 8); } if (policyToken.getVersion() == SPConstants.SPVersion.SP12) { properties.setUse200512Namespace(true); } List<WSSConstants.Action> actionList = properties.getActions(); // Add a Signature directly before Kerberos, otherwise just append it boolean actionAdded = false; for (int i = 0; i < actionList.size(); i++) { WSSConstants.Action action = actionList.get(i); if (action.equals(WSSConstants.KERBEROS_TOKEN)) { actionList.add(i, actionToPerform); actionAdded = true; break; } } if (!actionAdded) { actionList.add(actionToPerform); } properties.getSignatureSecureParts().addAll(sigParts); AbstractToken sigToken = wrapper.getToken(); if (sbinding.isProtectTokens() && sigToken instanceof X509Token && isRequestor()) { SecurePart securePart = new SecurePart(new QName(XMLSecurityConstants.NS_XMLENC, "EncryptedKey"), Modifier.Element); properties.addSignaturePart(securePart); } configureSignature(sigToken, false); if (policyToken instanceof X509Token) { properties.setIncludeSignatureToken(false); if (isRequestor()) { properties.setSignatureKeyIdentifier( WSSecurityTokenConstants.KeyIdentifier_EncryptedKey); } else { properties.setSignatureKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_ENCRYPTED_KEY_SHA1_IDENTIFIER); if (wrapper.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_ENCRYPTED_KEY_SHA1_IDENTIFIER); properties.setSignatureKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } } } else if (policyToken instanceof KerberosToken) { if (isRequestor()) { properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } else { if (wrapper.getToken().getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { properties.setSignatureKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } else { properties.setSignatureKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_KERBEROS_SHA1_IDENTIFIER); } properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_KERBEROS_SHA1_IDENTIFIER); } } else if (policyToken instanceof IssuedToken || policyToken instanceof SecurityContextToken || policyToken instanceof SpnegoContextToken) { if (!isRequestor()) { properties.setIncludeSignatureToken(false); } else { properties.setIncludeSignatureToken(true); } properties.setDerivedKeyKeyIdentifier( WSSecurityTokenConstants.KEYIDENTIFIER_SECURITY_TOKEN_DIRECT_REFERENCE); } if (sigToken.getDerivedKeys() == DerivedKeys.RequireDerivedKeys) { properties.setSignatureAlgorithm( sbinding.getAlgorithmSuite().getAlgorithmSuiteType().getSymmetricSignature()); } } private String setupEncryptedKey() throws WSSecurityException, TokenStoreException { Instant created = Instant.now(); Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L); SecurityToken tempTok = new SecurityToken(IDGenerator.generateID(null), created, expires); KeyGenerator keyGenerator = KeyUtils.getKeyGenerator(sbinding.getAlgorithmSuite().getAlgorithmSuiteType().getEncryption()); SecretKey symmetricKey = keyGenerator.generateKey(); tempTok.setKey(symmetricKey); tempTok.setSecret(symmetricKey.getEncoded()); TokenStoreUtils.getTokenStore(message).add(tempTok); return tempTok.getId(); } private org.apache.xml.security.stax.securityToken.SecurityToken findEncryptedKeyToken() throws XMLSecurityException { @SuppressWarnings("unchecked") final List<SecurityEvent> incomingEventList = (List<SecurityEvent>) message.getExchange().get(SecurityEvent.class.getName() + ".in"); if (incomingEventList != null) { for (SecurityEvent incomingEvent : incomingEventList) { if (WSSecurityEventConstants.ENCRYPTED_PART == incomingEvent.getSecurityEventType() || WSSecurityEventConstants.EncryptedElement == incomingEvent.getSecurityEventType()) { org.apache.xml.security.stax.securityToken.SecurityToken token = ((AbstractSecuredElementSecurityEvent)incomingEvent).getSecurityToken(); if (token != null && token.getKeyWrappingToken() != null && token.getKeyWrappingToken().getSecretKey() != null && token.getKeyWrappingToken().getSha1Identifier() != null) { return token.getKeyWrappingToken(); } else if (token != null && token.getSecretKey() != null && token.getSha1Identifier() != null) { return token; } } } // Fall back to a Signature in case there was no encrypted Element in the request for (SecurityEvent incomingEvent : incomingEventList) { if (WSSecurityEventConstants.SIGNED_PART == incomingEvent.getSecurityEventType() || WSSecurityEventConstants.SignedElement == incomingEvent.getSecurityEventType()) { org.apache.xml.security.stax.securityToken.SecurityToken token = ((AbstractSecuredElementSecurityEvent)incomingEvent).getSecurityToken(); if (token != null && token.getKeyWrappingToken() != null && token.getKeyWrappingToken().getSecretKey() != null && token.getKeyWrappingToken().getSha1Identifier() != null) { return token.getKeyWrappingToken(); } else if (token != null && token.getSecretKey() != null && token.getSha1Identifier() != null) { return token; } } } } return null; } }
47.720654
112
0.627195
0d749fc81081e8106e18369195fddc8b60ff667c
3,013
/* * Copyright 2020 Nextworks s.r.l. * * 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 it.nextworks.sdk; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import java.util.Objects; import java.util.StringJoiner; /** * Helper class to avoid having string in keys * * @author Marco Capitani <m.capitani AT nextworks.it> */ @Entity public class Metadata { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "metadata_key") private String key; @Column(name = "metadata_value", length = 10000) private String value; @ManyToOne private SdkFunction function; @ManyToOne private SdkService service; private Metadata() { // JPA only } public Metadata(String key, String value, SdkFunction function) { this.key = key; this.value = value; this.function = function; } public Metadata(String key, String value, SdkService service) { this.key = key; this.value = value; this.service = service; } public String getKey() { return key; } public String getValue() { return value; } @JsonIgnore public Long getId() { return id; } @JsonIgnore public SdkFunction getFunction() { return function; } @JsonIgnore public void setFunction(SdkFunction function) { this.function = function; } @JsonIgnore public SdkService getService() { return service; } @JsonIgnore public void setService(SdkService service) { this.service = service; } @Override public String toString() { return new StringJoiner(", ", Metadata.class.getSimpleName() + "[", "]") .add("key='" + key + "'") .add("value='" + value.split("\n")[0] + "'") .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Metadata)) return false; Metadata metadata = (Metadata) o; return Objects.equals(getKey(), metadata.getKey()) && Objects.equals(getValue(), metadata.getValue()); } @Override public int hashCode() { return Objects.hash(getKey(), getValue()); } }
24.696721
80
0.645204
76d7f23f309d476f8b23629acfe18a16bfb2b8f5
5,738
package net.minecraft.util.datafix.fixes; import com.google.common.collect.Maps; import com.mojang.datafixers.DataFix; import com.mojang.datafixers.DataFixUtils; import com.mojang.datafixers.TypeRewriteRule; import com.mojang.datafixers.schemas.Schema; import com.mojang.datafixers.types.Type; import com.mojang.datafixers.types.templates.TaggedChoice.TaggedChoiceType; import java.util.Map; public class EntityIdFix extends DataFix { private static final Map<String, String> ID_MAP = DataFixUtils.make(Maps.newHashMap(), (p_15465_) -> { p_15465_.put("AreaEffectCloud", "minecraft:area_effect_cloud"); p_15465_.put("ArmorStand", "minecraft:armor_stand"); p_15465_.put("Arrow", "minecraft:arrow"); p_15465_.put("Bat", "minecraft:bat"); p_15465_.put("Blaze", "minecraft:blaze"); p_15465_.put("Boat", "minecraft:boat"); p_15465_.put("CaveSpider", "minecraft:cave_spider"); p_15465_.put("Chicken", "minecraft:chicken"); p_15465_.put("Cow", "minecraft:cow"); p_15465_.put("Creeper", "minecraft:creeper"); p_15465_.put("Donkey", "minecraft:donkey"); p_15465_.put("DragonFireball", "minecraft:dragon_fireball"); p_15465_.put("ElderGuardian", "minecraft:elder_guardian"); p_15465_.put("EnderCrystal", "minecraft:ender_crystal"); p_15465_.put("EnderDragon", "minecraft:ender_dragon"); p_15465_.put("Enderman", "minecraft:enderman"); p_15465_.put("Endermite", "minecraft:endermite"); p_15465_.put("EyeOfEnderSignal", "minecraft:eye_of_ender_signal"); p_15465_.put("FallingSand", "minecraft:falling_block"); p_15465_.put("Fireball", "minecraft:fireball"); p_15465_.put("FireworksRocketEntity", "minecraft:fireworks_rocket"); p_15465_.put("Ghast", "minecraft:ghast"); p_15465_.put("Giant", "minecraft:giant"); p_15465_.put("Guardian", "minecraft:guardian"); p_15465_.put("Horse", "minecraft:horse"); p_15465_.put("Husk", "minecraft:husk"); p_15465_.put("Item", "minecraft:item"); p_15465_.put("ItemFrame", "minecraft:item_frame"); p_15465_.put("LavaSlime", "minecraft:magma_cube"); p_15465_.put("LeashKnot", "minecraft:leash_knot"); p_15465_.put("MinecartChest", "minecraft:chest_minecart"); p_15465_.put("MinecartCommandBlock", "minecraft:commandblock_minecart"); p_15465_.put("MinecartFurnace", "minecraft:furnace_minecart"); p_15465_.put("MinecartHopper", "minecraft:hopper_minecart"); p_15465_.put("MinecartRideable", "minecraft:minecart"); p_15465_.put("MinecartSpawner", "minecraft:spawner_minecart"); p_15465_.put("MinecartTNT", "minecraft:tnt_minecart"); p_15465_.put("Mule", "minecraft:mule"); p_15465_.put("MushroomCow", "minecraft:mooshroom"); p_15465_.put("Ozelot", "minecraft:ocelot"); p_15465_.put("Painting", "minecraft:painting"); p_15465_.put("Pig", "minecraft:pig"); p_15465_.put("PigZombie", "minecraft:zombie_pigman"); p_15465_.put("PolarBear", "minecraft:polar_bear"); p_15465_.put("PrimedTnt", "minecraft:tnt"); p_15465_.put("Rabbit", "minecraft:rabbit"); p_15465_.put("Sheep", "minecraft:sheep"); p_15465_.put("Shulker", "minecraft:shulker"); p_15465_.put("ShulkerBullet", "minecraft:shulker_bullet"); p_15465_.put("Silverfish", "minecraft:silverfish"); p_15465_.put("Skeleton", "minecraft:skeleton"); p_15465_.put("SkeletonHorse", "minecraft:skeleton_horse"); p_15465_.put("Slime", "minecraft:slime"); p_15465_.put("SmallFireball", "minecraft:small_fireball"); p_15465_.put("SnowMan", "minecraft:snowman"); p_15465_.put("Snowball", "minecraft:snowball"); p_15465_.put("SpectralArrow", "minecraft:spectral_arrow"); p_15465_.put("Spider", "minecraft:spider"); p_15465_.put("Squid", "minecraft:squid"); p_15465_.put("Stray", "minecraft:stray"); p_15465_.put("ThrownEgg", "minecraft:egg"); p_15465_.put("ThrownEnderpearl", "minecraft:ender_pearl"); p_15465_.put("ThrownExpBottle", "minecraft:xp_bottle"); p_15465_.put("ThrownPotion", "minecraft:potion"); p_15465_.put("Villager", "minecraft:villager"); p_15465_.put("VillagerGolem", "minecraft:villager_golem"); p_15465_.put("Witch", "minecraft:witch"); p_15465_.put("WitherBoss", "minecraft:wither"); p_15465_.put("WitherSkeleton", "minecraft:wither_skeleton"); p_15465_.put("WitherSkull", "minecraft:wither_skull"); p_15465_.put("Wolf", "minecraft:wolf"); p_15465_.put("XPOrb", "minecraft:xp_orb"); p_15465_.put("Zombie", "minecraft:zombie"); p_15465_.put("ZombieHorse", "minecraft:zombie_horse"); p_15465_.put("ZombieVillager", "minecraft:zombie_villager"); }); public EntityIdFix(Schema p_15456_, boolean p_15457_) { super(p_15456_, p_15457_); } public TypeRewriteRule makeRule() { TaggedChoiceType<String> taggedchoicetype = (TaggedChoiceType<String>)this.getInputSchema().findChoiceType(References.ENTITY); TaggedChoiceType<String> taggedchoicetype1 = (TaggedChoiceType<String>)this.getOutputSchema().findChoiceType(References.ENTITY); Type<?> type = this.getInputSchema().getType(References.ITEM_STACK); Type<?> type1 = this.getOutputSchema().getType(References.ITEM_STACK); return TypeRewriteRule.seq(this.convertUnchecked("item stack entity name hook converter", type, type1), this.fixTypeEverywhere("EntityIdFix", taggedchoicetype, taggedchoicetype1, (p_15461_) -> { return (p_145282_) -> { return p_145282_.mapFirst((p_145284_) -> { return ID_MAP.getOrDefault(p_145284_, p_145284_); }); }; })); } }
53.12963
200
0.696236
d19ace69ce74b79335ec7acafe4bad21efd9dd53
1,409
package com.multi.thread.guide.core.chapter9; import java.util.concurrent.Callable; import java.util.concurrent.Executor; /** * @author dongzonglei * @description * @date 2019-01-31 11:57 */ public abstract class AsyncTask<V> implements Runnable, Callable<V> { protected final Executor executor; public AsyncTask(Executor executor) { this.executor = executor; } public AsyncTask() { this(new Executor() { @Override public void execute(Runnable command) { command.run(); } }); } @Override public void run() { Exception exp = null; V r = null; try { r = call(); } catch (Exception e) { exp = e; } final V result = r; if (null == exp) { executor.execute(new Runnable() { @Override public void run() { onResult(result); } }); } else { final Exception exceptionCaught = exp; executor.execute(new Runnable() { @Override public void run() { onError(exceptionCaught); } }); } } protected abstract void onResult(V result); protected void onError(Exception e) { e.printStackTrace(); } }
22.725806
69
0.498935
8e2558299bc74baf23001b6a7645bd6284b0c825
1,123
/* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache 2 License for the specific language governing permissions and limitations under the License. */ package com.msopentech.thali.local.toronionproxy; import android.test.AndroidTestCase; import com.msopentech.thali.android.toronionproxy.AndroidOnionProxyManager; import com.msopentech.thali.toronionproxy.OnionProxyManager; public class TorOnionProxyTestCase extends AndroidTestCase { public OnionProxyManager getOnionProxyManager(String workingSubDirectoryName) { return new AndroidOnionProxyManager(getContext(), workingSubDirectoryName); } }
43.192308
119
0.813891
4a3efa1c32d29bb4fc3593693c44c6241b9184a0
1,176
package com.twu.biblioteca.requester; import com.twu.biblioteca.command.Command; public class Keypad { private Command listCommand; private Command checkoutCommand; private Command returnbackCommand; private Command stopCommand; private Command warnCommand; public void setListCommand(Command listCommand) { this.listCommand = listCommand; } public void setCheckoutCommand(Command checkoutCommand) { this.checkoutCommand = checkoutCommand; } public void setReturnbackCommand(Command returnbackCommand) { this.returnbackCommand = returnbackCommand; } public void setStopCommand(Command stopCommand) { this.stopCommand = stopCommand; } public void setWarnCommand(Command warnCommand) { this.warnCommand = warnCommand; } public void list() { listCommand.execute(); } public void checkout(Long id) { checkoutCommand.execute(); } public void returnback(Long id) { returnbackCommand.execute(); } public void stop() { stopCommand.execute(); } public void warn() { warnCommand.execute(); } }
22.615385
65
0.673469
b673a951056344a03181aafcb08c45756190933a
3,076
/* * Copyright (c) 2017 Nova Ordis LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.novaordis.jmx.tree; import io.novaordis.jmx.tree.nodes.JmxContainer; import io.novaordis.jmx.tree.nodes.JmxNode; import io.novaordis.jmx.tree.nodes.JmxRoot; import io.novaordis.utilities.UserErrorException; import javax.management.MBeanServerConnection; import java.io.IOException; /** * @author Ovidiu Feodorov <[email protected]> * @since 7/6/17 */ public class JmxTreeImpl implements JmxTree { // Constants ------------------------------------------------------------------------------------------------------- // Static ---------------------------------------------------------------------------------------------------------- // Attributes ------------------------------------------------------------------------------------------------------ private MBeanServerConnection c; private JmxNode current; // Constructors ---------------------------------------------------------------------------------------------------- // Public ---------------------------------------------------------------------------------------------------------- public JmxTreeImpl(MBeanServerConnection c) { this.c = c; current = new JmxRoot(this); } @Override public JmxNode getCurrent() throws IOException { return current; } @Override public void setCurrent(String location) throws IOException, UserErrorException { JmxNode c = getCurrent(); if (!(c instanceof JmxContainer)) { throw new IllegalStateException("the current node cannot be a non-container"); } JmxContainer cnt = (JmxContainer)c; JmxNode target = cnt.getRelative(location); if (!target.isContainer()) { throw new UserErrorException(target.getName() + ": not a location to be navigating into"); } this.current = target; } @Override public MBeanServerConnection getMBeanServerConnection() { return c; } // Package protected ----------------------------------------------------------------------------------------------- // Protected ------------------------------------------------------------------------------------------------------- // Private --------------------------------------------------------------------------------------------------------- // Inner classes --------------------------------------------------------------------------------------------------- }
31.387755
120
0.473667
61b73e9947d8d3f5c59da17e1707c968b52f0723
678
package cn.amap.service2.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /** * @author 狮少 * @version 1.0 * @date 2021/6/30 * @describtion TraceCtoller * @since 1.0 */ @Slf4j @RequestMapping @RestController public class TraceController { @PostMapping("/service2") public String service() { log.info("service2 开始执行"); log.info("service2 执行完毕"); return "service2"; } }
22.6
62
0.733038
fbc6d09b10d8fbd015a9c0f6f01ce760671a7954
1,043
package hr.from.ivantoplak.recipeappreactive.config; import hr.from.ivantoplak.recipeappreactive.domain.Recipe; import hr.from.ivantoplak.recipeappreactive.services.RecipeService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; @Configuration public class WebConfig { @Bean public RouterFunction<?> routes(RecipeService recipeService) { return RouterFunctions.route(GET("/api/recipes"), serverRequest -> ServerResponse .ok() .contentType(MediaType.APPLICATION_JSON) .body(recipeService.getRecipes(), Recipe.class)); } }
40.115385
85
0.756472
42c22957fb78cb497379efdcf0bd57c9d5950d38
3,003
package xyz.tostring.cloud.errands.common.dto; import lombok.Data; import java.io.Serializable; import java.util.List; @Data public class BaseResult implements Serializable { public static final String RESULT_OK = "ok"; public static final String RESULT_NOT_OK = "not_ok"; public static final String SUCCESS = "成功操作"; private String result; private Object data; private Cursor cursor; private String success; private List<Error> errors; public BaseResult ok() { return createBaseResult(RESULT_OK, null, null, SUCCESS, null); } public BaseResult ok(Object object) { return createBaseResult(RESULT_OK, object, null, SUCCESS, null); } public BaseResult notOk(List<BaseResult.Error> errors) { return createBaseResult(RESULT_NOT_OK, null, null, "", errors); } private static BaseResult createBaseResult(String result, Object data, Cursor cursor, String success, List<Error> errors) { BaseResult baseResult = new BaseResult(); baseResult.setResult(result); baseResult.setData(data); baseResult.setCursor(cursor); baseResult.setSuccess(success); baseResult.setErrors(errors); return baseResult; } @Data public static class Cursor { private int total; private int offset; private int limit; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } } @Data public static class Error { private String field; private String message; public String getField() { return field; } public void setField(String field) { this.field = field; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Cursor getCursor() { return cursor; } public void setCursor(Cursor cursor) { this.cursor = cursor; } public String getSuccess() { return success; } public void setSuccess(String success) { this.success = success; } public List<Error> getErrors() { return errors; } public void setErrors(List<Error> errors) { this.errors = errors; } }
21.919708
127
0.591409
0767331be6649a54bfc396e6d575df415e78269c
6,298
package com.mediatek.engineermode.hqanfc; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.mediatek.engineermode.Elog; import com.mediatek.engineermode.R; import com.mediatek.engineermode.hqanfc.NfcCommand.CommandType; import com.mediatek.engineermode.hqanfc.NfcCommand.EmAction; import com.mediatek.engineermode.hqanfc.NfcCommand.RspResult; import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmLoopbackReq; import com.mediatek.engineermode.hqanfc.NfcEmReqRsp.NfcEmLoopbackRsp; import java.nio.ByteBuffer; public class LoopBackTest extends Activity { private static final int HANDLER_MSG_GET_RSP = 200; private static final int DIALOG_ID_WAIT = 0; private Button mBtnStart; private Button mBtnReturn; private NfcEmLoopbackRsp mResponse; private byte[] mRspArray; private boolean mEnableBackKey = true; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Elog.v(NfcMainPage.TAG, "[LoopBackTest]mReceiver onReceive"); String action = intent.getAction(); if ((NfcCommand.ACTION_PRE + CommandType.MTK_EM_LOOPBACK_TEST_RSP) .equals(action)) { mRspArray = intent.getExtras().getByteArray(NfcCommand.MESSAGE_CONTENT_KEY); if (null != mRspArray) { ByteBuffer buffer = ByteBuffer.wrap(mRspArray); mResponse = new NfcEmLoopbackRsp(); mResponse.readRaw(buffer); mHandler.sendEmptyMessage(HANDLER_MSG_GET_RSP); } } else { Elog.v(NfcMainPage.TAG, "[LoopBackTest]Other response"); } } }; private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (HANDLER_MSG_GET_RSP == msg.what) { dismissDialog(DIALOG_ID_WAIT); String toastMsg = null; switch (mResponse.mResult) { case RspResult.SUCCESS: toastMsg = "LoopBackTest Rsp Result: SUCCESS"; if (mBtnStart.getText().equals( LoopBackTest.this.getString(R.string.hqa_nfc_start))) { setButtonsStatus(false); } else { setButtonsStatus(true); } break; case RspResult.FAIL: toastMsg = "LoopBackTest Rsp Result: FAIL"; break; default: toastMsg = "LoopBackTest Rsp Result: ERROR"; break; } Toast.makeText(LoopBackTest.this, toastMsg, Toast.LENGTH_SHORT).show(); } } }; private final Button.OnClickListener mClickListener = new Button.OnClickListener() { @Override public void onClick(View arg0) { Elog.v(NfcMainPage.TAG, "[LoopBackTest]onClick button view is " + ((Button) arg0).getText()); if (arg0.equals(mBtnStart)) { showDialog(DIALOG_ID_WAIT); doTestAction(mBtnStart.getText().equals( LoopBackTest.this.getString(R.string.hqa_nfc_start))); } else if (arg0.equals(mBtnReturn)) { LoopBackTest.this.onBackPressed(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hqa_nfc_loopback_test); mBtnStart = (Button) findViewById(R.id.hqa_loopback_btn_start_stop); mBtnStart.setOnClickListener(mClickListener); mBtnReturn = (Button) findViewById(R.id.hqa_loopback_btn_return); mBtnReturn.setOnClickListener(mClickListener); IntentFilter filter = new IntentFilter(); filter.addAction(NfcCommand.ACTION_PRE + CommandType.MTK_EM_LOOPBACK_TEST_RSP); registerReceiver(mReceiver, filter); } @Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } @Override public void onBackPressed() { if (!mEnableBackKey) { return; } super.onBackPressed(); } private void setButtonsStatus(boolean b) { Elog.v(NfcMainPage.TAG, "[LoopBackTest]setButtonsStatus " + b); if (b) { mBtnStart.setText(R.string.hqa_nfc_start); } else { mBtnStart.setText(R.string.hqa_nfc_stop); } mEnableBackKey = b; mBtnReturn.setEnabled(b); } private void doTestAction(Boolean bStart) { sendCommand(bStart); } private void sendCommand(Boolean bStart) { NfcEmLoopbackReq requestCmd = new NfcEmLoopbackReq(); fillRequest(bStart, requestCmd); NfcClient.getInstance().sendCommand(CommandType.MTK_EM_LOOPBACK_TEST_REQ, requestCmd); } private void fillRequest(Boolean bStart, NfcEmLoopbackReq requestCmd) { if (null == bStart) { requestCmd.mAction = EmAction.ACTION_RUNINBG; } else if (bStart.booleanValue()) { requestCmd.mAction = EmAction.ACTION_START; } else { requestCmd.mAction = EmAction.ACTION_STOP; } } @Override protected Dialog onCreateDialog(int id) { ProgressDialog dialog = null; if (id == DIALOG_ID_WAIT) { dialog = new ProgressDialog(this); dialog.setMessage(getString(R.string.hqa_nfc_dialog_wait_message)); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setCancelable(false); return dialog; } return dialog; } }
36.404624
92
0.616545
3db8aef58ee5930130763201b7111ec98b4de44e
2,173
package net.ozwolf.mongo.migrations; import net.ozwolf.mongo.migrations.exception.InvalidMigrationNameException; import org.apache.commons.lang.StringUtils; import org.jongo.Jongo; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <h1>Migration Command</h1> * * The command object all migrations should extend. Commands need to implement the `migrate` command. * * ## Naming Convention * * All migration commands should be named using the format V<version>__<description>. For example, `public class V1_0_0__MyFirstMigration...` * * ## Example Usage * * ```java * public class V2_1_0__AddUniqueEmailIndexToPersonCollection extends MigrationCommand { * {@literal @}Override * public void migrate(Jongo jongo){ * jongo.getCollection("person").ensureIndex("{email: 1}", "{unique: 1, name: 'email_idx'}"); * } * } * ``` */ public abstract class MigrationCommand { private final String version; private final String description; private final static Pattern NAME_PATTERN = Pattern.compile("V(?<version>.+)__(?<description>.+)"); protected MigrationCommand() { Matcher matcher = NAME_PATTERN.matcher(this.getClass().getSimpleName()); if (!matcher.matches()) throw new InvalidMigrationNameException(this.getClass(), NAME_PATTERN.pattern()); this.version = StringUtils.replace(matcher.group("version"), "_", "."); this.description = makeDescriptionFrom(matcher.group("description")); } public final String getVersion() { return version; } public final String getDescription() { return description; } public abstract void migrate(Jongo jongo); private static String makeDescriptionFrom(String value) { return StringUtils.capitalize( value.replaceAll( String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])" ), " " ).toLowerCase() ); } }
32.432836
142
0.610676
91af46977d40c1eb0b60f0bc143b90fe368caea4
5,500
package ${domain.namespace}.asset; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.DeleteObjectRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import lombok.extern.java.Log; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; import ${exceptionNamespace}.ServiceException; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; @Log @Service @ConditionalOnProperty(name = "app.asset.binaryPersistence", havingValue = "s3") public class S3Service implements BinaryPersistence { private AmazonS3 amazonS3; @Value("${$}{aws.s3.region:}") private String awsRegion; @Value("${$}{aws.s3.minioUrl:}") private String minioUrl; @Value("${$}{aws.s3.awsAccessKeyId:}") private String awsAccessKeyId; @Value("${$}{aws.s3.awsSecretAccessKey:}") private String awsSecretAccessKey; @Value("${$}{aws.cdn.hostname:}") private String awsCdnHostname; @PostConstruct private void initializeAmazon() { AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard(); boolean useMinio = StringUtils.isNotEmpty(minioUrl); if(useMinio){ builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(minioUrl, Regions.US_EAST_1.name())); ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.setSignerOverride("AWSS3V4SignerType"); builder.withClientConfiguration(clientConfiguration); builder.withPathStyleAccessEnabled(true); log.info(String.format("[S3Service] - using minio %s for S3 integration", minioUrl)); } else if (StringUtils.isNotEmpty(awsRegion)) { builder.withRegion(awsRegion); } if(StringUtils.isNotEmpty(awsAccessKeyId) && StringUtils.isNotEmpty(awsSecretAccessKey)) { builder.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey))); log.info("[S3Service] - using static credentials for S3 integration"); } this.amazonS3 = builder.build(); } @PreDestroy private void shutdownAmazonS3Client() { if (amazonS3 != null) { amazonS3.shutdown(); } } @Override public void save(String path, String filename, InputStream inputStream, Metadata metadata) throws ServiceException { final ObjectMetadata objectMetadata = new ObjectMetadata(); if (metadata.getContentLength() <= 0) { throw new IllegalArgumentException("Content length must be a positive number"); } objectMetadata.setContentLength(metadata.getContentLength()); if (metadata.getContentType() != null) { objectMetadata.setContentType(metadata.getContentType()); } if (metadata.getContentDisposition() != null) { objectMetadata.setContentDisposition(metadata.getContentDisposition()); } final PutObjectRequest putObjectRequest = new PutObjectRequest(path, filename, inputStream, objectMetadata); try { amazonS3.putObject(putObjectRequest); } catch (AmazonClientException e) { log.warning(String.format("S3 error saving file key %s into bucket %s", filename, path)); throw new ServiceException(String.format("S3 error saving file key %s into bucket %s", filename, path), e); } } @Override public void delete(String path, String filename) throws ServiceException { try { amazonS3.deleteObject(new DeleteObjectRequest(path, filename)); } catch (AmazonClientException e) { log.warning(String.format("S3 error deleting file key %s from bucket %s", filename, path)); throw new ServiceException(String.format("S3 error deleting file key %s from bucket %s", filename, path), e); } } @Override public String getUrl(String path, String filename) { try { URL url = amazonS3.getUrl(path,filename); if (awsCdnHostname != null) { url = new URL(url.getProtocol(), awsCdnHostname, url.getPort(), url.getFile()); } return url.toString(); } catch (AmazonServiceException ase) { log.warning(String.format("S3 error retrieving URL for asset key %s from bucket %s", filename, path)); } catch (AmazonClientException ace) { log.warning(String.format("S3 error retrieving URL for asset key %s from bucket %s", filename, path)); } catch (MalformedURLException mue) { log.warning(String.format("S3 error retrieving URL for asset key %s from bucket %s", filename, path)); } return null; } }
40.441176
131
0.696545
4de62d43c1cfe2ecbdd8b7877f7d167e9ab02d0a
1,872
package com.vk.api.sdk.queries.messages; import com.vk.api.sdk.client.AbstractQueryBuilder; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.GroupActor; import com.vk.api.sdk.objects.base.responses.OkResponse; import java.util.Arrays; import java.util.List; /** * Query for Messages.markAsImportantDialog method */ public class MessagesMarkAsImportantDialogQuery extends AbstractQueryBuilder<MessagesMarkAsImportantDialogQuery, OkResponse> { /** * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters * * @param client VK API client * @param actor actor with access token */ public MessagesMarkAsImportantDialogQuery(VkApiClient client, GroupActor actor, Integer peerId) { super(client, "messages.markAsImportantDialog", OkResponse.class); accessToken(actor.getAccessToken()); peerId(peerId); } /** * Dialog id * * @param value value of "peer_id" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ private MessagesMarkAsImportantDialogQuery peerId(Integer value) { return unsafeParam("peer_id", value); } /** * "true" - mark as important * "false" - remove mark * * @param value value of "important" parameter. Minimum is 0. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public MessagesMarkAsImportantDialogQuery important(Boolean value) { return unsafeParam("important", value); } @Override protected MessagesMarkAsImportantDialogQuery getThis() { return this; } @Override protected List<String> essentialKeys() { return Arrays.asList("peer_id", "access_token"); } }
32.275862
126
0.702457
1e4dd5cfc83943f4510d67ede90449898cb91a1a
9,196
package com.vondear.rxtools.activity; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.webkit.DownloadListener; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.vondear.rxtools.R; import com.vondear.rxtools.RxBarUtils; import com.vondear.rxtools.RxConstants; import com.vondear.rxtools.RxImageUtils; import com.vondear.rxtools.RxKeyboardUtils; import com.vondear.rxtools.view.RxTextAutoZoom; public class ActivityWebView extends ActivityBase { ProgressBar pbWebBase; TextView tvTitle; WebView webBase; ImageView ivFinish; RxTextAutoZoom mRxTextAutoZoom; LinearLayout llIncludeTitle; private String webPath = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RxBarUtils.setTransparentStatusBar(this); setContentView(R.layout.activity_webview); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); initView();// 初始化控件 - FindViewById之类的操作 initData();// 初始化控件的数据及监听事件 } private void initView() { // TODO Auto-generated method stub mRxTextAutoZoom = (RxTextAutoZoom) findViewById(R.id.afet_tv_title); llIncludeTitle = (LinearLayout) findViewById(R.id.ll_include_title); tvTitle = (TextView) findViewById(R.id.tv_title); pbWebBase = (ProgressBar) findViewById(R.id.pb_web_base); webBase = (WebView) findViewById(R.id.web_base); ivFinish = (ImageView) findViewById(R.id.iv_finish); ivFinish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (webBase.canGoBack()) { webBase.goBack(); } else { finish(); } } }); initAutoFitEditText(); } public void initAutoFitEditText() { mRxTextAutoZoom.clearFocus(); mRxTextAutoZoom.setEnabled(false); mRxTextAutoZoom.setFocusableInTouchMode(false); mRxTextAutoZoom.setFocusable(false); mRxTextAutoZoom.setEnableSizeCache(false); //might cause crash on some devices mRxTextAutoZoom.setMovementMethod(null); // can be added after layout inflation; mRxTextAutoZoom.setMaxHeight(RxImageUtils.dip2px(this,55f)); //don't forget to add min text size programmatically mRxTextAutoZoom.setMinTextSize(37f); RxTextAutoZoom.setNormalization(this, llIncludeTitle, mRxTextAutoZoom); RxKeyboardUtils.hideSoftInput(this); } private void initData() { pbWebBase.setMax(100);//设置加载进度最大值 // webPath = getIntent().getStringExtra("URL"); webPath = RxConstants.URL_BAIDU_SEARCH;//加载的URL if (webPath.equals("")) { webPath = "http://www.baidu.com"; } WebSettings webSettings = webBase.getSettings(); if (Build.VERSION.SDK_INT >= 19) { webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//加载缓存否则网络 } if (Build.VERSION.SDK_INT >= 19) { webSettings.setLoadsImagesAutomatically(true);//图片自动缩放 打开 } else { webSettings.setLoadsImagesAutomatically(false);//图片自动缩放 关闭 } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webBase.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码 } webBase.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码 // webSettings.setAllowContentAccess(true); // webSettings.setAllowFileAccessFromFileURLs(true); // webSettings.setAppCacheEnabled(true); /* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); }*/ // setMediaPlaybackRequiresUserGesture(boolean require) //是否需要用户手势来播放Media,默认true webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本 // webSettings.setPluginState(WebSettings.PluginState.ON); webSettings.setSupportZoom(true);// 设置可以支持缩放 webSettings.setBuiltInZoomControls(true);// 设置出现缩放工具 是否使用WebView内置的缩放组件,由浮动在窗口上的缩放控制和手势缩放控制组成,默认false webSettings.setDisplayZoomControls(false);//隐藏缩放工具 webSettings.setUseWideViewPort(true);// 扩大比例的缩放 webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕 webSettings.setLoadWithOverviewMode(true); webSettings.setDatabaseEnabled(true);// webSettings.setSavePassword(true);//保存密码 webSettings.setDomStorageEnabled(true);//是否开启本地DOM存储 鉴于它的安全特性(任何人都能读取到它,尽管有相应的限制,将敏感数据存储在这里依然不是明智之举),Android 默认是关闭该功能的。 webBase.setSaveEnabled(true); webBase.setKeepScreenOn(true); // 设置setWebChromeClient对象 webBase.setWebChromeClient(new WebChromeClient() { @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); mRxTextAutoZoom.setText(title); } @Override public void onProgressChanged(WebView view, int newProgress) { // TODO Auto-generated method stub pbWebBase.setProgress(newProgress); super.onProgressChanged(view, newProgress); } }); //设置此方法可在WebView中打开链接,反之用浏览器打开 webBase.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (!webBase.getSettings().getLoadsImagesAutomatically()) { webBase.getSettings().setLoadsImagesAutomatically(true); } pbWebBase.setVisibility(View.GONE); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub pbWebBase.setVisibility(View.VISIBLE); super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("http:") || url.startsWith("https:")) { view.loadUrl(url); return false; } // Otherwise allow the OS to handle things like tel, mailto, etc. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }); webBase.setDownloadListener(new DownloadListener() { public void onDownloadStart(String paramAnonymousString1, String paramAnonymousString2, String paramAnonymousString3, String paramAnonymousString4, long paramAnonymousLong) { Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(Uri.parse(paramAnonymousString1)); startActivity(intent); } }); webBase.loadUrl(webPath); Log.v("帮助类完整连接", webPath); // webBase.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,webBase.getHeight())); } protected void onSaveInstanceState(Bundle paramBundle) { super.onSaveInstanceState(paramBundle); paramBundle.putString("url", webBase.getUrl()); } public void onConfigurationChanged(Configuration newConfig) { try { super.onConfigurationChanged(newConfig); if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.v("Himi", "onConfigurationChanged_ORIENTATION_LANDSCAPE"); } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { Log.v("Himi", "onConfigurationChanged_ORIENTATION_PORTRAIT"); } } catch (Exception ex) { } } private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses. private long mBackPressed; @Override public void onBackPressed() { if (webBase.canGoBack()) { webBase.goBack(); } else { if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) { super.onBackPressed(); return; } else { Toast.makeText(getBaseContext(), "再次点击返回键退出", Toast.LENGTH_SHORT).show(); } mBackPressed = System.currentTimeMillis(); } } }
37.382114
186
0.653545
f2e95ab75b955daad4b974247bed17cbdb32e4d2
1,079
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package persistencia; import classesDados.Professor; /** * * @author M */ public class OrdenarPorEscolaNome extends ProfessorPersistenciaTemplateMethod { public OrdenarPorEscolaNome(String nomeDoArquivo) { super(nomeDoArquivo); } @Override public boolean ePrimeiro(Professor professor1, Professor professor2) { /* int saida = professor1.getEscola().compareToIgnoreCase(professor2.getEscola()); saida = (saida == 0) ? professor1.getNome().compareToIgnoreCase(professor2.getNome()) : saida; return(saida <= 0); */ if (professor1.getEscola().compareToIgnoreCase(professor2.getEscola()) == 0 && (professor1.getNome().compareToIgnoreCase(professor2.getNome()) < 0)) { return true; } return professor1.getEscola().compareToIgnoreCase(professor2.getEscola()) < 0; } }
30.828571
102
0.674699
0f08c0a400183f734e6b5905b2c77a8f70fc552d
203
package artrointel.designpattern.creational.factory_method; public class NewyorkPizzaStore extends PizzaStore { @Override public Pizza createPizza() { return new NewyorkPizza(); } }
22.555556
59
0.738916
55611111a653dc2d7dc5514c5cf71340bc29297b
3,874
/* * <p>Copyright (c) 2016, Authors</p> * * <p>Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at</p> * * <p>http://www.apache.org/licenses/LICENSE-2.0</p> * * <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.</p> */ package pl.hycom.jira.plugins.gitlab.integration.gitpanel; import com.atlassian.jira.issue.tabpanels.GenericMessageAction; import com.atlassian.jira.permission.ProjectPermissions; import com.atlassian.jira.plugin.issuetabpanel.*; import com.atlassian.jira.project.Project; import com.atlassian.jira.security.PermissionManager; import com.atlassian.jira.user.ApplicationUser; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j; import org.springframework.stereotype.Controller; import pl.hycom.jira.plugins.gitlab.integration.model.Commit; import pl.hycom.jira.plugins.gitlab.integration.service.impl.CommitService; import javax.inject.Inject; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @Log4j @Controller @RequiredArgsConstructor(onConstructor = @__(@Inject)) //Inject all final variables. public class GitTabPanel extends AbstractIssueTabPanel2 { private IssueTabPanelModuleDescriptor descriptor; private final CommitService commitService; private final PermissionManager permissionManager; private final ActionFactory actionFactory; @Override public ShowPanelReply showPanel(ShowPanelRequest showPanelRequest) { try { final Project project = showPanelRequest.issue().getProjectObject(); final ApplicationUser user = showPanelRequest.remoteUser(); final boolean hasPermission = permissionManager.hasPermission(ProjectPermissions.WORK_ON_ISSUES, project, user); log.debug("User: " + (user != null ? user.getUsername() : null) + " requested to see git panel for project: " + project.getKey() + ", issue: " + showPanelRequest.issue().getKey() + ". Displaying panel? " + hasPermission); return ShowPanelReply.create(hasPermission); } catch (Exception e) { log.error("Exception occurred while trying to determine if panel should be seen, with message: " + e.getMessage(), e); return ShowPanelReply.create(Boolean.FALSE); } } @Override public GetActionsReply getActions(GetActionsRequest getActionsRequest) { try { List<Commit> commitsListForIssue = commitService.getAllIssueCommits(getActionsRequest.issue()); log.info("Returning actions for commits: " + commitsListForIssue); final List<IssueAction> actions = createActionList(commitsListForIssue); if (actions.isEmpty()) { actions.add(new GenericMessageAction("There are no commits for this issue, yet. Maybe you should add some?")); } return GetActionsReply.create(actions); } catch (IOException e) { log.info("There was an error while trying to get commits for issue: " + getActionsRequest.issue(), e); } return GetActionsReply.create(Collections.singletonList(new GenericMessageAction("There was an error processing commits for this issue. Please consult your administrator"))); } private List<IssueAction> createActionList(List<Commit> commitsListForIssue) { return commitsListForIssue.stream().map(actionFactory::createAction).collect(Collectors.toList()); } }
46.119048
182
0.72509
32c26c62d71bfb9c1b887ee573bfcca4a96b9906
1,329
/** * Copyright 2020 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.maxgraph.groot.store; import com.alibaba.maxgraph.common.RoleType; import com.alibaba.maxgraph.groot.common.rpc.ChannelManager; import com.alibaba.maxgraph.groot.common.rpc.RoleClients; import java.util.List; public class DefaultSnapshotCommitter extends RoleClients<SnapshotCommitClient> implements SnapshotCommitter { public DefaultSnapshotCommitter(ChannelManager channelManager) { super(channelManager, RoleType.COORDINATOR, SnapshotCommitClient::new); } @Override public void commitSnapshotId(int storeId, long snapshotId, long ddlSnapshotId, List<Long> offsets) { getClient(0).commitSnapshotId(storeId, snapshotId, ddlSnapshotId, offsets); } }
37.971429
110
0.766742
c4b357499f08cc6929622e2fd428edafe4249e87
13,938
/** * Copyright (C) 2016 - present McLeod Moores Software Limited. All rights reserved. */ package com.mcleodmoores.starling.client.portfolio.fpml5_8; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.joda.beans.Bean; import org.joda.beans.BeanDefinition; import org.joda.beans.ImmutableBean; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectFieldsBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.threeten.bp.LocalTime; import org.threeten.bp.ZoneId; /** * An object containing information to source FX spot rates containing the data source, the fixing time and the business centre time zone. */ @BeanDefinition public class FxSpotRateSource implements ImmutableBean { /** * The rate source. */ @PropertyDefinition(validate = "notNull") private final PrimaryRateSource _primaryRateSource; /** * The fixing time. */ @PropertyDefinition(validate = "notNull") private final LocalTime _fixingTime; /** * The fixing business center time zone. */ @PropertyDefinition(validate = "notNull") private final ZoneId _businessCenterZone; //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code FxSpotRateSource}. * @return the meta-bean, not null */ public static FxSpotRateSource.Meta meta() { return FxSpotRateSource.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(FxSpotRateSource.Meta.INSTANCE); } /** * Returns a builder used to create an instance of the bean. * @return the builder, not null */ public static FxSpotRateSource.Builder builder() { return new FxSpotRateSource.Builder(); } /** * Restricted constructor. * @param builder the builder to copy from, not null */ protected FxSpotRateSource(FxSpotRateSource.Builder builder) { JodaBeanUtils.notNull(builder._primaryRateSource, "primaryRateSource"); JodaBeanUtils.notNull(builder._fixingTime, "fixingTime"); JodaBeanUtils.notNull(builder._businessCenterZone, "businessCenterZone"); this._primaryRateSource = builder._primaryRateSource; this._fixingTime = builder._fixingTime; this._businessCenterZone = builder._businessCenterZone; } @Override public FxSpotRateSource.Meta metaBean() { return FxSpotRateSource.Meta.INSTANCE; } @Override public <R> Property<R> property(String propertyName) { return metaBean().<R>metaProperty(propertyName).createProperty(this); } @Override public Set<String> propertyNames() { return metaBean().metaPropertyMap().keySet(); } //----------------------------------------------------------------------- /** * Gets the rate source. * @return the value of the property, not null */ public PrimaryRateSource getPrimaryRateSource() { return _primaryRateSource; } //----------------------------------------------------------------------- /** * Gets the fixing time. * @return the value of the property, not null */ public LocalTime getFixingTime() { return _fixingTime; } //----------------------------------------------------------------------- /** * Gets the fixing business center time zone. * @return the value of the property, not null */ public ZoneId getBusinessCenterZone() { return _businessCenterZone; } //----------------------------------------------------------------------- /** * Returns a builder that allows this bean to be mutated. * @return the mutable builder, not null */ public Builder toBuilder() { return new Builder(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { FxSpotRateSource other = (FxSpotRateSource) obj; return JodaBeanUtils.equal(getPrimaryRateSource(), other.getPrimaryRateSource()) && JodaBeanUtils.equal(getFixingTime(), other.getFixingTime()) && JodaBeanUtils.equal(getBusinessCenterZone(), other.getBusinessCenterZone()); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(getPrimaryRateSource()); hash = hash * 31 + JodaBeanUtils.hashCode(getFixingTime()); hash = hash * 31 + JodaBeanUtils.hashCode(getBusinessCenterZone()); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("FxSpotRateSource{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("primaryRateSource").append('=').append(JodaBeanUtils.toString(getPrimaryRateSource())).append(',').append(' '); buf.append("fixingTime").append('=').append(JodaBeanUtils.toString(getFixingTime())).append(',').append(' '); buf.append("businessCenterZone").append('=').append(JodaBeanUtils.toString(getBusinessCenterZone())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code FxSpotRateSource}. */ public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code primaryRateSource} property. */ private final MetaProperty<PrimaryRateSource> _primaryRateSource = DirectMetaProperty.ofImmutable( this, "primaryRateSource", FxSpotRateSource.class, PrimaryRateSource.class); /** * The meta-property for the {@code fixingTime} property. */ private final MetaProperty<LocalTime> _fixingTime = DirectMetaProperty.ofImmutable( this, "fixingTime", FxSpotRateSource.class, LocalTime.class); /** * The meta-property for the {@code businessCenterZone} property. */ private final MetaProperty<ZoneId> _businessCenterZone = DirectMetaProperty.ofImmutable( this, "businessCenterZone", FxSpotRateSource.class, ZoneId.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "primaryRateSource", "fixingTime", "businessCenterZone"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -489404227: // primaryRateSource return _primaryRateSource; case 1255686170: // fixingTime return _fixingTime; case -2019615359: // businessCenterZone return _businessCenterZone; } return super.metaPropertyGet(propertyName); } @Override public FxSpotRateSource.Builder builder() { return new FxSpotRateSource.Builder(); } @Override public Class<? extends FxSpotRateSource> beanType() { return FxSpotRateSource.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code primaryRateSource} property. * @return the meta-property, not null */ public final MetaProperty<PrimaryRateSource> primaryRateSource() { return _primaryRateSource; } /** * The meta-property for the {@code fixingTime} property. * @return the meta-property, not null */ public final MetaProperty<LocalTime> fixingTime() { return _fixingTime; } /** * The meta-property for the {@code businessCenterZone} property. * @return the meta-property, not null */ public final MetaProperty<ZoneId> businessCenterZone() { return _businessCenterZone; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -489404227: // primaryRateSource return ((FxSpotRateSource) bean).getPrimaryRateSource(); case 1255686170: // fixingTime return ((FxSpotRateSource) bean).getFixingTime(); case -2019615359: // businessCenterZone return ((FxSpotRateSource) bean).getBusinessCenterZone(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { metaProperty(propertyName); if (quiet) { return; } throw new UnsupportedOperationException("Property cannot be written: " + propertyName); } } //----------------------------------------------------------------------- /** * The bean-builder for {@code FxSpotRateSource}. */ public static class Builder extends DirectFieldsBeanBuilder<FxSpotRateSource> { private PrimaryRateSource _primaryRateSource; private LocalTime _fixingTime; private ZoneId _businessCenterZone; /** * Restricted constructor. */ protected Builder() { } /** * Restricted copy constructor. * @param beanToCopy the bean to copy from, not null */ protected Builder(FxSpotRateSource beanToCopy) { this._primaryRateSource = beanToCopy.getPrimaryRateSource(); this._fixingTime = beanToCopy.getFixingTime(); this._businessCenterZone = beanToCopy.getBusinessCenterZone(); } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { switch (propertyName.hashCode()) { case -489404227: // primaryRateSource return _primaryRateSource; case 1255686170: // fixingTime return _fixingTime; case -2019615359: // businessCenterZone return _businessCenterZone; default: throw new NoSuchElementException("Unknown property: " + propertyName); } } @Override public Builder set(String propertyName, Object newValue) { switch (propertyName.hashCode()) { case -489404227: // primaryRateSource this._primaryRateSource = (PrimaryRateSource) newValue; break; case 1255686170: // fixingTime this._fixingTime = (LocalTime) newValue; break; case -2019615359: // businessCenterZone this._businessCenterZone = (ZoneId) newValue; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public Builder set(MetaProperty<?> property, Object value) { super.set(property, value); return this; } @Override public Builder setString(String propertyName, String value) { setString(meta().metaProperty(propertyName), value); return this; } @Override public Builder setString(MetaProperty<?> property, String value) { super.setString(property, value); return this; } @Override public Builder setAll(Map<String, ? extends Object> propertyValueMap) { super.setAll(propertyValueMap); return this; } @Override public FxSpotRateSource build() { return new FxSpotRateSource(this); } //----------------------------------------------------------------------- /** * Sets the rate source. * @param primaryRateSource the new value, not null * @return this, for chaining, not null */ public Builder primaryRateSource(PrimaryRateSource primaryRateSource) { JodaBeanUtils.notNull(primaryRateSource, "primaryRateSource"); this._primaryRateSource = primaryRateSource; return this; } /** * Sets the fixing time. * @param fixingTime the new value, not null * @return this, for chaining, not null */ public Builder fixingTime(LocalTime fixingTime) { JodaBeanUtils.notNull(fixingTime, "fixingTime"); this._fixingTime = fixingTime; return this; } /** * Sets the fixing business center time zone. * @param businessCenterZone the new value, not null * @return this, for chaining, not null */ public Builder businessCenterZone(ZoneId businessCenterZone) { JodaBeanUtils.notNull(businessCenterZone, "businessCenterZone"); this._businessCenterZone = businessCenterZone; return this; } //----------------------------------------------------------------------- @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("FxSpotRateSource.Builder{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("primaryRateSource").append('=').append(JodaBeanUtils.toString(_primaryRateSource)).append(',').append(' '); buf.append("fixingTime").append('=').append(JodaBeanUtils.toString(_fixingTime)).append(',').append(' '); buf.append("businessCenterZone").append('=').append(JodaBeanUtils.toString(_businessCenterZone)).append(',').append(' '); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
31.605442
138
0.628426
e3c1090e0821eef2833ada71dc753a11b4ef8c4e
1,936
package com.crowsofwar.avatar.common; import com.crowsofwar.avatar.AvatarInfo; import com.crowsofwar.avatar.common.analytics.AnalyticEvents; import com.crowsofwar.avatar.common.analytics.AvatarAnalytics; import com.crowsofwar.avatar.common.data.Bender; import com.crowsofwar.avatar.common.entity.mob.EntityBender; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.DamageSource; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; /** * @author CrowsOfWar */ @Mod.EventBusSubscriber(modid = AvatarInfo.MOD_ID) public class AvatarPlayerDeath { @SubscribeEvent public static void onPlayerDeath(LivingDeathEvent e) { EntityLivingBase died = e.getEntityLiving(); if (died instanceof EntityPlayer) { Bender bender = Bender.get(died); //noinspection ConstantConditions bender.onDeath(); sendDeathAnalytic(e); } } /** * Possibly sends analytics for the player being killed by PvP or Av2 entity. */ private static void sendDeathAnalytic(LivingDeathEvent e) { if (!e.getEntity().world.isRemote) { DamageSource source = e.getSource(); Entity causeEntity = source.getTrueSource(); if (causeEntity instanceof EntityPlayer) { if (AvatarDamageSource.isAvatarDamageSource(source)) { // Chop off initial "avatar_" from the damage source name String dsName = source.getDamageType().substring("avatar_".length()); AvatarAnalytics.INSTANCE.pushEvent(AnalyticEvents.onPvpKillWithAbility(dsName)); } } if (causeEntity instanceof EntityBender) { String mobName = EntityList.getEntityString(causeEntity); AvatarAnalytics.INSTANCE.pushEvent(AnalyticEvents.onPlayerDeathWithMob(mobName)); } } } }
29.333333
85
0.775826
e0750c028e7a04c9a34cf4f960dc096807b26d11
4,946
class nkBHD3UuA { public static void Q1JGf3A2YiwFz (String[] YkFGH6QAuSy_XB) throws D2au7 { void mizy6IPc9; return; !yGO_NcDyGOS1u().ydmsTjx(); return -null.NzeU2MuJ1PYN; int PNuzv = !new Oxr9KI382bn[ ( -95026.ZEkM()).aV2SWnoJZgkPC].zXKx() = !-033087788.QQUQE(); while ( null.lfHY6d()) -!Sy4JURkKr0u5().hs8pfO7UNtc(); DZ07 YZ31sd; S[][][][][][] BXRS; _I4XLnltHZS[] i1Y; if ( -061.lfsCVK2bd2) true[ null.SuBMktpxK80]; GLFBK_ExBy Hnzl9fxrkmy; void[] gfQH3T; boolean Bc3h7xQehk; void IHVZrrdLmQ = -8.fryExPipo523CB(); boolean[][] lVtN89Ocx2d = new void[ true.jtfVU7()].L_qwuzu; void nVFXh = ( !i[ -SoNGvQBUew7F7.nn7zx()])[ ( !!!new boolean[ !-null[ !-!!BC3ToK6YTOl()[ 0.chq]]].foS7wJXXqYvev).JA]; return; boolean xBRU9i5Zg; ; b67[] U4P8wktGfts981; } public static void pUAlni95gPG (String[] h04Fg) { boolean[] JCp = -( -!true.wOR).k7Y15kmXb8t = ( -new boolean[ new kUa2[ new int[ true.a()].YRwDAWR7uad_6()].linGw].H0l).FTfDY4wLJ(); return; -!-true.nYY(); boolean _uFCn3qLYvpY = null.nC = -new klAj9NCeA().rPqmwYDvGM(); return !!!-new Wb0NotpofH().yVe0yFQ_1sj2g; boolean ggBd4AvoVXJj4O = -!null.tBf() = null.p4Kat; boolean fgy; void[][] b4Lo_TeDt; int PwW4; ; boolean[][] PX; int bFhLWUl2R; void[] DsoX; ; void[][] klvJ = a9GG.fF; void bO = false.IoRM9 = 49[ !this.NDORv6nxy()]; boolean yhINSVDo9y = -( -true.PXTw).k6n_9d_I16Bc(); while ( !new boolean[ R().h5xFzG()].f()) { cw_YKfu1ms W01rwdpbHL1G4u; } } } class _Y { } class QOUreTO8Z4B { public boolean[] nFJ; public boolean[] l5gcS; public static void gesor55VhP (String[] tzpGgQCY6) throws g_nApB { GVpJ WByOqqC2o; int Dlq2TV; int[] BFhH1; int[] fwyz_xfL = new P()[ --( this.xrTBHvbe).f6V3wZAJ()]; { boolean V7; int rUeB7; return; void[][][][][][] qzNdXuU; int q0qO; return; } return; return; ipR63q[] OI = !true[ new void[ true.a6].cW0FvWX3] = !new pr9svqPXMBQUR()[ !( -false.Dz3MiX0aN7a()).o30RUjyZhKaCk]; --this.rI; boolean[][][] uBOhayQ = ---this[ null.jRptELj] = false.i2yaHAsg1OVxok(); boolean[][][] ukHYdm07IO4drc; } public boolean[] cOPNVld7xUUuE (int Soa, void[] XCSS2YwO, iWTopeVcxEqX IO2l3ZtNXwB) throws U5Hlxposjp { beHXHKc6x[][] aAFL7o1 = this.PnyFR = false.K3dVKC(); return !--this.M6K44(); return null.jQop9MHYITF8(); int uQOBwL1n; L[][][][][] MHG3AvZxTpr9l7 = !--this.jgO; int[][] BTWF1UWChTB5Y2; UF j; if ( new tKfh[ !new boolean[ -----!!P6JQ()[ 9921.VHLYON0_F]].eJNa6g()].yX()) if ( !true.mlH) if ( 3654260.gfVViCx5eSOHY4) false.DJKqWBpqzw4J; } } class bwWKGakByN79mr { public static void W0DMaW07 (String[] Bzi) { ; RTaXSc8rR xDGAYAhgs1j3HS; } public static void C4vu (String[] RzGWcoc) { o9O5tMjjD kGzrXzb3bS893u = !!!new mHbxcTGQzvJ1k()[ this.tiouF_fm]; return 6167186.VMORx(); while ( -VdAa_g().ZQK7wFXm) 601591107[ this[ -false.i]]; ; !-!--Z5wB.K233v5XcrR(); boolean[] Rwf84r7; while ( !null.q3_Y2c1()) { int RRWeJ10TFif2; } int sR = !!!( 321823051.HAnDYYrbh8m).OvwE = new void[ ( -null.YW()).Z0u()].DJiAMCgM6sznT(); rg Seul = this.OSjR = -new C1Zg2y().v9zqC_RUzilV9(); return -vIykIGbGTm7.h5CsFehy(); RCjD YZJk1; if ( --KYxyrALwEPxMhB.roNEWEnv_RLIm8()) { { boolean[] KPFS3q9; } } ; if ( new void[ -new FeGdQCD4QE0nN()[ -!dodz5vcLrlB.vEPWYCXwQ0SHML()]].E8W) while ( !( --null.UIzwouiMW())[ new void[ !false._()].c8cVSz]) { void o5_tMss9; }else ; int[] mnFBDwZ0TFgR1D; return !--true.AIPHBEfpbMcV8x; boolean icborFw = WQ[ -TC()[ -new Ru()[ true._()]]]; } public static void Kn0vJq (String[] vPDF7vf) throws BZTrs { void[] AYlibE2 = new zs3MXd37Hz[ !false.pVup()].v1g = 9.ZSdFBkhY(); return hzv2NgI[ -2013[ new Sumn().Qa]]; ; ; boolean FrKFqDp; void kXrs1ItM4c0D = this[ 464634758[ l9V9rnh().LXEdWsbKqRcz()]] = !!22847.O; boolean cXU; ; return; BLw2KhiiJ SFcY9UZQT = this.cf3zQC(); true.Y5UIMPTuxh_(); ; if ( !this.vXVGMGmEzQGZ) { if ( -!false.Yd) if ( -!( uRARDbjW.X4tf4Kd())[ new WXYk_m39_().EsTs1]) { return; } } while ( !false[ new boolean[ --this[ 48.U2A__os]].bX_xuJPxZV()]) ; } } class tZsY { }
34.347222
150
0.534169
5d2fe0a9805842997ed2b56f08a33cbcdf0242b0
264
package network.warzone.warzoneapi.models; import lombok.AllArgsConstructor; /** * Created by Jorge on 11/01/2019 */ @AllArgsConstructor public class PlayerTagsUpdateRequest { private String tag; public enum Action { ADD, REMOVE, SET } }
15.529412
42
0.708333
ec75e03852b4a2bda53795adaee6a0439bcb9f7b
207
package org.tron.core.exception; public class ZksnarkException extends TronException { public ZksnarkException() { super(); } public ZksnarkException(String message) { super(message); } }
15.923077
53
0.714976
a15d7fb28c04d6b270f408b652fb40da797cfa5c
2,594
/******************************************************************************* * Copyright 2016 Antoine Nicolas SAMAHA * * 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.foc.business.workflow.implementation.join; import com.foc.desc.FocDesc; import com.foc.desc.field.FField; import com.foc.list.filter.FilterDesc; import com.foc.list.filter.FocDescForFilter; import com.foc.property.validators.UniquePropertyValidator; public abstract class WFLogJoinFilterDesc extends FocDescForFilter { protected abstract WFLogJoinDesc getLogJoinDesc(); public static final int FLD_VIEW_NAME = 1000; public static final String COND_PROCESSED = "PROCESSED"; public WFLogJoinFilterDesc(WFLogJoinDesc logJoinDesc){ super(WFLogJoinFilter.class, FocDesc.DB_RESIDENT, logJoinDesc.getStorageName()+"_FILTER", true); FField nameFld = getFieldByID(FField.FLD_NAME); if(nameFld != null){ nameFld.setSize(50); nameFld.setMandatory(true); nameFld.setPropertyValidator(new UniquePropertyValidator()); } } @Override public FilterDesc getFilterDesc(){ if(filterDesc == null){ filterDesc = new FilterDesc(getLogJoinDesc()); // DateCondition startDateCondition = new DateCondition(FFieldPath.newFieldPath(GenInspJoinDesc.SHIFT_INSPECTION+GenInspectionDesc.FLD_START_DATE), COND_START_DATE); // filterDesc.addCondition(startDateCondition); // // DateCondition endDateCondition = new DateCondition(FFieldPath.newFieldPath(GenInspJoinDesc.SHIFT_INSPECTION+GenInspectionDesc.FLD_END_DATE), COND_END_DATE); // filterDesc.addCondition(endDateCondition); // // BooleanCondition processedCondition = new BooleanCondition(FFieldPath.newFieldPath(GenInspJoinDesc.SHIFT_INSPECTION+GenInspectionDesc.FLD_PROCESSED), COND_PROCESSED); // filterDesc.addCondition(processedCondition); filterDesc.setNbrOfGuiColumns(1); } return filterDesc; } }
41.174603
175
0.700848
7ba46a39be6a462f454c66865ec59be0a5f6badf
1,000
package com.mapp.demo.controller; import com.mapp.shiro.entity.Authority; import com.mapp.shiro.util.ShiroUtil; import com.mapp.shiro.util.StaticData; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class TestController { @RequestMapping("/getVersion") public Object getVersion() { Map<String, String> res = new HashMap<>(); res.put("version", "0.1"); res.put("name", "皮皮马权限管理系统"); res.put("author", "mapp"); return res; } @RequestMapping("/saveAuthorty") public Object saveAuthorty(Authority authority) { // 模拟数据库新增 StaticData.AUTHORITIES.add(authority); // 重新加载权限 ShiroUtil.reloadFilterChainDefinitionMap(); Map<String, Object> res = new HashMap<>(); res.put("code", 0); res.put("msg", "权限设置成功!"); return res; } }
26.315789
62
0.66
1d9312e08faa2a92d08957d4e3f92c92673bcc86
7,850
package com.buahbatu.elderlywatch.adapter; import android.content.Context; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.buahbatu.elderlywatch.AppSetting; import com.buahbatu.elderlywatch.R; import com.buahbatu.elderlywatch.SocketController; import com.buahbatu.elderlywatch.loader.ProfileLoader; import com.buahbatu.elderlywatch.model.User; import com.robinhood.spark.SparkView; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.BindView; public class ProfileRecyclerAdapter extends RecyclerView.Adapter<ProfileRecyclerAdapter.ProfileViewHolder>{ public static final String SELF = "self"; private Context context; private OnItemListener listener; private List<User> userList; private List<SocketController> socketControllers; // load user profile data private ProfileLoader profileLoader; private MediaPlayer mediaPlayer; private boolean ringtoneIsIdle = true; public ProfileRecyclerAdapter(Context context, OnItemListener itemClickedListener) { this.context = context; this.listener = itemClickedListener; this.userList = new ArrayList<>(); this.socketControllers= new ArrayList<>(); Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // Ringtone r = RingtoneManager.getRingtone(context, notification); // r.play(); // media player this.mediaPlayer = MediaPlayer.create(context, notification); this.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { ringtoneIsIdle = true; } }); this.mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mediaPlayer, int i, int i1) { ringtoneIsIdle = true; return true; } }); profileLoader = new ProfileLoader(context, new ProfileLoader.OnProfileReadyListener() { @Override public void onProfileDataReady(User user) { userList.add(user); notifyItemInserted(userList.size()-1); } }); } public void addUser(String user){ loadUserData(user); } public void disconnectAllConnector(){ for(SocketController s : socketControllers){ s.disconnect(); } socketControllers.clear(); } private void soundOnDrop(){ if (ringtoneIsIdle){ ringtoneIsIdle = false; mediaPlayer.start(); } } private void loadUserData(String username){ if (TextUtils.equals(username, SELF)) username = AppSetting.getUsername(context); profileLoader.addLoadQueue(username); } class ProfileViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.text_status) TextView mStatusText; @BindView(R.id.text_full_name) TextView mFullNameText; @BindView(R.id.text_address) TextView mAddressText; @BindView(R.id.text_phone_number) TextView mPhoneNumberText; @BindView(R.id.text_birth_date) TextView mBirthDateText; @BindView(R.id.spark_graph) SparkView mSparkView; SocketController controller; ProfileViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } @Override public int getItemViewType(int position) { String role = userList.get(position).Role; switch (role){ case "3": return 1; case "4": return 2; default: return 2; } } @Override public ProfileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View layout; Log.i("CREATE", "onCreateViewHolder: " + viewType); if (viewType == 1) { layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_doctor, parent, false); } else{ layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile, parent, false); } return new ProfileViewHolder(layout); } private void setStatusText(String status, TextView textView){ // setup status switch (status){ case "idle": textView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorIdle)); break; case "sit": textView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorSit)); break; case "walk": textView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorWalk)); break; case "fall": textView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorDrop)); soundOnDrop(); break; case "drop": textView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorDrop)); soundOnDrop(); break; } textView.setText(status.toUpperCase()); } @Override public void onBindViewHolder(final ProfileViewHolder holder, int position) { holder.mFullNameText.setText(userList.get(position).FullName); holder.mAddressText.setText(userList.get(position).Address); holder.mBirthDateText.setText(userList.get(position).BirthDate); holder.mPhoneNumberText.setText(userList.get(position).PhoneNumber); final ElderlyAdapter elderlyAdapter = new ElderlyAdapter(); holder.mSparkView.setAdapter(elderlyAdapter); if (getItemViewType(position) != 1) { setStatusText(userList.get(position).Status, holder.mStatusText); holder.controller = new SocketController(context, userList.get(position).Username, new SocketController.OnMessageArriveListener() { @Override public void onMessageArrive(double y, String status) { elderlyAdapter.addDataToChart((float) y); elderlyAdapter.notifyDataSetChanged(); setStatusText(status, holder.mStatusText); } }); socketControllers.add(holder.controller); holder.controller.connect(); if (position == 0){ holder.mSparkView.setVisibility(View.VISIBLE); } } holder.mSparkView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { view.setVisibility(View.GONE); } }); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (getItemViewType(holder.getAdapterPosition()) != 1 && holder.mSparkView.getVisibility() == View.GONE){ holder.mSparkView.setVisibility(View.VISIBLE); }else { listener.itemClicked(holder.getAdapterPosition(), userList.get(holder.getAdapterPosition())); } } }); } @Override public int getItemCount() { return userList.size(); } public interface OnItemListener { void itemClicked(int position, User user); } }
35.36036
115
0.639873
a6d1c92fec148176794fd953c4b87a56e3fc6e4c
2,445
/* * Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. * * Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * * BK-BASE 蓝鲸基础平台 is licensed under the MIT License. * * License for BK-BASE 蓝鲸基础平台: * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tencent.bk.base.datahub.databus.connect.hdfs; public class HdfsConsts { public static final String COMMMITTED_FILENAME_SEPARATOR = "+"; public static final String COMMMITTED_FILENAME_SEPARATOR_REGEX = "[\\.|\\+]"; // +tmp is a invalid topic name, naming the tmp directory this way to avoid conflicts. public static final String TEMPFILE_DIRECTORY = "/+tmp/"; public static final String JSON_SUFFIX = ".json"; public static final String JSON = "json"; public static final String PARQUET_SUFFIX = ".parquet"; public static final String PARQUET = "parquet"; public static final String META_CONN_URL = "meta.conn.url"; public static final String META_CONN_USER = "meta.conn.user"; public static final String META_CONN_PASS = "meta.conn.pass"; public static final String LEASE_EXCEPTION = "org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException"; public static final String CLOSE_EXCEPTION = "You cannot call toBytes() more than once without calling reset()"; }
47.941176
116
0.731697
8b8b90e75a0eeecaa2737ad8b1ae610e977e4ced
1,050
package test.socket.tcp; import java.io.IOException; import java.net.Socket; /** * 服务端 */ public class SocketTCPClient { public static void start(String host, int port, String name) { while (true) { Socket socket; try { socket = new Socket(host, port); Thread receiveStart = SocketTCPTool.receiveStart(socket, 61, "Client R" + name);//接收 Thread sendStart = SocketTCPTool.sendStart(socket, "Client S" + name, false);//发送 try { receiveStart.join(); sendStart.join(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (IOException e) { System.out.println("连接失败,重试:" + e.toString()); } finally { try { Thread.sleep(3000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } }
30
100
0.478095
874fd0ac253beecad219c7faed518e18da5cd504
21,814
package org.esupportail.portal.ws.server; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.groups.GroupsException; import org.jasig.portal.groups.IEntity; import org.jasig.portal.groups.IEntityGroup; import org.jasig.portal.groups.IGroupConstants; import org.jasig.portal.groups.IGroupMember; import org.jasig.portal.security.IPerson; import org.jasig.portal.services.GroupService; import org.jasig.portal.spring.locator.PersonAttributeDaoLocator; /** * The uPortal web service for portlets. */ public class UportalService { /** * Constructor. */ public UportalService() { super(); } ////////////////////////////////////////////////////////// // user methods ////////////////////////////////////////////////////////// /** * @param userId * @return the uPortal user with id userId. */ private IEntity getUportalUser( final String userId) throws UportalServiceErrorException, UportalServiceUserNotFoundException { IEntity user; try { user = GroupService.getEntity(userId, IPerson.class); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } if (user == null) { throw UportalServiceUserNotFoundException.userIdNotFound(userId); } return user; } /** * @param userId * @return all the attributes of the user with id userId. * @throws UportalServiceErrorException * @throws UportalServiceUserNotFoundException */ @SuppressWarnings("unchecked") private Map<String, List<String>> getUportalUserAttributes(final String userId) throws UportalServiceErrorException, UportalServiceUserNotFoundException { Map<String, List<String>> result = new HashMap<String, List<String>>(); Map<String, Object> portalAttributes = PersonAttributeDaoLocator.getPersonAttributeDao().getUserAttributes(userId); if (portalAttributes == null) { throw UportalServiceUserNotFoundException.userIdNotFound(userId); } Iterator<String> keyIterator = portalAttributes.keySet().iterator(); if (!keyIterator.hasNext()) { throw UportalServiceUserNotFoundException.userIdNotFound(userId); } while (keyIterator.hasNext()) { String key = keyIterator.next(); Object portalAttribute = portalAttributes.get(key); List<String> valueList = new ArrayList<String>(); if (portalAttribute != null) { if (portalAttribute instanceof List) { for (Object listItem : (List) portalAttribute) { if (listItem instanceof String) { valueList.add((String) listItem); } else { valueList.add(listItem.toString()); } } } else if (portalAttribute instanceof String) { valueList.add((String) portalAttribute); } else { valueList.add(portalAttribute.toString()); } } result.put(key, valueList); } return result; } // /** // * @return a string that represents the object. // */ // private static String objectToString(final Object object) { // if (object == null) { // return null; // } // if (!(object instanceof Object[])) { // return "[" + object.toString() + "]"; // } // Object [] objects = (Object[]) object; // String separator = ""; // StringBuffer sb = new StringBuffer(); // for (int i = 0; i < objects.length; i++) { // sb.append(separator).append(i).append(" => ").append(objectToString(objects[i])); // separator = " "; // } // return sb.toString(); // } /** * Debug the result of a method. */ private static void debugResult( @SuppressWarnings("unused") final String methodName, @SuppressWarnings("unused") final Object result) { // LogFactory.getLog(UportalService.class).info(methodName + "(): " + objectToString(result)); } /** * @return an array that represent the attribute. */ private static Object[] toArray( final String name, final List<String> values) { Object [] result = new Object[2]; result[0] = name; Object [] valueListArray = new Object[values.size()]; int i = 0; for (String value : values) { valueListArray[i] = value; i++; } result[1] = valueListArray; return result; } /** * @return the group converted to an object array (to pass through web services). */ private static Object[] toArray( final String userId, final Map<String, List<String>> attributes) { Object [] result = new Object[2]; result[0] = userId; Object [] attributeListArray = new Object[attributes.size()]; Iterator<String> attributeNameIter = attributes.keySet().iterator(); int i = 0; while (attributeNameIter.hasNext()) { String attributeName = attributeNameIter.next(); attributeListArray[i] = toArray(attributeName, attributes.get(attributeName)); i++; } result[1] = attributeListArray; return result; } /** * This method returns a 2-array: * 0: the user's id * 1: an array to store the user's attributes * @param userId * @return the user that corresponds to userId. * @throws UportalServiceErrorException * @throws UportalServiceUserNotFoundException */ public Object [] getUser(final String userId) throws UportalServiceErrorException, UportalServiceUserNotFoundException { Object [] result = toArray(userId, getUportalUserAttributes(userId)); debugResult("getUser", result); return result; } /** * @param token * @return the id of the users of which name contains token. * @throws GroupsException */ @SuppressWarnings("unchecked") private List<String> searchUportalUsers(final String token) throws UportalServiceErrorException { try { EntityIdentifier [] userIds = GroupService.searchForEntities( token, IGroupConstants.CONTAINS, IPerson.class); List<String> result = new ArrayList<String>(); if (userIds != null) { for (EntityIdentifier userId : userIds) { result.add(userId.getKey()); } } return result; } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param token * @return the groups of which name contains token. * @throws UportalServiceErrorException */ public Object[] searchUsers( final String token) throws UportalServiceErrorException { List<String> userIds = searchUportalUsers(token); Object [] result = new Object[userIds.size()]; for (int i = 0; i < userIds.size(); i++) { result[i] = getUser(userIds.get(i)); } debugResult("searchUsers", result); return result; } ////////////////////////////////////////////////////////// // group methods ////////////////////////////////////////////////////////// /** * @return the group converted to an object array (to pass through web services). */ private static Object[] toArray(final IEntityGroup group) { Object[] groupArray = new Object[2]; groupArray[0] = group.getKey(); groupArray[1] = group.getName(); return groupArray; } /** * @param groupId * @return the group with id groupId. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ private static IEntityGroup getUportalGroupById( final String groupId) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { IEntityGroup group; try { group = GroupService.findGroup(groupId); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } if (group == null) { throw UportalServiceGroupNotFoundException.groupIdNotFound(groupId); } return group; } /** * The result of this method is a 2-array: * 0: the id of the group. * 1: the name of the group. * @param groupId * @return the group with id groupId. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ public Object [] getGroupById(final String groupId) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = toArray(getUportalGroupById(groupId)); debugResult("getGroupById", result); return result; } /** * The result of this method is a 2-array: * 0: the id of the group. * 1: the name of the group. * @param groupName * @return the group with name groupName. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ private IEntityGroup getUportalGroupByName(final String groupName) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { try { EntityIdentifier [] groupIds = GroupService.searchForGroups( groupName, IGroupConstants.IS, IPerson.class); if (groupIds == null || groupIds.length == 0) { throw UportalServiceGroupNotFoundException.groupNameNotFound(groupName); } return GroupService.findGroup(groupIds[0].getKey()); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } } /** * The result of this method is a 2-array: * 0: the id of the group. * 1: the name of the group. * @param groupName * @return the group with name groupName. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ public Object [] getGroupByName(final String groupName) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = toArray(getUportalGroupByName(groupName)); debugResult("getGroupByName", result); return result; } /** * @param token * @return the groups of which name contains token. * @throws GroupsException */ @SuppressWarnings("unchecked") private List<IEntityGroup> searchUportalGroupsByName(final String token) throws UportalServiceErrorException { try { EntityIdentifier [] groupIds = GroupService.searchForGroups( token, IGroupConstants.CONTAINS, IPerson.class); List<IEntityGroup> groups = new ArrayList<IEntityGroup>(); if (groupIds != null) { for (EntityIdentifier groupId : groupIds) { groups.add(GroupService.findGroup(groupId.getKey())); } } return groups; } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param token * @return the groups of which name contains token. * @throws UportalServiceErrorException */ public Object[] searchGroupsByName(final String token) throws UportalServiceErrorException { List<IEntityGroup> groups = searchUportalGroupsByName(token); Object [] result = new Object[groups.size()]; for (int i = 0; i < groups.size(); i++) { result[i] = toArray(groups.get(i)); } debugResult("searchGroupsByName", result); return result; } ////////////////////////////////////////////////////////// // group hierarchy methods ////////////////////////////////////////////////////////// /** * The result of this method is a 2-array: * 0: the id of the group. * 1: the name of the group. * @param groupName * @return the group with distinguished name groupName. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ private IEntityGroup getUportalGroupByDistinguishedName(final String groupName) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { IEntityGroup group; try { group = GroupService.getDistinguishedGroup(groupName); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } if (group == null) { throw UportalServiceGroupNotFoundException.groupNameNotFound(groupName); } return group; } /** * @return the root group. */ private IEntityGroup getUportalRootGroup() { return getUportalGroupByDistinguishedName(IGroupConstants.EVERYONE); } /** * The result of this method is a 2-array: * 0: the id of the root group. * 1: the name of the root group. * @return the root group. */ public Object [] getRootGroup() { Object [] result = toArray(getUportalRootGroup()); debugResult("getRootGroup", result); return result; } /** * @param group * @return the sub groups of a group. * @throws GroupsException */ @SuppressWarnings("unchecked") private List<IEntityGroup> getUportalSubGroups(final IEntityGroup group) throws UportalServiceErrorException { List<IEntityGroup> subGroups = new ArrayList<IEntityGroup>(); Iterator<IGroupMember> groupMemberIter; try { groupMemberIter = group.getChildren().iterator(); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } while (groupMemberIter.hasNext()) { IGroupMember groupMember = groupMemberIter.next(); if (groupMember instanceof IEntityGroup) { subGroups.add((IEntityGroup) groupMember); } } return subGroups; } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param group * @return the sub groups of a group. * @throws GroupsException */ @SuppressWarnings("unchecked") private Object[] getSubGroups(final IEntityGroup group) throws UportalServiceErrorException { List<IEntityGroup> groups = getUportalSubGroups(group); Object [] result = new Object[groups.size()]; for (int i = 0; i < groups.size(); i++) { result[i] = toArray(groups.get(i)); } return result; } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param groupId * @return the sub groups of the group with id groupId. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ @SuppressWarnings("unchecked") public Object[] getSubGroupsById(final String groupId) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getSubGroups(getUportalGroupById(groupId)); debugResult("getSubGroupsById", result); return result; } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param groupName * @return the sub groups of the group with name groupName. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ @SuppressWarnings("unchecked") public Object[] getSubGroupsByName(final String groupName) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getSubGroups(getUportalGroupByName(groupName)); debugResult("getSubGroupsByName", result); return result; } /** * @param group * @return the containing groups of a group. * @throws GroupsException */ private List<IEntityGroup> getUportalContainingGroups(final IEntityGroup group) throws UportalServiceErrorException { List<IEntityGroup> containingGroups = new ArrayList<IEntityGroup>(); Iterator<IEntityGroup> containingGroupsIter; try { containingGroupsIter = group.getParentGroups().iterator(); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } while (containingGroupsIter.hasNext()) { IEntityGroup containingGroup = containingGroupsIter.next(); containingGroups.add(containingGroup); } return containingGroups; } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param group * @return the containing groups of a group. * @throws GroupsException */ @SuppressWarnings("unchecked") private Object[] getContainingGroups(final IEntityGroup group) throws UportalServiceErrorException { List<IEntityGroup> groups = getUportalContainingGroups(group); Object [] result = new Object[groups.size()]; for (int i = 0; i < groups.size(); i++) { result[i] = toArray(groups.get(i)); } return result; } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param groupId * @return the containing groups of the group with id groupId. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ @SuppressWarnings("unchecked") public Object[] getContainingGroupsById(final String groupId) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getContainingGroups(getUportalGroupById(groupId)); debugResult("getContainingGroupsById", result); return result; } /** * This method returns an array of 2-array objects: * 0: the group id * 1: the group name * @param groupName * @return the sub groups of the group with name groupName. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ @SuppressWarnings("unchecked") public Object[] getContainingGroupsByName(final String groupName) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getContainingGroups(getUportalGroupByName(groupName)); debugResult("getContainingGroupsByName", result); return result; } /** * @param group * @return the hierarchy of a group. * @throws UportalServiceErrorException */ @SuppressWarnings("unchecked") private UportalGroupHierarchy getGroupHierarchy(final IEntityGroup group) throws UportalServiceErrorException { List<UportalGroupHierarchy> subHierarchies = new ArrayList<UportalGroupHierarchy>(); for (IEntityGroup subGroup : getUportalSubGroups(group)) { subHierarchies.add(getGroupHierarchy(subGroup)); } if (subHierarchies.size() == 0) { return new UportalGroupHierarchy(group, null); } return new UportalGroupHierarchy(group, subHierarchies); } /** * This method returns a 2-array object: * 0: a 2-array object (0: the group id, 1: the group name). * 1: an array of group hierarchies (null if no sub group). * @param groupId * @return the hierarchy of the group with id groupId. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ public Object[] getGroupHierarchyById(final String groupId) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getGroupHierarchy(getUportalGroupById(groupId)).toArray(); debugResult("getGroupHierarchyById", result); return result; } /** * This method returns a 2-array object: * 0: a 2-array object (0: the group id, 1: the group name). * 1: an array of group hierarchies (null if no sub group). * @param groupName * @return the hierarchy of the group with name groupName. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ public Object[] getGroupHierarchyByName(final String groupName) throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getGroupHierarchy(getUportalGroupByName(groupName)).toArray(); debugResult("getGroupHierarchyByName", result); return result; } /** * @return the complete group hierarchy. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException */ public Object[] getGroupHierarchy() throws UportalServiceErrorException, UportalServiceGroupNotFoundException { Object [] result = getGroupHierarchy(getUportalRootGroup()).toArray(); debugResult("getGroupHierarchy", result); return result; } ////////////////////////////////////////////////////////// // group membership methods ////////////////////////////////////////////////////////// /** * @return the groups the user with id userId belongs to, as an array. * Each entry of the array represents a group: * 0: the id of the group. * 1: the name of the group. * @param userId * @throws UportalServiceErrorException * @throws UportalServiceUserNotFoundException */ @SuppressWarnings("unchecked") public Object [] getUserGroups(final String userId) throws UportalServiceErrorException, UportalServiceUserNotFoundException { Iterator<IEntityGroup> groupIter; try { groupIter = getUportalUser(userId).getAncestorGroups().iterator(); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } List<IEntityGroup> groups = new ArrayList<IEntityGroup>(); while (groupIter.hasNext()) { IGroupMember groupMember = groupIter.next(); if (groupMember instanceof IEntityGroup) { groups.add((IEntityGroup) groupMember); } } Object [] result = new Object[groups.size()]; for (int i = 0; i < groups.size(); i++) { result[i] = toArray(groups.get(i)); } debugResult("getUserGroups", result); return result; } /** * @param userId * @param groupId * @return true if the user with id userId belongs to the group with group groupId. * @throws UportalServiceErrorException * @throws UportalServiceGroupNotFoundException * @throws UportalServiceUserNotFoundException */ public boolean isUserMemberOfGroup(final String userId, final String groupId) throws UportalServiceErrorException, UportalServiceGroupNotFoundException, UportalServiceUserNotFoundException { boolean result; try { result = getUportalGroupById(groupId).deepContains(getUportalUser(userId)); } catch (GroupsException e) { throw UportalServiceErrorException.error(e); } debugResult("isUserMemberOfGroup", result); return result; } }
32.221566
96
0.686623
521b7351036c24db7947a4a16a1dfc62229c0489
1,495
package com.satish.commandserver; import java.io.*; import java.net.*; public class Application { public static void main(String[] args) throws Exception{ System.out.println("Server Signing ON"); ServerSocket ss = new ServerSocket(9095); Socket soc = ss.accept(); PrintWriter nos = new PrintWriter( new BufferedWriter( new OutputStreamWriter( soc.getOutputStream() ) ) ,true); BufferedReader nis = new BufferedReader( new InputStreamReader( soc.getInputStream() ) ); String str = nis.readLine(); while(!str.equals("End")){ System.out.println("Server received "+ str); try{ Class c = Class.forName("com.satish.commandserver."+str); IAction a = (IAction) c.newInstance(); a.execute(nos); }catch(ClassNotFoundException | InstantiationException | IllegalAccessException e) { DefaultAction b = new DefaultAction(); b.execute(nos); } str = nis.readLine(); } nos.println("End"); System.out.println("Server Signing OFF"); } }
33.222222
72
0.459532
226283c38b47f478ef4035d73b29f4aabc3ba36d
5,531
package org.tll.canyon.dao.hibernate; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringEscapeUtils; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Example; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.springframework.orm.ObjectRetrievalFailureException; import org.springframework.orm.hibernate3.HibernateCallback; import org.tll.canyon.dao.AssetHitStatDao; import org.tll.canyon.model.AssetDetail; import org.tll.canyon.model.AssetHitStat; import org.tll.canyon.model.viewwrappers.AssetHitStatSearchForm; public class AssetHitStatDaoHibernate extends BaseDaoHibernate implements AssetHitStatDao { public AssetHitStat getAssetHitStat(Long assetHitStatId) { AssetHitStat assetHitStat = (AssetHitStat) getHibernateTemplate().get(AssetHitStat.class, assetHitStatId); if (assetHitStat == null) { throw new ObjectRetrievalFailureException(AssetHitStat.class, assetHitStatId); } return assetHitStat; } public void saveAssetHitStat(AssetHitStat assetHitStat) { getHibernateTemplate().saveOrUpdate(assetHitStat); } public void removeAssetHitStat(Long assetHitStatId) { // object must be loaded before it can be deleted getHibernateTemplate().delete(getAssetHitStat(assetHitStatId)); } @SuppressWarnings("unchecked") public List<AssetHitStat> getAssetHitStats(final AssetHitStat example) { //return getHibernateTemplate().find("from AssetHitStat"); if (example == null) { return getHibernateTemplate().find("from AssetHitStat"); } else { // filter on properties set in the assetRole HibernateCallback callback = new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Example ex = Example.create(example).ignoreCase().enableLike(MatchMode.ANYWHERE); return session.createCriteria(AssetHitStat.class).add(ex).list(); } }; return (List) getHibernateTemplate().execute(callback); } } @SuppressWarnings("unchecked") public List<AssetHitStat> getAssetHitStatsForAssetDetail(AssetDetail assetDetail) { List items = getHibernateTemplate().find("from AssetHitStat where assetDetailId=?", assetDetail.getId()); if (items == null || items.isEmpty()) { return new ArrayList(); } else { return items; } } @SuppressWarnings("unchecked") public List<AssetHitStat> getAssetHitStatsBySearch(final AssetHitStatSearchForm assetHitStatSearchForm) { return getHibernateTemplate().executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(AssetHitStat.class); criteria.add(Restrictions.eq("assetDetailId", new Long(assetHitStatSearchForm.getAssetDetailId()))); // Last Login DATE RANGE if (assetHitStatSearchForm.getStartLastLoginTimestamp() != null && assetHitStatSearchForm.getEndLastLoginTimestamp() != null) { criteria.add(Restrictions.between("lastLoginTimestamp", assetHitStatSearchForm .getStartLastLoginTimestamp(), assetHitStatSearchForm.getEndLastLoginTimestamp())); } if (assetHitStatSearchForm.getUserIdentifierConnectingToAsset() != null) { criteria.add(Restrictions.ilike("userIdentifierConnectingToAsset", assetHitStatSearchForm .getUserIdentifierConnectingToAsset(), MatchMode.ANYWHERE)); } if (assetHitStatSearchForm.getApplicationUsedToConnect() != null) { criteria.add(Restrictions.ilike("applicationUsedToConnect", assetHitStatSearchForm .getApplicationUsedToConnect(), MatchMode.ANYWHERE)); } if (assetHitStatSearchForm.getUserIdentifierFromOS() != null) { criteria.add(Restrictions.ilike("userIdentifierFromOS", assetHitStatSearchForm .getUserIdentifierFromOS(), MatchMode.ANYWHERE)); } if (assetHitStatSearchForm.getHost() != null) { criteria.add(Restrictions.ilike("host", StringEscapeUtils.escapeJava(assetHitStatSearchForm.getHost()), MatchMode.ANYWHERE)); } if (assetHitStatSearchForm.getMinNumberOfLogins()!=null && assetHitStatSearchForm.getMaxNumberOfLogins()!=null){ criteria.add(Restrictions.between("numberOfLogins", assetHitStatSearchForm.getMinNumberOfLogins(), assetHitStatSearchForm.getMaxNumberOfLogins())); } if (assetHitStatSearchForm.getConnectingIP() != null) { criteria.add(Restrictions.ilike("connectingIP", assetHitStatSearchForm .getConnectingIP(), MatchMode.ANYWHERE)); } return criteria.list(); } }); } }
49.383929
168
0.653046
cf77d32eec667e05fe0413ce45479d9c0cb6df9f
7,929
package UserPackage; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.ResourceBundle; import java.util.Set; import cellpackage.Cell; import cellpackage.CellHandler; import cellpackage.FireCellHandler; import cellpackage.GameOfLifeCellHandler; import cellpackage.PredatorPreyCellHandler; import cellpackage.SegregationCellHandler; import cellpackage.SugarCellHandler; import grid.Grid; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import javafx.scene.effect.DropShadow; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.scene.text.Font; /** * the UserInterface class defines the choice of simulation and the buttons * * @author Zhiyong * */ public class UserInterface { public static final double WIDTH = 800; public static final double HEIGHT = 600; public static final int KEY_INPUT_SPEED = 5; public static final int NUMBER_OF_BUTTON = 5; public static final double DISTANCE = 50; public static final String Package_FOR_BUTTON = "resources/Button"; public static final String LABELNAME = " Welcome To The Cell Society\n Please Choose The Shape For Simulation\n Then Choose One XML File\n\n " + " Creator: Alex Kyle Zhiyong"; // kind of data files to look for public static final String PACKAGE_FOR_COLOR = "resources/Color"; private Scene scene; private Pane root; private ResourceBundle buttonResources; private CellHandler cellHandler; private Grid grid; // store all the buttons on the pane private Map<String, Button> buttonList; private Map<String, TextField> textFieldList; private String simulationName; private int dimension; private Slider slider; private String shapeOfSimulation; //store the state and list of percentage of that state private Map<String, List<Double>> statePercentage; private Draw draw; private List<String> stateList; private double space; private PercentageHandler percentageHandler; private ShapeManager shapeManager; private ResourceBundle colorResources; private ButtonAdder buttonAdder; private TextFieldAdder textFieldAdder; private SliderSetUp sliderSetUp; private LabelSetUp labelSetUp; public UserInterface() { initInterface(); scene = new Scene(root, WIDTH, HEIGHT); scene.setFill(Color.RED); buttonResources = ResourceBundle.getBundle(Package_FOR_BUTTON); initialButton("fileselection"); initialButton("triangle"); initialButton("rectangle"); Label label = new Label(LABELNAME); label.setLayoutX(200); label.setLayoutY(10); label.setTextFill(Color.BLUE); label.setFont(Font.font("Cambria", 20)); root.getChildren().add(label); } public UserInterface(int dim, String simName, List<String> states, String shape){ initInterface(states); grid = new Grid(dim, states, simName, shape); switch (simName) { case "Fire": cellHandler = new FireCellHandler(grid); break; case "GameOfLife": cellHandler = new GameOfLifeCellHandler(grid); break; case "PredatorPrey": cellHandler = new PredatorPreyCellHandler(grid); break; case "Segregation": cellHandler = new SegregationCellHandler(grid); break; case "Sugar": cellHandler = new SugarCellHandler(grid); break; } colorResources = ResourceBundle.getBundle(PACKAGE_FOR_COLOR); shapeManager = new ShapeManager(); initialState(dim, simName, states, shape); buttonAdder = new ButtonAdder(); buttonAdder.setUpButton(); buttonList = buttonAdder.getButtonList(); root.getChildren().add(buttonAdder.getVBox()); textFieldAdder = new TextFieldAdder(); textFieldAdder.setUpTextfield(simName); textFieldList = textFieldAdder.getTextField(); root.getChildren().addAll(textFieldAdder.getLabelList()); for(TextField t : textFieldAdder.getTextField().values()){ root.getChildren().add(t); } sliderSetUp = new SliderSetUp(); sliderSetUp.setUpSlider(); slider = sliderSetUp.getSlider(); root.getChildren().add(sliderSetUp.getSlider()); root.getChildren().add(sliderSetUp.getLabelForSlider()); labelSetUp = new LabelSetUp(); labelSetUp.setUpLabel(650, 15, "Percentage"); root.getChildren().addAll(labelSetUp.getLabelList()); scene = new Scene(root, WIDTH, HEIGHT); } private void initialButton(String s){ Button btnSelect = new Button(buttonResources.getString(s)); btnSelect.setLayoutX(10); btnSelect.setLayoutY(10 + space); space +=50; buttonList.put(buttonResources.getString(s), btnSelect); root.getChildren().add(btnSelect); } public void initInterface(List<String> states) { initInterface(); percentageHandler = new PercentageHandler(); statePercentage = new HashMap<>(); statePercentage = percentageHandler.calculatePercentage(states, statePercentage); draw = new Draw(statePercentage); } public void initInterface(){ root = new Pane(); buttonList = new HashMap<>(); textFieldList = new HashMap<>(); } private void initialState(int dim, String simName, List<String> states, String shape) { switch(shape){ case "rectangle": shapeManager.setRec(dim, states); root.getChildren().addAll(shapeManager.getShapeList()); break; case "triangle": shapeManager.setTri(dim, states); root.getChildren().addAll(shapeManager.getShapeList()); break; case "hexagon": shapeManager.setHex(dim, states); root.getChildren().addAll(shapeManager.getShapeList()); break; default: shapeManager.setRec(dim, states); root.getChildren().addAll(shapeManager.getShapeList()); break; } simulationName = simName; dimension = dim; shapeOfSimulation = shape; stateList = states; } // update the state of each grid after each step of animation public void updateDisplay() { // here initialize the name of CellHandler according to the // simulationName grid = cellHandler.updateGrid(); updateShape(shapeManager.getShapeList()); } private void updateShape(List<Polygon> list){ root.getChildren().removeAll(list); root.getChildren().removeAll(draw.getPath()); stateList.clear(); for (int r = 0; r < dimension; r++) { for (int c = 0; c < dimension; c++) { Cell cell = grid.getCell(r, c); String stateTemp = cell.getState(); stateList.add(stateTemp); list.get(dimension * r + c).setFill(Color.web(colorResources.getString(stateTemp))); } } statePercentage = percentageHandler.calculatePercentage(stateList, statePercentage); //draw = new Draw(statePercentage); root.getChildren().addAll(draw.getPath()); root.getChildren().addAll(list); } public Scene getScene() { return scene; } public Map<String, Button> getButton() { return buttonList; } public Map<String, TextField> getTextField(){ return textFieldList; } public String getSimName(){ return simulationName; } public Slider getSlider(){ return slider; } public int getDimension(){ return dimension; } public List<String> getStateList(){ return stateList; } //update the state randomly after the user click on the shape public void mouseUpdate(double x, double y) { int index = -1; for(int i = 0; i < shapeManager.getShapeList().size(); i++){ if(shapeManager.getShapeList().get(i).contains(x, y)){ index = i; break; } } if(index > 0){ Random random = new Random(); int newIndex = random.nextInt(stateList.size()); stateList.remove(index); stateList.add(index, stateList.get(newIndex)); shapeManager.getShapeList().get(index).setFill(Color.web(colorResources.getString(stateList.get(newIndex)))); } updateShape(shapeManager.getShapeList()); } }
27.341379
164
0.732249
d189547b41bcdce8dde8562e982640d2324e036a
2,163
package entidade; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.UUID; public class Cliente { private String id; private String nome; private String cpf; private Date dataNascimento; private Date dataEmpresa; private List<Endereco> enderecos = new ArrayList<>(); private List<Contato> contatos = new ArrayList<>(); public Cliente() { this.id = UUID.randomUUID().toString(); } public Cliente(String nome, String cpf, Date dataNascimento, Date dataEmpresa, List<Endereco> enderecos, List<Contato> contatos) { this(); this.nome = nome; this.cpf = cpf; this.dataNascimento = dataNascimento; this.dataEmpresa = dataEmpresa; this.enderecos = enderecos; this.contatos = contatos; } public Cliente(String id, String nome, String cpf, Date dataNascimento, Date dataEmpresa, List<Endereco> enderecos, List<Contato> contatos) { this.id = id; this.nome = nome; this.cpf = cpf; this.dataNascimento = dataNascimento; this.dataEmpresa = dataEmpresa; this.enderecos = enderecos; this.contatos = contatos; } public String getId() { return id; } public Date getDataEmpresa() { return dataEmpresa; } public String getNome() { return nome; } public String getCpf() { return cpf; } public void setId(String id) { this.id = id; } public List<Contato> getContatos() { return contatos; } public List<Endereco> getEnderecos() { return enderecos; } public void adicionarContatos(Integer ddd, String telefone){ this.contatos.add(new Contato(ddd, telefone)); } public void setEnderecos(String logradouro, Integer numero, String bairro, String cidade, String cep) { this.enderecos.add(new Endereco(logradouro, numero, bairro, cidade, cep)); } public Date getDataNascimento() { return dataNascimento; } public void setNome(String nome) { this.nome = nome; } public void setCpf(String cpf) { this.cpf = cpf; } public void setDataNascimento(Date dataNascimento) { this.dataNascimento = dataNascimento; } public void setDataEmpresa(Date dataEmpresa) { this.dataEmpresa = dataEmpresa; } }
21.205882
116
0.717522
98a9b43d0961674416240d5804065cae78d55c53
2,800
package com.cloudberry.cloudberry.topology.model.mapping.useMetadata; import com.cloudberry.cloudberry.kafka.event.generic.ComputationEvent; import com.cloudberry.cloudberry.topology.model.mapping.MappingEvaluation; import com.cloudberry.cloudberry.topology.model.mapping.MappingExpression; import com.cloudberry.cloudberry.topology.model.mapping.arguments.EntryMapArgument; import com.cloudberry.cloudberry.topology.model.mapping.arguments.EntryMapRecord; import com.cloudberry.cloudberry.topology.model.mapping.operators.OperationEnum; import lombok.val; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.List; import java.util.Map; import static com.cloudberry.cloudberry.db.influx.InfluxDefaults.CommonTags.COMPUTATION_ID; import static com.cloudberry.cloudberry.db.mongo.service.DataGenerator.COMPUTATION_ID_1_A_A; import static com.cloudberry.cloudberry.db.mongo.service.DataGenerator.CONFIGURATION_1_A_PRICE_KEY; import static com.cloudberry.cloudberry.db.mongo.service.DataGenerator.CONFIGURATION_1_A_PRICE_VALUE; import static com.cloudberry.cloudberry.topology.model.ComputationEventMapType.FIELDS; import static com.cloudberry.cloudberry.topology.model.ComputationEventMapType.METADATA; public class MappingNodeEvaluatorMultiplyFieldsByMetaTest extends MappingNodeEvaluatorUseMetadataTestBase { @Test void multiplyValueFromFieldsByValueFromMeta() { val fitnessKey = "fitness"; val newFieldInEventName = "CALCULATED"; val fitnessValue = 1000; val incomingEvent = new ComputationEvent( Instant.ofEpochMilli(0), "some-test-measurement-name", Map.of(fitnessKey, fitnessValue), Map.of(COMPUTATION_ID, COMPUTATION_ID_1_A_A.toHexString()) ); val newEvent = mappingNodeEvaluator.calculateNewComputationEvent(incomingEvent, new MappingExpression( List.of(new MappingEvaluation<>( newFieldInEventName, FIELDS, OperationEnum.MULTIPLY_DIFFERENT_FIELDS, List.of( new EntryMapArgument(new EntryMapRecord(FIELDS, fitnessKey)), new EntryMapArgument(new EntryMapRecord(METADATA, CONFIGURATION_1_A_PRICE_KEY)) ) ) ))); Map<String, Object> expectedFields = Map.of(fitnessKey, fitnessValue, newFieldInEventName, (double) fitnessValue * CONFIGURATION_1_A_PRICE_VALUE ); Assertions.assertEquals(expectedFields, newEvent.getFields()); } }
49.122807
119
0.700714
6c5f18befa1b94ebf9160ea3df3f8c80c1896090
1,875
package butterknife.internal; import com.google.common.base.Joiner; import com.google.testing.compile.JavaFileObjects; import javax.tools.JavaFileObject; import org.junit.Test; import static butterknife.internal.ProcessorTestUtilities.butterknifeProcessors; import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; import static org.truth0.Truth.ASSERT; public class OnFocusChangeTest { @Test public void focusChange() { JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join( "package test;", "import android.app.Activity;", "import butterknife.OnFocusChange;", "public class Test extends Activity {", " @OnFocusChange(1) void doStuff() {}", "}" )); JavaFileObject expectedSource = JavaFileObjects.forSourceString("test/Test$$ViewInjector", Joiner.on('\n').join( "package test;", "import android.view.View;", "import butterknife.ButterKnife.Finder;", "public class Test$$ViewInjector {", " public static void inject(Finder finder, final test.Test target, Object source) {", " View view;", " view = finder.findRequiredView(source, 1, \"method 'doStuff'\");", " view.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {", " @Override public void onFocusChange(android.view.View p0, boolean p1) {", " target.doStuff();", " }", " });", " }", " public static void reset(test.Test target) {", " }", "}" )); ASSERT.about(javaSource()).that(source) .processedWith(butterknifeProcessors()) .compilesWithoutError() .and() .generatesSources(expectedSource); } }
37.5
98
0.6192
e8ac1e38db245be7200d9b805240a1d9887992f3
1,547
package com.example.springboot; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.example.springboot.pojo.Student; import org.springframework.util.CollectionUtils; public class LambdaTest { public static void main(String[] args) { // list2map(); listSort(); } private static void listSort() { List<Student> list=new ArrayList<>(); Student student=new Student(); student.setId(1); student.setName("tom"); Student student2=new Student(); student2.setId(2); student2.setName("tom2"); list.add(student); list.add(student2); Collections.sort(list,(o1,o2)->{ //>返回1为正序,返回-1为降序 if(o1.getId()>o2.getId()){ return -1; }else if(o1.getId()<o2.getId()){ return 1; }else{ return 0; } }); System.out.println(list); } private static void list2map() { List<Student> list=new ArrayList<>(); /*Student student=new Student(); student.setId(1); student.setName("tom"); list.add(student);*/ // list=null; //转为map,需要list判null if(!CollectionUtils.isEmpty(list)){ Map<Integer, Student> map = list.stream() .collect(Collectors.toMap(Student::getId, Student -> Student)); System.out.println(map); } } }
24.555556
83
0.559147
5d1bfc7558aedde3c9ef84a4ea9ca1830309b38d
363
package com.cupshe.data.access.common; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * 权限 * <p>Title: Permission</p> * <p>Description: </p> * @author zhoutaoping * @date 2020年10月29日 */ @Data @NoArgsConstructor @AllArgsConstructor public class Permission { private Integer dataScope; }
16.5
39
0.699725
cff1a5f896d9fb3dd9e4a5d5769ac3db2c57c694
11,877
package fr.bruju.rmeventreader.implementation.detectiondeformules.transformation; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Stack; import fr.bruju.rmeventreader.implementation.detectiondeformules.EtatInitial; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.algorithme.Algorithme; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.algorithme.BlocConditionnel; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.algorithme.InstructionAffectation; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.algorithme.InstructionAffichage; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.condition.Condition; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.condition.ConditionVariable; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.expression.Constante; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.expression.ExprVariable; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.expression.Expression; import fr.bruju.rmeventreader.implementation.detectiondeformules.modele.visiteurs.VisiteurReecrivainDExpression; import fr.bruju.util.MapsUtils; /** * Un constructeur d'algorithme qui retient les instructions qu'il lit afin de déduire des valeurs pour les variables. * L'objectif étant de remplacer "x = 3; y = x;" par "x = 3; y = 3;" afin de simplifier l'algorithme ainsi constitué. * <br><br>Cette classe implémente VisiteurReecrivainDExpression : elle peut visiter des expressions afin de * substituer les variables par des valeurs qu'elle connait. */ public class ConstructeurValue extends VisiteurReecrivainDExpression { /** Algorithme en cours de construction */ private Algorithme algorithmeCourant = new Algorithme(); /** Pile d'exploration conditionnelle (ie instructions conditionnelles en cours de construction) */ private Stack<ExplorationConditionnelle> pile = new Stack<>(); /** Valeurs actuellement connues pour les variables */ private Map<Integer, Integer> valeursCourantes; /** * Construit un constructeur d'algorithme valué en utilisant l'état initial présent dans un fichier de * onfiguration défini par la classe EtatInitial. */ public ConstructeurValue() { EtatInitial etatInitial = EtatInitial.getEtatInitial(); valeursCourantes = new HashMap<>(); etatInitial.forEach(valeursCourantes::put); } /** * Constuit un constructeur d'algorithme valué en utilisant une table d'association id de variable - constante de * base. * @param valeursInitiales Une table associant id de variable - valeur initiale. La table de hashage est recopiée, * cette classe ne modifie donc pas le contenu de valeursInitiales. */ public ConstructeurValue(Map<Integer, Integer> valeursInitiales) { this.valeursCourantes = new HashMap<>(valeursInitiales); } /** * Renvoie l'algorithme en cours de construction. Lance une exception sur une condition est en cours de * construction. * <br>Si le constructeur valué continue à être utilisé suite à une utilisation de get(), l'algorithme retourné sera * modifié. En d'autres termes, l'algorithme renvoyé par get() n'est pas une copie mais l'objet utilisé pour la * construction. * @return L'algorithme construit */ public Algorithme get() { if (!pile.isEmpty()) { throw new RuntimeException("Exécution non terminée " + pile.size()); } return algorithmeCourant; } /** * Ajoute l'instruction d'affectation donnée à l'algorithme en cours de construction. L'instruction peut être * reecrite selon les connaissances actuelles sur l'état des variables. * @param affectation L'instruction d'affectation à ajouter. */ public void ajouter(InstructionAffectation affectation) { affectation = reecrire(affectation); algorithmeCourant.ajouterInstruction(affectation); } /** * Reecrit l'instruction en prenant en compte des valeurs connues pour les variables. Rempli éventuellement la table * des valeurs courantes si l'évaluation de l'expression est possible. */ private InstructionAffectation reecrire(InstructionAffectation affectation) { Expression nouvelleExpression = explorer(affectation.expression); if (nouvelleExpression != affectation.expression) { affectation = new InstructionAffectation(affectation.variableAssignee, nouvelleExpression); } Integer evaluation = nouvelleExpression.evaluer(); valeursCourantes.put(affectation.variableAssignee.idVariable, evaluation); return affectation; } /** * Ajoute l'instruction d'affichage. Aucun traîtement n'est fait. * @param affichage L'instruction d'affichage. */ public void ajouter(InstructionAffichage affichage) { algorithmeCourant.ajouterInstruction(affichage); } /** * Permet de déclarer le début d'une condition. On donne en paramètre la condition. La fonction renvoie un résultat * selon le désir de la classe de recevoir ou non les instructions contenues dans certaines branches. * <br>Si la fonction déclare ne vouloir recevoir qu'une des deux branches, l'objet s'attend à ne recevoir que * des ajout d'instructions, avec un appel à conditionFinie() lorsque le branchement conditionnel s'arrête. * <br>Si la fonction déclare vouloir recevoir les deux branches, on s'attend à recevoir la suite d'instructions * dans la branche si, puis un appel à conditionSinon, la suite d'instructions dans la branche sinon puis un * appel à conditionFin. Les appels à conditionSinon et la suite d'instructions dans la branche sinon peuvent être * ignorés si il n'y a pas d'instructions dans le sinon. * <br><br>Le code de retour de cette fonction est identique à ce qu'attend la structure d'Exécuteur d'Instructions * dans RMDechiffreur, d'où le choix de ne pas utiliser d'énumération (le code peut être simplement renvoyé par la * fonction de traitement). * @param condition La condition déclenchant le branchement conditionnel. * @return 0 = explorer tout, 1 = explorer vrai, 2 = explorer faux */ public int commencerCondition(Condition condition) { if (condition instanceof ConditionVariable) { ConditionVariable cv = (ConditionVariable) condition; Expression gauche = explorer(cv.gauche); Expression droite = explorer(cv.droite); if (gauche != cv.gauche || droite != cv.droite) { cv = new ConditionVariable(gauche, cv.comparateur, droite); condition = cv; } Boolean test = cv.evaluer(); if (test != null) { pile.push(new ExplorationPartielle()); pile.peek().utiliser(); return test ? 1 : 2; } } ExplorationTotale explorationTotale = new ExplorationTotale(condition); pile.push(explorationTotale); explorationTotale.utiliser(); return 0; } /** * Met fin à l'exploration de la branche si du branchement conditionnel pour commencer à explorer la branche sinon. * Peut lever une exception de temps de course si une exploration partielle du branchement conditionnel a été * demandé par l'objet. */ public void conditionElse() { pile.peek().recevoirSinon(); } /** * Met fin à l'exploration du branchement conditionnel actuel. */ public void conditionFinie() { pile.pop().recevoirFin(); } /** * Si a = b, renvoie a. Sinon renvoie null. * @param a Le premier nombre * @param b Le second nombre * @return Objects.equals(a, b) ? a : null */ private static Integer combiner(Integer a, Integer b) { return Objects.equals(a, b) ? a : null; } /** * Objet permettant de gérer les imbrications de conditions. Les objets implémentant cette interface sont appelés * pour mettre en mémoire l'état de la mémoire avant une condition, et d'unifier les valeurs de la branche si * et de la branche sinon. */ public static interface ExplorationConditionnelle { /** Commence l'exploration du branchement conditionnel */ public void utiliser(); /** Commence l'exploration de la branche sinon */ public void recevoirSinon(); /** Met fin à l'exploration du branchement conditionnel */ public void recevoirFin(); } /** * Un explorateur qui ne fait rien, à part provoquer une erreur si il reçoit un sinon. * <br>Son but est de continuer à compléter l'algorithme si seule une branche est explorée (on enlève le * branchement conditionnel). */ public class ExplorationPartielle implements ExplorationConditionnelle { @Override public void recevoirFin() { } @Override public void recevoirSinon() { throw new UnsupportedOperationException("Partiel a reçu un sinon"); } @Override public void utiliser() { } } /** * Un explorateur qui traite les branches si et sinon et construit l'instruction conditionnelle. */ public class ExplorationTotale implements ExplorationConditionnelle { // L'idée étant que chaque branche a sa propre version de la valeur actuelle de chaque variable. // A la fin du branchement, on ne garde que les affectations dont les deux branches ont la même valeur. // Cela permet de garder les informations déjà connues (si une variable n'est pas modifiée, ce procédéne perd // pas la connaissance sur l'état de cette variable) entre autres. /** Algorithme possédant l'instruction conditionnelle en cours de construction */ private final Algorithme pere; /** La condition générant l'instruction conditionnelle */ private final Condition condition; /** Algorithme dans la branche si */ private final Algorithme vrai; /** Valeurs courantes de la branche si */ private final Map<Integer, Integer> valeursCourantesVrai; /** Algorithme dans la branche sinon */ private final Algorithme faux; /** Valeurs courantes de la branche sinon */ private final Map<Integer, Integer> valeursCourantesFaux; /** * Construit un objet permettant de construire une instruction conditionnelle pouvant posséder une branche si * et une branche sinon. * @param condition La condition générant le branchement */ public ExplorationTotale(Condition condition) { this.pere = algorithmeCourant; this.condition = condition; this.vrai = new Algorithme(); this.valeursCourantesVrai = new HashMap<>(ConstructeurValue.this.valeursCourantes); this.faux = new Algorithme(); this.valeursCourantesFaux = new HashMap<>(ConstructeurValue.this.valeursCourantes); } @Override public void utiliser() { // Remplace l'état de la mémoire par l'état de la branche si ConstructeurValue.this.algorithmeCourant = vrai; ConstructeurValue.this.valeursCourantes = valeursCourantesVrai; } @Override public void recevoirSinon() { // Remplace l'état de la mémoire par l'état de la branche sinon ConstructeurValue.this.algorithmeCourant = faux; ConstructeurValue.this.valeursCourantes = valeursCourantesFaux; } @Override public void recevoirFin() { // Combine les branches si et sinon if (!(vrai.estVide() && faux.estVide())) { pere.ajouterInstruction(new BlocConditionnel(condition, vrai, faux)); } ConstructeurValue.this.algorithmeCourant = pere; // Crée le nouvel état des variables à partir de l'état à la fin des branches si et sinon. Concrètement, si // la sortie, une variable a le même état dans les deux branches, on garde sa valeur. Sinon on déclare // qu'elle * n'a plus de valeur connue. ConstructeurValue.this.valeursCourantes = MapsUtils.combiner(new HashMap<>(), valeursCourantesVrai, valeursCourantesFaux, ConstructeurValue::combiner); } } /* ============================================ * SUBSTITUTION DE VALEURS DANS LES EXPRESSIONS * ============================================ */ @Override public Expression explorer(ExprVariable composant) { Integer valeur = valeursCourantes.get(composant.idVariable); return valeur == null ? composant : new Constante(valeur); } }
41.527972
118
0.752042
3d435f3fafe5f0f73afcd8c1b0671a9312d4e3b3
497
package org.cthul.api4j.api1; import groovy.lang.Closure; /** * Helper class to allow `generatedClass "Foo" { ... }` in Groovy scripts. */ public class GenerateTask { private final String name; private final Closure<?> closure; public GenerateTask(String name, Closure<?> closure) { this.name = name; this.closure = closure; } public String getName() { return name; } public Closure<?> getClosure() { return closure; } }
19.115385
74
0.613682
aad59875c1668eaa6c7a29e47df86d3652c4cd69
1,311
package com.okode.cordova.sightcall.events; import android.util.Log; import com.okode.cordova.sightcall.Constants; import com.sightcall.universal.media.MediaSavedEvent; import org.json.JSONException; import org.json.JSONObject; /** * Created by rpanadero on 21/7/17. */ public class MediaSaved implements Event { private static final String MEDIA_EVENT_RECEIVED = "sightcall.mediaevent"; private static final String FILE_PATH_PARAM = "filePath"; private static final String FILE_SIZE_PARAM = "size"; private static final String CASE_REPORT_ID = "caseReportId"; private MediaSavedEvent event; public MediaSaved(MediaSavedEvent event) { this.event = event; } @Override public String getEventName() { return MEDIA_EVENT_RECEIVED; } @Override public JSONObject getEventData() { JSONObject data = new JSONObject(); try { data.putOpt(FILE_PATH_PARAM, this.event.media().image().getPath()); data.putOpt(FILE_SIZE_PARAM, this.event.media().lengthInBytes()); data.putOpt(CASE_REPORT_ID, this.event.metadata().caseReportId()); } catch (JSONException e) { Log.e(Constants.TAG, "Error constructing notification object. Message: " + e); } return data; } }
28.5
90
0.687262
70b6755b2649e5c6d0110e6145c6b6220d6af9d8
3,168
/******************************************************************************* * Copyright 2012 Analog Devices, 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.analog.lyric.dimple.schedulers.scheduleEntry; import java.util.ArrayList; import java.util.Map; import com.analog.lyric.dimple.model.core.INode; import com.analog.lyric.dimple.model.core.Node; import com.analog.lyric.dimple.model.core.Port; /** * A schedule entry that contains a collection of nodes to be updated together. * <p> * This class is primarily targeted at the Gibbs solver for block Gibbs updates. For that case, all * of the nodes in the collection would be variables. * * @author jeffb * @since 0.06 */ public class BlockScheduleEntry implements IScheduleEntry { IBlockUpdater _blockUpdater; public BlockScheduleEntry(IBlockUpdater blockUpdater, INode... nodeList) { _blockUpdater = blockUpdater; _blockUpdater.attachNodes(nodeList); } public BlockScheduleEntry(Class<IBlockUpdater> blockUpdaterClass, INode... nodeList) throws Exception { this(blockUpdaterClass.newInstance(), nodeList); } public BlockScheduleEntry(IBlockUpdater blockUpdater, Object... nodeList) // For MATLAB { _blockUpdater = blockUpdater; INode[] nodes = new INode[nodeList.length]; System.arraycopy(nodeList, 0, nodes, 0, nodeList.length); _blockUpdater.attachNodes(nodes); } @Override public void update() { _blockUpdater.update(); } public INode[] getNodeList() { return _blockUpdater.getNodeList(); } public IBlockUpdater getBlockUpdater() { return _blockUpdater; } @Override public IScheduleEntry copy(Map<Node,Node> old2newObjs) { return copy(old2newObjs, false); } @Override public IScheduleEntry copyToRoot(Map<Node,Node> old2newObjs) { return copy(old2newObjs, true); } public IScheduleEntry copy(Map<Node,Node> old2newObjs, boolean copyToRoot) { INode[] oldNodeList = _blockUpdater.getNodeList(); INode[] newNodeList = new INode[oldNodeList.length]; for (int i = 0; i < oldNodeList.length; i++) newNodeList[i] = old2newObjs.get(oldNodeList[i]); return new BlockScheduleEntry(_blockUpdater.create(), newNodeList); } @Override public Iterable<Port> getPorts() { ArrayList<Port> ports = new ArrayList<Port>(); // For all nodes in the block for (INode node : _blockUpdater.getNodeList()) { // Add each port of this node to the list. for (int index = 0, end = node.getSiblingCount(); index < end; index++) { ports.add(new Port(node,index)); } } return ports; } }
27.547826
102
0.693813
009de216694425c901a9f3c542c37a5d4c51c6d5
5,621
package org.firstinspires.ftc.teamcode.test; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.subsystem.Arm; import org.firstinspires.ftc.teamcode.subsystem.DriveMecanumWW; import org.firstinspires.ftc.teamcode.subsystem.LandingLiftLeadScrew; @TeleOp(name="Lift Performance", group="test") @Disabled public class LiftPerformance extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); //private IMU imu; private LandingLiftLeadScrew lift; //private Arm arm; //private Servo intake = hardwareMap.get(Servo.class, "intake"); @Override public void runOpMode() { //initialization //imu = new IMU(telemetry, hardwareMap); lift = new LandingLiftLeadScrew(telemetry, hardwareMap); //arm = new Arm(hardwareMap, telemetry); //arm.v_position = 0; // Send telemetry message to signify robot waiting; telemetry.addData("lift ", "position %5.2f ", lift.position); telemetry.update(); // Set up our telemetry dashboard //imu.composeTelemetry(); // Wait for the game to start (driver presses PLAY) waitForStart(); //boolean field = false; //regular run by default while (opModeIsActive() ) { //---------------------------------------------------------------------------- // y: up // a: down // controlled by min and max allowed position: // dpad_up up all the way // dpad_downa down all the way // x up a little bit // b down a little bit //dpad free play up and down if (gamepad1.y) { lift.reset(1.0); } else if (gamepad1.a) { lift.reset(-1.0); } /*else if (gamepad1.x) { //a little up lift.up(); } else if (gamepad1.b) { //a little down lift.down(); } else if (gamepad1.dpad_up) { //a little up if (!GAMEPAD1_Y) { //first time press y button lift.up(12.0); GAMEPAD1_Y = true; } // else holding y, do nothing } else if (gamepad1.dpad_down) { //a little down if (!GAMEPAD1_A) { //first time press y button lift.down(12.0); GAMEPAD1_A = true; } }*/ else { lift.stop(); } telemetry.addData("lift position: ", lift.position); /* //---------------------------------------------------------------------------- //gamepad2 lift arm up and down, expand (out) and shrink (in) if (gamepad2.left_stick_y < -0.1) arm.move(20, gamepad2.left_stick_y); //up else if (gamepad2.left_stick_y > 0.1) arm.move(-20, gamepad2.left_stick_y); //down else if (gamepad2.left_trigger > 0.2) arm.shrink(); else if (gamepad2.right_trigger > 0.2) arm.expand(); else if (gamepad2.x) { //some quick action //shink all the way //arm.shrink(); arm.up(2.0, 1270); // all the up arm.expand(2.0,-5722); arm.h_pivot.setPosition(0.0); //sleep(1500); } else if (gamepad2.y) { // "I dont actually know what this is supposed to do?" - Brian /* arm.shrink(); sleep(500); arm.down(2.0, 33600); sleep(500); arm.h_pivot.setPosition(0.0); sleep(500); // expand all the way //arm.expand(); //sleep(1500); } else { //arm.v_hold(); //arm.v_pivot.setTargetPosition(arm.v_pivot.getCurrentPosition()); arm.cascade.setTargetPosition(arm.cascade.getCurrentPosition()); } //claw if (gamepad2.a){ arm.open(); sleep(400); telemetry.addData("claw open: ", arm.claw.getPower()); arm.hold(); } else if (gamepad2.b){ arm.closed(); sleep(400); telemetry.addData("claw close: ", arm.claw.getPower()); arm.hold(); } else{ arm.hold(); telemetry.addData("claw hold: ", arm.claw.getPower()); } if (gamepad2.right_stick_x < -.2 ) { arm.right(); sleep(100); } else if(gamepad2.right_stick_x >.2) { arm.left(); sleep(100); } //combine action //if (gamepad2.dpad_up) arm.gold("CENTER", 20.0); // arm.up(3.0, 350); //else if (gamepad2.dpad_down) arm.down(3.0); telemetry.addData("arm v position: ", arm.v_position); telemetry.addData("arm h position: ", arm.h_position); telemetry.addData("arm out position: ", arm.out_position); */ telemetry.update(); } } }
34.697531
94
0.484611
88477cfe69745d29694597537f1b6df895436a7e
1,031
final class Solution { private static boolean isKeithNumber(final int n) { final String digits = String.valueOf(n); final int len = digits.length(); final java.util.Queue<Integer> terms = new java.util.ArrayDeque<>(len); int acc = 0; for (int i = 0; i != len; ++i) { final int d = digits.charAt(i) - '0'; if (d >= n) return d == n; acc += d; terms.add(d); } while (acc < n) { final int front = terms.remove(); terms.add(acc); acc += acc - front; } return acc == n; } public static void main(final String[] args) { try (final java.util.Scanner sc = new java.util.Scanner(System.in)) { for (int t = sc.nextInt(); t > 0; --t) System.out.println(isKeithNumber(sc.nextInt()) ? 1 : 0); } } private Solution() { } // the Solution class should not be instantated }
28.638889
79
0.483996
72796f006767c80246429a6c1b2e448d235a7bd0
441
package com.antheminc.oss.nimbus.test.exclude.core; import com.antheminc.oss.nimbus.domain.defn.Domain; import com.antheminc.oss.nimbus.domain.defn.Domain.ListenerType; import com.antheminc.oss.nimbus.domain.defn.Repo; import lombok.Data; @Domain(value = "sampleExcludeEntity", includeListeners = { ListenerType.websocket }) @Repo(value = Repo.Database.rep_none, cache = Repo.Cache.rep_device) @Data public class SampleExcludeEntity { }
29.4
85
0.798186
9f956875b97cb1abf96cc094c17ec7a8d066b61b
1,683
package com.troycardozo.lib.config; import java.io.File; import java.io.IOException; import com.troycardozo.lib.App; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; public class YmlConfig { final App plugin; final String filename; private FileConfiguration config = null; private File configFile = null; public YmlConfig(App instance, String name) { plugin = instance; filename = name; } public <T> void set(String path, T val) { getConfig().set(path, val); saveConfig(); } public void loadConfig() { getConfig().options().copyDefaults(true); saveConfig(); } public FileConfiguration getConfig() { if (config == null) { reloadConfig(); } return config; } public void reloadConfig() { if (configFile == null) { configFile = new File(plugin.getDataFolder(), filename); } if (!configFile.exists()) { configFile.getParentFile().mkdirs(); plugin.saveResource(filename, false); } config = new YamlConfiguration(); try { config.load(configFile); } catch (IOException | InvalidConfigurationException e) { e.printStackTrace(); } } public void saveConfig() { if ((config == null) || (configFile == null)) { return; } try { config.save(configFile); } catch (IOException e) { e.printStackTrace(); } } }
22.743243
68
0.588235
375706058a900dd7dcf49cf13cd275d24016178c
2,769
package com.token.jwt.jwt.security; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.fasterxml.jackson.databind.ObjectMapper; import com.token.jwt.jwt.data.UserDetailsData; import com.token.jwt.jwt.model.UserModel; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { public static final int TOKEN_EXPIRATION = 600_000; public static final String TOKEN_PASSWORD = "7b91c5d9-21c1-430a-8756-9bd1c5207fca"; //Por segurança deve está em um arquivo de configuração. private final AuthenticationManager authenticationManager; public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { UserModel user = new ObjectMapper().readValue(request.getInputStream(), UserModel.class); return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken( user.getLogin(), user.getPassword(), new ArrayList<>() )); } catch (IOException e) { throw new RuntimeException("Falha ao autenticar usuario", e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { UserDetailsData userData = (UserDetailsData) authResult.getPrincipal(); String token = JWT.create() .withSubject(userData.getUsername()) .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION)) .sign(Algorithm.HMAC512(TOKEN_PASSWORD)); response.getWriter().write(token); response.getWriter().flush(); } }
41.328358
144
0.710365
1a5684ed713875a0e2a5648e07470cff7f4255da
1,907
package cn.hutool.poi.excel; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import cn.hutool.core.util.StrUtil; import cn.hutool.poi.excel.cell.CellEditor; import cn.hutool.poi.excel.cell.CellUtil; /** * Excel中的行{@link Row}封装工具类 * * @author looly * @since 4.0.7 */ public class RowUtil { /** * 获取已有行或创建新行 * * @param sheet Excel表 * @param rowIndex 行号 * @return {@link Row} * @since 4.0.2 */ public static Row getOrCreateRow(Sheet sheet, int rowIndex) { Row row = sheet.getRow(rowIndex); if (null == row) { row = sheet.createRow(rowIndex); } return row; } /** * 读取一行 * * @param row 行 * @param cellEditor 单元格编辑器 * @return 单元格值列表 */ public static List<Object> readRow(Row row, CellEditor cellEditor) { if (null == row) { return new ArrayList<>(0); } final short length = row.getLastCellNum(); if (length < 0) { return new ArrayList<>(0); } final List<Object> cellValues = new ArrayList<>(length); Object cellValue; boolean isAllNull = true; for (short i = 0; i < length; i++) { cellValue = CellUtil.getCellValue(row.getCell(i), cellEditor); isAllNull &= StrUtil.isEmptyIfStr(cellValue); cellValues.add(cellValue); } if (isAllNull) { // 如果每个元素都为空,则定义为空行 return new ArrayList<>(0); } return cellValues; } /** * 写一行数据 * * @param row 行 * @param rowData 一行的数据 * @param styleSet 单元格样式集,包括日期等样式 * @param isHeader 是否为标题行 */ public static void writeRow(Row row, Iterable<?> rowData, StyleSet styleSet, boolean isHeader) { int i = 0; Cell cell; for (Object value : rowData) { cell = row.createCell(i); CellUtil.setCellValue(cell, value, styleSet, isHeader); i++; } } }
22.174419
98
0.631883
dceebe8fbf9f6aa4df86c23e1a4e736838ea6bc4
1,607
package org.bluedb.disk.segment; import java.io.Serializable; import java.nio.file.Path; import java.util.List; import org.bluedb.api.keys.BlueKey; import org.bluedb.disk.segment.path.SegmentPathManager; import org.bluedb.disk.segment.path.SegmentSizeConfiguration; public abstract class ReadableSegmentManager<T extends Serializable> { protected final SegmentPathManager pathManager; public abstract ReadableSegment<T> getFirstSegment(BlueKey key); public abstract ReadableSegment<T> getSegment(long groupingNumber); public abstract List<? extends ReadableSegment<T>> getAllExistingSegments(); public abstract List<? extends ReadableSegment<T>> getExistingSegments(Range range); public ReadableSegmentManager(Path collectionPath, SegmentSizeConfiguration sizeConfig) { this.pathManager = createSegmentPathManager(sizeConfig, collectionPath); } public Range getSegmentRange(long groupingValue) { return Range.forValueAndRangeSize(groupingValue, getSegmentSize()); } public SegmentPathManager getPathManager() { return pathManager; } public Range toRange(Path path) { String filename = path.toFile().getName(); long rangeStart = Long.valueOf(filename) * getSegmentSize(); Range range = new Range(rangeStart, rangeStart + getSegmentSize() - 1); return range; } public long getSegmentSize() { return pathManager.getSegmentSize(); } protected static SegmentPathManager createSegmentPathManager(SegmentSizeConfiguration sizeConfig, Path collectionPath) { return new SegmentPathManager(collectionPath, sizeConfig); } }
33.479167
122
0.779714
c758f1e86b23655754dc9de4487d18e116ff0e86
3,370
/* * traQ v3 * traQ v3 API * * The version of the OpenAPI document: 3.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.github.motoki317.traq4j.api; import com.github.motoki317.traq4j.ApiException; import java.io.File; import com.github.motoki317.traq4j.model.FileInfo; import org.threeten.bp.OffsetDateTime; import com.github.motoki317.traq4j.model.ThumbnailType; import java.util.UUID; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for FileApi */ @Ignore public class FileApiTest { private final FileApi api = new FileApi(); /** * ファイルを削除 * * 指定したファイルを削除します。 指定したファイルの削除権限が必要です。 * * @throws ApiException * if the Api call fails */ @Test public void deleteFileTest() throws ApiException { UUID fileId = null; api.deleteFile(fileId); // TODO: test validations } /** * ファイルをダウンロード * * 指定したファイル本体を取得します。 指定したファイルへのアクセス権限が必要です。 * * @throws ApiException * if the Api call fails */ @Test public void getFileTest() throws ApiException { UUID fileId = null; Integer dl = null; File response = api.getFile(fileId, dl); // TODO: test validations } /** * ファイルメタを取得 * * 指定したファイルのメタ情報を取得します。 指定したファイルへのアクセス権限が必要です。 * * @throws ApiException * if the Api call fails */ @Test public void getFileMetaTest() throws ApiException { UUID fileId = null; FileInfo response = api.getFileMeta(fileId); // TODO: test validations } /** * ファイルメタのリストを取得 * * 指定したクエリでファイルメタのリストを取得します。 クエリパラメータ&#x60;channelId&#x60;, &#x60;mine&#x60;の少なくともいずれかが必須です。 * * @throws ApiException * if the Api call fails */ @Test public void getFilesTest() throws ApiException { UUID channelId = null; Integer limit = null; Integer offset = null; OffsetDateTime since = null; OffsetDateTime until = null; Boolean inclusive = null; String order = null; Boolean mine = null; List<FileInfo> response = api.getFiles(channelId, limit, offset, since, until, inclusive, order, mine); // TODO: test validations } /** * サムネイル画像を取得 * * 指定したファイルのサムネイル画像を取得します。 指定したファイルへのアクセス権限が必要です。 * * @throws ApiException * if the Api call fails */ @Test public void getThumbnailImageTest() throws ApiException { UUID fileId = null; ThumbnailType type = null; File response = api.getThumbnailImage(fileId, type); // TODO: test validations } /** * ファイルをアップロード * * 指定したチャンネルにファイルをアップロードします。 アーカイブされているチャンネルにはアップロード出来ません。 * * @throws ApiException * if the Api call fails */ @Test public void postFileTest() throws ApiException { File file = null; String channelId = null; FileInfo response = api.postFile(file, channelId); // TODO: test validations } }
23.082192
111
0.607715
7be03da487cca0c59ab0f7f9bc664be18a9e9598
62
package com.example.datastructs; public class BinaryTree { }
12.4
32
0.790323
e88d91c9db63c0641b1031d78886a5108dd93a47
36,386
package jetbrains.mps.lang.structure.behavior; /*Generated by MPS */ import jetbrains.mps.core.aspects.behaviour.BaseBHDescriptor; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.core.aspects.behaviour.api.SMethod; import org.jetbrains.mps.openapi.model.SModel; import jetbrains.mps.core.aspects.behaviour.SMethodBuilder; import jetbrains.mps.core.aspects.behaviour.SJavaCompoundTypeImpl; import jetbrains.mps.core.aspects.behaviour.AccessPrivileges; import jetbrains.mps.smodel.LanguageAspect; import java.util.List; import org.jetbrains.mps.openapi.model.SNode; import org.jetbrains.mps.openapi.module.SModule; import java.util.Set; import jetbrains.mps.baseLanguage.closures.runtime._FunctionTypes; import jetbrains.mps.util.Pair; import java.util.Arrays; import org.jetbrains.annotations.NotNull; import jetbrains.mps.smodel.Language; import jetbrains.mps.kernel.model.SModelUtil; import java.util.ArrayList; import org.jetbrains.mps.openapi.module.SModuleId; import jetbrains.mps.project.ModuleId; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SModelOperations; import jetbrains.mps.internal.collections.runtime.ListSequence; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.internal.collections.runtime.SetSequence; import java.util.HashSet; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.lang.behavior.behavior.ConceptMethodDeclaration__BehaviorDescriptor; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SEnumOperations; import jetbrains.mps.smodel.SNodePointer; import java.util.LinkedHashSet; import jetbrains.mps.smodel.adapter.MetaAdapterByDeclaration; import java.util.Objects; import jetbrains.mps.core.aspects.behaviour.api.SConstructor; import org.jetbrains.annotations.Nullable; import jetbrains.mps.core.aspects.behaviour.api.BHMethodNotFoundException; import org.jetbrains.mps.openapi.language.SProperty; import org.jetbrains.mps.openapi.language.SInterfaceConcept; import org.jetbrains.mps.openapi.language.SConcept; import org.jetbrains.mps.openapi.language.SContainmentLink; import org.jetbrains.mps.openapi.language.SReferenceLink; public final class AbstractConceptDeclaration__BehaviorDescriptor extends BaseBHDescriptor { private static final SAbstractConcept CONCEPT = MetaAdapterFactory.getConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, "jetbrains.mps.lang.structure.structure.AbstractConceptDeclaration"); /*package*/ static final SMethod<SModel> getAspectModel_id7g4OXB0yli3 = new SMethodBuilder<SModel>(new SJavaCompoundTypeImpl((Class<SModel>) ((Class) Object.class))).name("getAspectModel").modifiers(0, AccessPrivileges.PRIVATE).concept(CONCEPT).id("7g4OXB0yli3").build(SMethodBuilder.createJavaParameter(LanguageAspect.class, "")); public static final SMethod<List<SNode>> findConceptAspectCollection_id1n18fON7w20 = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("findConceptAspectCollection").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("1n18fON7w20").build(SMethodBuilder.createJavaParameter(LanguageAspect.class, "")); public static final SMethod<SNode> findConceptAspect_id7g4OXB0ykew = new SMethodBuilder<SNode>(new SJavaCompoundTypeImpl((Class<SNode>) ((Class) Object.class))).name("findConceptAspect").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("7g4OXB0ykew").build(SMethodBuilder.createJavaParameter(LanguageAspect.class, "")); public static final SMethod<Void> setLanguageIdFromModule_id7NTi8jM8SJY = new SMethodBuilder<Void>(new SJavaCompoundTypeImpl(Void.class)).name("setLanguageIdFromModule").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("7NTi8jM8SJY").build(SMethodBuilder.createJavaParameter(SModule.class, "")); public static final SMethod<SNode> findConceptAspect_id7g4OXB0yku$ = new SMethodBuilder<SNode>(new SJavaCompoundTypeImpl((Class<SNode>) ((Class) Object.class))).name("findConceptAspect").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("7g4OXB0yku$").build(SMethodBuilder.createJavaParameter((Class<SModel>) ((Class) Object.class), "")); public static final SMethod<Void> findConceptAspectCollection_id7g4OXB0yl26 = new SMethodBuilder<Void>(new SJavaCompoundTypeImpl(Void.class)).name("findConceptAspectCollection").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("7g4OXB0yl26").build(SMethodBuilder.createJavaParameter((Class<SModel>) ((Class) Object.class), ""), SMethodBuilder.createJavaParameter((Class<List<SNode>>) ((Class) Object.class), "")); public static final SMethod<Iterable<SNode>> findConceptAspects_id4G9PD8$NvPM = new SMethodBuilder<Iterable<SNode>>(new SJavaCompoundTypeImpl((Class<Iterable<SNode>>) ((Class) Object.class))).name("findConceptAspects").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("4G9PD8$NvPM").build(SMethodBuilder.createJavaParameter((Class<SModel>) ((Class) Object.class), "")); public static final SMethod<String> getPresentation_id280s3ZNTXNS = new SMethodBuilder<String>(new SJavaCompoundTypeImpl(String.class)).name("getPresentation").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("280s3ZNTXNS").build(); public static final SMethod<List<SNode>> getAvailableConceptMethods_idhEwILGo = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getAvailableConceptMethods").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILGo").build(SMethodBuilder.createJavaParameter((Class<SNode>) ((Class) Object.class), "")); public static final SMethod<Iterable<SNode>> getVisibleConceptMethods_idwrIPXhfIPX = new SMethodBuilder<Iterable<SNode>>(new SJavaCompoundTypeImpl((Class<Iterable<SNode>>) ((Class) Object.class))).name("getVisibleConceptMethods").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("wrIPXhfIPX").build(SMethodBuilder.createJavaParameter((Class<SNode>) ((Class) Object.class), "")); public static final SMethod<List<SNode>> getVirtualConceptMethods_idhEwILHM = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getVirtualConceptMethods").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILHM").build(); public static final SMethod<List<SNode>> getNotImplementedConceptMethods_idhEwILIz = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getNotImplementedConceptMethods").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILIz").build(); public static final SMethod<List<SNode>> getLinkDeclarations_idhEwILKK = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getLinkDeclarations").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILKK").build(); public static final SMethod<List<SNode>> getReferenceLinkDeclarations_idhEwILL0 = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getReferenceLinkDeclarations").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILL0").build(); public static final SMethod<List<SNode>> getAggregationLinkDeclarations_idhEwILLp = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getAggregationLinkDeclarations").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILLp").build(); public static final SMethod<List<SNode>> getPropertyDeclarations_idhEwILLM = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getPropertyDeclarations").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hEwILLM").build(); public static final SMethod<Boolean> isSubconceptOf_id73yVtVlWOga = new SMethodBuilder<Boolean>(new SJavaCompoundTypeImpl(Boolean.TYPE)).name("isSubconceptOf").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("73yVtVlWOga").build(SMethodBuilder.createJavaParameter((Class<SNode>) ((Class) Object.class), "")); public static final SMethod<Boolean> isSubconceptOf_id4UTtJHK9fEJ = new SMethodBuilder<Boolean>(new SJavaCompoundTypeImpl(Boolean.TYPE)).name("isSubconceptOf").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("4UTtJHK9fEJ").build(SMethodBuilder.createJavaParameter((Class<SAbstractConcept>) ((Class) Object.class), "")); public static final SMethod<List<SNode>> getImmediateSuperconcepts_idhMuxyK2 = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("getImmediateSuperconcepts").modifiers(12, AccessPrivileges.PUBLIC).concept(CONCEPT).id("hMuxyK2").build(); public static final SMethod<Iterable<SNode>> getAllSuperConcepts_id2A8AB0rAWpG = new SMethodBuilder<Iterable<SNode>>(new SJavaCompoundTypeImpl((Class<Iterable<SNode>>) ((Class) Object.class))).name("getAllSuperConcepts").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("2A8AB0rAWpG").build(SMethodBuilder.createJavaParameter(Boolean.TYPE, "")); /*package*/ static final SMethod<Void> collectSuperConcepts_id2A8AB0rB3NH = new SMethodBuilder<Void>(new SJavaCompoundTypeImpl(Void.class)).name("collectSuperConcepts").modifiers(1, AccessPrivileges.PRIVATE).concept(CONCEPT).id("2A8AB0rB3NH").build(SMethodBuilder.createJavaParameter((Class<SNode>) ((Class) Object.class), ""), SMethodBuilder.createJavaParameter((Class<Set<SNode>>) ((Class) Object.class), "")); public static final SMethod<SNode> computeInHierarchy_id3CiBrVcn5fe = new SMethodBuilder<SNode>(new SJavaCompoundTypeImpl((Class<SNode>) ((Class) Object.class))).name("computeInHierarchy").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("3CiBrVcn5fe").build(SMethodBuilder.createJavaParameter((Class<_FunctionTypes._return_P1_E0<? extends SNode, ? super SNode>>) ((Class) Object.class), "")); public static final SMethod<Pair<Set<SNode>, Set<SNode>>> getInLanguageAndNotInLanguageAncestors_id54xSEBmK0MK = new SMethodBuilder<Pair<Set<SNode>, Set<SNode>>>(new SJavaCompoundTypeImpl(Pair.class)).name("getInLanguageAndNotInLanguageAncestors").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("54xSEBmK0MK").build(); public static final SMethod<Boolean> is_id4MKjpUYmGW0 = new SMethodBuilder<Boolean>(new SJavaCompoundTypeImpl(Boolean.TYPE)).name("is").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("4MKjpUYmGW0").build(SMethodBuilder.createJavaParameter(SAbstractConcept.class, "")); private static final List<SMethod<?>> BH_METHODS = Arrays.<SMethod<?>>asList(getAspectModel_id7g4OXB0yli3, findConceptAspectCollection_id1n18fON7w20, findConceptAspect_id7g4OXB0ykew, setLanguageIdFromModule_id7NTi8jM8SJY, findConceptAspect_id7g4OXB0yku$, findConceptAspectCollection_id7g4OXB0yl26, findConceptAspects_id4G9PD8$NvPM, getPresentation_id280s3ZNTXNS, getAvailableConceptMethods_idhEwILGo, getVisibleConceptMethods_idwrIPXhfIPX, getVirtualConceptMethods_idhEwILHM, getNotImplementedConceptMethods_idhEwILIz, getLinkDeclarations_idhEwILKK, getReferenceLinkDeclarations_idhEwILL0, getAggregationLinkDeclarations_idhEwILLp, getPropertyDeclarations_idhEwILLM, isSubconceptOf_id73yVtVlWOga, isSubconceptOf_id4UTtJHK9fEJ, getImmediateSuperconcepts_idhMuxyK2, getAllSuperConcepts_id2A8AB0rAWpG, collectSuperConcepts_id2A8AB0rB3NH, computeInHierarchy_id3CiBrVcn5fe, getInLanguageAndNotInLanguageAncestors_id54xSEBmK0MK, is_id4MKjpUYmGW0); private static void ___init___(@NotNull SNode __thisNode__) { } @Deprecated(since = "3.3", forRemoval = true) /*package*/ static SModel getAspectModel_id7g4OXB0yli3(@NotNull SNode __thisNode__, LanguageAspect aspect) { // [MM] this usage of LanguageAspect is reviewed Language language = SModelUtil.getDeclaringLanguage(__thisNode__); if (language == null) { return null; } SModel md = aspect.get(language); if (md == null) { return null; } return md; } @Deprecated(since = "3.3", forRemoval = true) /*package*/ static List<SNode> findConceptAspectCollection_id1n18fON7w20(@NotNull SNode __thisNode__, LanguageAspect aspect) { // [MM] this usage of LanguageAspect is reviewed List<SNode> result = new ArrayList<SNode>(); SModel model = AbstractConceptDeclaration__BehaviorDescriptor.getAspectModel_id7g4OXB0yli3.invoke(__thisNode__, aspect); AbstractConceptDeclaration__BehaviorDescriptor.findConceptAspectCollection_id7g4OXB0yl26.invoke(__thisNode__, model, result); return result; } @Deprecated(since = "3.3", forRemoval = true) /*package*/ static SNode findConceptAspect_id7g4OXB0ykew(@NotNull SNode __thisNode__, LanguageAspect aspect) { SModel model = AbstractConceptDeclaration__BehaviorDescriptor.getAspectModel_id7g4OXB0yli3.invoke(__thisNode__, aspect); return AbstractConceptDeclaration__BehaviorDescriptor.findConceptAspect_id7g4OXB0yku$.invoke(__thisNode__, model); } /*package*/ static void setLanguageIdFromModule_id7NTi8jM8SJY(@NotNull SNode __thisNode__, SModule m) { SModuleId mid = m.getModuleId(); assert mid instanceof ModuleId.Regular; SPropertyOperations.assign(__thisNode__, PROPS.languageId$79NI, ((ModuleId.Regular) mid).getUUID().toString()); } /*package*/ static SNode findConceptAspect_id7g4OXB0yku$(@NotNull SNode __thisNode__, SModel model) { if (model == null) { return null; } for (SNode aspectConcept : SModelOperations.roots(model, CONCEPTS.IConceptAspect$Z3)) { if ((IConceptAspect__BehaviorDescriptor.getBaseConcept_id2hxg_BDjKM8.invoke(aspectConcept) != null) && IConceptAspect__BehaviorDescriptor.getBaseConcept_id2hxg_BDjKM8.invoke(aspectConcept) == __thisNode__) { return aspectConcept; } } return null; } @Deprecated(since = "3.3", forRemoval = true) /*package*/ static void findConceptAspectCollection_id7g4OXB0yl26(@NotNull SNode __thisNode__, SModel model, List<SNode> collection) { if (model == null) { return; } for (SNode aspectConcept : SModelOperations.roots(model, CONCEPTS.IConceptAspect$Z3)) { if (ListSequence.fromList(IConceptAspect__BehaviorDescriptor.getBaseConceptCollection_id4$$3zrO3UBG.invoke(aspectConcept)).contains(__thisNode__)) { ListSequence.fromList(collection).addElement(aspectConcept); } } } /*package*/ static Iterable<SNode> findConceptAspects_id4G9PD8$NvPM(@NotNull final SNode __thisNode__, @NotNull SModel model) { return ListSequence.fromList(SModelOperations.roots(model, CONCEPTS.IConceptAspect$Z3)).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return ListSequence.fromList(IConceptAspect__BehaviorDescriptor.getBaseConceptCollection_id4$$3zrO3UBG.invoke(it)).contains(__thisNode__); } }); } /*package*/ static String getPresentation_id280s3ZNTXNS(@NotNull SNode __thisNode__) { return (isNotEmptyString(SPropertyOperations.getString(__thisNode__, PROPS.conceptAlias$OL_L)) ? SPropertyOperations.getString(__thisNode__, PROPS.conceptAlias$OL_L) : SPropertyOperations.getString(__thisNode__, PROPS.name$MnvL)); } @Deprecated /*package*/ static List<SNode> getAvailableConceptMethods_idhEwILGo(@NotNull SNode __thisNode__, SNode context) { return Sequence.fromIterable(AbstractConceptDeclaration__BehaviorDescriptor.getVisibleConceptMethods_idwrIPXhfIPX.invoke(__thisNode__, context)).toListSequence(); } /*package*/ static Iterable<SNode> getVisibleConceptMethods_idwrIPXhfIPX(@NotNull SNode __thisNode__, SNode context) { Set<SNode> methods = SetSequence.fromSet(new HashSet<SNode>()); if (__thisNode__ == null) { return methods; } SNode contextBehaviour = SNodeOperations.getNodeAncestor(context, CONCEPTS.ConceptBehavior$2, true, false); List<SNode> allSupers = Sequence.fromIterable(AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(__thisNode__, ((boolean) true))).toListSequence(); ListSequence.fromList(allSupers).addElement(SNodeOperations.getNode("r:00000000-0000-4000-0000-011c89590288(jetbrains.mps.lang.core.structure)", "1133920641626")); for (SNode concept : allSupers) { SNode behaviour = SNodeOperations.cast(AbstractConceptDeclaration__BehaviorDescriptor.findConceptAspect_id7g4OXB0ykew.invoke(concept, LanguageAspect.BEHAVIOR), CONCEPTS.ConceptBehavior$2); if (behaviour != null) { for (SNode method : SLinkOperations.getChildren(behaviour, LINKS.method$w_in)) { if (SLinkOperations.getTarget(method, LINKS.overriddenMethod$quKH) != null) { continue; } if (SLinkOperations.getTarget(method, LINKS.visibility$Yyua) == null) { if (SNodeOperations.getModel(contextBehaviour) == SNodeOperations.getModel(method)) { SetSequence.fromSet(methods).addElement(method); } } if (SNodeOperations.isInstanceOf(SLinkOperations.getTarget(method, LINKS.visibility$Yyua), CONCEPTS.PrivateVisibility$l0)) { if (SNodeOperations.getNodeAncestor(method, CONCEPTS.ConceptBehavior$2, true, false) == contextBehaviour) { SetSequence.fromSet(methods).addElement(method); } } if (SNodeOperations.isInstanceOf(SLinkOperations.getTarget(method, LINKS.visibility$Yyua), CONCEPTS.PublicVisibility$R0)) { SetSequence.fromSet(methods).addElement(method); } if (SNodeOperations.isInstanceOf(SLinkOperations.getTarget(method, LINKS.visibility$Yyua), CONCEPTS.ProtectedVisibility$hr)) { if (Sequence.fromIterable(AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(SLinkOperations.getTarget(contextBehaviour, LINKS.concept$u6dL), ((boolean) true))).contains(SLinkOperations.getTarget(SNodeOperations.getNodeAncestor(method, CONCEPTS.ConceptBehavior$2, true, false), LINKS.concept$u6dL))) { SetSequence.fromSet(methods).addElement(method); } } } } } return methods; } /*package*/ static List<SNode> getVirtualConceptMethods_idhEwILHM(@NotNull SNode __thisNode__) { List<SNode> methods = new ArrayList<SNode>(); for (SNode concept : AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(__thisNode__, ((boolean) false))) { SNode behaviour = SNodeOperations.cast(AbstractConceptDeclaration__BehaviorDescriptor.findConceptAspect_id7g4OXB0ykew.invoke(concept, LanguageAspect.BEHAVIOR), CONCEPTS.ConceptBehavior$2); if (behaviour != null) { for (SNode method : SLinkOperations.getChildren(behaviour, LINKS.method$w_in)) { if ((boolean) ConceptMethodDeclaration__BehaviorDescriptor.isVirtual_id6WSEafdhbZX.invoke(method)) { ListSequence.fromList(methods).addElement(method); } } } } return methods; } /*package*/ static List<SNode> getNotImplementedConceptMethods_idhEwILIz(@NotNull SNode __thisNode__) { List<SNode> abstractMethods = new ArrayList<SNode>(); List<SNode> implementedMethods = new ArrayList<SNode>(); List<SNode> concepts = ListSequence.fromListWithValues(new ArrayList<SNode>(), AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(__thisNode__, ((boolean) false))); ListSequence.fromList(concepts).addElement(__thisNode__); for (SNode concept : concepts) { SNode behavior = SNodeOperations.cast(AbstractConceptDeclaration__BehaviorDescriptor.findConceptAspect_id7g4OXB0ykew.invoke(concept, LanguageAspect.BEHAVIOR), CONCEPTS.ConceptBehavior$2); for (SNode method : SLinkOperations.getChildren(behavior, LINKS.method$w_in)) { if (SPropertyOperations.getBoolean(method, PROPS.isAbstract$qvtK)) { ListSequence.fromList(abstractMethods).addElement(method); } if (SLinkOperations.getTarget(method, LINKS.overriddenMethod$quKH) != null && !(SPropertyOperations.getBoolean(method, PROPS.isAbstract$qvtK))) { ListSequence.fromList(implementedMethods).addElement(SLinkOperations.getTarget(method, LINKS.overriddenMethod$quKH)); } } } ListSequence.fromList(abstractMethods).removeSequence(ListSequence.fromList(implementedMethods)); return abstractMethods; } /*package*/ static List<SNode> getLinkDeclarations_idhEwILKK(@NotNull SNode __thisNode__) { // aka ConceptAndSuperConceptsCache.getLinkDeclarationsExcludingOverridden List<SNode> allLinks = Sequence.fromIterable(SLinkOperations.collectMany(AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(__thisNode__, ((boolean) true)), LINKS.linkDeclaration$YU1f)).distinct().toListSequence(); final Set<SNode> overridden = SetSequence.fromSet(new HashSet<SNode>()); // here I imply concepts are sorted from top to bottom, i.e. this concept coming first, its immediate superconcepts next and so on up to BaseConcept. // therefore, the moment we get to a link declaration that has been overridden in a subconcept, we expect it to be recorded in the 'overridden' set. // // Two scenarios in mind: given (C1.r1), (C2.r2) and (C3.r3), C3 extends C2 extends C1; first scenario is transitive, r2 specializes r1, r3 specializes r2; // second when both r2 and r3 specialize r1. For C3, there'd be 1 link declaration in the first scenario, namely {r3}, while for the second case it would be {r3,r2} ListSequence.fromList(allLinks).removeWhere(new IWhereFilter<SNode>() { public boolean accept(SNode it) { if ((SLinkOperations.getTarget(it, LINKS.specializedLink$7ZCN) != null)) { SetSequence.fromSet(overridden).addElement(SLinkOperations.getTarget(it, LINKS.specializedLink$7ZCN)); } return SetSequence.fromSet(overridden).contains(it); } }); return allLinks; } /*package*/ static List<SNode> getReferenceLinkDeclarations_idhEwILL0(@NotNull SNode __thisNode__) { List<SNode> links = AbstractConceptDeclaration__BehaviorDescriptor.getLinkDeclarations_idhEwILKK.invoke(__thisNode__); return ListSequence.fromList(links).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return SEnumOperations.isMember(SPropertyOperations.getEnum(it, PROPS.metaClass$PeKc), 0xfc6f4e95b8L); } }).toListSequence(); } /*package*/ static List<SNode> getAggregationLinkDeclarations_idhEwILLp(@NotNull SNode __thisNode__) { List<SNode> links = AbstractConceptDeclaration__BehaviorDescriptor.getLinkDeclarations_idhEwILKK.invoke(__thisNode__); return ListSequence.fromList(links).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return SEnumOperations.isMember(SPropertyOperations.getEnum(it, PROPS.metaClass$PeKc), 0xfc6f4e95b9L); } }).toListSequence(); } /*package*/ static List<SNode> getPropertyDeclarations_idhEwILLM(@NotNull SNode __thisNode__) { return Sequence.fromIterable(SLinkOperations.collectMany(AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(__thisNode__, ((boolean) true)), LINKS.propertyDeclaration$YUgg)).distinct().toListSequence(); } /*package*/ static boolean isSubconceptOf_id73yVtVlWOga(@NotNull SNode __thisNode__, SNode superconcept) { if (SNodeOperations.is(superconcept, new SNodePointer("r:00000000-0000-4000-0000-011c89590288(jetbrains.mps.lang.core.structure)", "1133920641626"))) { return true; } return Sequence.fromIterable(AbstractConceptDeclaration__BehaviorDescriptor.getAllSuperConcepts_id2A8AB0rAWpG.invoke(__thisNode__, ((boolean) true))).contains(superconcept); } /*package*/ static boolean isSubconceptOf_id4UTtJHK9fEJ(@NotNull SNode __thisNode__, SAbstractConcept superconcept) { // XXX perhaps, worth having alternative with node-ptr<AbstractConceptDeclaration>, but at the moment, // node.is() operation doesn't take anything but direct NodeIdentity if (CONCEPTS.BaseConcept$gP.equals(superconcept)) { return true; } if (superconcept == null) { return false; } Set<SNode> concepts = SetSequence.fromSet(new LinkedHashSet<SNode>()); SetSequence.fromSet(concepts).addElement(__thisNode__); AbstractConceptDeclaration__BehaviorDescriptor.collectSuperConcepts_id2A8AB0rB3NH.invokeSpecial(__thisNode__.getConcept(), __thisNode__, concepts); for (SNode c : SetSequence.fromSet(concepts)) { if (superconcept.equals(MetaAdapterByDeclaration.getConcept(c))) { return true; } } return false; } /*package*/ static Iterable<SNode> getAllSuperConcepts_id2A8AB0rAWpG(@NotNull SNode __thisNode__, boolean includeSelf) { Set<SNode> concepts = SetSequence.fromSet(new LinkedHashSet<SNode>()); if (includeSelf) { SetSequence.fromSet(concepts).addElement(__thisNode__); } AbstractConceptDeclaration__BehaviorDescriptor.collectSuperConcepts_id2A8AB0rB3NH.invokeSpecial(__thisNode__.getConcept(), __thisNode__, concepts); // getImmediateSuperconcepts for an interface declaration doesn't give BaseConcept, while it's necessary when we'd like to access BaseConcept properties and links // for a node with type of pure interface (e.g. DotExpression.operation:IOperation.virtualPackage) SetSequence.fromSet(concepts).addElement(SNodeOperations.getNode("r:00000000-0000-4000-0000-011c89590288(jetbrains.mps.lang.core.structure)", "1133920641626")); return concepts; } /*package*/ static void collectSuperConcepts_id2A8AB0rB3NH(@NotNull SAbstractConcept __thisConcept__, SNode concept, final Set<SNode> result) { List<SNode> seq = ListSequence.fromList(AbstractConceptDeclaration__BehaviorDescriptor.getImmediateSuperconcepts_idhMuxyK2.invoke(concept)).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return !(SetSequence.fromSet(result).contains(it)); } }).toListSequence(); SetSequence.fromSet(result).addSequence(ListSequence.fromList(seq)); for (SNode superConcept : ListSequence.fromList(seq)) { AbstractConceptDeclaration__BehaviorDescriptor.collectSuperConcepts_id2A8AB0rB3NH.invokeSpecial(__thisConcept__, superConcept, result); } } /*package*/ static SNode computeInHierarchy_id3CiBrVcn5fe(@NotNull SNode __thisNode__, _FunctionTypes._return_P1_E0<? extends SNode, ? super SNode> predicate) { // todo: comment method!, use generics SNode result = predicate.invoke(__thisNode__); if (result != null) { return result; } for (SNode superconcept : ListSequence.fromList(AbstractConceptDeclaration__BehaviorDescriptor.getImmediateSuperconcepts_idhMuxyK2.invoke(__thisNode__)).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return (it != null); } })) { SNode superconceptResult = AbstractConceptDeclaration__BehaviorDescriptor.computeInHierarchy_id3CiBrVcn5fe.invoke(superconcept, predicate); if (superconceptResult != null) { return superconceptResult; } } return null; } /*package*/ static Pair<Set<SNode>, Set<SNode>> getInLanguageAndNotInLanguageAncestors_id54xSEBmK0MK(@NotNull SNode __thisNode__) { // todo: use tuple Set<SNode> inLanguageAncestors = SetSequence.fromSet(new HashSet<SNode>()); Set<SNode> notInLanguageAncestors = SetSequence.fromSet(new HashSet<SNode>()); for (SNode superconcept : AbstractConceptDeclaration__BehaviorDescriptor.getImmediateSuperconcepts_idhMuxyK2.invoke(__thisNode__)) { if ((superconcept != null)) { if (SNodeOperations.getModel(superconcept) == SNodeOperations.getModel(__thisNode__)) { Pair<Set<SNode>, Set<SNode>> superconceptResult = AbstractConceptDeclaration__BehaviorDescriptor.getInLanguageAndNotInLanguageAncestors_id54xSEBmK0MK.invoke(superconcept); SetSequence.fromSet(inLanguageAncestors).addElement(superconcept); SetSequence.fromSet(inLanguageAncestors).addSequence(SetSequence.fromSet(superconceptResult.o1)); SetSequence.fromSet(notInLanguageAncestors).addSequence(SetSequence.fromSet(superconceptResult.o2)); } else { // other language SetSequence.fromSet(notInLanguageAncestors).addElement(superconcept); } } } return new Pair(inLanguageAncestors, notInLanguageAncestors); } /*package*/ static boolean is_id4MKjpUYmGW0(@NotNull SNode __thisNode__, SAbstractConcept concept) { return Objects.equals(MetaAdapterByDeclaration.getConcept(__thisNode__), concept); } /*package*/ AbstractConceptDeclaration__BehaviorDescriptor() { } @Override protected void initNode(@NotNull SNode node, @NotNull SConstructor constructor, @Nullable Object[] parameters) { ___init___(node); } @Override protected <T> T invokeSpecial0(@NotNull SNode node, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { case 0: return (T) ((SModel) getAspectModel_id7g4OXB0yli3(node, (LanguageAspect) parameters[0])); case 1: return (T) ((List<SNode>) findConceptAspectCollection_id1n18fON7w20(node, (LanguageAspect) parameters[0])); case 2: return (T) ((SNode) findConceptAspect_id7g4OXB0ykew(node, (LanguageAspect) parameters[0])); case 3: setLanguageIdFromModule_id7NTi8jM8SJY(node, (SModule) parameters[0]); return null; case 4: return (T) ((SNode) findConceptAspect_id7g4OXB0yku$(node, (SModel) parameters[0])); case 5: findConceptAspectCollection_id7g4OXB0yl26(node, (SModel) parameters[0], (List<SNode>) parameters[1]); return null; case 6: return (T) ((Iterable<SNode>) findConceptAspects_id4G9PD8$NvPM(node, (SModel) parameters[0])); case 7: return (T) ((String) getPresentation_id280s3ZNTXNS(node)); case 8: return (T) ((List<SNode>) getAvailableConceptMethods_idhEwILGo(node, (SNode) parameters[0])); case 9: return (T) ((Iterable<SNode>) getVisibleConceptMethods_idwrIPXhfIPX(node, (SNode) parameters[0])); case 10: return (T) ((List<SNode>) getVirtualConceptMethods_idhEwILHM(node)); case 11: return (T) ((List<SNode>) getNotImplementedConceptMethods_idhEwILIz(node)); case 12: return (T) ((List<SNode>) getLinkDeclarations_idhEwILKK(node)); case 13: return (T) ((List<SNode>) getReferenceLinkDeclarations_idhEwILL0(node)); case 14: return (T) ((List<SNode>) getAggregationLinkDeclarations_idhEwILLp(node)); case 15: return (T) ((List<SNode>) getPropertyDeclarations_idhEwILLM(node)); case 16: return (T) ((Boolean) isSubconceptOf_id73yVtVlWOga(node, (SNode) parameters[0])); case 17: return (T) ((Boolean) isSubconceptOf_id4UTtJHK9fEJ(node, (SAbstractConcept) parameters[0])); case 19: return (T) ((Iterable<SNode>) getAllSuperConcepts_id2A8AB0rAWpG(node, ((boolean) (Boolean) parameters[0]))); case 21: return (T) ((SNode) computeInHierarchy_id3CiBrVcn5fe(node, (_FunctionTypes._return_P1_E0<? extends SNode, ? super SNode>) parameters[0])); case 22: return (T) ((Pair<Set<SNode>, Set<SNode>>) getInLanguageAndNotInLanguageAncestors_id54xSEBmK0MK(node)); case 23: return (T) ((Boolean) is_id4MKjpUYmGW0(node, (SAbstractConcept) parameters[0])); default: throw new BHMethodNotFoundException(this, method); } } @Override protected <T> T invokeSpecial0(@NotNull SAbstractConcept concept, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { case 20: collectSuperConcepts_id2A8AB0rB3NH(concept, (SNode) parameters[0], (Set<SNode>) parameters[1]); return null; default: throw new BHMethodNotFoundException(this, method); } } @NotNull @Override public List<SMethod<?>> getDeclaredMethods() { return BH_METHODS; } @NotNull @Override public SAbstractConcept getConcept() { return CONCEPT; } private static boolean isNotEmptyString(String str) { return str != null && str.length() > 0; } private static final class PROPS { /*package*/ static final SProperty languageId$79NI = MetaAdapterFactory.getProperty(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0x7cf94884f2237423L, "languageId"); /*package*/ static final SProperty conceptAlias$OL_L = MetaAdapterFactory.getProperty(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0x46ab0ad5826c74caL, "conceptAlias"); /*package*/ static final SProperty name$MnvL = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"); /*package*/ static final SProperty isAbstract$qvtK = MetaAdapterFactory.getProperty(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d4348057eL, 0x11d43480582L, "isAbstract"); /*package*/ static final SProperty metaClass$PeKc = MetaAdapterFactory.getProperty(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979bd086aL, 0xf980556927L, "metaClass"); } private static final class CONCEPTS { /*package*/ static final SInterfaceConcept IConceptAspect$Z3 = MetaAdapterFactory.getInterfaceConcept(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x24614259e94f0c84L, "jetbrains.mps.lang.structure.structure.IConceptAspect"); /*package*/ static final SConcept ConceptBehavior$2 = MetaAdapterFactory.getConcept(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d43447b1aL, "jetbrains.mps.lang.behavior.structure.ConceptBehavior"); /*package*/ static final SConcept PrivateVisibility$l0 = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x10af9586f0cL, "jetbrains.mps.baseLanguage.structure.PrivateVisibility"); /*package*/ static final SConcept PublicVisibility$R0 = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x10af9581ff1L, "jetbrains.mps.baseLanguage.structure.PublicVisibility"); /*package*/ static final SConcept ProtectedVisibility$hr = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x10af958b686L, "jetbrains.mps.baseLanguage.structure.ProtectedVisibility"); /*package*/ static final SConcept BaseConcept$gP = MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x10802efe25aL, "jetbrains.mps.lang.core.structure.BaseConcept"); } private static final class LINKS { /*package*/ static final SContainmentLink method$w_in = MetaAdapterFactory.getContainmentLink(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d43447b1aL, 0x11d43447b25L, "method"); /*package*/ static final SReferenceLink overriddenMethod$quKH = MetaAdapterFactory.getReferenceLink(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d4348057eL, 0x11d4348057fL, "overriddenMethod"); /*package*/ static final SContainmentLink visibility$Yyua = MetaAdapterFactory.getContainmentLink(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x112670d273fL, 0x112670d886aL, "visibility"); /*package*/ static final SReferenceLink concept$u6dL = MetaAdapterFactory.getReferenceLink(0xaf65afd8f0dd4942L, 0x87d963a55f2a9db1L, 0x11d43447b1aL, 0x11d43447b1fL, "concept"); /*package*/ static final SContainmentLink linkDeclaration$YU1f = MetaAdapterFactory.getContainmentLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0xf979c3ba6bL, "linkDeclaration"); /*package*/ static final SReferenceLink specializedLink$7ZCN = MetaAdapterFactory.getReferenceLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0xf979bd086aL, 0xf98051c244L, "specializedLink"); /*package*/ static final SContainmentLink propertyDeclaration$YUgg = MetaAdapterFactory.getContainmentLink(0xc72da2b97cce4447L, 0x8389f407dc1158b7L, 0x1103553c5ffL, 0xf979c3ba6cL, "propertyDeclaration"); } }
76.121339
943
0.777085
e9f4b8aa8231e3e13bf48fcbc86d4a8de676ab73
6,815
/* ************************************************************************************ * Copyright (C) 2001-2015 Openbravo S.L.U. * Licensed under the Apache Software License version 2.0 * 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.openbravo.base; import java.io.IOException; import java.io.InputStream; import java.util.Vector; import org.apache.commons.fileupload.FileItem; import org.openbravo.data.FieldProvider; public class MultipartRequest implements FieldProvider { public VariablesBase vars; public String filename; public boolean firstRowHeads = false; public String format = "C"; public Vector<Object> vector = new Vector<Object>(); public FieldProvider[] rows; FieldProvider objectFieldProvider[]; public MultipartRequest() { } public MultipartRequest(VariablesBase vars, String filename, boolean firstLineHeads, String format, FieldProvider[] data) throws IOException { init(vars, filename, firstLineHeads, format, data); readSubmittedFile(); } public MultipartRequest(VariablesBase vars, InputStream in, boolean firstLineHeads, String format, FieldProvider[] data) throws IOException { init(vars, "", firstLineHeads, format, data); readSubmittedFile(in); } public MultipartRequest(InputStream in, boolean firstLineHeads, String format, FieldProvider[] data) throws IOException { init("", firstLineHeads, format, data); readSubmittedFile(in); } public String getField(String index) { int i = Integer.valueOf(index).intValue(); if (i >= vector.size()) return null; return ((String) vector.elementAt(i)); } public void addField(String value) { if (vector == null) vector = new Vector<Object>(); vector.addElement(value); } private String setFormatSeparator(String _format) { if (_format.equalsIgnoreCase("F")) return ("FIXED"); else if (_format.equalsIgnoreCase("T")) return ("\t"); else if (_format.equalsIgnoreCase("S")) return (";"); else if (_format.equalsIgnoreCase("P")) return ("+"); else if (_format.equalsIgnoreCase("C")) return (","); else return (""); } public FieldProvider[] getFieldProvider() { return objectFieldProvider; } public FieldProvider setFieldProvider(String linea) { if (format.equalsIgnoreCase("FIXED")) return lineFixedSize(linea); else if (format.equals("")) return lineComplete(linea); else return lineSeparatorFormated(linea); } public void init(VariablesBase _vars, String _filename, boolean firstLineHeads, String _format, FieldProvider[] data) throws IOException { if (_vars == null) throw new IllegalArgumentException("VariablesBase cannot be null"); // if (filename==null || filename.equals("")) throw new // IllegalArgumentException("filename cannot be null"); this.vars = _vars; this.filename = _filename; this.firstRowHeads = firstLineHeads; this.format = setFormatSeparator(_format); this.rows = data; } private void init(String _filename, boolean firstLineHeads, String _format, FieldProvider[] data) throws IOException { this.filename = _filename; this.firstRowHeads = firstLineHeads; this.format = setFormatSeparator(_format); this.rows = data; } public FieldProvider lineFixedSize(String linea) { if (linea == null || linea.length() < 1) return null; MultipartRequest data = new MultipartRequest(); if (rows == null || rows.length == 0) data.addField(linea); else { for (int i = 0; i < rows.length; i++) { int init = Integer.valueOf(rows[i].getField("startno")).intValue(); int end = Integer.valueOf(rows[i].getField("endno")).intValue(); if (init > linea.length()) { data.addField(""); } else { if (init < 0) init = 0; if (end < 0 || end < init) end = init; else if (end > linea.length()) end = linea.length(); String actual = linea.substring(init, end); data.addField(actual); } } } return data; } public FieldProvider lineSeparatorFormated(String linea) { return null; } public FieldProvider lineComplete(String linea) { if (linea == null || linea.length() < 1) return null; MultipartRequest data = new MultipartRequest(); data.addField(linea); return data; } protected void readSubmittedFile(InputStream in) throws IOException { Vector<FieldProvider> _vector = new Vector<FieldProvider>(); int result = 0; String linea = ""; Vector<Byte> vectorInt = new Vector<Byte>(); boolean isFirstRow = true; while ((result = in.read()) != -1) { if (result == 13 || result == 10) { if (vectorInt.size() > 0) { byte[] b = new byte[vectorInt.size()]; for (int i = 0; i < vectorInt.size(); i++) { Byte bAux = vectorInt.elementAt(i); b[i] = bAux.byteValue(); } vectorInt = new Vector<Byte>(); linea = new String(b, "UTF-8"); if (!isFirstRow || !firstRowHeads) { FieldProvider fieldProvider = setFieldProvider(linea); _vector.addElement(fieldProvider); } } isFirstRow = false; } else { byte aux = new Integer(result).byteValue(); vectorInt.addElement(new Byte(aux)); } } if (vectorInt.size() > 0 && (!isFirstRow || !firstRowHeads)) { byte[] b = new byte[vectorInt.size()]; for (int i = 0; i < vectorInt.size(); i++) { Byte bAux = vectorInt.elementAt(i); b[i] = bAux.byteValue(); } vectorInt = new Vector<Byte>(); linea = new String(b); FieldProvider fieldProvider = setFieldProvider(linea); _vector.addElement(fieldProvider); } objectFieldProvider = new FieldProvider[_vector.size()]; _vector.copyInto(objectFieldProvider); } protected void readSubmittedFile() throws IOException { FileItem fi = vars.getMultiFile(filename); if (fi == null) throw new IOException("Invalid filename: " + filename); InputStream in = fi.getInputStream(); if (in == null) throw new IOException("Corrupted filename: " + filename); readSubmittedFile(in); } }
32.922705
99
0.628907
fa0ce2d5c16ed85107a8ee4f119cffcfdba43af2
3,311
package examples; import javax.swing.*; import java.awt.event.*; import java.util.List; import java.util.concurrent.*; import java.lang.reflect.*; public class Execl extends JFrame implements ActionListener { int k = 0; int n = 15; JTextArea ta = new JTextArea(40,20); Execl() { add(new JScrollPane(ta)); JPanel p = new JPanel(); JButton b = new JButton("Start"); b.addActionListener(this); p.add(b); b = new JButton("Stop current"); b.setActionCommand("Stop"); b.addActionListener(this); p.add(b); b = new JButton("Curent result"); b.setActionCommand("Result"); b.addActionListener(this); p.add(b); b = new JButton("Shutdown"); b.addActionListener(this); p.add(b); b = new JButton("ShutdownNow"); b.addActionListener(this); p.add(b); add(p, "South"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); try { Method m = this.getClass().getDeclaredMethod("task"+cmd); m.invoke(this); } catch(Exception exc) { exc.printStackTrace(); } } class SumTask implements Callable<Integer> { private int taskNum, limit; public SumTask(int taskNum, int limit) { this.taskNum = taskNum; this.limit = limit; } public Integer call() throws Exception { int sum = 0; for (int i = 1; i <= limit; i++) { if (Thread.currentThread().isInterrupted()) return null; sum+=i; ta.append("Task " + taskNum + " part result = " + sum + '\n'); Thread.sleep(1000); } return sum; } }; Future<Integer> task; //ExecutorService exec = Executors.newSingleThreadExecutor(); ExecutorService exec = Executors.newFixedThreadPool(3); public void taskStart() { try { task = exec.submit(new SumTask(++k, 15)); } catch(RejectedExecutionException exc) { ta.append("Execution rejected\n"); return; } ta.append("Task " + k + " submitted\n"); } public void taskResult() { String msg = ""; if (task.isCancelled()) msg = "Task cancelled."; else if (task.isDone()) { try { msg = "Ready. Result = " + task.get(); } catch(Exception exc) { msg = exc.getMessage(); } } else msg = "Task is running or waiting for execution"; JOptionPane.showMessageDialog(null, msg); } public void taskStop() { task.cancel(true); } public void taskShutdown() { exec.shutdown(); ta.append("Executor shutdown\n"); } public void taskShutdownNow() { List<Runnable> awaiting = exec.shutdownNow(); ta.append("Eeecutor shutdown now - awaiting tasks:\n"); for (Runnable r : awaiting) { ta.append(r.getClass().getName()+'\n'); } } public static void main(String[] args) { new Execl(); } }
26.701613
78
0.536394
6aef4a2f1570aaa441993b4e2da6e29ef7b16b1e
5,411
package com.jcodes.jms.mq; import java.util.ArrayList; import java.util.Collection; import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.TextMessage; import org.apache.log4j.Logger; import com.ibm.mq.jms.MQConnection; import com.ibm.mq.jms.MQMessageConsumer; import com.ibm.mq.jms.MQMessageProducer; import com.ibm.mq.jms.MQQueueConnection; import com.ibm.mq.jms.MQQueueConnectionFactory; import com.ibm.mq.jms.MQQueueReceiver; import com.ibm.mq.jms.MQQueueSession; import com.ibm.mq.jms.MQSession; import com.ibm.msg.client.wmq.WMQConstants; import com.ibm.msg.client.wmq.v6.jms.internal.JMSC; public class MQUtil { public static final String CORRELATIONID = "REQ\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; //上面的16进制写法 public static final String JMS_CORRELATIONID = "ID:524551000000000000000000000000000000000000000000"; public static final String JMS_UUID = "uuid"; private static Logger logger = Logger.getLogger(MQUtil.class); /** * 获取MQ队列连接 * @throws JMSException */ public static MQQueueConnection getMQConnection(String ip, int port, String channel, String queueManager, int ccsid) throws JMSException{ MQQueueConnection con = null; try{ MQQueueConnectionFactory factory = new MQQueueConnectionFactory(); factory.setHostName(ip); factory.setPort(port); factory.setQueueManager(queueManager); factory.setChannel(channel); factory.setCCSID(ccsid); factory.setShareConvAllowed(0); //factory.setClientReconnectOptions(options) //此设置对应MQI的MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES); factory.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP); // factory.setTransportType(JMSC.MQJMS_TP_CLIENT_MQ_TCPIP); con = (MQQueueConnection)factory.createQueueConnection(); }catch(JMSException e){ logger.error("MQ创建连接失败" + e.getMessage(), e); throw e; } return con; } /** * 压缩集合,采用服务器——服务器方式和人行连接,不需要设置 * 在通道的发送通道和接收通道设置压缩格式 * @return */ @SuppressWarnings("unchecked") public static Collection getMsgCompList(){ ArrayList msgComp = new ArrayList(); msgComp.add(new Integer( WMQConstants.WMQ_COMPMSG_ZLIBFAST)); msgComp.add(new Integer(WMQConstants.WMQ_COMPMSG_RLE )); msgComp.add(new Integer(WMQConstants.WMQ_COMPMSG_ZLIBHIGH)); msgComp.add(new Integer(WMQConstants.WMQ_COMPHDR_NONE)); msgComp.add(new Integer(WMQConstants.WMQ_COMPMSG_DEFAULT)); return msgComp; } /** * 数据压缩分为消息头压缩和消息本身压缩 * @return */ @SuppressWarnings("unchecked") public static Collection getHdrCompList(){ ArrayList msgComp = new ArrayList(); msgComp.add(new Integer( WMQConstants.WMQ_COMPHDR_DEFAULT)); msgComp.add(new Integer( WMQConstants.WMQ_COMPHDR_SYSTEM)); msgComp.add(new Integer( WMQConstants.WMQ_COMPHDR_NONE)); return msgComp; } public static byte[] readByteFromMsg(Message message) throws JMSException{ byte[] ret = null; if (message instanceof BytesMessage) { BytesMessage bm = (BytesMessage) message; ret = new byte[new Long(bm.getBodyLength()).intValue()]; bm.readBytes(ret); } else if (message instanceof TextMessage) { TextMessage tm = (TextMessage)message; if(tm.getText() != null){ ret = tm.getText().getBytes(); } } return ret; } public static void closeMQConnection(MQConnection o){ if(o != null){ try { //o.stop(); o.close(); } catch (JMSException e) { logger.error("关闭mq连接失败", e); }finally{ o = null; } } } public static void closeMQSession(MQSession o){ if(o != null){ try { o.close(); } catch (JMSException e) { logger.error("关闭mq会话失败", e); }finally{ o = null; } } } public static void closeMQSession(ArrayList<MQQueueSession> sessions){ if(sessions != null){ for(MQQueueSession session : sessions){ MQUtil.closeMQSession(session); } } } public static void colseMQMessageConsumer(ArrayList<MQQueueReceiver> consumers){ if(consumers != null){ for(MQQueueReceiver consumer : consumers){ MQUtil.colseMQMessageConsumer(consumer); } } } public static void colseMQMessageProducer(MQMessageProducer o){ if(o != null){ try { o.close(); } catch (JMSException e) { logger.error("关闭mq消息生产者失败", e); }finally{ o = null; } } } public static void colseMQMessageConsumer(MQMessageConsumer o){ if(o != null){ try { o.close(); } catch (JMSException e) { logger.error("关闭mq消息消费者失败", e); }finally{ o = null; } } } public static String getJMSCorrelationID(String s){ String receJMSCorrelationID = null; if(s.startsWith("ID:")){ receJMSCorrelationID = s; }else{ //receJMSCorrelationID ; String str = "ID:"; for(int i=0; i<24; i++){ int ch = '\0'; if(i<s.length()){ ch = (int)s.charAt(i); } String s4 = Integer.toHexString(ch); if(s4.length() == 1){ s4 = "0" + s4; } str = str+s4; } receJMSCorrelationID = str; } return receJMSCorrelationID; } public static String getJMSCorrelationIDSelector(String s){ if(!s.contains("=")){ return "JMSCorrelationID='" + getJMSCorrelationID(s) + "'"; }else{ return s; } } public static void main(String[] args){ System.out.println(CORRELATIONID.getBytes()); byte[] bs = CORRELATIONID.getBytes(); for(int i=0;i<bs.length;i++){ System.out.print(bs[i]); } } }
24.484163
138
0.695805
f53fec5887f1d1ec4a2eac87138addef04a3a42a
2,838
package com.eva.core.servlet; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import java.io.*; import java.nio.charset.Charset; /** * 包含副本的输入流 * @author Eva.Caesar Liu * @date 2021/07/13 22:37 */ public class ServletDuplicateInputStream extends ServletInputStream { private ServletInputStream stream; private ByteArrayInputStream duplicate; private String body; public ServletDuplicateInputStream (ServletInputStream servletInputStream) { this.stream = servletInputStream; this.body = this.getBodyString(); this.duplicate = new ByteArrayInputStream(body.getBytes(Charset.forName("UTF-8"))); } @Override public int read() { return duplicate.read(); } @Override public boolean isFinished() { return stream.isFinished(); } @Override public boolean isReady() { return stream.isReady(); } @Override public void setReadListener(ReadListener readListener) { stream.setReadListener(readListener); } /** * 获取请求体参数字符串 */ private String getBodyString() { StringBuilder sb = new StringBuilder(); InputStream inputStream = null; BufferedReader reader = null; try { inputStream = cloneInputStream(this.stream); reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); String line; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } /** * 复制输入流 */ private InputStream cloneInputStream(ServletInputStream inputStream) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; try { while ((len = inputStream.read(buffer)) > -1) { byteArrayOutputStream.write(buffer, 0, len); } byteArrayOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } /** * 获取请求体内容 */ public String getBody () { return body; } }
26.036697
102
0.55814
dbdcc142ecdc18802ff032b14957a7d4061cfe2c
2,269
// Copyright 2015 Eivind Vegsundvåg // // 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 ninja.eivind.hotsreplayuploader.services; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.concurrent.ScheduledService; import javafx.concurrent.Task; import javafx.util.Duration; import ninja.eivind.hotsreplayuploader.models.Account; import ninja.eivind.hotsreplayuploader.utils.SimpleHttpClient; import ninja.eivind.hotsreplayuploader.utils.StormHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * {@link ScheduledService} for checking the current values of * a user's {@link Account}s. Will be checked often for MMR changes. */ @Component public class AccountService extends ScheduledService<List<Account>> { @Autowired private StormHandler stormHandler; @Autowired private SimpleHttpClient httpClient; @Autowired private ObjectMapper mapper; public AccountService() { setDelay(Duration.ZERO); setPeriod(Duration.minutes(10)); } @Override protected Task<List<Account>> createTask() { return new Task<List<Account>>() { @Override protected List<Account> call() throws Exception { final List<String> accountUris = stormHandler.getAccountStringUris(); final List<Account> value = new ArrayList<>(); for (final String accountUri : accountUris) { final String response = httpClient.simpleRequest(accountUri); value.add(mapper.readValue(response, Account.class)); } return value; } }; } }
34.907692
85
0.709564
81c6eb867b4a716dc28b92dd2da10b6569503af2
4,671
package demo.phone; import demo.phone.dto.PhoneDTO; import demo.phone.repository.PhoneRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static com.jayway.restassured.RestAssured.given; import static com.jayway.restassured.http.ContentType.JSON; import static demo.phone.dto.PhoneDTO.Builder; import static demo.phone.dto.PhoneDTO.newBuilder; import static org.hamcrest.Matchers.is; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = DemoApplication.class) @WebIntegrationTest public class PhoneDTOControllerTest { @Autowired private PhoneRepository phoneRepository; // test phone 1 private String serial1 = "123456789"; private String num1 = "0798653214"; private boolean stolen1 = true; // test phone 2 private String serial2 = "987654321"; private String num2 = "0698653214"; private boolean stolen2 = true; private String anonymous = "**********"; @Before public void setUp() { // RestAssured.port = 8080; // RestAssured.baseURI = "http://192.168.43.182"; } @Test public void should_GetAllPhone() { given() .log().all() .when() .get("/phone") .then() .log().all() .statusCode(200) // first phone .body("[0].id", is(1)) .body("[0].serialNumber", is(serial1)) .body("[0].number", is(num1)) .body("[0].firstName", is(anonymous)) .body("[0].lastName", is(anonymous)) .body("[0].stolen", is(stolen1)) // second phone .body("[1].id", is(2)) .body("[1].serialNumber", is(serial2)) .body("[1].number", is(num2)) .body("[1].firstName", is(anonymous)) .body("[1].lastName", is(anonymous)) .body("[1].stolen", is(stolen2)); } @Test public void should_GetOnePhone() { given() .log().all() .when() .get("/phone/1") .then() .log().all() .statusCode(200) .body("id", is(1)) .body("serialNumber", is(serial1)) .body("number", is(num1)) .body("firstName", is(anonymous)) .body("lastName", is(anonymous)) .body("stolen", is(stolen1)); } @Test public void should_UpdateStolen() { given() .log().all() .contentType(JSON) .accept(JSON) .body("{\"stolen\": " + !stolen1 + "}") .when() .put("/phone/1") .then() .log().all() .statusCode(200) .body("id", is(1)) .body("serialNumber", is(serial1)) .body("number", is(num1)) .body("stolen", is(!stolen1)); // revert update given() .log().all() .contentType(JSON) .accept(JSON) .body("{\"stolen\": " + stolen1 + "}") .when() .put("/phone/1"); } @Test public void should_CreatePhone_AndGetIt() { String serialNumber = "12568923"; String number = "0732657846"; String firstName = "Jane"; String lastName = "Banana"; boolean stolen = false; Builder phoneDTOBuilder = newBuilder(serialNumber, number, stolen); phoneDTOBuilder.withFirstName(firstName); phoneDTOBuilder.withLastName(lastName); PhoneDTO phoneDTO = phoneDTOBuilder.build(); given() .log().all() .contentType(JSON) .accept(JSON) .body(phoneDTO) .when() .post("/phone") .then() .log().all() .statusCode(200) .body("id", is(3)) .body("serialNumber", is(serialNumber)) .body("number", is(number)) .body("firstName", is(anonymous)) .body("lastName", is(anonymous)) .body("stolen", is(stolen)); // a healthy DB is a nice DB phoneRepository.delete(3L); } @Test public void shouldNot_GetOnePhone() { given() .log().all() .when() .get("/phone/0") .then() .log().all() .statusCode(404) .body("message", is("Phone not found")); } }
29.012422
75
0.54164
576e2077f704c19166a55ef0a55f2307a0f93b01
1,879
/* * Copyright (c) Kevin KDA 2019. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.kevin.courseprojectb.servlet; import com.kevin.courseprojectb.dao.UserDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author Kevin KDA on 2019/12/12 9:41 * @version 1.0 * @project JSP_Course_Assignments * @package ${PACKAGE_NAME} * @classname ${NAME} * @description TODO ${description} * @interface/enum */ @WebServlet(name = "ValiLoginIDServlet", urlPatterns = "/ValiLoginIDServlet") public class ValiLoginIDServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=UTF-8"); if (request.getParameter("loginID") != null) { String loginID = request.getParameter("loginID"); boolean state = UserDao.valiLoginID(loginID); if (state) { response.getWriter().write("账号可用"); } else { response.getWriter().write("账号已被注册"); } } else { response.getWriter().write("请输入账号"); } } }
36.134615
122
0.70942
6ee680acb4a69b9d876ad80710ccb7778bc9dd05
11,141
package org.qrinvoice.core; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.math.BigDecimal; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import static org.qrinvoice.core.InvoiceAttributesConstants.*; /** * Created by zcg on 5.6.2016. * Holder for invoice data, internal. Validation constraints set using bean validation * */ public class InvoiceParamDomain { //ID @NotNull @Size(max = 40) private String id; //DD private DateParam dateOfIssue; //AM @Digits(integer = 15, fraction = 2) @NotNull private BigDecimal totalAmount; //TP @Digits(integer = 1, fraction = 0) private Byte typeOfTax; //TD @Digits(integer = 1, fraction = 0) private Byte typeOfIdentification; //SA @Digits(integer = 1, fraction = 0) private Byte taxDeposit; //MSG @Size(max = 40) private String message; //ON @Size(max = 20) private String orderNumber; //VS @Size(max = 10) private String variableString; // VII @Size(max = 14) private String taxIdentificationNumberDrawer; // INI @Digits(integer = 8, fraction = 0) private String identificationNumberDrawer; //VIR @Size(max = 14) private String taxIdentificationNumberBene; //INR @Digits(integer = 8, fraction = 0) private String identificationNumberBene; //DUZP private DateParam dateOfTax; //DPPD private DateParam dateOfTaxDuty; //DT private DateParam dateOfDue; //TB0 @Digits(integer = 15, fraction = 2) private BigDecimal taxBaseAmount; // T0 @Digits(integer = 15, fraction = 2) private BigDecimal taxAmount; //TB1 @Digits(integer = 15, fraction = 2) private BigDecimal taxBaseReduced1Amount; //T1 @Digits(integer = 15, fraction = 2) private BigDecimal taxReduced1Amount; //TB2 @Digits(integer = 15, fraction = 2) private BigDecimal taxBaseReduced2Amount; //T2 @Digits(integer = 15, fraction = 2) private BigDecimal taxReduced2Amount; //NTB @Digits(integer = 15, fraction = 2) private BigDecimal nonTaxAmount; //CC @Size(max = 3) private String currencyCode; //FX @Digits(integer = 15, fraction = 2) private BigDecimal exchangeRate; //FXA @Digits(integer = 5, fraction = 0) private BigDecimal exchangeUnits; // special attributes //ACC @Size(max = 34) private String IBAN; // no code @Size(max = 11) private String BIC; //X-SW @Size(max = 30) private String softwareOrigin; //X-URL @Size(max = 70) private String url; //X-URL @Size(max = 70) private String spaydUrl; //MSG @Size(max = 40) private String spaydMessage; private Map<String, Object> paramMap = new TreeMap<>(); /** * add parameter to internal map of * * @param value * @param code */ private void setValueCodePair(Object value, String code) { if (value != null) { paramMap.put(code, value); } } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; setValueCodePair(currencyCode, CC); } public DateParam getDateOfDue() { return dateOfDue; } public void setDateOfDue(DateParam dateOfDue) { this.dateOfDue = dateOfDue; setValueCodePair(dateOfDue, DT); } public DateParam getDateOfIssue() { return dateOfIssue; } public void setDateOfIssue(DateParam dateOfIssue) { this.dateOfIssue = dateOfIssue; setValueCodePair(dateOfIssue, DD); } public DateParam getDateOfTax() { return dateOfTax; } public void setDateOfTax(DateParam dateOfTax) { this.dateOfTax = dateOfTax; setValueCodePair(dateOfTax, DUZP); } public DateParam getDateOfTaxDuty() { return dateOfTaxDuty; } public void setDateOfTaxDuty(DateParam dateOfTaxDuty) { this.dateOfTaxDuty = dateOfTaxDuty; setValueCodePair(dateOfTaxDuty, DPPD); } public String getIdentificationNumberBene() { return identificationNumberBene; } public void setIdentificationNumberBene(String dentificationNumberBene) { this.identificationNumberBene = dentificationNumberBene; setValueCodePair(identificationNumberBene, INR); } public Number getExchangeRate() { return exchangeRate; } public void setExchangeRate(BigDecimal exchangeRate) { this.exchangeRate = exchangeRate; setValueCodePair(exchangeRate, FX); } public Number getExchangeUnits() { return exchangeUnits; } public void setExchangeUnits(BigDecimal exchangeUnits) { this.exchangeUnits = exchangeUnits; setValueCodePair(exchangeUnits, FXA); } public String getBIC() { return BIC; } public void setBIC(String BIC) { this.BIC = BIC; if (getIBAN() != null) { setValueCodePair(getIBAN() + "+" + BIC, ACC); } else { setValueCodePair(BIC, ACC); } } public String getIBAN() { return IBAN; } public void setIBAN(String IBAN) { this.IBAN = IBAN; if (getBIC() != null) { setValueCodePair(getIBAN() + "+" + getBIC(), ACC); } else { setValueCodePair(IBAN, ACC); } } public String getId() { return id; } public void setId(String id) { this.id = id; setValueCodePair(id, ID); } public String getIdentificationNumberDrawer() { return identificationNumberDrawer; } public void setIdentificationNumberDrawer(String identificationNumberDrawer) { this.identificationNumberDrawer = identificationNumberDrawer; setValueCodePair(identificationNumberDrawer, INI); } public BigDecimal getNonTaxAmount() { return nonTaxAmount; } public void setNonTaxAmount(BigDecimal nonTaxAmount) { this.nonTaxAmount = nonTaxAmount; setValueCodePair(nonTaxAmount, NTB); } public String getSoftwareOrigin() { return softwareOrigin; } public void setSoftwareOrigin(String softwareOrigin) { this.softwareOrigin = softwareOrigin; setValueCodePair(softwareOrigin, X_SW); } public BigDecimal getTaxAmount() { return taxAmount; } public void setTaxAmount(BigDecimal taxAmount) { this.taxAmount = taxAmount; setValueCodePair(taxAmount, T0); } public BigDecimal getTaxBaseAmount() { return taxBaseAmount; } public void setTaxBaseAmount(BigDecimal taxBaseAmount) { this.taxBaseAmount = taxBaseAmount; setValueCodePair(taxBaseAmount, TB0); } public BigDecimal getTaxBaseReduced1Amount() { return taxBaseReduced1Amount; } public void setTaxBaseReduced1Amount(BigDecimal taxBaseReduced1Amount) { this.taxBaseReduced1Amount = taxBaseReduced1Amount; setValueCodePair(taxBaseReduced1Amount, TB1); } public BigDecimal getTaxBaseReduced2Amount() { return taxBaseReduced2Amount; } public void setTaxBaseReduced2Amount(BigDecimal taxBaseReduced2Amount) { this.taxBaseReduced2Amount = taxBaseReduced2Amount; setValueCodePair(taxBaseReduced2Amount, TB2); } public Byte getTaxDeposit() { return taxDeposit; } public void setTaxDeposit(Byte taxDeposit) { this.taxDeposit = taxDeposit; setValueCodePair(taxDeposit, SA); } public String getTaxIdentificationNumberBene() { return taxIdentificationNumberBene; } public void setTaxIdentificationNumberBene(String taxIdentificationNumberBene) { this.taxIdentificationNumberBene = taxIdentificationNumberBene; setValueCodePair(taxIdentificationNumberBene, VIR); } public String getTaxIdentificationNumberDrawer() { return taxIdentificationNumberDrawer; } public void setTaxIdentificationNumberDrawer(String taxIdentificationNumberDrawer) { this.taxIdentificationNumberDrawer = taxIdentificationNumberDrawer; setValueCodePair(taxIdentificationNumberDrawer, VII); } public BigDecimal getTaxReduced1Amount() { return taxReduced1Amount; } public void setTaxReduced1Amount(BigDecimal taxReduced1Amount) { this.taxReduced1Amount = taxReduced1Amount; setValueCodePair(taxReduced1Amount, T1); } public BigDecimal getTaxReduced2Amount() { return taxReduced2Amount; } public void setTaxReduced2Amount(BigDecimal taxReduced2Amount) { this.taxReduced2Amount = taxReduced2Amount; setValueCodePair(taxReduced2Amount, T2); } public BigDecimal getTotalAmount() { return totalAmount; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; setValueCodePair(totalAmount, AM); } public Byte getTypeOfIdentification() { return typeOfIdentification; } public void setTypeOfIdentification(Byte typeOfIdentification) { this.typeOfIdentification = typeOfIdentification; setValueCodePair(typeOfIdentification, TD); } public Byte getTypeOfTax() { return typeOfTax; } public void setTypeOfTax(Byte typeOfTax) { this.typeOfTax = typeOfTax; setValueCodePair(typeOfTax, TP); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; setValueCodePair(url, X_URL); } public String getVariableString() { return variableString; } public void setVariableString(String variableString) { this.variableString = variableString; setValueCodePair(variableString, VS); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; setValueCodePair(message, MSG); } public String getOrderNumber() { return orderNumber; } public void setOrderNumber(String orderNumber) { this.orderNumber = orderNumber; setValueCodePair(orderNumber, ON); } public Map<String, Object> getParamMap() { return (paramMap == null) ? null : Collections.unmodifiableMap(paramMap); } public String getSpaydUrl() { return spaydUrl; } public void setSpaydUrl(String spaydUrl) { this.spaydUrl = spaydUrl; setValueCodePair(spaydUrl, X_URL_SPAYD); } public String getSpaydMessage() { return spaydMessage; } public void setSpaydMessage(String spaydMessage) { this.spaydMessage = spaydMessage; setValueCodePair(spaydMessage, MSG_SPAYD); } }
21.63301
88
0.653712
4fbeb863355a094cc98cf959573414c244ac516d
818
package com.thoughtbot.expandablerecyclerview.sample.singlecheck; import android.view.View; import android.widget.Checkable; import android.widget.CheckedTextView; import com.thoughtbot.expandablecheckrecyclerview.viewholders.CheckableChildViewHolder; import com.thoughtbot.expandablerecyclerview.sample.R; public class SingleCheckArtistViewHolder extends CheckableChildViewHolder { private CheckedTextView childCheckedTextView; public SingleCheckArtistViewHolder(View itemView) { super(itemView); childCheckedTextView = (CheckedTextView) itemView.findViewById(R.id.list_item_singlecheck_artist_name); } @Override public Checkable getCheckable() { return childCheckedTextView; } public void setArtistName(String artistName) { childCheckedTextView.setText(artistName); } }
29.214286
88
0.816626
af56e83637914f90668243fba9c99082f5f6ffda
4,334
/* * Copyright 2015 Martin Bella * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.orange_box.storebox.utils; import android.net.Uri; import net.orange_box.storebox.adapters.extra.DateTypeAdapter; import net.orange_box.storebox.adapters.extra.EnumTypeAdapter; import net.orange_box.storebox.adapters.StoreBoxTypeAdapter; import net.orange_box.storebox.adapters.standard.BooleanTypeAdapter; import net.orange_box.storebox.adapters.standard.FloatTypeAdapter; import net.orange_box.storebox.adapters.standard.IntegerTypeAdapter; import net.orange_box.storebox.adapters.standard.LongTypeAdapter; import net.orange_box.storebox.adapters.standard.StringSetTypeAdapter; import net.orange_box.storebox.adapters.standard.StringTypeAdapter; import net.orange_box.storebox.adapters.extra.UriTypeAdapter; import net.orange_box.storebox.annotations.method.TypeAdapter; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; public final class TypeUtils { private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_BOXED_MAP; static { final Map<Class<?>, Class<?>> map = new HashMap<>(4); map.put(boolean.class, Boolean.class); map.put(float.class, Float.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); PRIMITIVE_TO_BOXED_MAP = map; } private static final Map<Class<?>, StoreBoxTypeAdapter> ADAPTERS_MAP; static { final Map<Class<?>, StoreBoxTypeAdapter> map = new HashMap<>(8); // standard map.put(Boolean.class, new BooleanTypeAdapter()); map.put(Float.class, new FloatTypeAdapter()); map.put(Integer.class, new IntegerTypeAdapter()); map.put(Long.class, new LongTypeAdapter()); map.put(String.class, new StringTypeAdapter()); map.put(Set.class, new StringSetTypeAdapter()); // extra map.put(Date.class, new DateTypeAdapter()); map.put(Uri.class, new UriTypeAdapter()); ADAPTERS_MAP = map; } public static Class<?> wrapToBoxedType(Class<?> type) { if (type.isPrimitive() && PRIMITIVE_TO_BOXED_MAP.containsKey(type)) { return PRIMITIVE_TO_BOXED_MAP.get(type); } else { return type; } } @SuppressWarnings("unchecked") public static StoreBoxTypeAdapter getTypeAdapter( Class<?> type, TypeAdapter annotation) { if (ADAPTERS_MAP.containsKey(type)) { return ADAPTERS_MAP.get(type); } else if (type.isEnum()) { // enums have a special type adapter return new EnumTypeAdapter((Class<Enum>) type); } if (annotation == null) { throw new RuntimeException(String.format( Locale.ENGLISH, "Failed to find type adapter for %1$s", type.getName())); } try { return annotation.value().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(String.format( Locale.ENGLISH, "Failed to instantiate %1$s, perhaps the no-arguments " + "constructor is missing?", annotation.value().getSimpleName()), e); } catch (IllegalAccessException e) { throw new RuntimeException(String.format( Locale.ENGLISH, "Failed to instantiate %1$s, perhaps the no-arguments " + "constructor is not public?", annotation.value().getSimpleName()), e); } } private TypeUtils() {} }
37.042735
77
0.636825