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
791e6ea90b4fd800056fb8af6c6affa7f6d1cdd6
1,511
package info.u_team.extreme_cobble_generator.data.provider; import static info.u_team.extreme_cobble_generator.init.ExtremeCobbleGeneratorBlocks.GENERATOR; import java.util.function.BiConsumer; import info.u_team.u_team_core.data.CommonLootTablesProvider; import info.u_team.u_team_core.data.GenerationData; import info.u_team.u_team_core.intern.loot.SetTileEntityNBTLootFunction; import net.minecraft.loot.ConstantRange; import net.minecraft.loot.ItemLootEntry; import net.minecraft.loot.LootParameterSets; import net.minecraft.loot.LootPool; import net.minecraft.loot.LootTable; import net.minecraft.loot.conditions.SurvivesExplosion; import net.minecraft.util.IItemProvider; import net.minecraft.util.ResourceLocation; public class ExtremeCobbleGeneratorLootTablesProvider extends CommonLootTablesProvider { public ExtremeCobbleGeneratorLootTablesProvider(GenerationData data) { super(data); } @Override protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) { registerBlock(GENERATOR, addTileEntityLootTable(GENERATOR.get()), consumer); } protected static LootTable addTileEntityLootTable(IItemProvider item) { return LootTable.builder() // .setParameterSet(LootParameterSets.BLOCK) // .addLootPool(LootPool.builder() // .rolls(ConstantRange.of(1)) // .addEntry(ItemLootEntry.builder(item)) // .acceptFunction(SetTileEntityNBTLootFunction.builder()) // .acceptCondition(SurvivesExplosion.builder())) // .build(); } }
35.97619
95
0.81006
8621fe86d14026f39db687d5b44c1201fc09caee
2,678
package com.ossez.usreio.tests.client; import com.ossez.usreio.client.RetsException; import com.ossez.usreio.client.RetsSession; import com.ossez.usreio.common.rets.RetsVersion; import com.ossez.usreio.util.SessionUtils; import org.apache.commons.lang3.ObjectUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * RETS Connection Test * * @author YuCheng Hu */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class RetsSessionTest extends RetsTestCase { private final Logger logger = LoggerFactory.getLogger(RetsSessionTest.class); /** * Test Login should return SessionID from server */ @Test public void testLogin() { logger.debug("Test Rets Session Login by URL: [{}]", retsLoginUrl); try { RetsSession session = SessionUtils.retsLogin(retsLoginUrl, retsUsername, retsPassword, RetsVersion.RETS_1_7_2); assertNotNull(session.getSessionId()); // CHECK MetaData logger.error("Session ID - [{}]", session.getSessionId()); logger.error("MetaData version - [{}]", session.getMetadataVersion()); logger.error("MetaData Timestamp - [{}]", session.getMetadataTimestamp()); } catch (RetsException ex) { logger.error("Session Login Error", ex); } } /** * Test Login should return SessionID from server */ @Test public void testLoginWithConfigurator() { logger.debug("Test Rets Session Login by URL: [{}]", retsLoginUrl); try { RetsSession session = SessionUtils.retsLogin(retsConfigurator); // session.login() assertNotNull(session.getSessionId()); } catch (RetsException ex) { logger.debug("Session Login Error", ex); } } /** * TEST Logout */ @Test public void testLogout() { logger.debug("RETS Session Login URL: [{}]", retsLoginUrl); RetsSession session = null; try { session = SessionUtils.retsLogin(retsLoginUrl, retsUsername, retsPassword, RetsVersion.RETS_1_7_2); assertNotNull(session.getSessionId()); } catch (RetsException ex) { logger.debug("Session Login Error", ex); } // If Session is not Empty then Logout if (ObjectUtils.isNotEmpty(session)) { try { session.logout(); } catch (RetsException e) { logger.error("Logout Error: ", e); } } } }
28.795699
123
0.629948
49dc32e820a505575c870c07ee11bbf68426c80d
7,999
/** * 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.smartloli.kafka.eagle.web.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.smartloli.kafka.eagle.web.config.KafkaClustersConfig; import org.smartloli.kafka.eagle.web.constant.KafkaConstants; import org.smartloli.kafka.eagle.web.constant.TopicConstants; import org.smartloli.kafka.eagle.web.dao.MBeanDao; import org.smartloli.kafka.eagle.web.dao.TopicDao; import org.smartloli.kafka.eagle.web.protocol.DashboardInfo; import org.smartloli.kafka.eagle.web.protocol.KafkaBrokerInfo; import org.smartloli.kafka.eagle.web.protocol.KpiInfo; import org.smartloli.kafka.eagle.web.protocol.topic.TopicLogSize; import org.smartloli.kafka.eagle.web.protocol.topic.TopicRank; import org.smartloli.kafka.eagle.web.service.BrokerService; import org.smartloli.kafka.eagle.web.service.ConsumerService; import org.smartloli.kafka.eagle.web.service.DashboardService; import org.smartloli.kafka.eagle.web.service.KafkaService; import org.smartloli.kafka.eagle.web.util.StrUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Kafka Eagle dashboard data generator. * * @author smartloli. * * Created by Aug 12, 2016. * * Update by hexiang 20170216 */ @Service public class DashboardServiceImpl implements DashboardService { /** Kafka service interface. */ @Autowired private KafkaService kafkaService; /** Broker service interface. */ @Autowired private BrokerService brokerService; @Autowired private TopicDao topicDao; @Autowired private MBeanDao mbeanDao; @Autowired private ConsumerService consumerService; @Autowired private KafkaClustersConfig kafkaClustersConfig; /** * Get consumer number from zookeeper. */ private int getConsumerNumbers(String clusterAlias) { Map<String, List<String>> consumers = consumerService.getConsumers(clusterAlias); int count = 0; for (Entry<String, List<String>> entry : consumers.entrySet()) { count += entry.getValue().size(); } return count; } /** Get kafka & dashboard dataset. */ public String getDashboard(String clusterAlias) { JSONObject target = new JSONObject(); target.put("kafka", kafkaBrokersGraph(clusterAlias)); target.put("dashboard", panel(clusterAlias)); return target.toJSONString(); } /** Get kafka data. */ private String kafkaBrokersGraph(String clusterAlias) { List<KafkaBrokerInfo> brokers = kafkaService.getBrokerInfos(clusterAlias); JSONObject target = new JSONObject(); target.put("name", "Kafka Brokers"); JSONArray targets = new JSONArray(); int count = 0; for (KafkaBrokerInfo broker : brokers) { if (count > KafkaConstants.SIZE) { JSONObject subTarget = new JSONObject(); subTarget.put("name", "..."); targets.add(subTarget); break; } else { JSONObject subTarget = new JSONObject(); subTarget.put("name", broker.getHost() + ":" + broker.getPort()); targets.add(subTarget); } count++; } target.put("children", targets); return target.toJSONString(); } /** Get dashboard data. */ private String panel(String clusterAlias) { int zks = kafkaClustersConfig.getClusterConfigByName(clusterAlias).getZkList().split(",").length; DashboardInfo dashboard = new DashboardInfo(); dashboard.setBrokers(brokerService.brokerNumbers(clusterAlias)); dashboard.setTopics(brokerService.topicNumbers(clusterAlias)); dashboard.setZks(zks); String formatter = kafkaClustersConfig.getClusterConfigByName(clusterAlias).getOffsetStorage(); if ("kafka".equals(formatter)) { dashboard.setConsumers(consumerService.getKafkaConsumerGroups(clusterAlias)); } else { dashboard.setConsumers(getConsumerNumbers(clusterAlias)); } return JSON.toJSONString(dashboard); } /** Get topic rank data,such as logsize and topic capacity. */ @Override public JSONArray getTopicRank(Map<String, Object> params) { List<TopicRank> topicRank = topicDao.readTopicRank(params); JSONArray array = new JSONArray(); if (TopicConstants.LOGSIZE.equals(params.get("tkey"))) { int index = 1; for (int i = 0; i < 10; i++) { JSONObject object = new JSONObject(); if (i < topicRank.size()) { object.put("id", index); object.put("topic", "<a href='/topic/meta/page/" + topicRank.get(i).getTopic() + "'>" + topicRank.get(i).getTopic() + "</a>"); object.put("logsize", topicRank.get(i).getTvalue()); } else { object.put("id", index); object.put("topic", ""); object.put("logsize", ""); } index++; array.add(object); } } else if (TopicConstants.CAPACITY.equals(params.get("tkey"))) { int index = 1; for (int i = 0; i < 10; i++) { JSONObject object = new JSONObject(); if (i < topicRank.size()) { object.put("id", index); object.put("topic", "<a href='/topic/meta/page/" + topicRank.get(i).getTopic() + "/'>" + topicRank.get(i).getTopic() + "</a>"); object.put("capacity", StrUtils.stringify(topicRank.get(i).getTvalue())); } else { object.put("id", index); object.put("topic", ""); object.put("capacity", ""); } index++; array.add(object); } } return array; } /** Write statistics topic rank data from kafka jmx & insert into table. */ public int writeTopicRank(List<TopicRank> topicRanks) { return topicDao.writeTopicRank(topicRanks); } /** * Write statistics topic logsize data from kafka jmx & insert into table. */ public int writeTopicLogSize(List<TopicLogSize> topicLogSize) { return topicDao.writeTopicLogSize(topicLogSize); } @Override public JSONObject getOSMem(Map<String, Object> params) { List<KpiInfo> kpis = mbeanDao.getOsMem(params); JSONObject object = new JSONObject(); object.put("mem", 0.0); if (kpis.size() == 2) { long valueFirst = Long.parseLong(kpis.get(0).getValue()); long valueSecond = Long.parseLong(kpis.get(1).getValue()); if (valueFirst >= valueSecond && valueFirst != 0L) { object.put("mem", 100 * StrUtils.numberic((valueFirst - valueSecond) * 1.0 / valueFirst, "###.###")); } else if (valueSecond != 0L) { object.put("mem", 100 * StrUtils.numberic((valueSecond - valueFirst) * 1.0 / valueSecond, "###.###")); } } return object; } /** Read topic lastest logsize diffval data. */ public TopicLogSize readLastTopicLogSize(Map<String, Object> params) { return topicDao.readLastTopicLogSize(params); } /** Get all clean topic list. */ public List<TopicRank> getCleanTopicList(Map<String, Object> params) { return topicDao.getCleanTopicList(params); } }
36.861751
147
0.671209
f97728fb3df20bc2d5b7e003b617cf81042702b0
4,943
package pt.ulisboa.tecnico.cmov.ubibike.Friends; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import pt.ulisboa.tecnico.cmov.ubibike.Database.ChatEntry; import pt.ulisboa.tecnico.cmov.ubibike.Database.MyDBHandler; import pt.ulisboa.tecnico.cmov.ubibike.Login.Login; import pt.ulisboa.tecnico.cmov.ubibike.R; import pt.ulisboa.tecnico.cmov.ubibike.Utilities.CustomAdapter; public class TabConversations extends Fragment{ ListView conv; View rootView; HashMap<String,String> friendsNearby; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i("OnCreateView","View Created"); TabConversations.Callbacks callbacks = (TabConversations.Callbacks) getActivity(); friendsNearby = callbacks.getNearbyFriends(); rootView = inflater.inflate(R.layout.fragment_tab_conversations, container, false); Button plus_button = (Button) rootView.findViewById(R.id.plus_button); final Button points_button = (Button) rootView.findViewById(R.id.point_button); final Button talk_button = (Button) rootView.findViewById(R.id.talk_button); points_button.setVisibility(View.GONE); talk_button.setVisibility(View.GONE); setupUI(); plus_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (talk_button.getVisibility() == View.VISIBLE && points_button.getVisibility() == View.VISIBLE) { talk_button.setVisibility(View.GONE); points_button.setVisibility(View.GONE); } else { talk_button.setVisibility(View.VISIBLE); points_button.setVisibility(View.VISIBLE); } } }); return rootView; } public void setupUI() { final ArrayList<String[]> conversas = setupConversations(); Log.d("Conversas", " Conversas size " + conversas.size()); //ListAdapter adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, conversas); ListAdapter adapter = new CustomAdapter(getActivity(),conversas); conv = (ListView) rootView.findViewById(R.id.listView2); conv.setAdapter(adapter); conv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(getActivity(), ChatActivity.class); String friendName = conversas.get(position)[1]; i.putExtra("friendSelected", friendName); i.putExtra("friendsIP", friendsNearby.get(friendName)); i.putExtra("chatEntry", conversas.get(position)[3]); startActivity(i); } }); } //interface utilizada para passar informação entre as activities e as tabs public interface Callbacks { HashMap<String,String> getNearbyFriends(); void generateFriends(); ArrayList<ChatEntry> getConversations(); String getChat(String friendName); } //código corrido quando vamos para esta tab @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (getView() != null) { setupUI(); } } } public ArrayList<String[]> setupConversations() { TabConversations.Callbacks callbacks = (TabConversations.Callbacks) getActivity(); ArrayList<ChatEntry> conversations = callbacks.getConversations(); ArrayList<String[]> conversas = new ArrayList<String[]>(); for (ChatEntry entry : conversations) { String chat = entry.getChat(); String[] chatParts = chat.split(System.getProperty("line.separator")); int chatPartsLength = chatParts.length; String mostRecent = chatParts[chatPartsLength-1]; //obter o que foi dito mais recentemente String[] mostRecent2 = mostRecent.split(":"); if(mostRecent2.length == 2) conversas.add(new String[]{mostRecent2[1], entry.getFriendName(), entry.getDate(), chat}); else if(chatPartsLength == 1) conversas.add(new String[]{mostRecent2[1], entry.getFriendName(), entry.getDate(), chat}); } return conversas; } }
35.056738
125
0.658305
35622c00948741b162167dec5da4048200ccd54d
1,425
package com.midas.junior.msglegion; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.CustomView> { class CustomView extends RecyclerView.ViewHolder{ TextView txt; TextView time; public CustomView(View itemView){ super(itemView); txt=itemView.findViewById(R.id.textMessage); time=itemView.findViewById(R.id.time); } } @Override public int getItemViewType(int position) { if(listA.get(position).isBubble()){ return R.layout.me_bubble; } return R.layout.bot_bubble; } List<Message> listA; public MessageAdapter(List ls){ this.listA=ls; } @Override public CustomView onCreateViewHolder(ViewGroup viewGroup, int i) { return new CustomView(LayoutInflater.from(viewGroup.getContext()).inflate(i,viewGroup,false)); } @Override public void onBindViewHolder(MessageAdapter.CustomView viewHolder, int i) { viewHolder.txt.setText(listA.get(i).msg); viewHolder.time.setText(listA.get(i).time); } @Override public int getItemCount() { return listA.size(); } }
26.886792
102
0.682105
7a53db8df7a4d2e319647ff9c4007560614ee043
13,681
package lecturerPackage; public class DisplayLecturerProfile extends javax.swing.JFrame { public int index; public DisplayLecturerProfile() { initComponents(); } public void DisplayLecturerProfile(int in){ this.index = in; name.setText(LecturerRecord.getLecturerList().get(index).getName()); tp.setText(LecturerRecord.getLecturerList().get(index).getId()); email.setText(LecturerRecord.getLecturerList().get(index).getEmail()); phone.setText(LecturerRecord.getLecturerList().get(index).getPhone()); department.setText(LecturerRecord.getLecturerList().get(index).getDepartment()); tp.setEnabled(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); backs = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); tp = new javax.swing.JTextField(); name = new javax.swing.JTextField(); email = new javax.swing.JTextField(); phone = new javax.swing.JTextField(); department = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(0, 153, 153)); jPanel2.setBackground(new java.awt.Color(0, 102, 102)); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Lecturer Profile"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(357, 357, 357) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE) .addContainerGap()) ); backs.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N backs.setText("Back"); backs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { backsActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(0, 0, 0)); jLabel2.setText("ID"); jLabel3.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(0, 0, 0)); jLabel3.setText("Name"); jLabel4.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(0, 0, 0)); jLabel4.setText("Email"); jLabel6.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(0, 0, 0)); jLabel6.setText("Phone No"); jLabel7.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(0, 0, 0)); jLabel7.setText("Department"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(backs, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(59, 59, 59) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(name)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tp, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(email))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 115, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(phone)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(department, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(66, 66, 66)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(27, 27, 27) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(name, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(phone, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(department, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)))) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(email, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 181, Short.MAX_VALUE) .addComponent(backs, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void backsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backsActionPerformed // TODO add your handling code here: setVisible(false); LecturerMenu admin = new LecturerMenu(index); this.dispose(); admin.setLocationRelativeTo(null); admin.setVisible(true); }//GEN-LAST:event_backsActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(DisplayLecturerProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DisplayLecturerProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DisplayLecturerProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DisplayLecturerProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DisplayLecturerProfile().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton backs; private javax.swing.JTextField department; private javax.swing.JTextField email; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField name; private javax.swing.JTextField phone; private javax.swing.JTextField tp; // End of variables declaration//GEN-END:variables }
56.533058
171
0.658212
c25d2ea1748c67da83b54abcb65c754408e612a7
831
package com.wfsample.service; import com.wfsample.common.dto.ResponseDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class ShoppingService { @Autowired @LoadBalanced protected RestTemplate restTemplate; public static final String STYLING_SERVICE_URL = "http://SHOPPING-SERVICE"; protected String serviceUrl; public ShoppingService(String serviceUrl) { this.serviceUrl = serviceUrl.startsWith("http") ? serviceUrl : "http://" + serviceUrl; } public ResponseDTO getHello() { ResponseDTO response = restTemplate.getForObject(serviceUrl + "/hello", ResponseDTO.class); return response; } }
29.678571
95
0.77858
5f51748f1663703e0c30766a8296f4ddd1c02629
3,593
package com.kxmall.market.app.api.api.goods; import com.kxmall.market.core.annotation.HttpMethod; import com.kxmall.market.core.annotation.HttpOpenApi; import com.kxmall.market.core.annotation.HttpParam; import com.kxmall.market.core.annotation.HttpParamType; import com.kxmall.market.core.annotation.param.NotNull; import com.kxmall.market.core.exception.ServiceException; import com.kxmall.market.data.dto.goods.SpuDTO; import com.kxmall.market.data.model.Page; /** * 提供给app端口商品业务类 * * @author kaixin * @date 2020/02/22 */ @HttpOpenApi(group = "goods", description = "商品服务") public interface GoodsService { @Deprecated @HttpMethod(description = "搜索Goods列表") public Page<SpuDTO> getGoodsPage( @HttpParam(name = "pageNo", type = HttpParamType.COMMON, description = "页码", valueDef = "1") Integer pageNo, @HttpParam(name = "pageSize", type = HttpParamType.COMMON, description = "页码长度", valueDef = "10") Integer pageSize, @HttpParam(name = "categoryId", type = HttpParamType.COMMON, description = "搜索分类") Long categoryId, @HttpParam(name = "orderBy", type = HttpParamType.COMMON, description = "排序 id 或 sales", valueDef = "a.id") String orderBy, @HttpParam(name = "isAsc", type = HttpParamType.COMMON, description = "是否升序", valueDef = "false") Boolean isAsc, @HttpParam(name = "title", type = HttpParamType.COMMON, description = "搜索标题") String title) throws ServiceException; @Deprecated @HttpMethod(description = "获取商品详情") public SpuDTO getGoods( @NotNull @HttpParam(name = "spuId", type = HttpParamType.COMMON, description = "商品Id") Long spuId, @HttpParam(name = "groupShopId", type = HttpParamType.COMMON, description = "团购Id") Long groupShopId, @HttpParam(name = "userId", type = HttpParamType.USER_ID, description = "用户Id") Long userId) throws ServiceException; @HttpMethod(description = "APP端-制定仓库下搜索Goods列表") public Page<SpuDTO> getGoodsPageByStorage( @NotNull @HttpParam(name = "storageId", type = HttpParamType.COMMON, description = "仓库id") Long storageId, @HttpParam(name = "pageNo", type = HttpParamType.COMMON, description = "页码", valueDef = "1") Integer pageNo, @HttpParam(name = "pageSize", type = HttpParamType.COMMON, description = "页码长度", valueDef = "10") Integer pageSize, @HttpParam(name = "categoryId", type = HttpParamType.COMMON, description = "搜索分类") Long categoryId, @HttpParam(name = "orderBy", type = HttpParamType.COMMON, description = "排序 id 或 sales", valueDef = "a.id") String orderBy, @HttpParam(name = "isAsc", type = HttpParamType.COMMON, description = "是否升序", valueDef = "false") Boolean isAsc, @HttpParam(name = "title", type = HttpParamType.COMMON, description = "搜索标题") String title) throws ServiceException; @HttpMethod(description = "APP端-制定仓库下获取商品详情") public SpuDTO getGoodsByStorage( @NotNull @HttpParam(name = "storageId", type = HttpParamType.COMMON, description = "仓库id") Long storageId, @NotNull @HttpParam(name = "spuId", type = HttpParamType.COMMON, description = "商品Id") Long spuId, @HttpParam(name = "userId", type = HttpParamType.USER_ID, description = "用户Id") Long userId, @HttpParam(name = "activityId", type = HttpParamType.COMMON, description = "活动id",valueDef = "0") Long activityId, @HttpParam(name = "couponId", type = HttpParamType.COMMON, description = "购物券id",valueDef = "0") Long couponId ) throws ServiceException; }
59.883333
135
0.687169
778c83dc83d75b544ec92b29385eb4122852d1fa
912
package mage.cards.d; import mage.abilities.effects.common.search.SearchLibraryAndExileTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.TargetPlayer; import java.util.UUID; /** * @author fireshoes */ public final class DenyingWind extends CardImpl { public DenyingWind(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{7}{U}{U}"); // Search target player's library for up to seven cards and exile them. Then that player shuffles their library. getSpellAbility().addEffect(new SearchLibraryAndExileTargetEffect(7, true)); getSpellAbility().addTarget(new TargetPlayer()); } private DenyingWind(final DenyingWind card) { super(card); } @Override public DenyingWind copy() { return new DenyingWind(this); } }
27.636364
120
0.717105
be712a6efdde348c787babe688166b3916dbea32
2,838
/******************************************************************************* * Copyright 2016 Intuit * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.intuit.wasabi.email; import io.swagger.annotations.ApiModelProperty; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.ArrayList; import java.util.List; /** * A Class to hold a list of email links for email. */ public class EmailLinksList { public static final String LINE_SEPARATOR = " \n"; @ApiModelProperty(value = "List of clickable email links for application Admins") private List<String> emailLinks = new ArrayList<>(); protected EmailLinksList() { super(); } public static Builder newInstance() { return new Builder(); } public static Builder from(EmailLinksList value) { return new Builder(value); } public static Builder withEmailLinksList(List<String> emailLinks) { return new Builder(emailLinks); } public List<String> getEmailLinks() { return emailLinks; } @Override public String toString() { StringBuilder allLinks = new StringBuilder(); for (String link : getEmailLinks()) { allLinks.append(link); allLinks.append(LINE_SEPARATOR); } return allLinks.toString(); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } public static class Builder { private EmailLinksList instance; private Builder() { instance = new EmailLinksList(); } private Builder(EmailLinksList other) { this(); instance.emailLinks = new ArrayList<>(other.emailLinks); } public Builder(List<String> emailLinks) { this(); instance.emailLinks = new ArrayList<>(emailLinks); } public EmailLinksList build() { EmailLinksList result = instance; instance = null; return result; } } }
27.823529
85
0.615574
8fa43930ddf4a86f899225fbe40984a6d2b065e2
7,441
package com.serenegiant.libcommon; /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2021 saki t_saki@serenegiant.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.serenegiant.dialog.ConfirmDialogV4; import com.serenegiant.libcommon.databinding.FragmentSafutilsBinding; import com.serenegiant.libcommon.viewmodel.SAFUtilsViewModel; import com.serenegiant.system.SAFPermission; import com.serenegiant.system.SAFUtils; import com.serenegiant.widget.ArrayListRecyclerViewAdapter; import com.serenegiant.widget.StringsRecyclerViewAdapter; import java.util.ArrayList; import java.util.List; import java.util.Map; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.databinding.DataBindingUtil; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; /** * SAFUtilクラスのテスト用Fragment */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public class SAFUtilsFragment extends BaseFragment implements ConfirmDialogV4.ConfirmDialogListener { private static final boolean DEBUG = true; // set false on production private static final String TAG = SAFUtilsFragment.class.getSimpleName(); private FragmentSafutilsBinding mBinding; private StringsRecyclerViewAdapter mAdapter; private SAFPermission mSAFPermission; /** * デフォルトコンストラクタ */ public SAFUtilsFragment() { super(); // デフォルトコンストラクタが必要 } @Override public void onAttach(@NonNull final Context context) { super.onAttach(context); // XXX Fragmentの場合SAFPermissionを#onAttachまたは#onCreateで初期化しないといけない mSAFPermission = new SAFPermission(this, SAFPermission.DEFAULT_CALLBACK); } @Nullable @Override public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) { if (DEBUG) Log.v(TAG, "onCreateView:"); mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_safutils, container, false); return mBinding.getRoot(); } @Override public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (DEBUG) Log.v(TAG, "onViewCreated:"); mBinding.setViewModel(mViewModel); initView(); } @Override protected void internalOnResume() { super.internalOnResume(); if (DEBUG) Log.v(TAG, "internalOnResume:"); updateSAFPermissions(); } @Override protected void internalOnPause() { if (DEBUG) Log.v(TAG, "internalOnPause:"); super.internalOnPause(); } /** * 指定したリクエストコードに対するパーミッションをすでに保持しているときに * 再設定するかどうかの問い合わせに対するユーザーレスポンスの処理 * @param dialog * @param requestCode * @param result DialogInterface#BUTTONxxx * @param userArgs */ @Override public void onConfirmResult( @NonNull final ConfirmDialogV4 dialog, final int requestCode, final int result, @Nullable final Bundle userArgs) { if (result == DialogInterface.BUTTON_POSITIVE) { // ユーザーがOKを押したときの処理, パーミッションを要求する requestPermission(requestCode); } } //-------------------------------------------------------------------------------- /** * 表示を初期化 */ private void initView() { mAdapter = new StringsRecyclerViewAdapter( R.layout.list_item_title, new ArrayList<String>()); mAdapter.setOnItemClickListener( new ArrayListRecyclerViewAdapter.ArrayListRecyclerViewListener<String>() { @Override public void onItemClick( @NonNull final RecyclerView.Adapter<?> parent, @NonNull final View view, final int position, @Nullable final String item) { } @Override public boolean onItemLongClick( @NonNull final RecyclerView.Adapter<?> parent, @NonNull final View view, final int position, @Nullable final String item) { if (!TextUtils.isEmpty(item)) { final String[] v = item.split("@"); if (v.length == 2) { try { final int requestCode = Integer.parseInt(v[0]); if (requestCode != 0) { Toast.makeText(requireContext(), "release permission,requestCode=" + requestCode, Toast.LENGTH_SHORT).show(); SAFUtils.releasePersistableUriPermission(requireContext(), requestCode); updateSAFPermissions(); return true; } } catch (final NumberFormatException e) { Log.w(TAG, e); } } } return false; } @Override public void onItemSelected( @NonNull final RecyclerView.Adapter<?> parent, @NonNull final View view, final int position, @Nullable final String item) { if (DEBUG) Log.v(TAG, "onItemSelected:position=" + position + ",item=" + item); } @Override public void onNothingSelected(@NonNull final RecyclerView.Adapter<?> parent) { if (DEBUG) Log.v(TAG, "onNothingSelected:"); } }); mBinding.list.setLayoutManager(new LinearLayoutManager(requireContext())); mBinding.list.setAdapter(mAdapter); } /** * 表示内容の処理用ViewModelオブジェクト */ private final SAFUtilsViewModel mViewModel = new SAFUtilsViewModel() { @Override public void onClick(final View v) { if (DEBUG) Log.v(TAG, "onClick:" + v); if (v.getId() == R.id.add_btn) { final int requestCode = mViewModel.getRequestCode(); if ((requestCode != 0) && ((requestCode & 0xffff) == requestCode)) { if (DEBUG) Log.v(TAG, "onClick:request SAF permission,requestCode=" + requestCode); if (!SAFUtils.hasPermission(requireContext(), requestCode)) { requestPermission(requestCode); } else { ConfirmDialogV4.showDialog(SAFUtilsFragment.this, requestCode, R.string.title_request_saf_permission, "Already has permission for requestCode(" + requestCode + ")", true); } } else { Toast.makeText(requireContext(), "Fragmentからは下位16ビットしかリクエストコードとして使えない," + requestCode, Toast.LENGTH_SHORT).show(); } } } }; /** * 指定したリクエストコードに対するパーミッションを要求 * @param requestCode */ private void requestPermission(final int requestCode) { SAFUtils.releasePersistableUriPermission(requireContext(), requestCode); mSAFPermission.requestPermission(requestCode); } /** * 保持しているパーミッション一覧表示を更新 */ private void updateSAFPermissions() { if (DEBUG) Log.v(TAG, "updateSAFPermissions:"); @NonNull final Map<Integer, Uri> map = SAFUtils.getStorageUriAll(requireContext()); final List<String> list = new ArrayList<>(); for (final Map.Entry<Integer, Uri> entry: map.entrySet()) { list.add(entry.getKey() + "@" + entry.getValue().toString()); } mAdapter.replaceAll(list); mAdapter.notifyDataSetChanged(); } }
29.883534
97
0.721005
dbeb73f2bc79bd8af5d755bb3ff7e7b7c78084de
1,285
package br.com.alura; public class TestaCursoComAluno { public static void main(String[] args) { Curso javaColecoes = new Curso("Dominando as coleções do Java", "Paulo Silveira"); javaColecoes.adiciona(new Aula("Trabalhando com ArrayList", 21)); javaColecoes.adiciona(new Aula("Criando uma Aula", 20)); javaColecoes.adiciona(new Aula("Modelando com coleções", 24)); Aluno a1 = new Aluno("Rodrigo Turini", 34672); Aluno a2 = new Aluno("Guilherme Silveira", 5617); Aluno a3 = new Aluno("Mauricio Aniche", 17645); javaColecoes.matricula(a1); javaColecoes.matricula(a2); javaColecoes.matricula(a3); System.out.println("Todos os alunos matriculados: "); javaColecoes.getAlunos().forEach(aluno -> { System.out.println(aluno); }); System.out.println("O aluno " + a1.getNome() + " está matriculado?"); System.out.println(javaColecoes.estaMatriculado(a1)); Aluno turini = new Aluno("Rodrigo Turini", 34672); System.out.println("E esse Turini, está matriculado?"); System.out.println(javaColecoes.estaMatriculado(turini)); System.out.println("O a1 é equals ao Turini?"); System.out.println(a1.equals(turini)); // obrigatoriamente o seguinte é true System.out.println(a1.hashCode() == turini.hashCode()); } }
29.883721
71
0.702724
4c26e66897ab4be0cada7000c32383512eaac188
787
package com.nd.android.rxjavademo.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import com.nd.android.rxjavademo.R; /** * BaseCompatActivity * <p> * Created by HuangYK on 16/8/30. */ public class BaseCompatActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { initTheme(); super.onCreate(savedInstanceState); } protected void initTheme() { setTheme(R.style.RJDTheme); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
21.861111
59
0.670902
c57f8307469dc0dfcaa9df7e872c9317342a6d52
16,136
/* * Artifactory is a binaries repository manager. * Copyright (C) 2012 JFrog Ltd. * * Artifactory is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Artifactory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Artifactory. If not, see <http://www.gnu.org/licenses/>. */ package org.artifactory.schedule.aop; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.artifactory.api.repo.Async; import org.artifactory.common.ConstantValues; import org.artifactory.sapi.common.Lock; import org.artifactory.schedule.CachedThreadPoolTaskExecutor; import org.artifactory.spring.InternalArtifactoryContext; import org.artifactory.spring.InternalContextHelper; import org.artifactory.storage.fs.lock.aop.LockingAdvice; import org.artifactory.storage.fs.session.StorageSession; import org.artifactory.storage.fs.session.StorageSessionHolder; import org.artifactory.storage.tx.SessionResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.framework.AopProxyUtils; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.aop.support.AopUtils; import org.springframework.core.task.TaskRejectedException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; /** * @author Yoav Landman */ public class AsyncAdvice implements MethodInterceptor { private static final Logger log = LoggerFactory.getLogger(AsyncAdvice.class); // holds all the pending and running invocations. used only during tests private ConcurrentHashMap<MethodInvocation, MethodInvocation> pendingInvocations = new ConcurrentHashMap<>(); @Override public Future<?> invoke(final MethodInvocation invocation) throws Throwable { MethodAnnotation<Lock> lockMethodAnnotation = getMethodAnnotation(invocation, Lock.class); if (lockMethodAnnotation.annotation != null) { throw new RuntimeException("The @Async annotation cannot be used with the @Lock annotation. " + "Use @Async#transactional=true instead: " + lockMethodAnnotation.method); } MethodAnnotation<Async> asyncMethodAnnotation = getMethodAnnotation(invocation, Async.class); boolean delayExecutionUntilCommit = asyncMethodAnnotation.annotation.delayUntilAfterCommit(); boolean failIfNotScheduledFromTransaction = asyncMethodAnnotation.annotation.failIfNotScheduledFromTransaction(); boolean inTransaction = LockingAdvice.isInTransaction(); if (!inTransaction && delayExecutionUntilCommit) { if (failIfNotScheduledFromTransaction) { throw new IllegalStateException("Async invocation scheduled for after commit, " + "cannot be scheduled outside a transaction: " + asyncMethodAnnotation.method); } else { log.debug("Async invocation scheduled for after commit, but not scheduled inside a transaction: {}", asyncMethodAnnotation.method); } } TraceableMethodInvocation traceableInvocation = new TraceableMethodInvocation(invocation, Thread.currentThread().getName()); log.trace("Adding: {}", traceableInvocation); if (ConstantValues.test.getBoolean()) { pendingInvocations.put(traceableInvocation, traceableInvocation); } try { if (delayExecutionUntilCommit && inTransaction) { //Schedule task submission for session save() StorageSession session = StorageSessionHolder.getSession(); MethodCallbackSessionResource sessionCallbacks = session.getOrCreateResource(MethodCallbackSessionResource.class); sessionCallbacks.setAdvice(this); sessionCallbacks.addInvocation(traceableInvocation, asyncMethodAnnotation.annotation.shared()); //No future return null; } else { //Submit immediately Future<?> future = submit(traceableInvocation); return future; } } catch (Exception e) { // making sure to remove the invocation from the pending/executing removeInvocation(traceableInvocation); throw e; } } @SuppressWarnings({"unchecked"}) private <T extends Annotation> MethodAnnotation<T> getMethodAnnotation(MethodInvocation invocation, Class<T> annotationClass) { Method method = invocation.getMethod(); T annotation = method.getAnnotation(annotationClass); //Try to read the class level annotation if the interface is not found if (annotation != null) { return new MethodAnnotation(method, annotation); } Class<?> targetClass = AopProxyUtils.ultimateTargetClass( ((ReflectiveMethodInvocation) invocation).getProxy()); Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); annotation = specificMethod.getAnnotation(annotationClass); return new MethodAnnotation(specificMethod, annotation); } private Future<?> submit(final MethodInvocation invocation) { InternalArtifactoryContext context = InternalContextHelper.get(); CachedThreadPoolTaskExecutor executor = context.beanForType(CachedThreadPoolTaskExecutor.class); Future<?> future = null; try { future = executor.submit(new Callable<Object>() { @Override public Object call() { try { if (TransactionSynchronizationManager.isSynchronizationActive()) { //Sanity check we should never have a tx sync on an existing pooled thread throw new IllegalStateException( "An async invocation (" + invocation.getMethod() + ") " + "should not be associated with an existing transaction."); } Object result = doInvoke(invocation); // if the result is not of type Future don't bother returning it (unless you are fond of ClassCastExceptions) if (result instanceof Future) { return ((Future) result).get(); } else { return null; } } catch (Throwable throwable) { Throwable loggedThrowable; if (invocation instanceof TraceableMethodInvocation) { Throwable original = ((TraceableMethodInvocation) invocation).getThrowable(); original.initCause(throwable); loggedThrowable = original; } else { loggedThrowable = throwable; } Method method; if (invocation instanceof CompoundInvocation) { method = ((CompoundInvocation) invocation).getLatestMethod(); } else { method = invocation.getMethod(); } log.error("Could not execute async method: '" + method + "'.", loggedThrowable); return null; } } }); } catch (TaskRejectedException e) { log.error("Task {} rejected by scheduler: {}", invocation, e.getMessage()); log.debug("Task {} rejected by scheduler: {}", invocation, e.getMessage(), e); } // only return the future result if the method returns a Future object if (!(invocation instanceof CompoundInvocation) && Future.class.isAssignableFrom(invocation.getMethod().getReturnType())) { return future; } else { return null; } } Object doInvoke(MethodInvocation invocation) throws Throwable { if (invocation instanceof CompoundInvocation) { invocation.proceed(); return null; // multiple invocations -> no single return type } Authentication originalAuthentication = null; try { MethodAnnotation<Async> methodAnnotation = getMethodAnnotation(((TraceableMethodInvocation) invocation).wrapped, Async.class); if (methodAnnotation.annotation == null) { throw new IllegalArgumentException( "An async invocation (" + invocation.getMethod() + ") should be used with an @Async annotated invocation."); } if (methodAnnotation.annotation.authenticateAsSystem()) { SecurityContext securityContext = SecurityContextHolder.getContext(); originalAuthentication = securityContext.getAuthentication(); InternalContextHelper.get().getSecurityService().authenticateAsSystem(); } if (methodAnnotation.annotation.transactional()) { //Wrap in a transaction log.trace("Invoking {} in transaction", invocation); return new LockingAdvice().invoke(invocation); } else { log.trace("Invoking {} ", invocation); return invocation.proceed(); } } catch (TaskRejectedException e) { log.warn("Task was rejected by scheduler: {}", e.getMessage()); log.debug("Task was reject by scheduler", e); return null; } finally { if (originalAuthentication != null) { SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(originalAuthentication); } // remove the invocations here (called from the Compound also) removeInvocation(invocation); } } private void removeInvocation(MethodInvocation invocation) { if (ConstantValues.test.getBoolean()) { log.trace("Removing: {}", invocation); pendingInvocations.remove(invocation); } } public ImmutableSet<MethodInvocation> getCurrentInvocations() { return ImmutableSet.copyOf(pendingInvocations.keySet()); } public void clearPendingInvocations() { if (ConstantValues.test.getBoolean()) { log.trace("Clearing all asyn invocations: {}", pendingInvocations); pendingInvocations.clear(); } } /** * @param method The method to check if pending execution (usually the interface method, not the implementation!) * @return True if there is an pending (or running) async call to the given method */ public boolean isPending(Method method) { // iterate on a copy to avoid ConcurrentModificationException for (MethodInvocation invocation : getCurrentInvocations()) { if (invocation instanceof CompoundInvocation) { ImmutableList<MethodInvocation> invocations = ((CompoundInvocation) invocation).getInvocations(); for (MethodInvocation methodInvocation : invocations) { if (method.equals(methodInvocation.getMethod())) { return true; } } } else { if (method.equals(invocation.getMethod())) { return true; } } } return false; } public static class MethodCallbackSessionResource implements SessionResource { AsyncAdvice advice; final List<MethodInvocation> invocations = new ArrayList<>(); final CompoundInvocation sharedInvocations = new CompoundInvocation(); public void setAdvice(AsyncAdvice advice) { this.advice = advice; sharedInvocations.setAdvice(advice); } public void addInvocation(TraceableMethodInvocation invocation, boolean shared) { if (shared) { sharedInvocations.add(invocation); } else { invocations.add(invocation); } } @Override public void afterCompletion(boolean commit) { if (commit) { //Submit the shared ones first if (!sharedInvocations.isEmpty()) { advice.submit(sharedInvocations); } if (!invocations.isEmpty()) { //Clear the invocations for this session and submit them for async execution ArrayList<MethodInvocation> tmpInvocations = Lists.newArrayList(invocations); //Reset internal state invocations.clear(); for (MethodInvocation invocation : tmpInvocations) { advice.submit(invocation); } } } else { sharedInvocations.clear(); invocations.clear(); } } @Override public boolean hasPendingResources() { return !invocations.isEmpty(); } @Override public void onSessionSave() { } } private static class TraceableMethodInvocation implements MethodInvocation { private final MethodInvocation wrapped; private final Throwable throwable; public TraceableMethodInvocation(MethodInvocation wrapped, String threadName) { this.wrapped = wrapped; String msg = "[" + threadName + "] async call to '" + wrapped.getMethod() + "' completed with error."; this.throwable = new Throwable(msg); } public Throwable getThrowable() { return throwable; } @Override public Method getMethod() { return wrapped.getMethod(); } @Override public Object[] getArguments() { return wrapped.getArguments(); } @Override public Object proceed() throws Throwable { return wrapped.proceed(); } @Override public Object getThis() { return wrapped.getThis(); } @Override public AccessibleObject getStaticPart() { return wrapped.getStaticPart(); } @Override public String toString() { return wrapped.toString(); } } private static class MethodAnnotation<T extends Annotation> { private MethodAnnotation(Method method, T annotation) { this.method = method; this.annotation = annotation; } private final Method method; private final T annotation; } }
42.914894
133
0.618741
6df3b087e56d681c4034a75bd757212b88b97d00
215
package com.rhymes.app.admin.chart.util; import java.util.Date; public class AdminChartLastDay { public int LastDay(int month) { int lastDay = ( new Date( 2019, month, 0) ).getDate(); return lastDay; } }
16.538462
56
0.697674
13e449d874c61f4893acb187e2ee4d1e3f5d91e1
632
/* * 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 Triangle.AbstractSyntaxTrees; import Triangle.SyntacticAnalyzer.SourcePosition; /** * * @author karol */ public class PackageEmptyDeclaration extends PackageDeclaration{ //Fields //Constructor public PackageEmptyDeclaration(SourcePosition thePosition) { super(thePosition); } //Visitor public Object visit(Visitor v, Object o) { return v.visitPackageEmptyDeclaration(this, o); } }
24.307692
79
0.71519
c132bf7e2a2c460a5f52e845e29190f906b9a524
4,168
package com.rob.model; import java.math.BigDecimal; import java.time.LocalDate; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonProperty; public class CandidatePrevEmployment { @JsonProperty(value = "id") private int id; @JsonProperty(value = "companyName") @NotBlank(message = "Company name cannot be blank.") private String companyName; @JsonProperty(value = "totalExperienceInMonths") private int totalExperienceInMonths; @JsonProperty(value = "relevantExperienceInMonths") private int relevantExperienceInMonths; @JsonProperty(value = "startDate") private LocalDate startDate; @JsonProperty(value = "endDate") private LocalDate endDate; @JsonProperty(value = "designation") @NotBlank(message = "Designation cannot be blank.") private String designation; @JsonProperty(value = "remuneration") private BigDecimal remuneration; @JsonProperty(value = "natureOfEmployment") @NotBlank(message = "Nature of Employment cannot be blank.") private String natureOfEmployment; @JsonProperty(value = "supervisorName") @NotBlank(message = "Supervisor name cannot be blank.") private String supervisorName; @JsonProperty(value = "supervisorDesignation") @NotBlank(message = "Supervisor designation cannot be blank.") private String supervisorDesignation; @JsonProperty(value = "reasonForLeaving") @NotBlank(message = "Reason for leaving cannot be blank.") private String reasonForLeaving; @JsonProperty(value = "supervisorEmailId") @Email @NotBlank(message = "Supervisor email cannot be blank.") private String supervisorEmailId; @JsonProperty(value = "employeeCode") @NotBlank(message = "Employee-Code cannot be blank.") private String employeeCode; public CandidatePrevEmployment() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public BigDecimal getRemuneration() { return remuneration; } public void setRemuneration(BigDecimal remuneration) { this.remuneration = remuneration; } public String getNatureOfEmployment() { return natureOfEmployment; } public void setNatureOfEmployment(String natureOfEmployment) { this.natureOfEmployment = natureOfEmployment; } public String getSupervisorName() { return supervisorName; } public void setSupervisorName(String supervisorName) { this.supervisorName = supervisorName; } public String getSupervisorDesignation() { return supervisorDesignation; } public void setSupervisorDesignation(String supervisorDesignation) { this.supervisorDesignation = supervisorDesignation; } public String getReasonForLeaving() { return reasonForLeaving; } public void setReasonForLeaving(String reasonForLeaving) { this.reasonForLeaving = reasonForLeaving; } public String getSupervisorEmailId() { return supervisorEmailId; } public void setSupervisorEmailId(String supervisorEmailId) { this.supervisorEmailId = supervisorEmailId; } public String getEmployeeCode() { return employeeCode; } public void setEmployeeCode(String employeeCode) { this.employeeCode = employeeCode; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public int getTotalExperienceInMonths() { return totalExperienceInMonths; } public void setTotalExperienceInMonths(int totalExperienceInMonths) { this.totalExperienceInMonths = totalExperienceInMonths; } public int getRelevantExperienceInMonths() { return relevantExperienceInMonths; } public void setRelevantExperienceInMonths(int relevantExperienceInMonths) { this.relevantExperienceInMonths = relevantExperienceInMonths; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } }
23.027624
76
0.774952
ddefa1a553c95e2ebd951839307aed0233cdf439
1,644
package com.qa.ims.persistence.domain; import org.junit.Test; import nl.jqno.equalsverifier.EqualsVerifier; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; public class OrderTest { List<Item> testItems = new ArrayList<>(); Order testOrder = new Order(null, null, testItems, 0.0); Item testItem = new Item("jordan", 50); Customer testCustomer = new Customer("jordan", "harrison"); @Test public void testEquals() { EqualsVerifier.simple().forClass(Order.class).verify(); } @Test public void testCalulateValueZero() { assertEquals(testOrder.getValue(), testOrder.calculateValue(), 0.9f); } @Test public void testCalulateValue() { testItems.add(testItem); assertEquals(testItem.getPrice(), testOrder.calculateValue(),0.9f); } @Test public void testGetToString() { Customer testCustomer = new Customer("jordan", "harrison"); Order testOrderToString = new Order(2L, testCustomer, testItems, 0.0); System.out.println(testOrderToString); } @Test public void testGetToStringWItems() { testItems.add(testItem); Order testOrderToStringDuo = new Order(2L, testCustomer, testItems, 0.0); System.out.println(testOrderToStringDuo); } @Test public void testGetCustomer() { Order testOrderCustomer = new Order(3L, testCustomer, testItems, 0.0); System.out.print(testOrderCustomer.getCustomer()); } @Test public void testGetItems() { testOrder.getItems(); System.out.println(testOrder.getItems()); assertEquals(testItems, testOrder.getItems()); } @Test public void testGetId() { assertEquals(null, testOrder.getId()); } }
23.15493
75
0.72871
534f20047b353af73509fc819365e7650f938285
1,130
package it.drwolf.alerting.conf; import java.io.Serializable; import javax.persistence.EntityManager; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import it.drwolf.alerting.entity.AppParam; @Name("componentBean") @AutoCreate @Scope(ScopeType.EVENT) public class ComponentBean implements Serializable { @In(create = true) private EntityManager entityManager; /** * */ private static final long serialVersionUID = 1L; public String getMailHost() { return this.entityManager.find(AppParam.class, "app.mail.host").toString(); } public int getMailPort() { return Integer.parseInt(this.entityManager.find(AppParam.class, "app.mail.port").toString().toString()); } public String getMailPassword(){ return this.entityManager.find(AppParam.class, "app.mail.password").toString().toString(); } public String getMailUsername(){ return this.entityManager.find(AppParam.class, "app.mail.user").toString().toString(); } }
20.178571
65
0.742478
933b871bb6b74288b555737869a58b7096cbfcb2
1,369
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.portlet.degreeprogress.model.xml; import java.util.ArrayList; import java.util.List; import org.jasig.portlet.degreeprogress.model.StudentCourseRegistration; abstract public class CourseRequirementWrapper { protected List<StudentCourseRegistration> registrations = new ArrayList<StudentCourseRegistration>(); public List<StudentCourseRegistration> getRegistrations() { return registrations; } public void setRegistrations(List<StudentCourseRegistration> registrations) { this.registrations = registrations; } }
38.027778
105
0.768444
535dbc30824b8629010eacb7acac5a4bf8a7b66f
792
package zdream.nsfplayer.ftm.executor.effect; import zdream.nsfplayer.ftm.executor.FamiTrackerRuntime; /** * 音键停止播放声音的效果. 单例 * * @author Zdream * @since 0.2.1 */ public class NoteHaltEffect implements IFtmEffect { private static NoteHaltEffect instance = new NoteHaltEffect(); private NoteHaltEffect() { // 单例 } public static NoteHaltEffect of() { return instance; } @Override public FtmEffectType type() { return FtmEffectType.HALT; } @Override public void execute(byte channelCode, FamiTrackerRuntime runtime) { runtime.channels.get(channelCode).doHalt(); } @Override public String toString() { return "Note:---"; } /** * 优先度必须大于 {@link NoteEffect} 和 {@link NoiseEffect}, * 以便静音之后, 允许放声音的效果重写 */ public int priority() { return 1; } }
16.851064
68
0.698232
4cd79e2fb341054ad39af24bc296db79049defeb
11,366
package bloom; import java.util.ArrayList; import java.util.Locale; import java.util.Random; import stream.ConcurrentGenericReadInputStream; import stream.ConcurrentReadInputStream; import stream.FASTQ; import stream.FastaReadInputStream; import stream.Read; import structures.ListNum; import dna.AminoAcid; import fileIO.FileFormat; import fileIO.ReadWrite; import shared.Timer; /** * @author Brian Bushnell * @date Jul 6, 2012 * */ public class LargeKmerCount2 { public static void main(String[] args){ Timer t=new Timer(); String fname1=args[0]; String fname2=(args.length>4 || args[1].contains(".") ? args[1] : null); int indexbits=Integer.parseInt(args[args.length-3]); int cbits=Integer.parseInt(args[args.length-2]); int k=Integer.parseInt(args[args.length-1]); KCountArray2 count=null; if(fileIO.FileFormat.hasFastaExtension(fname1)){ FastaReadInputStream.MIN_READ_LEN=k; } count=countFastq(fname1, fname2, indexbits, cbits, k); FastaReadInputStream.TARGET_READ_LEN=999999999; t.stop(); System.out.println("Finished counting; time = "+t); long[] freq=count.transformToFrequency(); // System.out.println(count+"\n"); // System.out.println(Arrays.toString(freq)+"\n"); long sum=sum(freq); System.out.println("Kmer fraction:"); int lim1=8, lim2=16; for(int i=0; i<lim1; i++){ String prefix=i+""; while(prefix.length()<8){prefix=prefix+" ";} System.out.println(prefix+"\t"+String.format(Locale.ROOT, "%.3f%% ",(100l*freq[i]/(double)sum))+"\t"+freq[i]); } while(lim1<=freq.length){ int x=0; for(int i=lim1; i<lim2; i++){ x+=freq[i]; } String prefix=lim1+"-"+(lim2-1); if(lim2>=freq.length){prefix=lim1+"+";} while(prefix.length()<8){prefix=prefix+" ";} System.out.println(prefix+"\t"+String.format(Locale.ROOT, "%.3f%% ",(100l*x/(double)sum))+"\t"+x); lim1*=2; lim2=min(lim2*2, freq.length); } long estKmers=load+min(actualCollisions, (long)expectedCollisions); long sum2=sum-freq[0]; long x=freq[1]; System.out.println(); System.out.println("Keys Counted: \t \t"+keysCounted); System.out.println("Unique: \t \t"+sum2); System.out.println("probCollisions:\t \t"+(long)probNewKeyCollisions); System.out.println("EstimateP: \t \t"+(sum2+(long)probNewKeyCollisions)); System.out.println("expectedColl: \t \t"+(long)expectedCollisions); System.out.println("actualColl: \t \t"+(long)actualCollisions); System.out.println("estimateKmers: \t \t"+estKmers); System.out.println(); System.out.println("Singleton: \t"+String.format(Locale.ROOT, "%.3f%% ",(100l*x/(double)sum2))+"\t"+x); x=sum2-x; System.out.println("Useful: \t"+String.format(Locale.ROOT, "%.3f%% ",(100l*x/(double)sum2))+"\t"+x); } public static KCountArray2 countFastq(String reads1, String reads2, int indexbits, int cbits, int k){ assert(indexbits>=1 && indexbits<40); final long cells=1L<<indexbits; final int kbits=ROTATE_DIST*k; final int xorShift=kbits%64; final long[] rotMasks=makeRotMasks(xorShift); final int[] buffer=new int[k]; if(verbose){System.err.println("k="+k+", kbits="+kbits+", indexbits="+indexbits+", cells="+cells+", cbits="+cbits);} if(verbose){System.err.println("xorShift="+xorShift+", rotMasks[3]="+Long.toHexString(rotMasks[3]));} final KCountArray2 count=new KCountArray2(cells, cbits); load=0; probNewKeyCollisions=0; invCells=1d/cells; invKmerSpace=Math.pow(0.5, 2*k); if(cells>=Math.pow(4, k)){invCells=0;} final ConcurrentReadInputStream cris; { FileFormat ff1=FileFormat.testInput(reads1, FileFormat.FASTQ, null, true, true); FileFormat ff2=FileFormat.testInput(reads2, FileFormat.FASTQ, null, true, true); cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff1, ff2); if(verbose){System.err.println("Started cris");} cris.start(); //4567 } boolean paired=cris.paired(); if(verbose){System.err.println("Paired: "+paired);} long kmer=0; //current kmer int len=0; //distance since last contig start or ambiguous base { ListNum<Read> ln=cris.nextList(); ArrayList<Read> reads=(ln!=null ? ln.list : null); if(reads!=null && !reads.isEmpty()){ Read r=reads.get(0); assert(paired==(r.mate!=null)); } while(reads!=null && reads.size()>0){ //System.err.println("reads.size()="+reads.size()); for(Read r : reads){ readsProcessed++; len=0; kmer=0; byte[] bases=r.bases; byte[] quals=r.quality; for(int i=0; i<bases.length; i++){ byte b=bases[i]; int x=AminoAcid.baseToNumber[b]; int x2=buffer[len%buffer.length]; buffer[len%buffer.length]=x; if(x<0){ len=0; kmer=0; }else{ kmer=(Long.rotateLeft(kmer,ROTATE_DIST)^x); len++; if(len>=k){ keysCounted++; if(len>k){kmer=kmer^rotMasks[x2];} long hashcode=kmer&0x7fffffffffffffffL; // hashcode=randy.nextLong()&~((-1L)<<(2*k)); long code1=hashcode%(cells-3); // long code2=((~hashcode)&0x7fffffffffffffffL)%(cells-5); int value=count.increment2(code1, 1); double probCollision=load*invCells; // expectedCollisions+=probCollision; expectedCollisions+=probCollision*(1-(load+min(expectedCollisions, actualCollisions))*invKmerSpace); if(value==0){load++;} else{ actualCollisions++; double probNewKey=(load*invCells)*expectedCollisions/(min(expectedCollisions, actualCollisions)); double estKeys=load+probNewKeyCollisions; double probOldKey=estKeys*invKmerSpace; probNewKeyCollisions+=probNewKey*(1-probOldKey); // double estKmers=load+min(actualCollisions, expectedCollisions); // double probOldKmer=estKmers*invKmerSpace; // probNewKeyCollisions+=(prob*(1-prob2)); } //// probCollisions+=(load*invCells); // if(value==0){load++;} // else{ //// long load2=keysCounted-load; // double prob=Math.sqrt(load*invCells); // double estKmers=load+probNewKeyCollisions; // double prob2=estKmers*invKmerSpace; //// probCollisions+=(prob*(1-prob2)); //// probCollisions+=Math.sqrt(prob*(1-prob2)); // probNewKeyCollisions+=Math.sqrt(prob*(1-prob2)); //// probCollisions+=min(prob, 1-prob2); //// probCollisions+=(load*invCells); // } } } } if(r.mate!=null){ len=0; kmer=0; bases=r.mate.bases; quals=r.mate.quality; for(int i=0; i<bases.length; i++){ byte b=bases[i]; int x=AminoAcid.baseToNumber[b]; int x2=buffer[len%buffer.length]; buffer[len%buffer.length]=x; if(x<0){ len=0; kmer=0; }else{ kmer=(Long.rotateLeft(kmer,ROTATE_DIST)^x); len++; if(len>=k){ keysCounted++; if(len>k){kmer=kmer^rotMasks[x2];} long hashcode=kmer&0x7fffffffffffffffL; // hashcode=randy.nextLong()&~((-1L)<<(2*k)); long code1=hashcode%(cells-3); // long code2=((~hashcode)&0x7fffffffffffffffL)%(cells-5); int value=count.increment2(code1, 1); double probCollision=load*invCells; // expectedCollisions+=probCollision; expectedCollisions+=probCollision*(1-(load+min(expectedCollisions, actualCollisions))*invKmerSpace); if(value==0){load++;} else{ actualCollisions++; double probNewKey=(load*invCells)*expectedCollisions/(min(expectedCollisions, actualCollisions)); double estKeys=load+probNewKeyCollisions; double probOldKey=estKeys*invKmerSpace; probNewKeyCollisions+=probNewKey*(1-probOldKey); // double estKmers=load+min(actualCollisions, expectedCollisions); // double probOldKmer=estKmers*invKmerSpace; // probNewKeyCollisions+=(prob*(1-prob2)); } //// probCollisions+=(load*invCells); // if(value==0){load++;} // else{ //// long load2=keysCounted-load; // double prob=Math.sqrt(load*invCells); // double estKmers=load+probNewKeyCollisions; // double prob2=estKmers*invKmerSpace; //// probCollisions+=(prob*(1-prob2)); //// probCollisions+=Math.sqrt(prob*(1-prob2)); // probNewKeyCollisions+=Math.sqrt(prob*(1-prob2)); //// probCollisions+=min(prob, 1-prob2); //// probCollisions+=(load*invCells); // } } } } } } //System.err.println("returning list"); cris.returnList(ln.id, ln.list.isEmpty()); //System.err.println("fetching list"); ln=cris.nextList(); reads=(ln!=null ? ln.list : null); } System.err.println("Finished reading"); cris.returnList(ln.id, ln.list.isEmpty()); System.err.println("Returned list"); ReadWrite.closeStream(cris); System.err.println("Closed stream"); System.err.println("Processed "+readsProcessed+" reads."); } return count; } public static final long[] makeRotMasks(int rotDist){ long[] masks=new long[4]; for(long i=0; i<4; i++){ masks[(int)i]=Long.rotateLeft(i, rotDist); } return masks; } public static long[] transformToFrequency(int[] count){ long[] freq=new long[2000]; int max=freq.length-1; for(int i=0; i<count.length; i++){ int x=count[i]; x=min(x, max); freq[x]++; } return freq; } public static long sum(int[] array){ long x=0; for(int y : array){x+=y;} return x; } public static long sum(long[] array){ long x=0; for(long y : array){x+=y;} return x; } public static final int min(int x, int y){return x<y ? x : y;} public static final int max(int x, int y){return x>y ? x : y;} public static final long min(long x, long y){return x<y ? x : y;} public static final long max(long x, long y){return x>y ? x : y;} public static final double min(double x, double y){return x<y ? x : y;} public static final double max(double x, double y){return x>y ? x : y;} public static boolean verbose=true; public static byte minQuality=-5; public static long readsProcessed=0; public static long maxReads=10000000L; public static final int ROTATE_DIST=2; /** Non-empty cells in hash table */ public static long load; /** Number of expected collisions */ public static double expectedCollisions; /** Number of actual collisions (possibly by same value) */ public static long actualCollisions; /** Number of probable collisions caused by new keys */ public static double probNewKeyCollisions; /** Inverse of hash table size */ public static double invCells; /** Inverse of number of potential kmers */ public static double invKmerSpace; /** Inverse of number of potential kmers */ public static long keysCounted; public static final Random randy=new Random(1); }
34.02994
119
0.616048
1690a725f3221fa49e1e4f1943813eebdf1543c2
3,674
package view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import com.a340team.tickettoride.R; import java.util.List; import java.util.Map; import shared.model.CityPoint; import shared.model.Route; import shared.model.interfaces.IRoute; import static shared.model.Color.BLACK; import static shared.model.Color.BLUE; import static shared.model.Color.GRAY; import static shared.model.Color.GREEN; import static shared.model.Color.ORANGE; import static shared.model.Color.PINK; import static shared.model.Color.RED; import static shared.model.Color.WHITE; import static shared.model.Color.YELLOW; /** * * Created by BenNelson on 3/8/18. */ public class DrawUtilities extends View { private Context _context; private static double scaleFactor = 0.665; public DrawUtilities(Context context) { super(context); this._context = context; } public void drawRoutes(Map<shared.model.Color, List<IRoute>> routesMap, ImageView view) { //super.onDraw(canvas); //Set the paint Paint paint = new Paint(); paint.setStrokeWidth(8); paint.setStrokeCap(Paint.Cap.ROUND); float screenScale = _context.getResources().getDisplayMetrics().density; //Set the bit map Bitmap gameMapBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ticket_to_ride_map_with_routes); Bitmap drawableBitmap = gameMapBitmap.copy(Bitmap.Config.ARGB_8888, true); //Get the final canvas Canvas canvas = new Canvas(drawableBitmap); for(shared.model.Color playerColor : routesMap.keySet()){ if(routesMap.containsKey(playerColor)){ List<IRoute> routes = routesMap.get(playerColor); for (IRoute route : routes) { CityPoint start = _scale(route.getStart().get_coordinates(), scaleFactor, screenScale); CityPoint end = _scale(route.getEnd().get_coordinates(), scaleFactor, screenScale); paint.setColor(_convertColor(playerColor)); canvas.drawLine(start.x(),start.y(),end.x(),end.y(),paint); } } } //Set the new bg image with the strokes view.setImageBitmap(drawableBitmap); } private CityPoint _scale(CityPoint coords, double scaleFactor, float screenScale) { double x = coords.x() * screenScale; double y = coords.y() * screenScale; x *= scaleFactor; y *= scaleFactor; return new CityPoint((int)x,(int)y); } /* This method converts our shared model colors to android graphics colors */ private int _convertColor(shared.model.Color color) { if(color.equals(PINK)){ return Color.MAGENTA; } if(color.equals(RED)){ return Color.RED; } if(color.equals(BLUE)){ return Color.BLUE; } if(color.equals(ORANGE)){ return Color.rgb(255,165,0); } if(color.equals(WHITE)){ return Color.WHITE; } if(color.equals(BLACK)){ return Color.BLACK; } if(color.equals(GREEN)){ return Color.GREEN; } if(color.equals(YELLOW)){ return Color.YELLOW; } if(color.equals(GRAY)){ return Color.GRAY; } return Color.CYAN;//CYAN MEANS ERROR } }
29.869919
117
0.638269
5ad8ec2b5c57a33a3f940e273b1117b71c96dff2
240
package com.example.verificationcodeservice.config; import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.context.annotation.Configuration; @EnableRabbit @Configuration public class RabbitMQConfig { }
24
63
0.858333
4231bbf08e81f1ac2a8651fb0403076be59042d1
309
package com.anor.behaviortree; public class LeafNode<Context extends Object> extends Node<Context> { private Action<Context> action; public LeafNode(Action<Context> action) { this.action = action; } @Override public NodeStatus process(Context w) { return action.perform(w); } }
18.176471
70
0.702265
b3558cfc50c1d09a0b1cd1da1db90cc17d666f62
165
package com.github.jolice.bot.command; import com.github.jolice.bot.MessageEvent; public interface CommandHandler { void handle(MessageEvent messageEvent); }
18.333333
43
0.793939
784242bcdd81a5758d15fe1b590322141095cf00
1,936
package io.quarkus.runner.bootstrap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; import org.jboss.logging.Logger; public class ForkJoinClassLoading { private static final Logger log = Logger.getLogger(ForkJoinClassLoading.class.getName()); /** * A yucky hack, basically attempt to make sure every thread in the common pool has * the correct CL. * * It's not perfect, but as this only affects test and dev mode and not production it is better * than nothing. * * Really we should just not use the common pool at all. */ public static void setForkJoinClassLoader(ClassLoader classLoader) { CountDownLatch allDone = new CountDownLatch(ForkJoinPool.getCommonPoolParallelism()); CountDownLatch taskRelease = new CountDownLatch(1); for (int i = 0; i < ForkJoinPool.getCommonPoolParallelism(); ++i) { ForkJoinPool.commonPool().execute(new Runnable() { @Override public void run() { Thread.currentThread().setContextClassLoader(classLoader); allDone.countDown(); try { taskRelease.await(); } catch (InterruptedException e) { log.error("Failed to set fork join ClassLoader", e); } } }); } try { if (!allDone.await(1, TimeUnit.SECONDS)) { log.error( "Timed out trying to set fork join ClassLoader, this should never happen unless something has tied up a fork join thread before the app launched"); } } catch (InterruptedException e) { log.error("Failed to set fork join ClassLoader", e); } finally { taskRelease.countDown(); } } }
37.960784
171
0.59814
4db69391f75f19c76978d4cc345d7c540cc1aa21
20,288
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * Structure describing ASTC HDR features that can be supported by an implementation. * * <h5>Description</h5> * * <p>If the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} structure is included in the {@code pNext} chain of the {@link VkPhysicalDeviceFeatures2} structure passed to {@link VK11#vkGetPhysicalDeviceFeatures2 GetPhysicalDeviceFeatures2}, it is filled in to indicate whether each corresponding feature is supported. {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} <b>can</b> also be used in the {@code pNext} chain of {@link VkDeviceCreateInfo} to selectively enable these features.</p> * * <h5>Valid Usage (Implicit)</h5> * * <ul> * <li>{@code sType} <b>must</b> be {@link EXTTextureCompressionAstcHdr#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXTURE_COMPRESSION_ASTC_HDR_FEATURES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXTURE_COMPRESSION_ASTC_HDR_FEATURES_EXT}</li> * </ul> * * <h3>Layout</h3> * * <pre><code> * struct VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT { * VkStructureType {@link #sType}; * void * {@link #pNext}; * VkBool32 {@link #textureCompressionASTC_HDR}; * }</code></pre> */ public class VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int STYPE, PNEXT, TEXTURECOMPRESSIONASTC_HDR; static { Layout layout = __struct( __member(4), __member(POINTER_SIZE), __member(4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); STYPE = layout.offsetof(0); PNEXT = layout.offsetof(1); TEXTURECOMPRESSIONASTC_HDR = layout.offsetof(2); } /** * Creates a {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** the type of this structure. */ @NativeType("VkStructureType") public int sType() { return nsType(address()); } /** {@code NULL} or a pointer to a structure extending this structure. */ @NativeType("void *") public long pNext() { return npNext(address()); } /** * indicates whether all of the ASTC HDR compressed texture formats are supported. If this feature is enabled, then the {@link VK10#VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT FORMAT_FEATURE_SAMPLED_IMAGE_BIT}, {@link VK10#VK_FORMAT_FEATURE_BLIT_SRC_BIT FORMAT_FEATURE_BLIT_SRC_BIT} and {@link VK10#VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT} features <b>must</b> be supported in {@code optimalTilingFeatures} for the following formats: * * <ul> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT}</li> * <li>{@link EXTTextureCompressionAstcHdr#VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT}</li> * </ul> * * <p>To query for additional properties, or if the feature is not enabled, {@link VK10#vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties} and {@link VK10#vkGetPhysicalDeviceImageFormatProperties GetPhysicalDeviceImageFormatProperties} <b>can</b> be used to check for supported properties of individual formats as normal.</p> */ @NativeType("VkBool32") public boolean textureCompressionASTC_HDR() { return ntextureCompressionASTC_HDR(address()) != 0; } /** Sets the specified value to the {@link #sType} field. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; } /** Sets the specified value to the {@link #pNext} field. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT pNext(@NativeType("void *") long value) { npNext(address(), value); return this; } /** Sets the specified value to the {@link #textureCompressionASTC_HDR} field. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT textureCompressionASTC_HDR(@NativeType("VkBool32") boolean value) { ntextureCompressionASTC_HDR(address(), value ? 1 : 0); return this; } /** Initializes this struct with the specified values. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT set( int sType, long pNext, boolean textureCompressionASTC_HDR ) { sType(sType); pNext(pNext); textureCompressionASTC_HDR(textureCompressionASTC_HDR); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT set(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT malloc() { return wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT calloc() { return wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance allocated with {@link BufferUtils}. */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, memAddress(container), container); } /** Returns a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance for the specified memory address. */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT create(long address) { return wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT createSafe(long address) { return address == NULL ? null : wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, address); } /** * Returns a new {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT malloc(MemoryStack stack) { return wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT calloc(MemoryStack stack) { return wrap(VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #sType}. */ public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.STYPE); } /** Unsafe version of {@link #pNext}. */ public static long npNext(long struct) { return memGetAddress(struct + VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.PNEXT); } /** Unsafe version of {@link #textureCompressionASTC_HDR}. */ public static int ntextureCompressionASTC_HDR(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.TEXTURECOMPRESSIONASTC_HDR); } /** Unsafe version of {@link #sType(int) sType}. */ public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.STYPE, value); } /** Unsafe version of {@link #pNext(long) pNext}. */ public static void npNext(long struct, long value) { memPutAddress(struct + VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.PNEXT, value); } /** Unsafe version of {@link #textureCompressionASTC_HDR(boolean) textureCompressionASTC_HDR}. */ public static void ntextureCompressionASTC_HDR(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.TEXTURECOMPRESSIONASTC_HDR, value); } // ----------------------------------- /** An array of {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT} structs. */ public static class Buffer extends StructBuffer<VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT, Buffer> implements NativeResource { private static final VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT ELEMENT_FACTORY = VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.create(-1L); /** * Creates a new {@code VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#sType} field. */ @NativeType("VkStructureType") public int sType() { return VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.nsType(address()); } /** @return the value of the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#pNext} field. */ @NativeType("void *") public long pNext() { return VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.npNext(address()); } /** @return the value of the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#textureCompressionASTC_HDR} field. */ @NativeType("VkBool32") public boolean textureCompressionASTC_HDR() { return VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.ntextureCompressionASTC_HDR(address()) != 0; } /** Sets the specified value to the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#sType} field. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer sType(@NativeType("VkStructureType") int value) { VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.nsType(address(), value); return this; } /** Sets the specified value to the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#pNext} field. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer pNext(@NativeType("void *") long value) { VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.npNext(address(), value); return this; } /** Sets the specified value to the {@link VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT#textureCompressionASTC_HDR} field. */ public VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.Buffer textureCompressionASTC_HDR(@NativeType("VkBool32") boolean value) { VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT.ntextureCompressionASTC_HDR(address(), value ? 1 : 0); return this; } } }
58.298851
514
0.744479
c55f19c4aa931a6ae485138eb774b93db7f4cf4d
6,236
package com.alibaba.tesla.appmanager.server.controller; import com.alibaba.fastjson.JSONObject; import com.alibaba.tesla.appmanager.api.provider.DeployAppProvider; import com.alibaba.tesla.appmanager.auth.controller.AppManagerBaseController; import com.alibaba.tesla.appmanager.common.pagination.Pagination; import com.alibaba.tesla.appmanager.domain.dto.DeployAppAttrDTO; import com.alibaba.tesla.appmanager.domain.dto.DeployAppDTO; import com.alibaba.tesla.appmanager.domain.dto.DeployComponentAttrDTO; import com.alibaba.tesla.appmanager.domain.req.deploy.*; import com.alibaba.tesla.appmanager.domain.res.deploy.DeployAppPackageLaunchRes; import com.alibaba.tesla.common.base.TeslaBaseResult; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.HashMap; /** * 部署单管理 * * @author yaoxing.gyx@alibaba-inc.com */ @Slf4j @RequestMapping("/deployments") @RestController public class DeploymentController extends AppManagerBaseController { @Autowired private DeployAppProvider deployAppProvider; // 发起部署 @PostMapping(value = "/launch") @ResponseBody public TeslaBaseResult launch( @Valid @ModelAttribute DeployAppLaunchReq request, @RequestBody String body, OAuth2Authentication auth ) { request.setConfiguration(body); try { DeployAppPackageLaunchRes response = deployAppProvider.launch(request, getOperator(auth)); return buildSucceedResult(response); } catch (Exception e) { log.error("cannot launch deployments|exception={}|yaml={}", ExceptionUtils.getStackTrace(e), body); return buildExceptionResult(e); } } // 发起部署 @PostMapping(value = "/fast-launch") @ResponseBody public TeslaBaseResult fastLaunch(@RequestBody FastDeployAppLaunchReq request, OAuth2Authentication auth) { try { DeployAppPackageLaunchRes response = deployAppProvider.fastLaunch(request, getOperator(auth)); return buildSucceedResult(response); } catch (Exception e) { log.error("cannot launch deployments|exception={}|request={}", ExceptionUtils.getStackTrace(e), JSONObject.toJSONString(request)); return buildExceptionResult(e); } } // 根据过滤条件查询部署单详情 @GetMapping @ResponseBody public TeslaBaseResult list( @ModelAttribute DeployAppListReq request, OAuth2Authentication auth ) throws Exception { Pagination<DeployAppDTO> response = deployAppProvider.list(request, getOperator(auth)); return buildSucceedResult(response); } // 重新部署当前部署单 @PostMapping("{deployAppId}/replay") @ResponseBody public TeslaBaseResult replay( @PathVariable("deployAppId") Long deployAppId, OAuth2Authentication auth ) throws Exception { DeployAppReplayReq request = DeployAppReplayReq.builder() .deployAppId(deployAppId) .build(); try { DeployAppPackageLaunchRes response = deployAppProvider.replay(request, getOperator(auth)); return buildSucceedResult(response); } catch (Exception e) { log.error("cannot launch deployments|exception={}|originDeployId={}", ExceptionUtils.getStackTrace(e), deployAppId); return buildExceptionResult(e); } } // 查询指定部署单详情 @GetMapping("{deployAppId}") @ResponseBody public TeslaBaseResult get( @PathVariable("deployAppId") Long deployAppId, OAuth2Authentication auth ) throws Exception { DeployAppGetReq request = DeployAppGetReq.builder() .deployAppId(deployAppId) .build(); DeployAppDTO response = deployAppProvider.get(request, getOperator(auth)); return buildSucceedResult(response); } // 查询指定部署单详情 @GetMapping("{deployAppId}/attributes") @ResponseBody public TeslaBaseResult getAttributes( @PathVariable("deployAppId") Long deployAppId, OAuth2Authentication auth ) throws Exception { DeployAppGetAttrReq request = DeployAppGetAttrReq.builder() .deployAppId(deployAppId) .build(); DeployAppAttrDTO response = deployAppProvider.getAttr(request, getOperator(auth)); return buildSucceedResult(response); } // 查询指定部署单的指定步骤详情 @GetMapping("{deployAppId}/components/{deployComponentId}/attributes") @ResponseBody public TeslaBaseResult getComponentAttributes( @PathVariable("deployAppId") Long deployAppId, @PathVariable("deployComponentId") Long deployComponentId, OAuth2Authentication auth ) { DeployAppGetComponentAttrReq request = DeployAppGetComponentAttrReq.builder() .deployComponentId(deployComponentId) .build(); DeployComponentAttrDTO response = deployAppProvider.getComponentAttr(request, getOperator(auth)); return buildSucceedResult(response); } // 重试指定部署单 @PostMapping("{deployAppId}/retry") @ResponseBody public TeslaBaseResult retry( @PathVariable("deployAppId") Long deployAppId, OAuth2Authentication auth) { DeployAppRetryReq request = DeployAppRetryReq.builder() .deployAppId(deployAppId) .build(); deployAppProvider.retry(request, getOperator(auth)); return buildSucceedResult(new HashMap<String, String>()); } // 终止指定部署单 @PostMapping("{deployAppId}/terminate") @ResponseBody public TeslaBaseResult terminate( @PathVariable("deployAppId") Long deployAppId, OAuth2Authentication auth) { DeployAppTerminateReq request = DeployAppTerminateReq.builder() .deployAppId(deployAppId) .build(); deployAppProvider.terminate(request, getOperator(auth)); return buildSucceedResult(new HashMap<String, String>()); } }
38.975
111
0.69628
06e65f6752108f5ab067724a271c1d3853001bb7
1,727
package com.mfinance.everjoy.app; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.os.Messenger; import android.view.View; import android.widget.Button; import com.mfinance.everjoy.R; import com.mfinance.everjoy.app.bo.OrderRecord; import com.mfinance.everjoy.app.widget.quickaction.CustomPopupWindow; import com.mfinance.everjoy.app.widget.wheel.WheelView; public class PopupOrder { private Context context; public CustomPopupWindow popup; public WheelView wvOrder; public Button btnCommit; public Button btnClose; public OrderWheelAdapter orderAdapter = null; public PopupOrder(Context context, View vParent, OrderWheelAdapter orderAdapter){ this.context = context; popup = new CustomPopupWindow(vParent); popup.setContentView(R.layout.popup_order); wvOrder = (WheelView) popup.findViewById(R.id.wvOrder); this.orderAdapter = orderAdapter; wvOrder.setViewAdapter(orderAdapter); wvOrder.setVisibleItems(5); wvOrder.setCurrentItem(0); btnCommit = (Button)popup.findViewById(R.id.btnPopCommit); btnClose = (Button)popup.findViewById(R.id.btnClose); } public void showLikeQuickAction(){ popup.showLikeQuickAction(); } public void dismiss(){ popup.dismiss(); } public String getValue(){ return (String) orderAdapter.getItemText(wvOrder.getCurrentItem()); } public String getRealValue(){ return (String) orderAdapter.getOrderRef(wvOrder.getCurrentItem()); } public void updateSelectedOrderIndex(HashMap<Integer, OrderRecord> record, int iRef){ orderAdapter.reload(record); if(-1 == iRef){ wvOrder.setCurrentItem(0); }else{ wvOrder.setCurrentItem(orderAdapter.getItemIndex(iRef)); } } }
26.166667
86
0.767226
f541d7f216ece5f319214501ba90da4689c8c21d
319
package org.mcupdater.carnivora; public class Version { public static final String MOD_ID = "Carnivora"; public static final String MOD_NAME = "Carnivora"; public static final String VERSION = "0.1.4"; public static final String CHANNEL = MOD_ID; public static final String TEXTURE_PREFIX = "carnivora:"; }
26.583333
58
0.749216
06608c12258726c059a916762c3be2c768ba52bf
4,302
package com.michaelfotiadis.androidclocks; import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.TextView; import com.michaelfotiadis.androidclocks.containers.ClockInstance; import com.michaelfotiadis.androidclocks.utils.PrimitiveConversions; import java.util.Calendar; public class DigitalClock extends TextView implements Clock { private final String TAG = "My Digital Clock"; private final String TIME_ZERO_VALUE = "00:00:00"; private long mStartTime = 0; private int prefFontSize = 12; private ClockInstance mClockInstance; private final Handler mHandler = new Handler(); private final long _updateInterval = 1000; private int mFontColour = Integer.MIN_VALUE; private String mFontName; private final Runnable mRunnable = new Runnable() { @Override public void run() { mHandler.postDelayed(this, _updateInterval); updateTime(); } }; public DigitalClock(Context context) { super(context); mClockInstance = new ClockInstance(); } public DigitalClock(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); mClockInstance = new ClockInstance(); } public DigitalClock(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs); mClockInstance = new ClockInstance(); } private void setFontName(final String fontName) { this.mFontName = fontName; } private void init(AttributeSet attrs) { prefFontSize = (int) getResources().getDimension(R.dimen.digital_clock_font_size); if (mFontName == null) mFontName = "digital_7_mono.ttf"; final Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/" + mFontName); try { setTypeface(typeface); } catch (Exception e1) { Log.e(TAG, e1.getLocalizedMessage()); } setTextSize(prefFontSize); try { if (mFontColour == Integer.MIN_VALUE) setFontColour("#ff0099cc"); this.setTextColor(mFontColour); } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage()); } // set the time initially to 00:00:00 this.setText(TIME_ZERO_VALUE); } public void setFontColour(final String colour) { try { this.mFontColour = Color.parseColor(colour); } catch (Exception e) { this.mFontColour = Color.parseColor("#ff0099cc"); Log.e(TAG, e.getLocalizedMessage()); } } @Override public boolean isVisible() { if (this.getVisibility() == View.VISIBLE) { return true; } return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); } @Override public void pauseClock() { mHandler.removeCallbacks(mRunnable); } @Override public void setTime(final int hours, final int minutes, final int seconds) { mClockInstance.setSeconds(6.0f*seconds); mClockInstance.setMinutes(minutes + seconds / 60.0f); mClockInstance.setHour(hours + minutes / 60.0f); updateTime(); } @Override public void startClock(final long startTime, final int minutesToAlarm) { mStartTime = startTime; mHandler.post(mRunnable); invalidate(); } @Override public void stopClock() { mClockInstance.reset(); this.setText(TIME_ZERO_VALUE); mHandler.removeCallbacks(mRunnable); } private long mTimeRunning; @Override public void updateTime() { setTimeRunning((Calendar.getInstance().getTimeInMillis() - mStartTime) / 1000); if (mStartTime == 0) { mClockInstance.reset(); this.setText(TIME_ZERO_VALUE); return; } int[] timeIntArray = PrimitiveConversions.getIntTimeArrayFromSeconds(getTimeRunning()); mClockInstance.setTime(timeIntArray[0], timeIntArray[1], timeIntArray[2]); this.setText(mClockInstance.getString()); invalidate(); } @Override public long getTimeRunning() { return mTimeRunning; } private void setTimeRunning(long timeRunning) { this.mTimeRunning = timeRunning; } @Override public void setMinutesToAlarm(int minutesToAlarm) { // TODO Auto-generated method stub } @Override public void setSystemTime() { // TODO Auto-generated method stub } }
23.380435
89
0.711762
b5029f8b047e2767470edab57e127b9dafbbc67a
538
package com.nano.common.logger; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * Log的实体类 * @author nano */ @Data @NoArgsConstructor @ToString public class LogInfo { /** * 等级 */ private String level; /** * 产生的来源 */ private String source; /** * 日志具体信息 */ private String content; public LogInfo(String level, String source, String content) { this.level = level; this.source = source; this.content = content; } }
14.540541
65
0.598513
6129c0457686ae8a0e1925cf002572202464bb6f
18,775
/* * 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.kafka.common.record; import org.apache.kafka.common.header.Header; import org.apache.kafka.common.header.internals.RecordHeader; import org.apache.kafka.common.utils.CloseableIterator; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.test.TestUtils; import org.junit.Test; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; import static org.apache.kafka.common.record.DefaultRecordBatch.RECORDS_COUNT_OFFSET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class DefaultRecordBatchTest { @Test public void testWriteEmptyHeader() { long producerId = 23423L; short producerEpoch = 145; int baseSequence = 983; long baseOffset = 15L; long lastOffset = 37; int partitionLeaderEpoch = 15; long timestamp = System.currentTimeMillis(); for (TimestampType timestampType : Arrays.asList(TimestampType.CREATE_TIME, TimestampType.LOG_APPEND_TIME)) { for (boolean isTransactional : Arrays.asList(true, false)) { for (boolean isControlBatch : Arrays.asList(true, false)) { ByteBuffer buffer = ByteBuffer.allocate(2048); DefaultRecordBatch.writeEmptyHeader(buffer, RecordBatch.CURRENT_MAGIC_VALUE, producerId, producerEpoch, baseSequence, baseOffset, lastOffset, partitionLeaderEpoch, timestampType, timestamp, isTransactional, isControlBatch); buffer.flip(); DefaultRecordBatch batch = new DefaultRecordBatch(buffer); assertEquals(producerId, batch.producerId()); assertEquals(producerEpoch, batch.producerEpoch()); assertEquals(baseSequence, batch.baseSequence()); assertEquals(baseSequence + ((int) (lastOffset - baseOffset)), batch.lastSequence()); assertEquals(baseOffset, batch.baseOffset()); assertEquals(lastOffset, batch.lastOffset()); assertEquals(partitionLeaderEpoch, batch.partitionLeaderEpoch()); assertEquals(isTransactional, batch.isTransactional()); assertEquals(timestampType, batch.timestampType()); assertEquals(timestamp, batch.maxTimestamp()); assertEquals(isControlBatch, batch.isControlBatch()); } } } } @Test public void buildDefaultRecordBatch() { ByteBuffer buffer = ByteBuffer.allocate(2048); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V2, CompressionType.NONE, TimestampType.CREATE_TIME, 1234567L); builder.appendWithOffset(1234567, 1L, "a".getBytes(), "v".getBytes()); builder.appendWithOffset(1234568, 2L, "b".getBytes(), "v".getBytes()); MemoryRecords records = builder.build(); for (MutableRecordBatch batch : records.batches()) { assertTrue(batch.isValid()); assertEquals(1234567, batch.baseOffset()); assertEquals(1234568, batch.lastOffset()); assertEquals(2L, batch.maxTimestamp()); assertEquals(RecordBatch.NO_PRODUCER_ID, batch.producerId()); assertEquals(RecordBatch.NO_PRODUCER_EPOCH, batch.producerEpoch()); assertEquals(RecordBatch.NO_SEQUENCE, batch.baseSequence()); assertEquals(RecordBatch.NO_SEQUENCE, batch.lastSequence()); for (Record record : batch) { assertTrue(record.isValid()); } } } @Test public void buildDefaultRecordBatchWithProducerId() { long pid = 23423L; short epoch = 145; int baseSequence = 983; ByteBuffer buffer = ByteBuffer.allocate(2048); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V2, CompressionType.NONE, TimestampType.CREATE_TIME, 1234567L, RecordBatch.NO_TIMESTAMP, pid, epoch, baseSequence); builder.appendWithOffset(1234567, 1L, "a".getBytes(), "v".getBytes()); builder.appendWithOffset(1234568, 2L, "b".getBytes(), "v".getBytes()); MemoryRecords records = builder.build(); for (MutableRecordBatch batch : records.batches()) { assertTrue(batch.isValid()); assertEquals(1234567, batch.baseOffset()); assertEquals(1234568, batch.lastOffset()); assertEquals(2L, batch.maxTimestamp()); assertEquals(pid, batch.producerId()); assertEquals(epoch, batch.producerEpoch()); assertEquals(baseSequence, batch.baseSequence()); assertEquals(baseSequence + 1, batch.lastSequence()); for (Record record : batch) { assertTrue(record.isValid()); } } } @Test public void buildDefaultRecordBatchWithSequenceWrapAround() { long pid = 23423L; short epoch = 145; int baseSequence = Integer.MAX_VALUE - 1; ByteBuffer buffer = ByteBuffer.allocate(2048); MemoryRecordsBuilder builder = MemoryRecords.builder(buffer, RecordBatch.MAGIC_VALUE_V2, CompressionType.NONE, TimestampType.CREATE_TIME, 1234567L, RecordBatch.NO_TIMESTAMP, pid, epoch, baseSequence); builder.appendWithOffset(1234567, 1L, "a".getBytes(), "v".getBytes()); builder.appendWithOffset(1234568, 2L, "b".getBytes(), "v".getBytes()); builder.appendWithOffset(1234569, 3L, "c".getBytes(), "v".getBytes()); MemoryRecords records = builder.build(); List<MutableRecordBatch> batches = TestUtils.toList(records.batches()); assertEquals(1, batches.size()); RecordBatch batch = batches.get(0); assertEquals(pid, batch.producerId()); assertEquals(epoch, batch.producerEpoch()); assertEquals(baseSequence, batch.baseSequence()); assertEquals(0, batch.lastSequence()); List<Record> allRecords = TestUtils.toList(batch); assertEquals(3, allRecords.size()); assertEquals(Integer.MAX_VALUE - 1, allRecords.get(0).sequence()); assertEquals(Integer.MAX_VALUE, allRecords.get(1).sequence()); assertEquals(0, allRecords.get(2).sequence()); } @Test public void testSizeInBytes() { Header[] headers = new Header[] { new RecordHeader("foo", "value".getBytes()), new RecordHeader("bar", (byte[]) null) }; long timestamp = System.currentTimeMillis(); SimpleRecord[] records = new SimpleRecord[] { new SimpleRecord(timestamp, "key".getBytes(), "value".getBytes()), new SimpleRecord(timestamp + 30000, null, "value".getBytes()), new SimpleRecord(timestamp + 60000, "key".getBytes(), null), new SimpleRecord(timestamp + 60000, "key".getBytes(), "value".getBytes(), headers) }; int actualSize = MemoryRecords.withRecords(CompressionType.NONE, records).sizeInBytes(); assertEquals(actualSize, DefaultRecordBatch.sizeInBytes(Arrays.asList(records))); } @Test(expected = InvalidRecordException.class) public void testInvalidRecordSize() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes())); ByteBuffer buffer = records.buffer(); buffer.putInt(DefaultRecordBatch.LENGTH_OFFSET, 10); DefaultRecordBatch batch = new DefaultRecordBatch(buffer); assertFalse(batch.isValid()); batch.ensureValid(); } @Test(expected = InvalidRecordException.class) public void testInvalidRecordCountTooManyNonCompressedV2() { long now = System.currentTimeMillis(); DefaultRecordBatch batch = recordsWithInvalidRecordCount(RecordBatch.MAGIC_VALUE_V2, now, CompressionType.NONE, 5); // force iteration through the batch to execute validation // batch validation is a part of normal workflow for LogValidator.validateMessagesAndAssignOffsets for (Record record: batch) { record.isValid(); } } @Test(expected = InvalidRecordException.class) public void testInvalidRecordCountTooLittleNonCompressedV2() { long now = System.currentTimeMillis(); DefaultRecordBatch batch = recordsWithInvalidRecordCount(RecordBatch.MAGIC_VALUE_V2, now, CompressionType.NONE, 2); // force iteration through the batch to execute validation // batch validation is a part of normal workflow for LogValidator.validateMessagesAndAssignOffsets for (Record record: batch) { record.isValid(); } } @Test(expected = InvalidRecordException.class) public void testInvalidRecordCountTooManyCompressedV2() { long now = System.currentTimeMillis(); DefaultRecordBatch batch = recordsWithInvalidRecordCount(RecordBatch.MAGIC_VALUE_V2, now, CompressionType.GZIP, 5); // force iteration through the batch to execute validation // batch validation is a part of normal workflow for LogValidator.validateMessagesAndAssignOffsets for (Record record: batch) { record.isValid(); } } @Test(expected = InvalidRecordException.class) public void testInvalidRecordCountTooLittleCompressedV2() { long now = System.currentTimeMillis(); DefaultRecordBatch batch = recordsWithInvalidRecordCount(RecordBatch.MAGIC_VALUE_V2, now, CompressionType.GZIP, 2); // force iteration through the batch to execute validation // batch validation is a part of normal workflow for LogValidator.validateMessagesAndAssignOffsets for (Record record: batch) { record.isValid(); } } @Test(expected = InvalidRecordException.class) public void testInvalidCrc() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes())); ByteBuffer buffer = records.buffer(); buffer.putInt(DefaultRecordBatch.LAST_OFFSET_DELTA_OFFSET, 23); DefaultRecordBatch batch = new DefaultRecordBatch(buffer); assertFalse(batch.isValid()); batch.ensureValid(); } @Test public void testSetLastOffset() { SimpleRecord[] simpleRecords = new SimpleRecord[] { new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes()) }; MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, simpleRecords); long lastOffset = 500L; long firstOffset = lastOffset - simpleRecords.length + 1; DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); batch.setLastOffset(lastOffset); assertEquals(lastOffset, batch.lastOffset()); assertEquals(firstOffset, batch.baseOffset()); assertTrue(batch.isValid()); List<MutableRecordBatch> recordBatches = Utils.toList(records.batches().iterator()); assertEquals(1, recordBatches.size()); assertEquals(lastOffset, recordBatches.get(0).lastOffset()); long offset = firstOffset; for (Record record : records.records()) assertEquals(offset++, record.offset()); } @Test public void testSetPartitionLeaderEpoch() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes())); int leaderEpoch = 500; DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); batch.setPartitionLeaderEpoch(leaderEpoch); assertEquals(leaderEpoch, batch.partitionLeaderEpoch()); assertTrue(batch.isValid()); List<MutableRecordBatch> recordBatches = Utils.toList(records.batches().iterator()); assertEquals(1, recordBatches.size()); assertEquals(leaderEpoch, recordBatches.get(0).partitionLeaderEpoch()); } @Test public void testSetLogAppendTime() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes())); long logAppendTime = 15L; DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); batch.setMaxTimestamp(TimestampType.LOG_APPEND_TIME, logAppendTime); assertEquals(TimestampType.LOG_APPEND_TIME, batch.timestampType()); assertEquals(logAppendTime, batch.maxTimestamp()); assertTrue(batch.isValid()); List<MutableRecordBatch> recordBatches = Utils.toList(records.batches().iterator()); assertEquals(1, recordBatches.size()); assertEquals(logAppendTime, recordBatches.get(0).maxTimestamp()); assertEquals(TimestampType.LOG_APPEND_TIME, recordBatches.get(0).timestampType()); for (Record record : records.records()) assertEquals(logAppendTime, record.timestamp()); } @Test(expected = IllegalArgumentException.class) public void testSetNoTimestampTypeNotAllowed() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.NONE, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes())); DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); batch.setMaxTimestamp(TimestampType.NO_TIMESTAMP_TYPE, RecordBatch.NO_TIMESTAMP); } @Test public void testReadAndWriteControlBatch() { long producerId = 1L; short producerEpoch = 0; int coordinatorEpoch = 15; ByteBuffer buffer = ByteBuffer.allocate(128); MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, CompressionType.NONE, TimestampType.CREATE_TIME, 0L, RecordBatch.NO_TIMESTAMP, producerId, producerEpoch, RecordBatch.NO_SEQUENCE, true, true, RecordBatch.NO_PARTITION_LEADER_EPOCH, buffer.remaining()); EndTransactionMarker marker = new EndTransactionMarker(ControlRecordType.COMMIT, coordinatorEpoch); builder.appendEndTxnMarker(System.currentTimeMillis(), marker); MemoryRecords records = builder.build(); List<MutableRecordBatch> batches = TestUtils.toList(records.batches()); assertEquals(1, batches.size()); MutableRecordBatch batch = batches.get(0); assertTrue(batch.isControlBatch()); List<Record> logRecords = TestUtils.toList(records.records()); assertEquals(1, logRecords.size()); Record commitRecord = logRecords.get(0); assertEquals(marker, EndTransactionMarker.deserialize(commitRecord)); } @Test public void testStreamingIteratorConsistency() { MemoryRecords records = MemoryRecords.withRecords(RecordBatch.MAGIC_VALUE_V2, 0L, CompressionType.GZIP, TimestampType.CREATE_TIME, new SimpleRecord(1L, "a".getBytes(), "1".getBytes()), new SimpleRecord(2L, "b".getBytes(), "2".getBytes()), new SimpleRecord(3L, "c".getBytes(), "3".getBytes())); DefaultRecordBatch batch = new DefaultRecordBatch(records.buffer()); try (CloseableIterator<Record> streamingIterator = batch.streamingIterator(BufferSupplier.create())) { TestUtils.checkEquals(streamingIterator, batch.iterator()); } } @Test public void testIncrementSequence() { assertEquals(10, DefaultRecordBatch.incrementSequence(5, 5)); assertEquals(0, DefaultRecordBatch.incrementSequence(Integer.MAX_VALUE, 1)); assertEquals(4, DefaultRecordBatch.incrementSequence(Integer.MAX_VALUE - 5, 10)); } private static DefaultRecordBatch recordsWithInvalidRecordCount(Byte magicValue, long timestamp, CompressionType codec, int invalidCount) { ByteBuffer buf = ByteBuffer.allocate(512); MemoryRecordsBuilder builder = MemoryRecords.builder(buf, magicValue, codec, TimestampType.CREATE_TIME, 0L); builder.appendWithOffset(0, timestamp, null, "hello".getBytes()); builder.appendWithOffset(1, timestamp, null, "there".getBytes()); builder.appendWithOffset(2, timestamp, null, "beautiful".getBytes()); MemoryRecords records = builder.build(); ByteBuffer buffer = records.buffer(); buffer.position(0); buffer.putInt(RECORDS_COUNT_OFFSET, invalidCount); buffer.position(0); return new DefaultRecordBatch(buffer); } }
47.055138
123
0.666738
1e303ca947f7fe8a9c0b8f99c66bc1cb8cb41790
2,551
package de.hw4.binance.marketmaker; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import de.hw4.binance.marketmaker.persistence.Authority; import de.hw4.binance.marketmaker.persistence.AuthorityRepository; import de.hw4.binance.marketmaker.persistence.User; import de.hw4.binance.marketmaker.persistence.UserRepository; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired private UserRepository userRepo; @Autowired private AuthorityRepository authorityRepo; @Value("${db.sa.password}") private String defaultSaPwd; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/register", "/img/**", "/css/**", "/js/**", "/*.js").permitAll().anyRequest().authenticated().and() .formLogin().loginPage("/login").permitAll().and().logout().permitAll(); http.authorizeRequests().antMatchers("/public/**").permitAll(); // for h2 console http.authorizeRequests().antMatchers("/console/**").hasRole("SA_ROLE"); http.csrf().ignoringAntMatchers("/console/**"); http.headers().frameOptions().disable(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { User sa = userRepo.findOne("sa"); if (sa == null) { sa = new User("sa"); sa.setPassword(defaultSaPwd); sa.setEnabled(true); userRepo.save(sa); Authority authority = new Authority("sa", "SA_ROLE"); authorityRepo.save(authority); } auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery("select username, password, enabled from user where username=?") .authoritiesByUsernameQuery("select username, authority from authority where username=?") .passwordEncoder(new BCryptPasswordEncoder()); //auth.inMemoryAuthentication().withUser("sa").password("sapwd").roles("USER"); } }
34.472973
139
0.777342
3721a2581feee152d9e4f4e2014d6814496ed308
673
package br.com.hoyler.apps.java.demojavafxspring.tools; public enum ViewFXML { LOGIN("Login", "br.com.hoyler.apps.java.demojavafxspring.gui"); private final String FileName; private final String FilePackage; ViewFXML(String FileName, String FilePackage) { this.FileName = FileName; this.FilePackage = FilePackage; } private String getFileName(){ return(FileName); }; private String getFilePackage(){ return(FilePackage); }; public String getFilePatch(){ String result = String.format("/%s/%s.fxml", (getFilePackage().replace(".", "/")), (getFileName())); return (result); } }
25.884615
108
0.643388
a41fb34a005e5e7deabda738269a4f9a8aaf234d
2,807
package pt.maisis.search.web; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import pt.maisis.search.config.SearchShareConfig; import pt.maisis.search.entity.Report; /** * * @author amador */ public class SearchSharePrepareServlet extends PrepareSearchServlet { private static Log log = LogFactory.getLog(SearchSharePrepareServlet.class); protected static final String OPERATION_PREPARE = "prepare"; /** * manageOperations */ protected boolean manageOperations(HttpServletRequest request, HttpServletResponse response, Map<String, Object> parameterMap) { boolean executeSearch = true; SearchShareConfig ssc = SearchShareConfig.getInstance(); if (request.getParameter(ssc.getOperation()) != null) { if (OPERATION_PREPARE.equals(request.getParameter(ssc.getOperation()))) { Report report = ( new Report() ).find(Long.parseLong(request.getParameter(ssc.getReportId()))); SearchShareHelper.fillParameterMap(report, parameterMap); } } return executeSearch; } /** * doGet */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Map<String, Object> parameterMap = new HashMap<String, Object>(); if (manageOperations(request, response, parameterMap)) { if (log.isDebugEnabled() && !parameterMap.isEmpty()) { for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { log.debug("parameter name=" + entry.getKey() + " value=" + entry.getValue()); } } super.doGet(request, response, parameterMap); } } /** * doPost */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Map<String, Object> parameterMap = new HashMap<String, Object>(); if (manageOperations(request, response, parameterMap)) { if (log.isDebugEnabled() && !parameterMap.isEmpty()) { for (Map.Entry<String, Object> entry : parameterMap.entrySet()) { log.debug("parameter name=" + entry.getKey() + " value=" + entry.getValue()); } } super.doPost(request, response, parameterMap); } } }
34.231707
112
0.619166
ec68c5052513e5bb327ce46d1e3e93e910c7b682
411
/* * Copyright (c) 2019. Aaron Beetstra & Anti-Social Engineers * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT license. * */ package acecardapi.apierrors; public class InputValueViolation extends FieldViolation { public InputValueViolation(String field) { super(false, "input_value_violation"); this.field = field; } }
22.833333
68
0.737226
c1815729510498084848b867acd9cc38e26c5b4d
3,077
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, 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 com.echothree.model.control.content.server.transfer; import com.echothree.model.control.content.common.transfer.ContentPageAreaTypeTransfer; import com.echothree.model.control.content.common.transfer.ContentPageLayoutAreaTransfer; import com.echothree.model.control.content.common.transfer.ContentPageLayoutTransfer; import com.echothree.model.control.content.server.control.ContentControl; import com.echothree.model.data.content.server.entity.ContentPageLayoutArea; import com.echothree.model.data.user.server.entity.UserVisit; public class ContentPageLayoutAreaTransferCache extends BaseContentTransferCache<ContentPageLayoutArea, ContentPageLayoutAreaTransfer> { /** Creates a new instance of ContentPageLayoutAreaTransferCache */ public ContentPageLayoutAreaTransferCache(UserVisit userVisit, ContentControl contentControl) { super(userVisit, contentControl); } public ContentPageLayoutAreaTransfer getContentPageLayoutAreaTransfer(ContentPageLayoutArea contentPageLayoutArea) { ContentPageLayoutAreaTransfer contentPageLayoutAreaTransfer = get(contentPageLayoutArea); if(contentPageLayoutAreaTransfer == null) { ContentTransferCaches contentTransferCaches = contentControl.getContentTransferCaches(userVisit); ContentPageLayoutTransfer contentPageLayoutTransfer = contentTransferCaches.getContentPageLayoutTransferCache().getTransfer(contentPageLayoutArea.getContentPageLayout()); ContentPageAreaTypeTransfer contentPageAreaTypeTransfer = contentTransferCaches.getContentPageAreaTypeTransferCache().getTransfer(contentPageLayoutArea.getContentPageAreaType()); Boolean showDescriptionField = contentPageLayoutArea.getShowDescriptionField(); Integer sortOrder = contentPageLayoutArea.getSortOrder(); String description = contentControl.getBestContentPageLayoutAreaDescription(contentPageLayoutArea, getLanguage()); contentPageLayoutAreaTransfer = new ContentPageLayoutAreaTransfer(contentPageLayoutTransfer, contentPageAreaTypeTransfer, showDescriptionField, sortOrder, description); put(contentPageLayoutArea, contentPageLayoutAreaTransfer); } return contentPageLayoutAreaTransfer; } }
58.056604
190
0.749756
7097864293ba7580cfcf5005ea472d925326da9d
387
package com.icepoint.framework.code.sysgroup.dao; import com.icepoint.framework.code.sysgroup.entity.SysGroup; import com.icepoint.framework.data.mybatis.RepositoryMapper; import org.apache.ibatis.annotations.Mapper; /** * 分组表(SysGroup)表数据库访问层 * * @author makejava * @since 2021-06-05 11:04:09 */ @Mapper public interface SysGroupDao extends RepositoryMapper<SysGroup, Long> { }
22.764706
71
0.782946
0a1c4aab25525660657017dfca1632440a62e61b
3,536
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.herograve.page.index; import com.herograve.topic.Topicarea; import com.herograve.util.HttpSessionUtil; import com.herograve.util.RequestValidate; import com.opensymphony.xwork2.ActionSupport; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; /** * * @author Administrator */ public class Index extends ActionSupport implements ServletRequestAware{ private HttpServletRequest request; private RequestValidate requestValidate; private int errCode; private List listTopicarea; public int getErrCode() { return errCode; } public void setErrCode(int errCode) { this.errCode = errCode; } public void setServletRequest(HttpServletRequest request) { this.request = request; } public List getListTopicarea() { return listTopicarea; } public void setListTopicarea(List listTopicarea) { this.listTopicarea = listTopicarea; } @Override public void validate() { if(request.getSession().getAttribute(HttpSessionUtil.LAST_REQ_TIME_KEY) == null){ //2008/06/24 15:20:42 request.getSession().setAttribute(HttpSessionUtil.LAST_REQ_TIME_KEY, 1214292042828l); } requestValidate = new RequestValidate(request); // if(requestValidate.isTooFast()){ // this.errCode = requestValidate.getErrCode(); // request.setAttribute("errRedirect", "welcome.jsp"); // addActionError("Request validate error!"); // } } @Override public String execute(){ request.getSession().setAttribute(HttpSessionUtil.LAST_REQ_TIME_KEY, new Date().getTime()); getDojoData(); return SUCCESS; } private void getDojoData(){ CRUDfromDojo crud = new CRUDfromDojo(); crud.getInfo(); request.setAttribute("TitleCount", crud.getTitleCount()); request.setAttribute("ReplyCount", crud.getReplyCount()); request.setAttribute("UserCount", crud.getUserCount()); request.setAttribute("LatestUserName", crud.getLatestUserName()); List list = crud.getTopicarea(); Topicarea topicarea = null; List<Topicarea> listLevel0 = new ArrayList<Topicarea>(0); List<Topicarea> listLevel1 = new ArrayList<Topicarea>(0); List<Topicarea> listLevel2 = new ArrayList<Topicarea>(0); List<List> listRet = new ArrayList<List>(0); Iterator iterator = list.iterator(); while(iterator.hasNext()){ topicarea = (Topicarea)iterator.next(); switch(topicarea.getLevel()){ case 0: listLevel0.add(topicarea); break; case 1: listLevel1.add(topicarea); break; case 2: listLevel2.add(topicarea); break; default: break; } } listRet.add(listLevel0); listRet.add(listLevel1); listRet.add(listLevel2); setListTopicarea(listRet); } }
28.063492
115
0.59983
558384e52008d8f659f841dc5036a856bea4c6c5
1,390
package com.mulesoft.raml1.java.parser.impl.methodsAndResources; import java.util.List; import javax.xml.bind.annotation.XmlElement; import com.mulesoft.raml1.java.parser.core.JavaNodeFactory; import com.mulesoft.raml1.java.parser.model.methodsAndResources.OAuth1SecuritySchemeSettings; import com.mulesoft.raml1.java.parser.model.systemTypes.FixedUri; import com.mulesoft.raml1.java.parser.impl.systemTypes.FixedUriImpl; public class OAuth1SecuritySchemeSettingsImpl extends SecuritySchemaSettingsImpl implements OAuth1SecuritySchemeSettings { public OAuth1SecuritySchemeSettingsImpl(Object jsNode, JavaNodeFactory factory){ super(jsNode,factory); } protected OAuth1SecuritySchemeSettingsImpl(){ super(); } @XmlElement(name="requestTokenUri") public FixedUri requestTokenUri(){ return super.getAttribute("requestTokenUri", FixedUriImpl.class); } @XmlElement(name="authorizationUri") public FixedUri authorizationUri(){ return super.getAttribute("authorizationUri", FixedUriImpl.class); } @XmlElement(name="tokenCredentialsUri") public FixedUri tokenCredentialsUri(){ return super.getAttribute("tokenCredentialsUri", FixedUriImpl.class); } @XmlElement(name="signatures") public List<String> signatures(){ return super.getAttributes("signatures", String.class); } }
30.888889
122
0.763309
1a35eb40cc511ae9476433e3f9a9e01b9c138601
5,205
package org.zcorp.java1.storage.serializer; import org.zcorp.java1.model.*; import java.io.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; public class DataStreamSerializer implements StreamSerializer { private interface ElementProcessor { void process() throws IOException; } private interface ElementReader<T> { T read() throws IOException; } private interface ElementWriter<T> { void write(T t) throws IOException; } private <T> void writeCollection(DataOutputStream dos, Collection<T> collection, ElementWriter<T> writer) throws IOException { dos.writeInt(collection.size()); for (T item : collection) { writer.write(item); } } private void writeLocalDate(DataOutputStream dos, LocalDate ld) throws IOException { dos.writeInt(ld.getYear()); dos.writeInt(ld.getMonth().getValue()); } private LocalDate readLocalDate(DataInputStream dis) throws IOException { return LocalDate.of(dis.readInt(), dis.readInt(), 1); } private <T> List<T> readList(DataInputStream dis, ElementReader<T> reader) throws IOException { int size = dis.readInt(); List<T> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(reader.read()); } return list; } private void readItems(DataInputStream dis, ElementProcessor processor) throws IOException { int size = dis.readInt(); for (int i = 0; i < size; i++) { processor.process(); } } private Section readSection(DataInputStream dis, SectionType sectionType) throws IOException { switch (sectionType) { case PERSONAL: case OBJECTIVE: return new TextSection(dis.readUTF()); case ACHIEVEMENT: case QUALIFICATIONS: return new ListSection(readList(dis, dis::readUTF)); case EXPERIENCE: case EDUCATION: return new OrganizationSection( readList(dis, () -> new Organization( new Link(dis.readUTF(), dis.readUTF()), readList(dis, () -> new Organization.Position( readLocalDate(dis), readLocalDate(dis), dis.readUTF(), dis.readUTF() )) ))); default: throw new IllegalStateException(); } } @Override public void doWrite(Resume r, OutputStream os) throws IOException { try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeUTF(r.getUuid()); dos.writeUTF(r.getFullName()); Map<ContactType, String> contacts = r.getContacts(); writeCollection(dos, contacts.entrySet(), entry -> { dos.writeUTF(entry.getKey().name()); dos.writeUTF(entry.getValue()); }); writeCollection(dos, r.getSections().entrySet(), entry -> { SectionType type = entry.getKey(); Section section = entry.getValue(); dos.writeUTF(type.name()); switch (type) { case PERSONAL: case OBJECTIVE: dos.writeUTF(((TextSection) section).getContent()); break; case ACHIEVEMENT: case QUALIFICATIONS: writeCollection(dos, ((ListSection) section).getItems(), dos::writeUTF); break; case EXPERIENCE: case EDUCATION: writeCollection(dos, ((OrganizationSection) section).getOrganizations(), org -> { dos.writeUTF(org.getHomePage().getName()); dos.writeUTF(org.getHomePage().getUrl()); writeCollection(dos, org.getPositions(), position -> { writeLocalDate(dos, position.getStartDate()); writeLocalDate(dos, position.getEndDate()); dos.writeUTF(position.getTitle()); dos.writeUTF(position.getDescription()); }); }); break; } }); } } @Override public Resume doRead(InputStream is) throws IOException { try (DataInputStream dis = new DataInputStream(is)) { String uuid = dis.readUTF(); String fullName = dis.readUTF(); Resume resume = new Resume(uuid, fullName); readItems(dis, () -> resume.putContact(ContactType.valueOf(dis.readUTF()), dis.readUTF())); readItems(dis, () -> { SectionType sectionType = SectionType.valueOf(dis.readUTF()); resume.putSection(sectionType, readSection(dis, sectionType)); }); return resume; } } }
37.992701
130
0.536984
01bf316e4bb8907243076e88b823921fd415776c
12,696
/* Copyright 2012 - 2014 Jerome Leleu Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.pac4j.oauth.client; import java.util.Date; import java.util.List; import java.util.Locale; import org.apache.commons.lang3.StringUtils; import org.pac4j.core.client.Client; import org.pac4j.core.profile.Gender; import org.pac4j.core.profile.ProfileHelper; import org.pac4j.core.profile.UserProfile; import org.pac4j.core.util.TestsHelper; import org.pac4j.oauth.profile.JsonList; import org.pac4j.oauth.profile.facebook.FacebookApplication; import org.pac4j.oauth.profile.facebook.FacebookEducation; import org.pac4j.oauth.profile.facebook.FacebookEvent; import org.pac4j.oauth.profile.facebook.FacebookGroup; import org.pac4j.oauth.profile.facebook.FacebookInfo; import org.pac4j.oauth.profile.facebook.FacebookMusicData; import org.pac4j.oauth.profile.facebook.FacebookMusicListen; import org.pac4j.oauth.profile.facebook.FacebookObject; import org.pac4j.oauth.profile.facebook.FacebookPhoto; import org.pac4j.oauth.profile.facebook.FacebookPicture; import org.pac4j.oauth.profile.facebook.FacebookProfile; import org.pac4j.oauth.profile.facebook.FacebookRelationshipStatus; import org.pac4j.oauth.profile.facebook.FacebookWork; import com.esotericsoftware.kryo.Kryo; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; /** * This class tests the {@link FacebookClient} class by simulating a complete authentication. * * @author Jerome Leleu * @since 1.0.0 */ public class TestFacebookClient extends TestOAuthClient { @Override public void testClone() { final FacebookClient oldClient = new FacebookClient(); oldClient.setScope(SCOPE); oldClient.setFields(FIELDS); oldClient.setLimit(LIMIT); final FacebookClient client = (FacebookClient) internalTestClone(oldClient); assertEquals(oldClient.getScope(), client.getScope()); assertEquals(oldClient.getFields(), client.getFields()); assertEquals(oldClient.getLimit(), client.getLimit()); } public void testMissingFields() { final FacebookClient client = (FacebookClient) getClient(); client.setFields(null); TestsHelper.initShouldFail(client, "fields cannot be blank"); } @SuppressWarnings("rawtypes") @Override protected Client getClient() { final FacebookClient facebookClient = new FacebookClient(); facebookClient.setKey("291329260930505"); facebookClient.setSecret("8ace9cbf90dcecfeb36c285854db55ab"); facebookClient.setCallbackUrl(PAC4J_URL); facebookClient .setScope("email,user_likes,user_about_me,user_birthday,user_education_history,user_hometown,user_relationship_details,user_location,user_religion_politics,user_relationships,user_work_history,user_website,user_photos,user_events,user_groups,user_actions.music"); facebookClient.setFields(FacebookClient.DEFAULT_FIELDS + ",friends,movies,music,books,likes,albums,events,groups,music.listens,picture"); facebookClient.setLimit(100); return facebookClient; } @Override protected String getCallbackUrl(final WebClient webClient, final HtmlPage authorizationPage) throws Exception { final HtmlForm form = authorizationPage.getForms().get(0); final HtmlTextInput email = form.getInputByName("email"); email.setValueAttribute("testscribeup@gmail.com"); final HtmlPasswordInput password = form.getInputByName("pass"); password.setValueAttribute("testpwdscribeup"); final HtmlSubmitInput submit = form.getInputByName("login"); final HtmlPage callbackPage = submit.click(); final String callbackUrl = callbackPage.getUrl().toString(); logger.debug("callbackUrl : {}", callbackUrl); return callbackUrl; } @Override protected void registerForKryo(final Kryo kryo) { kryo.register(FacebookProfile.class); kryo.register(FacebookObject.class); kryo.register(JsonList.class); kryo.register(FacebookEvent.class); kryo.register(FacebookInfo.class); kryo.register(FacebookMusicListen.class); kryo.register(FacebookApplication.class); kryo.register(FacebookMusicData.class); kryo.register(FacebookEducation.class); kryo.register(FacebookRelationshipStatus.class); kryo.register(FacebookGroup.class); kryo.register(FacebookWork.class); kryo.register(FacebookPicture.class); kryo.register(FacebookPhoto.class); } @Override protected void verifyProfile(final UserProfile userProfile) { final FacebookProfile profile = (FacebookProfile) userProfile; logger.debug("userProfile : {}", profile); assertEquals("100003571536393", profile.getId()); assertEquals(FacebookProfile.class.getSimpleName() + UserProfile.SEPARATOR + "100003571536393", profile.getTypedId()); assertTrue(ProfileHelper.isTypedIdOf(profile.getTypedId(), FacebookProfile.class)); assertTrue(StringUtils.isNotBlank(profile.getAccessToken())); assertCommonProfile(userProfile, null, "Jerome", "Testscribeup", "Jerome Testscribeup", "jerome.testscribeup", Gender.MALE, Locale.FRANCE, "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-", "https://www.facebook.com/jerome.testscribeup", "New York, New York"); assertNull(profile.getMiddleName()); final List<FacebookObject> languages = profile.getLanguages(); assertTrue(languages.get(0).getName().startsWith("Fr")); assertTrue(StringUtils.isNotBlank(profile.getThirdPartyId())); assertEquals(2, profile.getTimezone().intValue()); assertEquals(TestsHelper.getFormattedDate(1343375150000L, "yyyy-MM-dd'T'HH:mm:ssz", null), profile .getUpdateTime().toString()); assertFalse(profile.getVerified()); assertEquals("A propos de moi", profile.getBio()); assertEquals("03/10/1979", profile.getBirthday().toString()); final List<FacebookEducation> educations = profile.getEducation(); FacebookEducation education = educations.get(0); assertEquals("lycée mixte", education.getSchool().getName()); assertEquals("2000", education.getYear().getName()); assertEquals("High School", education.getType()); education = educations.get(1); assertEquals("Ingénieur", education.getDegree().getName()); assertNull(profile.getEmail()); assertEquals("San Francisco, California", (profile.getHometown()).getName()); assertEquals("female", (profile.getInterestedIn()).get(0)); assertEquals("New York, New York", (profile.getLocationObject()).getName()); assertEquals("Sans Opinion (desc)", profile.getPolitical()); final List<FacebookObject> favoriteAthletes = profile.getFavoriteAthletes(); assertEquals("Surfing", favoriteAthletes.get(0).getName()); final List<FacebookObject> favoriteTeams = profile.getFavoriteTeams(); assertEquals("Handball Féminin de France", favoriteTeams.get(0).getName()); assertEquals("citation", profile.getQuotes()); assertEquals(FacebookRelationshipStatus.MARRIED, profile.getRelationshipStatus()); assertEquals("Athéisme (desc)", profile.getReligion()); assertNull(profile.getSignificantOther()); assertEquals("web site", profile.getWebsite()); final List<FacebookWork> works = profile.getWork(); final FacebookWork work = works.get(0); assertEquals("Employeur", work.getEmployer().getName()); assertEquals("Paris, France", work.getLocation().getName()); assertEquals("Architecte Web", work.getPosition().getName()); assertEquals("Description", work.getDescription()); assertTrue(work.getStartDate() instanceof Date); assertNull(work.getEndDate()); final List<FacebookObject> friends = profile.getFriends(); assertEquals(1, friends.size()); final FacebookObject friend = friends.get(0); assertEquals("Jérôme Leleu", friend.getName()); assertEquals("100002406067613", friend.getId()); final List<FacebookInfo> movies = profile.getMovies(); assertEquals(1, movies.size()); final FacebookInfo movie = movies.get(0); assertEquals("Jean-Claude Van Damme", movie.getName()); assertEquals("21497365045", movie.getId()); assertEquals("Actor/director", movie.getCategory()); assertEquals(1330030350000L, movie.getCreatedTime().getTime()); final List<FacebookInfo> musics = profile.getMusic(); assertEquals(1, musics.size()); final FacebookInfo music = musics.get(0); assertEquals("Hard rock", music.getName()); assertEquals("112175695466436", music.getId()); assertEquals("Musical genre", music.getCategory()); assertEquals(1330030350000L, music.getCreatedTime().getTime()); final List<FacebookInfo> books = profile.getBooks(); assertEquals(1, books.size()); final FacebookInfo book = books.get(0); assertEquals("Science fiction", book.getName()); assertEquals("108157509212483", book.getId()); assertEquals("Tv genre", book.getCategory()); assertEquals(1330030350000L, book.getCreatedTime().getTime()); final List<FacebookInfo> likes = profile.getLikes(); assertEquals(8, likes.size()); final FacebookInfo like = likes.get(0); assertEquals("Boxing", like.getName()); assertEquals("105648929470083", like.getId()); assertEquals("Sport", like.getCategory()); assertEquals(1360152791000L, like.getCreatedTime().getTime()); final List<FacebookPhoto> albums = profile.getAlbums(); assertEquals(3, albums.size()); final FacebookPhoto album = albums.get(1); assertEquals("168023009993416", album.getId()); final FacebookObject from = album.getFrom(); assertEquals("100003571536393", from.getId()); assertEquals("Jerome Testscribeup", from.getName()); assertEquals("Profile Pictures", album.getName()); assertEquals("https://www.facebook.com/album.php?fbid=168023009993416&id=100003571536393&aid=34144", album.getLink()); assertEquals("168023156660068", album.getCoverPhoto()); assertEquals("everyone", album.getPrivacy()); assertEquals(1, album.getCount().intValue()); assertEquals("profile", album.getType()); assertEquals(1336472634000L, album.getCreatedTime().getTime()); assertEquals(1336472660000L, album.getUpdatedTime().getTime()); assertFalse(album.getCanUpload()); final List<FacebookEvent> events = profile.getEvents(); assertEquals(1, events.size()); final FacebookEvent event = events.get(0); assertEquals("Couronnement", event.getName()); assertEquals("301212149963131", event.getId()); assertTrue(event.getLocation().indexOf("Paris") >= 0); assertEquals("attending", event.getRsvpStatus()); assertNotNull(event.getStartTime()); assertNotNull(event.getEndTime()); final List<FacebookGroup> groups = profile.getGroups(); final FacebookGroup group = groups.get(0); assertNull(group.getVersion()); assertEquals("Dev ScribeUP", group.getName()); assertEquals("167694120024728", group.getId()); assertTrue(group.getAdministrator()); assertEquals(1, group.getBookmarkOrder().intValue()); final List<FacebookMusicListen> musicListens = profile.getMusicListens(); assertEquals(4, musicListens.size()); final FacebookPicture picture = profile.getPicture(); assertFalse(picture.getIsSilhouette()); assertEquals(37, profile.getAttributes().size()); } }
51.193548
279
0.705577
7ccc62f7d04983e96a9e7123d4770d472ee45a9a
1,729
package com.blockchain.store.playmarket.data.entities; import android.os.Parcel; import android.os.Parcelable; import java.text.DecimalFormat; public class IcoBalance implements Parcelable { public String address; public String balanceOf; public String decimals; protected IcoBalance(Parcel in) { this.address = in.readString(); this.balanceOf = in.readString(); this.decimals = in.readString(); } public String getTokenCountWithoutDecimals(){ return balanceOf; } public String getTokenCount() { long tokensNum = Long.valueOf(balanceOf); short decimalsNum = Short.valueOf(decimals); double transformedTokensNum = tokensNum * Math.pow(10, -decimalsNum); DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(3); df.setMinimumFractionDigits(0); df.setGroupingUsed(false); transformedTokensNum = Math.round(transformedTokensNum * 10000.0) / 10000.0; return String.valueOf(df.format(transformedTokensNum)).replaceAll(",", "."); } public IcoBalance() { } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.address); dest.writeString(this.balanceOf); dest.writeString(this.decimals); } public static final Creator<IcoBalance> CREATOR = new Creator<IcoBalance>() { @Override public IcoBalance createFromParcel(Parcel in) { return new IcoBalance(in); } @Override public IcoBalance[] newArray(int size) { return new IcoBalance[size]; } }; }
27.444444
84
0.651822
5b0115c0e1e27c2de2a67ef4c6b0276df61457cc
386
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc3; import org.postgresql.ds.PGConnectionPoolDataSource; /** * @deprecated Please use {@link PGConnectionPoolDataSource} */ @Deprecated public class Jdbc3ConnectionPool extends PGConnectionPoolDataSource { }
24.125
70
0.753886
a44942774033e7b0d2d4519d3c6f1fba8192450f
1,872
/* * - * #%L * Pipeline: AWS Steps * %% * Copyright (C) 2017 Taimos GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.taimos.pipeline.aws.cloudformation.parser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.yaml.snakeyaml.Yaml; import com.amazonaws.services.cloudformation.model.Parameter; import com.google.common.base.Charsets; import com.google.common.base.Joiner; public class YAMLParameterFileParser implements ParameterFileParser { @Override public Collection<Parameter> parseParams(InputStream fileContent) throws IOException { Yaml yaml = new Yaml(); @SuppressWarnings("unchecked") Map<String, Object> parse = yaml.load(new InputStreamReader(fileContent, Charsets.UTF_8)); Collection<Parameter> parameters = new ArrayList<>(); for (Map.Entry<String, Object> entry : parse.entrySet()) { Object value = entry.getValue(); if (value instanceof Collection) { String val = Joiner.on(",").join((Collection) value); parameters.add(new Parameter().withParameterKey(entry.getKey()).withParameterValue(val)); } else { parameters.add(new Parameter().withParameterKey(entry.getKey()).withParameterValue(value.toString())); } } return parameters; } }
31.728814
106
0.742521
44cdc9048984fec79beeca0339c31c71d979f696
349
package tech.aistar.design.factory.abstracts; /** * 本类用来演示: * * @author: success * @date: 2020/8/3 2:19 下午 */ public class PhoneXFactory implements ProductFactory{ @Override public Sender produceSender() { return new QQSender(); } @Override public Caller produceCaller() { return new DingCaller(); } }
17.45
53
0.638968
649d62fa1768a0cdd45013800d75f6283bed4d03
5,871
/* * Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cooee.virtualapk.utils; import android.content.Context; import android.os.Build; import com.cooee.virtualapk.Systems; import com.cooee.virtualapk.internal.Constants; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.List; import dalvik.system.DexClassLoader; import dalvik.system.PathClassLoader; public class DexUtil { private static boolean sHasInsertedNativeLibrary = false; public static void insertDex(DexClassLoader dexClassLoader) throws Exception { Object baseDexElements = getDexElements(getPathList(getPathClassLoader())); Object newDexElements = getDexElements(getPathList(dexClassLoader)); Object allDexElements = combineArray(baseDexElements, newDexElements); Object pathList = getPathList(getPathClassLoader()); ReflectUtil.setField(pathList.getClass(), pathList, "dexElements", allDexElements); insertNativeLibrary(dexClassLoader); } private static PathClassLoader getPathClassLoader() { PathClassLoader pathClassLoader = (PathClassLoader) DexUtil.class.getClassLoader(); return pathClassLoader; } private static Object getDexElements(Object pathList) throws Exception { return ReflectUtil.getField(pathList.getClass(), pathList, "dexElements"); } private static Object getPathList(Object baseDexClassLoader) throws Exception { return ReflectUtil.getField(Class.forName("dalvik.system.BaseDexClassLoader"), baseDexClassLoader, "pathList"); } private static Object combineArray(Object firstArray, Object secondArray) { Class<?> localClass = firstArray.getClass().getComponentType(); int firstArrayLength = Array.getLength(firstArray); int allLength = firstArrayLength + Array.getLength(secondArray); Object result = Array.newInstance(localClass, allLength); for (int k = 0; k < allLength; ++k) { if (k < firstArrayLength) { Array.set(result, k, Array.get(firstArray, k)); } else { Array.set(result, k, Array.get(secondArray, k - firstArrayLength)); } } return result; } private static synchronized void insertNativeLibrary(DexClassLoader dexClassLoader) throws Exception { if (sHasInsertedNativeLibrary) { return; } sHasInsertedNativeLibrary = true; Object basePathList = getPathList(getPathClassLoader()); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) { List<File> nativeLibraryDirectories = (List<File>) ReflectUtil.getField(basePathList.getClass(), basePathList, "nativeLibraryDirectories"); nativeLibraryDirectories.add(Systems.getContext().getDir(Constants.NATIVE_DIR, Context.MODE_PRIVATE)); Object baseNativeLibraryPathElements = ReflectUtil.getField(basePathList.getClass(), basePathList, "nativeLibraryPathElements"); final int baseArrayLength = Array.getLength(baseNativeLibraryPathElements); Object newPathList = getPathList(dexClassLoader); Object newNativeLibraryPathElements = ReflectUtil.getField(newPathList.getClass(), newPathList, "nativeLibraryPathElements"); Class<?> elementClass = newNativeLibraryPathElements.getClass().getComponentType(); Object allNativeLibraryPathElements = Array.newInstance(elementClass, baseArrayLength + 1); System.arraycopy(baseNativeLibraryPathElements, 0, allNativeLibraryPathElements, 0, baseArrayLength); Field soPathField; if (Build.VERSION.SDK_INT >= 26) { soPathField = elementClass.getDeclaredField("path"); } else { soPathField = elementClass.getDeclaredField("dir"); } soPathField.setAccessible(true); final int newArrayLength = Array.getLength(newNativeLibraryPathElements); for (int i = 0; i < newArrayLength; i++) { Object element = Array.get(newNativeLibraryPathElements, i); String dir = ((File)soPathField.get(element)).getAbsolutePath(); if (dir.contains(Constants.NATIVE_DIR)) { Array.set(allNativeLibraryPathElements, baseArrayLength, element); break; } } ReflectUtil.setField(basePathList.getClass(), basePathList, "nativeLibraryPathElements", allNativeLibraryPathElements); } else { File[] nativeLibraryDirectories = (File[]) ReflectUtil.getFieldNoException(basePathList.getClass(), basePathList, "nativeLibraryDirectories"); final int N = nativeLibraryDirectories.length; File[] newNativeLibraryDirectories = new File[N + 1]; System.arraycopy(nativeLibraryDirectories, 0, newNativeLibraryDirectories, 0, N); newNativeLibraryDirectories[N] = Systems.getContext().getDir(Constants.NATIVE_DIR, Context.MODE_PRIVATE); ReflectUtil.setField(basePathList.getClass(), basePathList, "nativeLibraryDirectories", newNativeLibraryDirectories); } } }
46.968
140
0.697666
56ae1595129376d165fbffe4b2328400677206ce
2,189
package com.xuzimian.java.learning.spring.security.configuration; import org.jasig.cas.client.session.SingleSignOutFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.cas.web.CasAuthenticationFilter; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.logout.LogoutFilter; @EnableWebSecurity(debug = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationProvider authenticationProvider; @Autowired private AuthenticationEntryPoint entryPoint; @Autowired private SingleSignOutFilter singleSignOutFilter; @Autowired private LogoutFilter requestSingleLogoutFilter; @Autowired private CasAuthenticationFilter casAuthenticationFilter; @Override protected void configure(AuthenticationManagerBuilder auth) { auth.authenticationProvider(authenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasRole("USER") .antMatchers("/login/cas", "/favicon.ico", "/error").permitAll() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(entryPoint) .and() .addFilter(casAuthenticationFilter) .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) .addFilterBefore(requestSingleLogoutFilter, LogoutFilter.class); } }
39.089286
107
0.751942
0d2a664796845675cd2ef39f781733c057b07a0a
11,866
/* 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.batik.dom.svg; import org.apache.batik.dom.AbstractDocument; import org.apache.batik.util.DoublyIndexedTable; import org.apache.batik.util.SVGTypes; import org.w3c.dom.Node; import org.w3c.dom.svg.SVGAnimatedBoolean; import org.w3c.dom.svg.SVGAnimatedEnumeration; import org.w3c.dom.svg.SVGAnimatedInteger; import org.w3c.dom.svg.SVGAnimatedLength; import org.w3c.dom.svg.SVGAnimatedNumber; import org.w3c.dom.svg.SVGAnimatedNumberList; import org.w3c.dom.svg.SVGAnimatedString; import org.w3c.dom.svg.SVGFEConvolveMatrixElement; /** * This class implements {@link SVGFEConvolveMatrixElement}. * * @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a> * @version $Id: SVGOMFEConvolveMatrixElement.java 592621 2007-11-07 05:58:12Z cam $ */ public class SVGOMFEConvolveMatrixElement extends SVGOMFilterPrimitiveStandardAttributes implements SVGFEConvolveMatrixElement { /** * Table mapping XML attribute names to TraitInformation objects. */ protected static DoublyIndexedTable xmlTraitInformation; static { DoublyIndexedTable t = new DoublyIndexedTable(SVGOMFilterPrimitiveStandardAttributes.xmlTraitInformation); t.put(null, SVG_IN_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_CDATA)); t.put(null, SVG_ORDER_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_NUMBER_OPTIONAL_NUMBER)); t.put(null, SVG_KERNEL_UNIT_LENGTH_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_NUMBER_OPTIONAL_NUMBER)); t.put(null, SVG_KERNEL_MATRIX_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_NUMBER_LIST)); t.put(null, SVG_DIVISOR_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_NUMBER)); t.put(null, SVG_BIAS_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_NUMBER)); t.put(null, SVG_TARGET_X_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_INTEGER)); t.put(null, SVG_TARGET_Y_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_INTEGER)); t.put(null, SVG_EDGE_MODE_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_IDENT)); t.put(null, SVG_PRESERVE_ALPHA_ATTRIBUTE, new TraitInformation(true, SVGTypes.TYPE_BOOLEAN)); xmlTraitInformation = t; } /** * The 'edgeMode' attribute values. */ protected static final String[] EDGE_MODE_VALUES = { "", SVG_DUPLICATE_VALUE, SVG_WRAP_VALUE, SVG_NONE_VALUE }; /** * The 'in' attribute value. */ protected SVGOMAnimatedString in; /** * The 'edgeMode' attribute value. */ protected SVGOMAnimatedEnumeration edgeMode; /** * The 'bias' attribute value. */ protected SVGOMAnimatedNumber bias; /** * The 'preserveAlpha' attribute value. */ protected SVGOMAnimatedBoolean preserveAlpha; /** * Creates a new SVGOMFEConvolveMatrixElement object. */ protected SVGOMFEConvolveMatrixElement() { } /** * Creates a new SVGOMFEConvolveMatrixElement object. * @param prefix The namespace prefix. * @param owner The owner document. */ public SVGOMFEConvolveMatrixElement(String prefix, AbstractDocument owner) { super(prefix, owner); initializeLiveAttributes(); } /** * Initializes all live attributes for this element. */ protected void initializeAllLiveAttributes() { super.initializeAllLiveAttributes(); initializeLiveAttributes(); } /** * Initializes the live attribute values of this element. */ private void initializeLiveAttributes() { in = createLiveAnimatedString(null, SVG_IN_ATTRIBUTE); edgeMode = createLiveAnimatedEnumeration (null, SVG_EDGE_MODE_ATTRIBUTE, EDGE_MODE_VALUES, (short) 1); bias = createLiveAnimatedNumber(null, SVG_BIAS_ATTRIBUTE, 0f); preserveAlpha = createLiveAnimatedBoolean (null, SVG_PRESERVE_ALPHA_ATTRIBUTE, false); } /** * <b>DOM</b>: Implements {@link Node#getLocalName()}. */ public String getLocalName() { return SVG_FE_CONVOLVE_MATRIX_TAG; } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getIn1()}. */ public SVGAnimatedString getIn1() { return in; } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getEdgeMode()}. */ public SVGAnimatedEnumeration getEdgeMode() { return edgeMode; } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getKernelMatrix()}. */ public SVGAnimatedNumberList getKernelMatrix() { throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getKernelMatrix is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getOrderX()}. */ public SVGAnimatedInteger getOrderX() { throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getOrderX is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getOrderY()}. */ public SVGAnimatedInteger getOrderY() { throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getOrderY is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getTargetX()}. */ public SVGAnimatedInteger getTargetX() { // Default value relative to orderX... throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getTargetX is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getTargetY()}. */ public SVGAnimatedInteger getTargetY() { // Default value relative to orderY... throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getTargetY is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link SVGFEConvolveMatrixElement#getDivisor()}. */ public SVGAnimatedNumber getDivisor() { // Default value relative to kernel matrix... throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getDivisor is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link * org.w3c.dom.svg.SVGFEConvolveMatrixElement#getBias()}. */ public SVGAnimatedNumber getBias() { return bias; } /** * <b>DOM</b>: Implements {@link * org.w3c.dom.svg.SVGFEConvolveMatrixElement#getKernelUnitLengthX()}. */ public SVGAnimatedLength getKernelUnitLengthX() { throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getKernelUnitLengthX is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link * org.w3c.dom.svg.SVGFEConvolveMatrixElement#getKernelUnitLengthY()}. */ public SVGAnimatedLength getKernelUnitLengthY() { throw new UnsupportedOperationException ("SVGFEConvolveMatrixElement.getKernelUnitLengthY is not implemented"); // XXX } /** * <b>DOM</b>: Implements {@link * org.w3c.dom.svg.SVGFEConvolveMatrixElement#getPreserveAlpha()}. */ public SVGAnimatedBoolean getPreserveAlpha() { return preserveAlpha; } /** * Returns a new uninitialized instance of this object's class. */ protected Node newNode() { return new SVGOMFEConvolveMatrixElement(); } /** * Returns the table of TraitInformation objects for this element. */ protected DoublyIndexedTable getTraitInformationTable() { return xmlTraitInformation; } // AnimationTarget /////////////////////////////////////////////////////// // XXX TBD // // /** // * Updates an attribute value in this target. // */ // public void updateAttributeValue(String ns, String ln, // AnimatableValue val) { // if (ns == null) { // if (ln.equals(SVG_ORDER_ATTRIBUTE)) { // if (val == null) { // // XXX Needs testing. // updateIntegerAttributeValue(getOrderX(), null); // updateIntegerAttributeValue(getOrderY(), null); // } else { // AnimatableNumberOptionalNumberValue anonv = // (AnimatableNumberOptionalNumberValue) val; // SVGOMAnimatedInteger ai = // (SVGOMAnimatedInteger) getOrderX(); // ai.setAnimatedValue(Math.round(anonv.getNumber())); // ai = (SVGOMAnimatedInteger) getOrderY(); // if (anonv.hasOptionalNumber()) { // ai.setAnimatedValue // (Math.round(anonv.getOptionalNumber())); // } else { // ai.setAnimatedValue(Math.round(anonv.getNumber())); // } // } // return; // } else if (ln.equals(SVG_KERNEL_UNIT_LENGTH_ATTRIBUTE)) { // // XXX Needs testing. // if (val == null) { // updateNumberAttributeValue(getKernelUnitLengthX(), null); // updateNumberAttributeValue(getKernelUnitLengthY(), null); // } else { // AnimatableNumberOptionalNumberValue anonv = // (AnimatableNumberOptionalNumberValue) val; // SVGOMAnimatedNumber an = // (SVGOMAnimatedNumber) getKernelUnitLengthX(); // an.setAnimatedValue(anonv.getNumber()); // an = (SVGOMAnimatedNumber) getKernelUnitLengthY(); // if (anonv.hasOptionalNumber()) { // an.setAnimatedValue(anonv.getOptionalNumber()); // } else { // an.setAnimatedValue(anonv.getNumber()); // } // } // return; // } // } // super.updateAttributeValue(ns, ln, val); // } // // /** // * Returns the underlying value of an animatable XML attribute. // */ // public AnimatableValue getUnderlyingValue(String ns, String ln) { // if (ns == null) { // if (ln.equals(SVG_KERNEL_UNIT_LENGTH_ATTRIBUTE)) { // return getBaseValue(getKernelUnitLengthX(), // getKernelUnitLengthY()); // } else if (ln.equals(SVG_ORDER_ATTRIBUTE)) { // return getBaseValue(getOrderX(), getOrderY()); // } // } // return super.getUnderlyingValue(ns, ln); // } }
35.740964
95
0.614276
6b1818e3fe05ac22c074eb34ff70bbc4351e993b
6,652
package dbao; import java.util.Arrays; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import dbo.Food; /** * * @author MatthewsLaptop * @see Food * @version 1.0.0 This class is used in conjunction with the Food class. It is * the go between for the database and the program code. * @param <T> */ public class FoodAccessor extends DatabaseAccessor<Object>{ /** * @param factory * - The SessionFactory is passed over to the class so it can use the * factory * @param session * - The session is made for the SessionFactory to use it */ public FoodAccessor(SessionFactory factory, Session session) { setFactory(factory); setSession(session); } public FoodAccessor() { // TODO Auto-generated constructor stub } /** * Updates the food item * * @param food * - the food item to be changed * @param InSession * @return */ public Boolean UpdateFoodItem(Food food, Session InSession) { try { session = InSession; session.beginTransaction(); // get Food Food myfood = session.get(Food.class, food.getFood_id()); // update object myfood.setCook_time(food.getCook_time()); myfood.setFood_name(food.getFood_name()); myfood.setIngredients(food.getIngredients()); myfood.setStation_name(food.getStation_name()); // commit to database session.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; } public boolean AddNewRecord(Food food, Session InSession) { return super.AddNewRecord(food, InSession, food.NotNull(), InsertValid(food)); } public Boolean DeleteFoodItem(Food food, Session InSession) { session = InSession; try { session = InSession; session.beginTransaction(); // get Food Food myfood = session.get(Food.class, food.getFood_id()); // Delete food session.delete(myfood); // commit to database session.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; } public List<Food> getFoodItem(Food food, Session InSession) { // Create query string String query = createFoodQuery(food); try { session = InSession; session.beginTransaction(); // Query Food @SuppressWarnings("unchecked") List<Food> theTickets = session.createQuery(query) // make sure to have the class object exactly not // the table name .getResultList(); System.out.println(theTickets + " The Food"); return theTickets; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public Food getFoodItem(int foodId, Session InSession) { // Create query string try { session = InSession; session.beginTransaction(); // get Food Food myfood = session.get(Food.class, foodId); //clean up session session.close(); return myfood; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public List<Food> getFoodItem(Session InSession) { final String query = "from Food"; try { session = InSession; session.beginTransaction(); // Query Food @SuppressWarnings("unchecked") List<Food> theTickets = session.createQuery(query) // make sure to have the class object exactly not // the table name .getResultList(); return theTickets; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * This function creates a string to query the data base. * * @param food * - The details of the food item to help narrow down the search * @return the string in a queryable format */ private String createFoodQuery(Food food) { StringBuilder query = new StringBuilder(); query.append("from Food f");// Beginning of query // used to determine if there is a variable already in query Boolean second = false; if (food.NotNull())// Enables query all { // add where clause query.append(" WHERE "); // check food id if (food.getFood_id() != 0) { query.append(" f.food_id = " + food.getFood_id() + " "); second = true; } if (food.getCook_time() != 0) { // Checks if previous is true if (second) { query.append(" AND "); } query.append("f.cook_time = " + food.getCook_time() + " "); second = true; } if (food.getFood_name() != "") { // checks if seconded if (second) { query.append(" AND "); } query.append("f.food_name = " + food.getFood_name() + " "); second = true; } if (food.getStation_name() != "") { // checks if seconded if (second) { query.append(" AND "); } query.append("f.station_name = " + food.getStation_name() + " "); second = true; } if (food.getIngredients() != "") { // checks if seconded if (second) { query.append(" AND "); } // split the list of food items into an array of items List<String> items = Arrays.asList(food.getIngredients().split("\\s*,\\s*")); Boolean twice = false; int counter = 0; if (items.size() > 1) // Make sure there is more than one item { twice = true; } /** * Learned about this and how to do it from App Shaw * http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/ * Collection stream() util: Returns a sequential Stream with this collection as * its source */ if (twice) //Make sure there is more than one item in the list { for (String temp : items) { // Go through each item and search for it in the database if (counter + 1 == temp.length()) // if on last item { query.append(" f.ingredients = " + temp.toString()); } else { query.append(" f.ingredients = " + temp.toString() + " AND "); } counter++; } } else { query.append(" f.ingredients = " + items.get(0)); } } //end ingredients if } //end not null if return query.toString(); } private boolean InsertValid(Food food) { if(!food.NotNull()) { return false; } else { if(food.getCook_time()<=0) { return false; } else if(food.getFood_name() == "" || food.getFood_name() == null) { return false; } else if(food.getIngredients() == "" ||food.getIngredients() == null) { return false; } else if(food.getStation_name() == ""|| food.getStation_name() == null) { return false; } } return true; } }
24.820896
133
0.624023
cbb5158df15a5d4afdc7ea63b7ad3c81eefb6238
1,870
/* * Copyright (C) 2017, Rockwell Collins * All rights reserved. * * This software may be modified and distributed under the terms * of the 3-clause BSD license. See the LICENSE file for details. * */ package fuzzm.lustre.evaluation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.Function; import jkind.lustre.NamedType; import jkind.lustre.VarDecl; public class FunctionSignature { final private Map<String,List<NamedType>> signatures; final private Map<String,NamedType> fout; private static List<NamedType> typeListFromVarDecl(List<VarDecl> args) { List<NamedType> res = new ArrayList<>(); for (VarDecl vd: args) { res.add((NamedType) vd.type); } return res; } public Collection<String> keySet() { return signatures.keySet(); } public FunctionSignature(List<Function> flist) { signatures = new HashMap<>(); fout = new HashMap<>(); for (Function f: flist) { assert(f.outputs.size() <= 1); signatures.put(f.id, typeListFromVarDecl(f.inputs)); if (f.outputs.size() > 1) throw new IllegalArgumentException(); fout.put(f.id,(NamedType) f.outputs.get(0).type); } } public List<NamedType> getArgTypes(String function) { List<NamedType> res = signatures.get(function); if (res == null) throw new IllegalArgumentException(); return res; } public NamedType getFnType(String function) { return fout.get(function); } @Override public String toString() { String res = "Function Signatures :\n\n"; for (String fn: fout.keySet()) { String delimit = ""; String args = "("; for (NamedType type: getArgTypes(fn)) { args += delimit + type; delimit = ","; } args += ")"; res += fn + args + ":" + getFnType(fn) + "\n"; } return res; } }
24.605263
73
0.670053
e1f5c55008b961ca2bce139169a43d6c25f1f4ef
797
package com.fit5136.missionToMars.model; import com.fasterxml.jackson.annotation.JsonProperty; public abstract class User { private final long userId; private final String userName; private String password; public User(@JsonProperty("userId") long userId, @JsonProperty("userName") String userName, @JsonProperty("password") String password) { this.userId = userId; this.userName = userName; this.password = password; } public long getUserId() { return userId; } public String getUserName() { return userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
24.151515
96
0.622334
4f1b24606620e22deb96cbb87adda70b68154dae
2,295
package com.example.navigationview; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.VH> { private final int TYPE_NORMAL=0; private final int TYPE_FOOT=1; ArrayList<String> list=null; int layout=0; Context context; static class VH extends RecyclerView.ViewHolder{ ImageView image; public VH(View view){ super(view); image=view.findViewById(R.id.imageView); } } public MyAdapter(ArrayList<String> list, int layout, Context context){ this.list=list; this.layout=layout; this.context=context; } @NonNull @Override public MyAdapter.VH onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { VH vh=null; if(i==TYPE_NORMAL){//为普通itemViewType时,返回普通itemView的ViewHolder View view= LayoutInflater.from(viewGroup.getContext()).inflate(layout,viewGroup,false); vh=new VH(view); }else if(i==TYPE_FOOT){//不为普通itemViewType时,返回footerItemView的ViewHolder View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.footer_view,viewGroup,false); vh=new VH(view); } return vh; } @Override public void onBindViewHolder(@NonNull VH viewHolder, int i) { if(getItemViewType(i)==TYPE_NORMAL){//不为footerItemView时才进行数据绑定 VH vh=(VH)viewHolder; String path=list.get(i); Glide.with(context).load(path).into(vh.image); } } @Override public int getItemCount() {//为了显示footerView要多返回一个item if(list.size()>0){ return list.size()+1; }else{ return 0; } } @Override public int getItemViewType(int position) {//根据返回的itemViewType去执行onCreateViewHolder和onBindViewHolder方法 if(position+1==getItemCount()){ return TYPE_FOOT; }else{ return TYPE_NORMAL; } } }
29.805195
116
0.655773
e1066ed14c175b9c87eb867a649f8bc003eccb63
14,979
package com.ouc.dcrms.video; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import java.awt.Frame; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.LayoutStyle; import javax.swing.WindowConstants; /***************************************************************************** * 类 : JDialogVoiceTalk * 类描述 :语音对讲 ****************************************************************************/ public class JDialogVoiceTalk extends JDialog { private static final long serialVersionUID = -6354306351002275782L; static HCNetSDK hCNetSDK = HCNetSDK.INSTANCE; NativeLong m_lUserID;// 用户ID HCNetSDK.NET_DVR_DEVICEINFO_V30 m_strDeviceInfo;// 设备信息 HCNetSDK.NET_DVR_WORKSTATE_V30 m_strWorkState;// 工作状态 FVoiceDataCallBack fVoiceDataCallBack;// 回调函数 int m_iSel;// 音频通道 boolean m_bInitialed;// 对话框是否已初始化 FileWriter fLocal;// 本地音频文件 FileWriter fDevice;// 设备发送的音频文件 /************************************************* * 函数: JDialogVoiceTalk * 函数描述: 构造函数 Creates new form JDialogVoiceTalk *************************************************/ public JDialogVoiceTalk(Frame parent, boolean modal, NativeLong lUserID, HCNetSDK.NET_DVR_DEVICEINFO_V30 strDeviceInfo) { super(parent, modal); try { initComponents(); m_lUserID = lUserID; m_strDeviceInfo = strDeviceInfo; m_iSel = 0; fVoiceDataCallBack = new FVoiceDataCallBack(); fLocal = new FileWriter("D:\\local.264"); fDevice = new FileWriter("D:\\device.264"); // 初始化对话框 initialDialog(); m_bInitialed = true; } catch (IOException ex) { Logger.getLogger(JDialogVoiceTalk.class.getName()).log( Level.SEVERE, null, ex); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" // desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel = new JPanel(); jLabel1 = new JLabel(); jComboBoxVoiceChannel = new JComboBox<Object>(); jLabelStatus = new JLabel(); jButtonStart = new JButton(); jButtonStop = new JButton(); jLabel2 = new JLabel(); jComboBoxDataType = new JComboBox<Object>(); jButtonRefresh = new JButton(); jButtonExit = new JButton(); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle("语音对讲"); jPanel.setBorder(BorderFactory.createTitledBorder("")); jLabel1.setText("对讲通道"); jComboBoxVoiceChannel .addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBoxVoiceChannelActionPerformed(evt); } }); jLabelStatus.setText("未占用"); jButtonStart.setText("开始对讲"); jButtonStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartActionPerformed(evt); } }); jButtonStop.setText("停止对讲"); jButtonStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStopActionPerformed(evt); } }); jLabel2.setText("回调数据类型"); jComboBoxDataType.setModel(new DefaultComboBoxModel<Object>( new String[] { "非PCM", "PCM" })); GroupLayout jPanelLayout = new GroupLayout(jPanel); jPanel.setLayout(jPanelLayout); jPanelLayout .setHorizontalGroup(jPanelLayout .createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( jPanelLayout .createSequentialGroup() .addGroup( jPanelLayout .createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( jPanelLayout .createSequentialGroup() .addGap(18, 18, 18) .addGroup( jPanelLayout .createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( jPanelLayout .createSequentialGroup() .addComponent( jButtonStart) .addGap(36, 36, 36) .addComponent( jButtonStop)) .addGroup( jPanelLayout .createSequentialGroup() .addComponent( jLabel1) .addGap(18, 18, 18) .addComponent( jComboBoxVoiceChannel, GroupLayout.PREFERRED_SIZE, 82, GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent( jLabelStatus, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)))) .addGroup( jPanelLayout .createSequentialGroup() .addGap(86, 86, 86) .addComponent( jLabel2) .addPreferredGap( LayoutStyle.ComponentPlacement.UNRELATED) .addComponent( jComboBoxDataType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addContainerGap( GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); jPanelLayout.setVerticalGroup(jPanelLayout.createParallelGroup( GroupLayout.Alignment.LEADING).addGroup( jPanelLayout .createSequentialGroup() .addContainerGap() .addGroup( jPanelLayout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jComboBoxVoiceChannel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(jLabelStatus)) .addGap(18, 18, 18) .addGroup( jPanelLayout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent(jButtonStart) .addComponent(jButtonStop)) .addGap(18, 18, 18) .addGroup( jPanelLayout .createParallelGroup( GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jComboBoxDataType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); jButtonRefresh.setText("刷新"); jButtonRefresh.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonRefreshActionPerformed(evt); } }); jButtonExit.setText("退出"); jButtonExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonExitActionPerformed(evt); } }); GroupLayout layout = new GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jButtonRefresh) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED, 97, Short.MAX_VALUE) .addComponent(jButtonExit).addGap(40, 40, 40)) .addGroup( layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap( LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING) .addComponent(jButtonRefresh) .addComponent(jButtonExit)) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents /************************************************* * 函数: "开始对讲" 按钮单击响应函数 函数描述: 开始对讲 *************************************************/ private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_jButtonStartActionPerformed {// GEN-HEADEREND:event_jButtonStartActionPerformed // 这里采用全局的句柄进行操作,因为子对话框销毁后语音对讲还可以进行,用全局的变量保存句柄 ClientDemo.g_lVoiceHandle = hCNetSDK.NET_DVR_StartVoiceCom_V30( m_lUserID, m_iSel + 1, jComboBoxDataType.getSelectedIndex() == 1, fVoiceDataCallBack, null); if (ClientDemo.g_lVoiceHandle.intValue() == -1) { JOptionPane.showMessageDialog(this, "语音对讲失败"); return; } EnableCtrl(); }// GEN-LAST:event_jButtonStartActionPerformed /************************************************* * 函数: "停止对讲" 按钮单击响应函数 函数描述: 停止对讲 *************************************************/ private void jButtonStopActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_jButtonStopActionPerformed {// GEN-HEADEREND:event_jButtonStopActionPerformed if (ClientDemo.g_lVoiceHandle.intValue() >= 0) { if (hCNetSDK.NET_DVR_StopVoiceCom(ClientDemo.g_lVoiceHandle)) { ClientDemo.g_lVoiceHandle.setValue(-1); } else { JOptionPane.showMessageDialog(this, "关闭对讲失败"); } } EnableCtrl(); }// GEN-LAST:event_jButtonStopActionPerformed /************************************************* * 函数: "对讲通道" 选项改变事件响应函数 函数描述: 显示通道状态 *************************************************/ private void jComboBoxVoiceChannelActionPerformed( java.awt.event.ActionEvent evt)// GEN-FIRST:event_jComboBoxVoiceChannelActionPerformed {// GEN-HEADEREND:event_jComboBoxVoiceChannelActionPerformed if (!m_bInitialed) { return; } m_iSel = jComboBoxVoiceChannel.getSelectedIndex(); if (0 == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setText("未使用"); jLabelStatus.setVisible(true); } else if (1 == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setText("已使用"); jLabelStatus.setVisible(true); } else if (0xff == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setVisible(false); } }// GEN-LAST:event_jComboBoxVoiceChannelActionPerformed /************************************************* * 函数: "刷新" 按钮单击响应函数 函数描述: 刷新状态 *************************************************/ private void jButtonRefreshActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_jButtonRefreshActionPerformed {// GEN-HEADEREND:event_jButtonRefreshActionPerformed if (!hCNetSDK.NET_DVR_GetDVRWorkState_V30(m_lUserID, m_strWorkState)) { JOptionPane.showMessageDialog(this, "获取工作状态失败"); jLabelStatus.setVisible(false); return; } m_iSel = jComboBoxVoiceChannel.getSelectedIndex(); if (0 == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setText("未使用"); jLabelStatus.setVisible(true); } else if (1 == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setText("已使用"); jLabelStatus.setVisible(true); } else if (0xff == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setVisible(false); } }// GEN-LAST:event_jButtonRefreshActionPerformed /************************************************* * 函数: "退出" 按钮单击响应函数 函数描述: 销毁对话框 *************************************************/ private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_jButtonExitActionPerformed {// GEN-HEADEREND:event_jButtonExitActionPerformed dispose(); }// GEN-LAST:event_jButtonExitActionPerformed /************************************************* * 函数: initialDialog 函数描述: 初始化对话框 *************************************************/ private void initialDialog() { EnableCtrl(); switch (m_strDeviceInfo.byAudioChanNum) { case 1: jComboBoxVoiceChannel.addItem("Audio1"); break; case 2: jComboBoxVoiceChannel.addItem("Audio1"); jComboBoxVoiceChannel.addItem("Audio2"); break; default: break; } m_strWorkState = new HCNetSDK.NET_DVR_WORKSTATE_V30(); if (!hCNetSDK.NET_DVR_GetDVRWorkState_V30(m_lUserID, m_strWorkState)) { JOptionPane.showMessageDialog(this, "获取工作状态失败"); jLabelStatus.setVisible(false); } else { if (0 == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setText("未使用"); jLabelStatus.setVisible(true); } else { if (1 == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setText("已使用"); jLabelStatus.setVisible(true); } else { if (0xff == m_strWorkState.byAudioChanStatus[m_iSel]) { jLabelStatus.setVisible(false); } } } } } /************************************************* * 函数: EnableCtrl 函数描述: 控件Enable属性 *************************************************/ private void EnableCtrl() { boolean bVoiceTalk = false; if (ClientDemo.g_lVoiceHandle.intValue() >= 0) { bVoiceTalk = true; jLabelStatus.setText("已使用"); } else { bVoiceTalk = false; jLabelStatus.setText("未使用"); } jButtonStart.setEnabled(!bVoiceTalk); jButtonStop.setEnabled(bVoiceTalk); jComboBoxVoiceChannel.setEnabled(!bVoiceTalk); } // Variables declaration - do not modify//GEN-BEGIN:variables private JButton jButtonExit; private JButton jButtonRefresh; private JButton jButtonStart; private JButton jButtonStop; private JComboBox<Object> jComboBoxDataType; private JComboBox<Object> jComboBoxVoiceChannel; private JLabel jLabel1; private JLabel jLabel2; private JLabel jLabelStatus; private JPanel jPanel; // End of variables declaration//GEN-END:variables /****************************************************************************** * 内部类: FVoiceDataCallBack 实现对讲音频数据回调 ******************************************************************************/ class FVoiceDataCallBack implements HCNetSDK.FVoiceDataCallBack_V30 { // 对对讲的音频数据进行回调操作,以下写入文件操作 public void invoke(NativeLong lVoiceComHandle, String pRecvDataBuffer, int dwBufSize, byte byAudioFlag, Pointer pUser) { // byAudioFlag为0表示本地文件,为1表示设备的音频文件 if (byAudioFlag == 0) { try { fLocal.write(pRecvDataBuffer); fLocal.flush(); } catch (IOException ex) { Logger.getLogger(JDialogVoiceTalk.class.getName()).log( Level.SEVERE, null, ex); } } else { if (byAudioFlag == 1) { try { fDevice.write(pRecvDataBuffer); fDevice.flush(); } catch (IOException ex) { Logger.getLogger(JDialogVoiceTalk.class.getName()).log( Level.SEVERE, null, ex); } } } } } }
32.00641
126
0.642166
8eae49b7bb306ef7c756d604b1d9f5bb2412140b
17,027
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.epam.dlab.backendapi.service.impl; import com.epam.dlab.auth.UserInfo; import com.epam.dlab.backendapi.conf.SelfServiceApplicationConfiguration; import com.epam.dlab.backendapi.dao.BillingDAO; import com.epam.dlab.backendapi.dao.ImageExploratoryDao; import com.epam.dlab.backendapi.domain.BillingReport; import com.epam.dlab.backendapi.domain.BillingReportLine; import com.epam.dlab.backendapi.domain.EndpointDTO; import com.epam.dlab.backendapi.domain.ProjectDTO; import com.epam.dlab.backendapi.domain.ProjectEndpointDTO; import com.epam.dlab.backendapi.resources.dto.BillingFilter; import com.epam.dlab.backendapi.roles.RoleType; import com.epam.dlab.backendapi.roles.UserRoles; import com.epam.dlab.backendapi.service.BillingService; import com.epam.dlab.backendapi.service.EndpointService; import com.epam.dlab.backendapi.service.ExploratoryService; import com.epam.dlab.backendapi.service.ProjectService; import com.epam.dlab.backendapi.util.BillingUtils; import com.epam.dlab.cloud.CloudProvider; import com.epam.dlab.constants.ServiceConsts; import com.epam.dlab.dto.UserInstanceStatus; import com.epam.dlab.dto.billing.BillingData; import com.epam.dlab.dto.billing.BillingResourceType; import com.epam.dlab.exceptions.DlabException; import com.epam.dlab.rest.client.RESTService; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.name.Named; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.http.client.utils.URIBuilder; import javax.ws.rs.core.GenericType; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @Slf4j public class BillingServiceImpl implements BillingService { private static final String BILLING_PATH = "/api/billing"; private static final String USAGE_DATE_FORMAT = "yyyy-MM"; private final ProjectService projectService; private final EndpointService endpointService; private final ExploratoryService exploratoryService; private final SelfServiceApplicationConfiguration configuration; private final RESTService provisioningService; private final ImageExploratoryDao imageExploratoryDao; private final BillingDAO billingDAO; private final String sbn; @Inject public BillingServiceImpl(ProjectService projectService, EndpointService endpointService, ExploratoryService exploratoryService, SelfServiceApplicationConfiguration configuration, @Named(ServiceConsts.BILLING_SERVICE_NAME) RESTService provisioningService, ImageExploratoryDao imageExploratoryDao, BillingDAO billingDAO) { this.projectService = projectService; this.endpointService = endpointService; this.exploratoryService = exploratoryService; this.configuration = configuration; this.provisioningService = provisioningService; this.imageExploratoryDao = imageExploratoryDao; this.billingDAO = billingDAO; sbn = configuration.getServiceBaseName(); } @Override public BillingReport getBillingReport(UserInfo user, BillingFilter filter) { setUserFilter(user, filter); List<BillingReportLine> billingReportLines = billingDAO.aggregateBillingData(filter) .stream() .peek(this::appendStatuses) .filter(bd -> CollectionUtils.isEmpty(filter.getStatuses()) || filter.getStatuses().contains(bd.getStatus())) .collect(Collectors.toList()); final LocalDate min = billingReportLines.stream().min(Comparator.comparing(BillingReportLine::getUsageDateFrom)).map(BillingReportLine::getUsageDateFrom).orElse(null); final LocalDate max = billingReportLines.stream().max(Comparator.comparing(BillingReportLine::getUsageDateTo)).map(BillingReportLine::getUsageDateTo).orElse(null); final double sum = billingReportLines.stream().mapToDouble(BillingReportLine::getCost).sum(); final String currency = billingReportLines.stream().map(BillingReportLine::getCurrency).distinct().count() == 1 ? billingReportLines.get(0).getCurrency() : null; return BillingReport.builder() .name("Billing report") .sbn(sbn) .reportLines(billingReportLines) .usageDateFrom(min) .usageDateTo(max) .totalCost(new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) .currency(currency) .isFull(isFullReport(user)) .build(); } @Override public String downloadReport(UserInfo user, BillingFilter filter) { boolean isFull = isFullReport(user); BillingReport report = getBillingReport(user, filter); StringBuilder builder = new StringBuilder(BillingUtils.getFirstLine(report.getSbn(), report.getUsageDateFrom(), report.getUsageDateTo())); builder.append(BillingUtils.getHeader(isFull)); try { report.getReportLines().forEach(r -> builder.append(BillingUtils.printLine(r, isFull))); builder.append(BillingUtils.getTotal(report.getTotalCost(), report.getCurrency())); return builder.toString(); } catch (Exception e) { log.error("Cannot write billing data ", e); throw new DlabException("Cannot write billing file ", e); } } public BillingReport getExploratoryBillingData(String project, String endpoint, String exploratoryName, List<String> compNames) { List<String> resourceNames = new ArrayList<>(compNames); resourceNames.add(exploratoryName); List<BillingReportLine> billingData = billingDAO.findBillingData(project, endpoint, resourceNames) .stream() .peek(bd -> bd.setCost(BigDecimal.valueOf(bd.getCost()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())) .collect(Collectors.toList()); final double sum = billingData.stream().mapToDouble(BillingReportLine::getCost).sum(); final String currency = billingData.stream().map(BillingReportLine::getCurrency).distinct().count() == 1 ? billingData.get(0).getCurrency() : null; return BillingReport.builder() .name(exploratoryName) .reportLines(billingData) .totalCost(new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) .currency(currency) .build(); } public void updateRemoteBillingData(UserInfo userInfo) { List<EndpointDTO> endpoints = endpointService.getEndpoints(); if (CollectionUtils.isEmpty(endpoints)) { log.error("Cannot update billing info. There are no endpoints"); throw new DlabException("Cannot update billing info. There are no endpoints"); } Map<EndpointDTO, List<BillingData>> billingDataMap = endpoints .stream() .collect(Collectors.toMap(e -> e, e -> getBillingData(userInfo, e))); billingDataMap.forEach((endpointDTO, billingData) -> { log.info("Updating billing information for endpoint {}. Billing data {}", endpointDTO.getName(), billingData); try { updateBillingData(endpointDTO, billingData); } catch (Exception e) { log.error("Something went wrong while trying to update billing for {}. {}", endpointDTO.getName(), e.getMessage()); } }); } private Map<String, BillingReportLine> getBillableResources() { Set<ProjectDTO> projects = new HashSet<>(projectService.getProjects()); final Stream<BillingReportLine> ssnBillingDataStream = BillingUtils.ssnBillingDataStream(sbn); final Stream<BillingReportLine> billableEdges = projects .stream() .collect(Collectors.toMap(ProjectDTO::getName, ProjectDTO::getEndpoints)) .entrySet() .stream() .flatMap(e -> projectEdges(sbn, e.getKey(), e.getValue())); final Stream<BillingReportLine> billableSharedEndpoints = endpointService.getEndpoints() .stream() .flatMap(endpoint -> BillingUtils.sharedEndpointBillingDataStream(endpoint.getName(), sbn)); final Stream<BillingReportLine> billableUserInstances = exploratoryService.findAll(projects) .stream() .filter(userInstance -> Objects.nonNull(userInstance.getExploratoryId())) .flatMap(ui -> BillingUtils.exploratoryBillingDataStream(ui, configuration.getMaxSparkInstanceCount())); final Stream<BillingReportLine> customImages = projects .stream() .map(p -> imageExploratoryDao.getImagesForProject(p.getName())) .flatMap(Collection::stream) .flatMap(i -> BillingUtils.customImageBillingDataStream(i, sbn)); final Map<String, BillingReportLine> billableResources = Stream.of(ssnBillingDataStream, billableEdges, billableSharedEndpoints, billableUserInstances, customImages) .flatMap(s -> s) .collect(Collectors.toMap(BillingReportLine::getDlabId, b -> b)); log.debug("Billable resources are: {}", billableResources); return billableResources; } private Stream<BillingReportLine> projectEdges(String serviceBaseName, String projectName, List<ProjectEndpointDTO> endpoints) { return endpoints .stream() .flatMap(endpoint -> BillingUtils.edgeBillingDataStream(projectName, serviceBaseName, endpoint.getName())); } private void updateBillingData(EndpointDTO endpointDTO, List<BillingData> billingData) { final String endpointName = endpointDTO.getName(); final CloudProvider cloudProvider = endpointDTO.getCloudProvider(); final Map<String, BillingReportLine> billableResources = getBillableResources(); final Stream<BillingReportLine> billingReportLineStream = billingData .stream() .peek(bd -> bd.setApplication(endpointName)) .map(bd -> toBillingReport(bd, getOrDefault(billableResources, bd.getTag()))); if (cloudProvider == CloudProvider.GCP) { final Map<String, List<BillingReportLine>> gcpBillingData = billingReportLineStream .collect(Collectors.groupingBy(bd -> bd.getUsageDate().substring(0, USAGE_DATE_FORMAT.length()))); updateGcpBillingData(endpointName, gcpBillingData); } else if (cloudProvider == CloudProvider.AWS) { final Map<String, List<BillingReportLine>> awsBillingData = billingReportLineStream .collect(Collectors.groupingBy(BillingReportLine::getUsageDate)); updateAwsBillingData(endpointName, awsBillingData); } else if (cloudProvider == CloudProvider.AZURE) { final List<BillingReportLine> billingReportLines = billingReportLineStream .collect(Collectors.toList()); updateAzureBillingData(billingReportLines); } } private BillingReportLine getOrDefault(Map<String, BillingReportLine> billableResources, String tag) { return billableResources.getOrDefault(tag, BillingReportLine.builder().dlabId(tag).build()); } private void updateGcpBillingData(String endpointName, Map<String, List<BillingReportLine>> billingData) { billingData.forEach((usageDate, billingReportLines) -> { billingDAO.deleteByUsageDateRegex(endpointName, usageDate); billingDAO.save(billingReportLines); }); } private void updateAwsBillingData(String endpointName, Map<String, List<BillingReportLine>> billingData) { billingData.forEach((usageDate, billingReportLines) -> { billingDAO.deleteByUsageDate(endpointName, usageDate); billingDAO.save(billingReportLines); }); } private void updateAzureBillingData(List<BillingReportLine> billingReportLines) { billingDAO.save(billingReportLines); } private List<BillingData> getBillingData(UserInfo userInfo, EndpointDTO e) { try { return provisioningService.get(getBillingUrl(e.getUrl(), BILLING_PATH), userInfo.getAccessToken(), new GenericType<List<BillingData>>() { }); } catch (Exception ex) { log.error("Cannot retrieve billing information for {}. {}", e.getName(), ex.getMessage()); return Collections.emptyList(); } } private String getBillingUrl(String endpointUrl, String path) { URI uri; try { uri = new URI(endpointUrl); } catch (URISyntaxException e) { log.error("Wrong URI syntax {}", e.getMessage(), e); throw new DlabException("Wrong URI syntax"); } return new URIBuilder() .setScheme(uri.getScheme()) .setHost(uri.getHost()) .setPort(8088) .setPath(path) .toString(); } private void appendStatuses(BillingReportLine br) { BillingResourceType resourceType = br.getResourceType(); if (BillingResourceType.EDGE == resourceType) { projectService.get(br.getProject()).getEndpoints() .stream() .filter(e -> e.getName().equals(br.getResourceName())) .findAny() .ifPresent(e -> br.setStatus(e.getStatus())); } else if (BillingResourceType.EXPLORATORY == resourceType) { exploratoryService.getUserInstance(br.getUser(), br.getProject(), br.getResourceName()) .ifPresent(ui -> br.setStatus(UserInstanceStatus.of(ui.getStatus()))); } else if (BillingResourceType.COMPUTATIONAL == resourceType) { exploratoryService.getUserInstance(br.getUser(), br.getProject(), br.getExploratoryName(), true) .flatMap(ui -> ui.getResources() .stream() .filter(cr -> cr.getComputationalName().equals(br.getResourceName())) .findAny()) .ifPresent(cr -> br.setStatus(UserInstanceStatus.of(cr.getStatus()))); } } private boolean isFullReport(UserInfo userInfo) { return UserRoles.checkAccess(userInfo, RoleType.PAGE, "/api/infrastructure_provision/billing", userInfo.getRoles()); } private void setUserFilter(UserInfo userInfo, BillingFilter filter) { if (!isFullReport(userInfo)) { filter.setUsers(Lists.newArrayList(userInfo.getName())); } } private BillingReportLine toBillingReport(BillingData billingData, BillingReportLine billingReportLine) { return BillingReportLine.builder() .application(billingData.getApplication()) .cost(billingData.getCost()) .currency(billingData.getCurrency()) .product(billingData.getProduct()) .project(billingReportLine.getProject()) .endpoint(billingReportLine.getEndpoint()) .usageDateFrom(billingData.getUsageDateFrom()) .usageDateTo(billingData.getUsageDateTo()) .usageDate(billingData.getUsageDate()) .usageType(billingData.getUsageType()) .user(billingReportLine.getUser()) .dlabId(billingData.getTag()) .resourceType(billingReportLine.getResourceType()) .resourceName(billingReportLine.getResourceName()) .shape(billingReportLine.getShape()) .exploratoryName(billingReportLine.getExploratoryName()) .build(); } }
50.227139
175
0.678687
0ec9267f0dfca4e9e3505db5406747325677fa0e
27,955
/* * Copyright <2021> Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ package software.amazon.documentdb.jdbc; import org.bson.BsonDocument; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.documentdb.jdbc.common.test.DocumentDbTestEnvironment; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DocumentDbStatementStringTest extends DocumentDbStatementTest { @DisplayName("Test that queries selecting a substring work with 2 and 3 arguments.") @ParameterizedTest(name = "testQuerySubstring - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQuerySubstring(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testSelectQuerySubstring"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"abcdefg\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"uvwxyz\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); final BsonDocument doc6 = BsonDocument.parse("{\"_id\": 106,\n" + "\"field\": \"ab\"}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5, doc6}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); // Test SUBSTRING(%1, %2, %3) format. final ResultSet resultSet1 = statement.executeQuery( String.format("SELECT SUBSTRING(\"field\", 1, 3) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet1); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("abc", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("uvw", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("ab", resultSet1.getString(1)); Assertions.assertFalse(resultSet1.next()); // Test SUBSTRING(%1, %2) format. final ResultSet resultSet2 = statement.executeQuery( String.format("SELECT SUBSTRING(\"field\", 1) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet2); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals("abcdefg", resultSet2.getString(1)); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals("uvwxyz", resultSet2.getString(1)); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals("", resultSet2.getString(1)); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals("", resultSet2.getString(1)); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals("", resultSet2.getString(1)); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals("ab", resultSet2.getString(1)); Assertions.assertFalse(resultSet2.next()); } } @DisplayName("Test queries calling CHAR_LENGTH().") @ParameterizedTest(name = "testQueryCharLength - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQueryCharLength(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "tesQueryCharLength"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"abcdefg\"}"); // 7 final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); // 2 final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); // 0 final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); // null final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); // null insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet = statement.executeQuery( String.format("SELECT CHAR_LENGTH(\"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(7, resultSet.getInt(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(2, resultSet.getInt(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals(0, resultSet.getInt(1)); Assertions.assertFalse(resultSet.wasNull()); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getObject(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getObject(1)); Assertions.assertTrue(resultSet.wasNull()); Assertions.assertFalse(resultSet.next()); } } @DisplayName("Test queries calling POSITION with 2 and 3 arguments.") @ParameterizedTest(name = "testQueryPosition - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQueryPosition(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testQueryPosition"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"BanaNa\"}"); // Contains "na" string in 2 places final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"Apple\"}"); // Does not contain "na" final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); // Empty string - does not contain "na" final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); // Null string final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); // Missing string insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); // Test POSITION(%1 IN %2 FROM %3) format with non-null search substring. final ResultSet resultSet1 = statement.executeQuery( String.format("SELECT POSITION('na' IN \"field\" FROM 4) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet1); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals(5, resultSet1.getInt(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals(0, resultSet1.getInt(1)); Assertions.assertFalse(resultSet1.wasNull()); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals(0, resultSet1.getInt(1)); Assertions.assertFalse(resultSet1.wasNull()); Assertions.assertTrue(resultSet1.next()); Assertions.assertNull(resultSet1.getObject(1)); Assertions.assertTrue(resultSet1.wasNull()); Assertions.assertTrue(resultSet1.next()); Assertions.assertNull(resultSet1.getObject(1)); Assertions.assertTrue(resultSet1.wasNull()); Assertions.assertFalse(resultSet1.next()); // Test POSITION(%1 IN %2) format with non-null search substring. final ResultSet resultSet2 = statement.executeQuery( String.format("SELECT POSITION('na' IN \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet2); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals(3, resultSet2.getInt(1)); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals(0, resultSet2.getInt(1)); Assertions.assertFalse(resultSet2.wasNull()); Assertions.assertTrue(resultSet2.next()); Assertions.assertEquals(0, resultSet2.getInt(1)); Assertions.assertFalse(resultSet2.wasNull()); Assertions.assertTrue(resultSet2.next()); Assertions.assertNull(resultSet2.getObject(1)); Assertions.assertTrue(resultSet2.wasNull()); Assertions.assertTrue(resultSet2.next()); Assertions.assertNull(resultSet2.getObject(1)); Assertions.assertTrue(resultSet2.wasNull()); Assertions.assertFalse(resultSet2.next()); // Test POSITION(%1 IN %2 FROM %3) format with negative start index. // Returns 0 unless strings are null in which case returns null. final ResultSet resultSet3 = statement.executeQuery( String.format("SELECT POSITION('na' IN \"field\" FROM -4) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet3); Assertions.assertTrue(resultSet3.next()); Assertions.assertEquals(0, resultSet3.getInt(1)); Assertions.assertFalse(resultSet3.wasNull()); Assertions.assertTrue(resultSet3.next()); Assertions.assertEquals(0, resultSet3.getInt(1)); Assertions.assertFalse(resultSet3.wasNull()); Assertions.assertTrue(resultSet3.next()); Assertions.assertEquals(0, resultSet3.getInt(1)); Assertions.assertFalse(resultSet3.wasNull()); Assertions.assertTrue(resultSet3.next()); Assertions.assertNull(resultSet3.getObject(1)); Assertions.assertTrue(resultSet3.wasNull()); Assertions.assertTrue(resultSet3.next()); Assertions.assertNull(resultSet3.getObject(1)); Assertions.assertTrue(resultSet3.wasNull()); Assertions.assertFalse(resultSet3.next()); // Test POSITION(%1 IN %2) format with null search substring. Always returns null. final ResultSet resultSet4 = statement.executeQuery( String.format("SELECT POSITION(NULL IN \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet4); while (resultSet4.next()) { Assertions.assertNull(resultSet4.getObject(1)); Assertions.assertTrue(resultSet4.wasNull()); } } } @DisplayName("Test queries using UPPER().") @ParameterizedTest(name = "testQueryUpper - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQueryUpper(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testQueryUpper"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello World!\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet = statement.executeQuery( String.format("SELECT UPPER(\"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("HELLO WORLD!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("寿司", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } } @DisplayName("Test queries using LOWER().") @ParameterizedTest(name = "testQueryLower - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQueryLower(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testQueryLower"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello World!\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet = statement.executeQuery( String.format("SELECT LOWER(\"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("hello world!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("寿司", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } } @DisplayName("Test queries using the || operator.") @ParameterizedTest(name = "testQueryConcatOperator - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testConcatOperator(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testConcatOperator"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet = statement.executeQuery( String.format("SELECT 'I want to say: ' || \"field\" || '!' FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: Hello!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: 寿司!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: !", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertNull(resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } } @DisplayName("Test queries using CONCAT().") @ParameterizedTest(name = "testQueryConcatFunction - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testConcatFunction(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testConcatFunction"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet = statement.executeQuery( String.format("SELECT CONCAT('I want to say: ', \"field\", '!') FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: Hello!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: 寿司!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: !", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: !", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I want to say: !", resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } } @DisplayName("Test query using combination of different string functions.") @ParameterizedTest(name = "testQueryCombinedStringFunctions - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testCombinedStringFunctions(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testCombinedStringFunctions"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet = statement.executeQuery( String.format("SELECT UPPER(CONCAT('I want to say: ', \"field\", '!')) " + "FROM \"%s\".\"%s\"" + "WHERE POSITION('o' IN \"field\") = CHAR_LENGTH(\"field\")", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet); // Returns 2 rows: the 1st row with 'Hello' (a proper match) // and the 3rd row with empty string since its length is 0 and none found is also 0. Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I WANT TO SAY: HELLO!", resultSet.getString(1)); Assertions.assertTrue(resultSet.next()); Assertions.assertEquals("I WANT TO SAY: !", resultSet.getString(1)); Assertions.assertFalse(resultSet.next()); } } @DisplayName("Test queries using LEFT().") @ParameterizedTest(name = "testQueryLeft - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQueryLeft(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testQueryLeft"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello World!\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet1 = statement.executeQuery( String.format("SELECT LEFT(\"field\", 5) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet1); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("Hello", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("寿司", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertNull(resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertNull(resultSet1.getString(1)); Assertions.assertFalse(resultSet1.next()); // A negative length always results in null. final ResultSet resultSet2 = statement.executeQuery( String.format("SELECT LEFT(\"field\", -2) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet2); while (resultSet2.next()) { Assertions.assertNull(resultSet2.getObject(1)); Assertions.assertTrue(resultSet2.wasNull()); } } } @DisplayName("Test queries using RIGHT().") @ParameterizedTest(name = "testQueryRight - [{index}] - {arguments}") @MethodSource({"getTestEnvironments"}) void testQueryRight(final DocumentDbTestEnvironment testEnvironment) throws SQLException { setTestEnvironment(testEnvironment); final String tableName = "testQueryRight"; final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101,\n" + "\"field\": \"Hello World!\"}"); final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102,\n" + "\"field\": \"寿司\"}"); final BsonDocument doc3 = BsonDocument.parse("{\"_id\": 103,\n" + "\"field\": \"\"}"); final BsonDocument doc4 = BsonDocument.parse("{\"_id\": 104, \n" + "\"field\": null}"); final BsonDocument doc5 = BsonDocument.parse("{\"_id\": 105}"); insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2, doc3, doc4, doc5}); try (Connection connection = getConnection()) { final Statement statement = getDocumentDbStatement(connection); final ResultSet resultSet1 = statement.executeQuery( String.format("SELECT RIGHT(\"field\", 5) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet1); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("orld!", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("寿司", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertEquals("", resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertNull(resultSet1.getString(1)); Assertions.assertTrue(resultSet1.next()); Assertions.assertNull(resultSet1.getString(1)); Assertions.assertFalse(resultSet1.next()); // A negative length always results in null. final ResultSet resultSet2 = statement.executeQuery( String.format("SELECT RIGHT(\"field\", -2) FROM \"%s\".\"%s\"", getDatabaseName(), tableName)); Assertions.assertNotNull(resultSet2); while (resultSet2.next()) { Assertions.assertNull(resultSet2.getObject(1)); Assertions.assertTrue(resultSet2.wasNull()); } } } }
54.281553
107
0.608693
52fdcb75119e75b6fdd17f379ba95b4e8db94980
1,469
package com.firebase.uidemo; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.firebase.uidemo.auth.AuthUiActivity; /** * Created by mgumiero9 on 04/12/16. * This is the splash screen activity. It also controls if the user has already used the app before. * If never launched, at first launch, it launched the tutorial first, or else launches without the * tutorial. */ public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** * This block restores SharedPreferences to read how many times the app was launched. */ String myCounter = ""; SharedPreferences myPreferences = getPreferences(0); int launchCounter = myPreferences.getInt(myCounter,0); Intent intent; if (launchCounter != 0) { intent = new Intent(this, AuthUiActivity.class); } else { intent = new Intent(this, TutorialActivity.class); } /** * This block increments launchCounter counter and save it persistently. */ launchCounter++; SharedPreferences.Editor editor = myPreferences.edit(); editor.putInt(myCounter, launchCounter) .apply(); startActivity(intent); finish(); } }
30.604167
100
0.667801
ae5bd49227bd743b988ce56ce86b992fa920a9a0
617
package org.rhett.mysecurity.service.impl; import org.rhett.mysecurity.entity.SysUser; import org.rhett.mysecurity.mapper.SysUserMapper; import org.rhett.mysecurity.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Author Rhett * @Date 2021/6/4 * @Description */ @Service public class SysUserServiceImpl implements SysUserService { @Autowired private SysUserMapper sysUserMapper; @Override public SysUser findByUsername(String username) { return sysUserMapper.findByUsername(username); } }
24.68
62
0.779579
4bfa455143f71723c954b13723194ac402b32277
3,442
/* * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.sherpa.v2; import java.util.List; import java.util.Map; /** * Plain java representation of a SHERPA Publisher Policy object, based on SHERPA API v2 responses. * * In a SHERPA search for deposit policies, each journal contains one or more publisher policies * Each publisher policies contains a list of different article versions (eg. submitted, accepted, published) * which hold the data about what can be done with each version. * This class also holds copyright URLs and other policy URLs, as well as some helper information for display * of overall policies in UI (as per legacy SHERPA data) * * @see SHERPAJournal * @see SHERPAPermittedVersion */ public class SHERPAPublisherPolicy { private int id; private boolean openAccessPermitted; private String uri; private String internalMoniker; private List<SHERPAPermittedVersion> permittedVersions; private Map<String, String> urls; private boolean openAccessProhibited; private int publicationCount; // The legacy "can" / "cannot" indicators private String preArchiving = "cannot"; private String postArchiving = "cannot"; private String pubArchiving = "cannot"; public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isOpenAccessPermitted() { return openAccessPermitted; } public void setOpenAccessPermitted(boolean openAccessPermitted) { this.openAccessPermitted = openAccessPermitted; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getInternalMoniker() { return internalMoniker; } public void setInternalMoniker(String internalMoniker) { this.internalMoniker = internalMoniker; } public List<SHERPAPermittedVersion> getPermittedVersions() { return permittedVersions; } public void setPermittedVersions(List<SHERPAPermittedVersion> permittedVersions) { this.permittedVersions = permittedVersions; } public Map<String, String> getUrls() { return urls; } public void setUrls(Map<String, String> urls) { this.urls = urls; } public boolean isOpenAccessProhibited() { return openAccessProhibited; } public void setOpenAccessProhibited(boolean openAccessProhibited) { this.openAccessProhibited = openAccessProhibited; } public int getPublicationCount() { return publicationCount; } public void setPublicationCount(int publicationCount) { this.publicationCount = publicationCount; } public String getPreArchiving() { return preArchiving; } public void setPreArchiving(String preArchiving) { this.preArchiving = preArchiving; } public String getPostArchiving() { return postArchiving; } public void setPostArchiving(String postArchiving) { this.postArchiving = postArchiving; } public String getPubArchiving() { return pubArchiving; } public void setPubArchiving(String pubArchiving) { this.pubArchiving = pubArchiving; } }
26.682171
109
0.695235
8321e3f0b39c7acdb6b8196c6a1e9a6319c88277
2,956
/** * 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.ambari.server.security; import java.util.Collection; import java.util.Collections; import org.apache.ambari.server.security.authorization.User; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; /** * Security related utilities. */ // TODO : combine with AuthorizationHelper. public class SecurityHelperImpl implements SecurityHelper { /** * The singleton instance. */ private static final SecurityHelper singleton = new SecurityHelperImpl(); // ----- Constructors -------------------------------------------------- /** * Hidden constructor. */ private SecurityHelperImpl() { } // ----- SecurityHelperImpl -------------------------------------------- public static SecurityHelper getInstance() { return singleton; } // ----- SecurityHelper ------------------------------------------------ @Override public String getCurrentUserName() { SecurityContext ctx = SecurityContextHolder.getContext(); Authentication authentication = ctx == null ? null : ctx.getAuthentication(); Object principal = authentication == null ? null : authentication.getPrincipal(); String username; if (principal instanceof UserDetails) { username = ((UserDetails) principal).getUsername(); } else if (principal instanceof User) { username = ((User) principal).getUserName(); } else { username = principal == null ? "" : principal.toString(); } return username; } @Override public Collection<? extends GrantedAuthority> getCurrentAuthorities() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); if (context.getAuthentication() != null && context.getAuthentication().isAuthenticated()) { return authentication.getAuthorities(); } return Collections.emptyList(); } }
32.483516
95
0.700271
36be92314dfc9fde8b5a5a45ed58648d7da0db75
11,844
/* * 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.kylin.job.impl.curator; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetAddress; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.apache.commons.io.IOUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.details.InstanceSerializer; import org.apache.curator.x.discovery.details.ServiceCacheListener; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.ServerMode; import org.apache.kylin.common.util.StringUtil; import org.apache.kylin.job.Scheduler; import org.apache.kylin.job.engine.JobEngineConfig; import org.apache.kylin.job.exception.SchedulerException; import org.apache.kylin.job.execution.AbstractExecutable; import org.apache.kylin.job.lock.JobLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Function; import com.google.common.collect.Lists; public class CuratorScheduler implements Scheduler<AbstractExecutable> { private static final Logger logger = LoggerFactory.getLogger(CuratorScheduler.class); private boolean started = false; private CuratorFramework curatorClient = null; private static CuratorLeaderSelector jobClient = null; private ServiceDiscovery<LinkedHashMap> serviceDiscovery = null; private ServiceCache<LinkedHashMap> serviceCache = null; private KylinConfig kylinConfig; private AtomicInteger count = new AtomicInteger(); static final String JOB_ENGINE_LEADER_PATH = "/kylin/%s/job_engine/leader"; static final String KYLIN_SERVICE_PATH = "/kylin/%s/service"; static final String SERVICE_NAME = "kylin"; static final String SERVICE_PAYLOAD_DESCRIPTION = "description"; public CuratorScheduler() { } @Override public void init(JobEngineConfig jobEngineConfig, JobLock jobLock) throws SchedulerException { kylinConfig = jobEngineConfig.getConfig(); String zkAddress = kylinConfig.getZookeeperConnectString(); synchronized (this) { if (started) { logger.info("CuratorScheduler already started, skipped."); return; } int baseSleepTimeMs = kylinConfig.getZKBaseSleepTimeMs(); int maxRetries = kylinConfig.getZKMaxRetries(); curatorClient = CuratorFrameworkFactory.newClient(zkAddress, new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries)); logger.info("New ZK Client start: ", zkAddress); curatorClient.start(); final String restAddress = kylinConfig.getServerRestAddress(); try { registerInstance(restAddress); } catch (Exception e) { throw new SchedulerException(e); } String jobEnginePath = getJobEnginePath(slickMetadataPrefix(kylinConfig.getMetadataUrlPrefix())); if (ServerMode.isJob(jobEngineConfig.getConfig())) { jobClient = new CuratorLeaderSelector(curatorClient, jobEnginePath, restAddress, jobEngineConfig); try { logger.info("start Job Engine, lock path is: " + jobEnginePath); jobClient.start(); monitorJobEngine(); } catch (IOException e) { throw new SchedulerException(e); } } else { logger.info("server mode: " + jobEngineConfig.getConfig().getServerMode() + ", no need to run job scheduler"); } started = true; } } private void registerInstance(String restAddress) throws Exception { final String host = restAddress.substring(0, restAddress.indexOf(":")); final String port = restAddress.substring(restAddress.indexOf(":") + 1); final JsonInstanceSerializer<LinkedHashMap> serializer = new JsonInstanceSerializer<>(LinkedHashMap.class); final String servicePath = getServicePath(slickMetadataPrefix(kylinConfig.getMetadataUrlPrefix())); serviceDiscovery = ServiceDiscoveryBuilder.builder(LinkedHashMap.class).client(curatorClient) .basePath(servicePath).serializer(serializer).build(); serviceDiscovery.start(); serviceCache = serviceDiscovery.serviceCacheBuilder().name(SERVICE_NAME) .threadFactory(Executors.defaultThreadFactory()).build(); serviceCache.addListener(new ServiceCacheListener() { @Override public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { } @Override public void cacheChanged() { logger.info("Service discovery get cacheChanged notification"); final List<ServiceInstance<LinkedHashMap>> instances = serviceCache.getInstances(); final List<String> instanceNodes = Lists.transform(instances, new Function<ServiceInstance<LinkedHashMap>, String>() { @Nullable @Override public String apply(@Nullable ServiceInstance<LinkedHashMap> stringServiceInstance) { return (String) stringServiceInstance.getPayload().get(SERVICE_PAYLOAD_DESCRIPTION); } }); final String restServersInCluster = StringUtil.join(instanceNodes, ","); logger.info("kylin.server.cluster-servers update to " + restServersInCluster); // update cluster servers System.setProperty("kylin.server.cluster-servers", restServersInCluster); } }); serviceCache.start(); final LinkedHashMap<String, String> instanceDetail = new LinkedHashMap<>(); instanceDetail.put(SERVICE_PAYLOAD_DESCRIPTION, restAddress); ServiceInstance<LinkedHashMap> thisInstance = ServiceInstance.<LinkedHashMap> builder().name(SERVICE_NAME) .payload(instanceDetail).port(Integer.valueOf(port)).address(host).build(); for (ServiceInstance<LinkedHashMap> instance : serviceCache.getInstances()) { // Check for registered instances to avoid being double registered if (instance.getAddress().equals(thisInstance.getAddress()) && instance.getPort().equals(thisInstance.getPort())) { serviceDiscovery.unregisterService(instance); } } serviceDiscovery.registerService(thisInstance); } static String getJobEnginePath(String metadataUrlPrefix) { return String.format(Locale.ROOT, JOB_ENGINE_LEADER_PATH, metadataUrlPrefix); } static String getServicePath(String metadataUrlPrefix) { return String.format(Locale.ROOT, KYLIN_SERVICE_PATH, metadataUrlPrefix); } private void monitorJobEngine() { logger.info("Start collect monitor ZK Participants"); Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() { @Override public void run() { try { boolean hasLeadership = jobClient.hasLeadership(); boolean hasDefaultSchedulerStarted = jobClient.hasDefaultSchedulerStarted(); if (!(hasLeadership == hasDefaultSchedulerStarted)) { logger.error("Node(" + InetAddress.getLocalHost().getHostAddress() + ") job server state conflict. Is ZK leader: " + hasLeadership + "; Is active job server: " + hasDefaultSchedulerStarted); } if (count.incrementAndGet() == 10) { logger.info("Current Participants: " + jobClient.getParticipants()); count.set(0); } } catch (Throwable th) { logger.error("Error when getting JVM info.", th); } } }, 3, kylinConfig.getInstanceFromEnv().getZKMonitorInterval(), TimeUnit.SECONDS); } @Override public void shutdown() throws SchedulerException { IOUtils.closeQuietly(serviceCache); IOUtils.closeQuietly(serviceDiscovery); IOUtils.closeQuietly(curatorClient); IOUtils.closeQuietly(jobClient); started = false; } public static String slickMetadataPrefix(String metadataPrefix) { if (metadataPrefix.indexOf("/") >= 0) { // for local test if (metadataPrefix.endsWith("/")) { metadataPrefix = metadataPrefix.substring(0, metadataPrefix.length() - 2); } return metadataPrefix.substring(metadataPrefix.lastIndexOf("/") + 1); } return metadataPrefix; } @Override public boolean hasStarted() { return started; } public static CuratorLeaderSelector getLeaderSelector() { return jobClient; } static class JsonInstanceSerializer<T> implements InstanceSerializer<T> { private final ObjectMapper mapper; private final Class<T> payloadClass; private final JavaType type; JsonInstanceSerializer(Class<T> payloadClass) { this.payloadClass = payloadClass; this.mapper = new ObjectMapper(); // to bypass https://issues.apache.org/jira/browse/CURATOR-394 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); this.type = this.mapper.getTypeFactory().constructType(ServiceInstance.class); } public ServiceInstance<T> deserialize(byte[] bytes) throws Exception { ServiceInstance rawServiceInstance = this.mapper.readValue(bytes, this.type); this.payloadClass.cast(rawServiceInstance.getPayload()); return rawServiceInstance; } public byte[] serialize(ServiceInstance<T> instance) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.convertValue(instance.getPayload(), payloadClass); this.mapper.writeValue(out, instance); return out.toByteArray(); } } }
43.069091
126
0.669453
f98ac8af12b913571d1e8e8d3e54b3a08ca2239f
392
/* * 开机启动接受boot complete消息 启动Device服务 */ package com.rongyan.hpmessage; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { Intent intent = new Intent(arg0, MessageService.class); arg0.startService(intent); } }
20.631579
57
0.783163
16aa797558a97967317677f0e71468bb0d48c362
2,427
package net.wukl.cacofony.http2; import net.wukl.cacofony.http2.frame.FrameReader; import net.wukl.cacofony.http2.frame.FrameWriter; import net.wukl.cacofony.server.Connection; import net.wukl.cacofony.server.ServerSettings; import net.wukl.cacofony.server.protocol.ProtocolFactory; import java.util.concurrent.ExecutorService; /** * A factory creating HTTP/2 protocol instances. */ public class Http2ProtocolFactory implements ProtocolFactory<Http2Protocol> { /** * The frame reader used by protocol instances. */ private final FrameReader frameReader; /** * The frame writer used by protocol instances. */ private final FrameWriter frameWriter; /** * The request handler. */ private final Http2RequestHandler requestHandler; /** * The thread pool. */ private final ExecutorService executor; /** * The server settings used by protocol instances. */ private final ServerSettings serverSettings; /** * Creates a new HTTP/2 protocol factory. * @param frameReader the frame reader used by protocol instances * @param frameWriter the frame writer used by protocol instances * @param requestHandler the request handler to use * @param executor the thread pool to use * @param serverSettings the server settings used by protocol instances */ public Http2ProtocolFactory( final FrameReader frameReader, final FrameWriter frameWriter, final Http2RequestHandler requestHandler, final ExecutorService executor, final ServerSettings serverSettings ) { this.frameReader = frameReader; this.frameWriter = frameWriter; this.requestHandler = requestHandler; this.executor = executor; this.serverSettings = serverSettings; } /** * Builds an instance of the protocol. * <p> * The protocol should be ready to handle incoming connections. * * @param conn the connection to build the protocol for * * @return the protocol instance */ @Override public Http2Protocol build(final Connection conn) { return new Http2Protocol( this.frameReader, this.frameWriter, this.requestHandler, this.executor, this.serverSettings, conn ); } }
29.240964
77
0.660898
cbebfb0950bbea12b458ae16e4944d5978d716a5
2,433
package com.game.misc.utils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; import static com.game.misc.Vars.PPM; /** * Created by Ash on 09/02/2016. */ public class Box2dUtils { private static float density = 1f; private static float friction = 0.9f; public static Body makeBody(World world, BodyDef.BodyType bodyType, Vector2 pos) { BodyDef bd = new BodyDef(); bd.type = bodyType; bd.position.set(pos.x / PPM, pos.y / PPM ); return world.createBody(bd); } public static void makePolygon(Body body, Vector2 size, String userData, boolean isSensor, short categoryBits, short maskBits) { FixtureDef fd = new FixtureDef(); PolygonShape shape = new PolygonShape(); shape.setAsBox((size.x / 2) / PPM, (size.y / 2) / PPM ); fd.shape = shape; fd.density = density; fd.friction = friction; fd.filter.categoryBits = categoryBits; fd.filter.maskBits = maskBits; fd.isSensor = isSensor; if(userData.equals("")) { body.createFixture(fd); } else { body.createFixture(fd).setUserData(userData); } } public static void makeCircle(Body body, float diameter, String userData, boolean isSensor, short categoryBits, short maskBits) { FixtureDef fd = new FixtureDef(); CircleShape shape = new CircleShape(); shape.setRadius((diameter / 2) / PPM); fd.shape = shape; fd.density = density; fd.friction = friction; fd.filter.categoryBits = categoryBits; fd.filter.maskBits = maskBits; fd.isSensor = isSensor; if(userData.equals("")) { body.createFixture(fd); } else { body.createFixture(fd).setUserData(userData); } } public static void makeChain(Body body, Vector2[] v, String userData, boolean isSensor, short categoryBits, short maskBits) { FixtureDef fd = new FixtureDef(); ChainShape shape = new ChainShape(); shape.createChain(v); fd.shape = shape; fd.density = density; fd.friction = friction; fd.filter.categoryBits = categoryBits; fd.filter.maskBits = maskBits; fd.isSensor = isSensor; if(userData.equals("")) { body.createFixture(fd); } else { body.createFixture(fd).setUserData(userData); } } }
30.037037
131
0.618989
9277b30982248033fc3b863551d47d595fb355ba
3,805
/* * Copyright (c) 2015, Florent Hedin, Markus Meuwly, and the University of Basel * All rights reserved. * * The 3-clause BSD license is applied to this software. * see LICENSE.txt * */ package ch.unibas.fittingwizard.infrastructure.base; import ch.unibas.fittingwizard.application.scripts.base.ScriptExecutionException; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; public class VmdRunner { private final static Logger logger = Logger.getLogger(VmdRunner.class); private final static String ExecutableName = "vmd"; private ProcessBuilder pb = new ProcessBuilder(); public void setWorkingDir(File path) { logger.debug("Setting workdir: " + path); if (!path.exists()) { throw new RuntimeException("Working directory does not exist"); } pb.directory(path); } public File getWorkingDir() { return pb.directory(); } public void putEnvironment(Map<String, String> environment) { logger.debug("Setting environment: " + environment); Map<String, String> env = pb.environment(); env.putAll(environment); } public Map<String, String> getEnvironment() { return pb.environment(); } public static boolean isAvailable() { File vmdScript = null; try { // create temporary file to exit vmd vmdScript = File.createTempFile("vmd", ".vmd"); FileUtils.write(vmdScript, "exit"); VmdRunner runner = new VmdRunner(); int retval = runner.exec(Arrays.asList("-dispdev", "none", "-e", vmdScript.getAbsolutePath())); if (retval == 0) { logger.info("Vmd found in path."); return true; } else { logger.warn("Vmd not found in path."); return false; } } catch (Exception e) { logger.warn("Vmd not found in path.", e); return false; } finally { if (vmdScript!=null) { vmdScript.delete(); } } } public int exec(String command) { return exec(Arrays.asList(command), null); } public int exec(List<String> args) { return exec(args, null); } public int exec(List<String> args, File outputFile) { setCommand(args, outputFile); return run(); } private int run() { logger.info("Running vmd:\n" + pb.command() + "\nin directory:\n" + pb.directory() + "\nwith environment:\n" + pb.environment()); int exitCode = 0; try { Process p = pb.start(); exitCode = p.waitFor(); } catch (Exception e) { throw new RuntimeException(String.format("Vmd [%s] failed.", e)); } logger.info("Vmd return value: " + exitCode); if (exitCode != 0) { throw new ScriptExecutionException( String.format("Vmd did not exit correctly. Exit code: %s", String.valueOf(exitCode))); } return exitCode; } private void setCommand(List<String> args, File outputFile) { ArrayList<String> list = new ArrayList<>(); list.add(ExecutableName); if (! args.isEmpty()) { list.addAll(args); } pb.command(list); if (logger.isDebugEnabled()) { logger.debug("ProcessBuilder.command = " + StringUtils.join(pb.command(), " ")); } if (outputFile != null) { logger.debug("redirectOutput set to " + FilenameUtils.normalize(outputFile.getAbsolutePath())); pb.redirectOutput(outputFile); } else { logger.debug("redirectOutput set to inheritIO"); pb.inheritIO(); } } }
27.773723
107
0.617608
a51e4b837462c2e1fa41fbf0e169e440a739702d
5,635
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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.server.lookup.namespace.cache; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.util.concurrent.Striped; import com.google.inject.Inject; import com.metamx.emitter.service.ServiceEmitter; import com.metamx.emitter.service.ServiceMetricEvent; import io.druid.java.util.common.lifecycle.Lifecycle; import io.druid.java.util.common.logger.Logger; import io.druid.query.lookup.namespace.ExtractionNamespace; import io.druid.query.lookup.namespace.ExtractionNamespaceCacheFactory; import org.mapdb.DB; import org.mapdb.DBMaker; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; /** * */ public class OffHeapNamespaceExtractionCacheManager extends NamespaceExtractionCacheManager { private static final Logger log = new Logger(OffHeapNamespaceExtractionCacheManager.class); private final DB mmapDB; private ConcurrentMap<String, String> currentNamespaceCache = new ConcurrentHashMap<>(); private Striped<Lock> nsLocks = Striped.lazyWeakLock(1024); // Needed to make sure delete() doesn't do weird things private final File tmpFile; @Inject public OffHeapNamespaceExtractionCacheManager( Lifecycle lifecycle, ServiceEmitter emitter, final Map<Class<? extends ExtractionNamespace>, ExtractionNamespaceCacheFactory<?>> namespaceFunctionFactoryMap ) { super(lifecycle, emitter, namespaceFunctionFactoryMap); try { tmpFile = File.createTempFile("druidMapDB", getClass().getCanonicalName()); log.info("Using file [%s] for mapDB off heap namespace cache", tmpFile.getAbsolutePath()); } catch (IOException e) { throw Throwables.propagate(e); } mmapDB = DBMaker .newFileDB(tmpFile) .closeOnJvmShutdown() .transactionDisable() .deleteFilesAfterClose() .strictDBGet() .asyncWriteEnable() .mmapFileEnable() .commitFileSyncDisable() .cacheSize(10_000_000) .make(); try { lifecycle.addMaybeStartHandler( new Lifecycle.Handler() { @Override public void start() throws Exception { // NOOP } @Override public synchronized void stop() { if (!mmapDB.isClosed()) { mmapDB.close(); if (!tmpFile.delete()) { log.warn("Unable to delete file at [%s]", tmpFile.getAbsolutePath()); } } } } ); } catch (Exception e) { throw Throwables.propagate(e); } } @Override protected boolean swapAndClearCache(String namespaceKey, String cacheKey) { final Lock lock = nsLocks.get(namespaceKey); lock.lock(); try { Preconditions.checkArgument(mmapDB.exists(cacheKey), "Namespace [%s] does not exist", cacheKey); final String swapCacheKey = UUID.randomUUID().toString(); mmapDB.rename(cacheKey, swapCacheKey); final String priorCache = currentNamespaceCache.put(namespaceKey, swapCacheKey); if (priorCache != null) { // TODO: resolve what happens here if query is actively going on mmapDB.delete(priorCache); return true; } else { return false; } } finally { lock.unlock(); } } @Override public boolean delete(final String namespaceKey) { // `super.delete` has a synchronization in it, don't call it in the lock. if (!super.delete(namespaceKey)) { return false; } final Lock lock = nsLocks.get(namespaceKey); lock.lock(); try { final String mmapDBkey = currentNamespaceCache.remove(namespaceKey); if (mmapDBkey == null) { return false; } final long pre = tmpFile.length(); mmapDB.delete(mmapDBkey); log.debug("MapDB file size: pre %d post %d", pre, tmpFile.length()); return true; } finally { lock.unlock(); } } @Override public ConcurrentMap<String, String> getCacheMap(String namespaceKey) { final Lock lock = nsLocks.get(namespaceKey); lock.lock(); try { String mapDBKey = currentNamespaceCache.get(namespaceKey); if (mapDBKey == null) { // Not something created by swapAndClearCache mapDBKey = namespaceKey; } return mmapDB.createHashMap(mapDBKey).makeOrGet(); } finally { lock.unlock(); } } @Override protected void monitor(ServiceEmitter serviceEmitter) { serviceEmitter.emit(ServiceMetricEvent.builder().build("namespace/cache/diskSize", tmpFile.length())); } }
30.961538
117
0.675599
428f7f089c88b865812012d72716d6ab0188e98e
1,458
package com.xxkj.bean; import org.springframework.context.annotation.Bean; /** * Created by Administrator on 2017/5/7. */ public class UserInfo { private int uid; private String username; private String password; private int status; private String code; private String email; public UserInfo() { } public UserInfo(int uid, String username, String password, int status, String code, String email) { this.uid = uid; this.username = username; this.password = password; this.status = status; this.code = code; this.email = email; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } 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 int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
19.184211
103
0.588477
965c74a8de678526d690efbaba8811ed4abf1c2d
973
package multithread.synchronize.test23; /** * @author: linghan.ma * @DATE: 2018/1/29 * @description: */ /** * 验证:volatile非原子性 * 100个线程,由于addCount未加synchronized */ public class MyThread extends Thread { //public static int count; volatile public static int count; //synchronized static private void addCount(){ private static void addCount(){ for (int i = 0; i < 100; i++) { count++; } System.out.println("count="+count); } @Override public void run() { addCount(); } public static void main(String[] args) { MyThread [] array= new MyThread[10000]; for (int i = 0; i < 10000; i++) { array[i]=new MyThread(); } for (int i = 0; i < 10000; i++) { array[i].start(); } } } /** * count=200 count=200 count=300 count=400 count=500 count=600 count=700 count=800 */
19.078431
52
0.526208
ca608c59addf8671090fe1f0c1cc3a7c8dbc07ad
466
package com.stats.aggregator.DTOs.enums; import com.stats.aggregator.common.utils.EnumHelper; public enum FilterDataType { UNKNOWN(0), STRING(1), INT(2), LONG(3), FLOAT(4), DATETIME(5); private final int id; FilterDataType(int id) { this.id = id; } public int getValue() { return id; } public static FilterDataType fromString(String name) { return EnumHelper.getEnumFromString(FilterDataType.class, name); } }
22.190476
72
0.671674
9cff3ed196ed01d0cbfba0ba9456201b064b24de
3,884
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.geometry.Pose2d; import edu.wpi.first.wpilibj.geometry.Rotation2d; import edu.wpi.first.wpilibj.geometry.Translation2d; import edu.wpi.first.wpilibj.kinematics.ChassisSpeeds; import edu.wpi.first.wpilibj.kinematics.SwerveDriveKinematics; import edu.wpi.first.wpilibj.kinematics.SwerveDriveOdometry; /** Represents a swerve drive style drivetrain. */ public class Drivetrain { public static final double kMaxSpeed = 3.0; // 3 meters per second public static final double kMaxAngularSpeed = Math.PI; // 1/2 rotation per second private final Translation2d m_frontLeftLocation = new Translation2d(0.381, 0.381); private final Translation2d m_frontRightLocation = new Translation2d(0.381, -0.381); private final Translation2d m_backLeftLocation = new Translation2d(-0.381, 0.381); private final Translation2d m_backRightLocation = new Translation2d(-0.381, -0.381); private final SwerveModule m_frontLeft = new SwerveModule(1, 2, 0, 1, 2, 3); private final SwerveModule m_frontRight = new SwerveModule(3, 4, 4, 5, 6, 7); private final SwerveModule m_backLeft = new SwerveModule(5, 6, 8, 9, 10, 11); private final SwerveModule m_backRight = new SwerveModule(7, 8, 12, 13, 14, 15); private final AnalogGyro m_gyro = new AnalogGyro(0); private final SwerveDriveKinematics m_kinematics = new SwerveDriveKinematics( m_frontLeftLocation, m_frontRightLocation, m_backLeftLocation, m_backRightLocation); private final SwerveDriveOdometry m_odometry = new SwerveDriveOdometry(m_kinematics, m_gyro.getRotation2d()); public Drivetrain() { m_gyro.reset(); } /** * Method to drive the robot using joystick info. * * @param xSpeed Speed of the robot in the x direction (forward). * @param ySpeed Speed of the robot in the y direction (sideways). * @param rot Angular rate of the robot. * @param fieldRelative Whether the provided x and y speeds are relative to the field. */ @SuppressWarnings("ParameterName") public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) { var swerveModuleStates = m_kinematics.toSwerveModuleStates( fieldRelative ? ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, m_gyro.getRotation2d()) : new ChassisSpeeds(xSpeed, ySpeed, rot)); SwerveDriveKinematics.normalizeWheelSpeeds(swerveModuleStates, kMaxSpeed); m_frontLeft.setDesiredState(swerveModuleStates[0]); m_frontRight.setDesiredState(swerveModuleStates[1]); m_backLeft.setDesiredState(swerveModuleStates[2]); m_backRight.setDesiredState(swerveModuleStates[3]); } /** Updates the field relative position of the robot. */ public void updateOdometry() { m_odometry.update( m_gyro.getRotation2d(), m_frontLeft.getState(), m_frontRight.getState(), m_backLeft.getState(), m_backRight.getState()); } public void resetOdometry(Pose2d pose, Rotation2d rotation) { m_odometry.resetPosition(pose, rotation); m_frontLeft.setPose(pose); m_frontRight.setPose(pose); m_backLeft.setPose(pose); m_backRight.setPose(pose); /*for(int i = 0; i < mSwerveModules.length; i++) { mSwerveModules[i].setPose(pose); mSwerveModules[i].resetEncoders(); }*/ } public Pose2d getPose() { return m_odometry.getPoseMeters(); } public Pose2d[] getModulePoses() { Pose2d[] modulePoses = { m_frontLeft.getPose(), m_frontRight.getPose(), m_backRight.getPose(), m_backLeft.getPose() }; return modulePoses; } }
38.455446
100
0.726313
886d834d113e4208090484754b334a27f5095f89
2,137
package tacos.data; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Repository public class JdbcOrderRepository implements OrderRepository { private SimpleJdbcInsert orderInserter; private SimpleJdbcInsert orderTacoInserter; private ObjectMapper objectMapper; @Autowired public JdbcOrderRepository(JdbcTemplate jdbc) { this.orderInserter = new SimpleJdbcInsert(jdbc).withTableName("Taco_Order").usingGeneratedKeyColumns("id"); this.orderTacoInserter = new SimpleJdbcInsert(jdbc).withTableName("Taco_Order_Tacos"); this.objectMapper = new ObjectMapper(); } @Override public Order save(Order order) { order.setPlacedAt(new Date()); long orderId = saveOrderDetails(order); order.setId(orderId); List<Taco> tacos = order.getTacos(); for (Taco taco : tacos) { saveTacoToOrder(taco, orderId); } return order; } private long saveOrderDetails(Order order) { @SuppressWarnings("unchecked") Map<String, Object> values = objectMapper.convertValue(order, Map.class); values.put("placedAt", order.getPlacedAt()); values.remove("tacos"); for (Map.Entry<String, Object> entry : values.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } long orderId = orderInserter .executeAndReturnKey(values) .longValue(); return orderId; } private void saveTacoToOrder(Taco taco, long orderId) { Map<String, Object> values = new HashMap<>(); values.put("tacoOrder", orderId); values.put("taco", taco.getId()); System.out.println("order id: " + orderId + " taco id: " + taco.getId()); orderTacoInserter.execute(values); } }
35.032787
115
0.679457
3fabc01ad1e3e61f1d9c19891cf9e15f8bafe00e
9,351
package com.github.mmolimar.kafka.connect.fs.file.reader; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static com.github.mmolimar.kafka.connect.fs.FsSourceTaskConfig.FILE_READER_PREFIX; public class JsonFileReader extends AbstractFileReader<JsonFileReader.JsonRecord> { private static final String FILE_READER_JSON = FILE_READER_PREFIX + "json."; private static final String FILE_READER_JSON_COMPRESSION = FILE_READER_JSON + "compression."; public static final String FILE_READER_JSON_RECORD_PER_LINE = FILE_READER_JSON + "record_per_line"; public static final String FILE_READER_JSON_DESERIALIZATION_CONFIGS = FILE_READER_JSON + "deserialization."; public static final String FILE_READER_JSON_COMPRESSION_TYPE = FILE_READER_JSON_COMPRESSION + "type"; public static final String FILE_READER_JSON_COMPRESSION_CONCATENATED = FILE_READER_JSON_COMPRESSION + "concatenated"; public static final String FILE_READER_JSON_ENCODING = FILE_READER_JSON + "encoding"; private final TextFileReader inner; private final Schema schema; private ObjectMapper mapper; public JsonFileReader(FileSystem fs, Path filePath, Map<String, Object> config) throws IOException { super(fs, filePath, new JsonToStruct(), config); config.put(TextFileReader.FILE_READER_TEXT_ENCODING, config.get(FILE_READER_JSON_ENCODING)); config.put(TextFileReader.FILE_READER_TEXT_RECORD_PER_LINE, config.get(FILE_READER_JSON_RECORD_PER_LINE)); config.put(TextFileReader.FILE_READER_TEXT_COMPRESSION_TYPE, config.get(FILE_READER_JSON_COMPRESSION_TYPE)); config.put(TextFileReader.FILE_READER_TEXT_COMPRESSION_CONCATENATED, config.get(FILE_READER_JSON_COMPRESSION_CONCATENATED)); this.inner = new TextFileReader(fs, filePath, config); if (hasNext()) { String line = inner.nextRecord().getValue(); this.schema = extractSchema(mapper.readTree(line)); //back to the first line inner.seek(0); } else { this.schema = SchemaBuilder.struct().build(); } } @Override protected void configure(Map<String, String> config) { mapper = new ObjectMapper(); Set<String> deserializationFeatures = Arrays.stream(DeserializationFeature.values()) .map(Enum::name) .collect(Collectors.toSet()); config.entrySet().stream() .filter(entry -> entry.getKey().startsWith(FILE_READER_JSON_DESERIALIZATION_CONFIGS)) .forEach(entry -> { String feature = entry.getKey().replaceAll(FILE_READER_JSON_DESERIALIZATION_CONFIGS, ""); if (deserializationFeatures.contains(feature)) { mapper.configure(DeserializationFeature.valueOf(feature), Boolean.parseBoolean(entry.getValue())); } else { log.warn("Ignoring deserialization configuration '{}' due to it does not exist.", feature); } }); } @Override protected JsonRecord nextRecord() throws IOException { JsonNode value = mapper.readTree(inner.nextRecord().getValue()); return new JsonRecord(schema, value); } @Override public boolean hasNextRecord() throws IOException { return inner.hasNextRecord(); } @Override public void seekFile(long offset) throws IOException { inner.seekFile(offset); } @Override public long currentOffset() { return inner.currentOffset(); } @Override public void close() throws IOException { inner.close(); } @Override public boolean isClosed() { return inner.isClosed(); } private static Schema extractSchema(JsonNode jsonNode) { switch (jsonNode.getNodeType()) { case BOOLEAN: return Schema.OPTIONAL_BOOLEAN_SCHEMA; case NUMBER: if (jsonNode.isShort()) { return Schema.OPTIONAL_INT8_SCHEMA; } else if (jsonNode.isInt()) { return Schema.OPTIONAL_INT32_SCHEMA; } else if (jsonNode.isLong()) { return Schema.OPTIONAL_INT64_SCHEMA; } else if (jsonNode.isFloat()) { return Schema.OPTIONAL_FLOAT32_SCHEMA; } else if (jsonNode.isDouble()) { return Schema.OPTIONAL_FLOAT64_SCHEMA; } else if (jsonNode.isBigInteger()) { return Schema.OPTIONAL_INT64_SCHEMA; } else if (jsonNode.isBigDecimal()) { return Schema.OPTIONAL_FLOAT64_SCHEMA; } else { return Schema.OPTIONAL_FLOAT64_SCHEMA; } case STRING: return Schema.OPTIONAL_STRING_SCHEMA; case BINARY: return Schema.OPTIONAL_BYTES_SCHEMA; case ARRAY: Iterable<JsonNode> elements = jsonNode::elements; Schema arraySchema = StreamSupport.stream(elements.spliterator(), false) .findFirst().map(JsonFileReader::extractSchema) .orElse(SchemaBuilder.struct().build()); return SchemaBuilder.array(arraySchema).build(); case OBJECT: SchemaBuilder builder = SchemaBuilder.struct(); jsonNode.fields() .forEachRemaining(field -> builder.field(field.getKey(), extractSchema(field.getValue()))); return builder.build(); default: return SchemaBuilder.struct().optional().build(); } } static class JsonToStruct implements ReaderAdapter<JsonRecord> { @Override public Struct apply(JsonRecord record) { return toStruct(record.schema, record.value); } private Struct toStruct(Schema schema, JsonNode jsonNode) { if (jsonNode.isNull()) return null; Struct struct = new Struct(schema); jsonNode.fields() .forEachRemaining(field -> struct.put(field.getKey(), mapValue(struct.schema().field(field.getKey()).schema(), field.getValue()))); return struct; } private Object mapValue(Schema schema, JsonNode value) { if (value == null) return null; switch (value.getNodeType()) { case BOOLEAN: return value.booleanValue(); case NUMBER: if (value.isShort()) { return value.shortValue(); } else if (value.isInt()) { return value.intValue(); } else if (value.isLong()) { return value.longValue(); } else if (value.isFloat()) { return value.floatValue(); } else if (value.isDouble()) { return value.doubleValue(); } else if (value.isBigInteger()) { return value.bigIntegerValue(); } else { return value.numberValue(); } case STRING: return value.asText(); case BINARY: try { return value.binaryValue(); } catch (IOException ioe) { throw new RuntimeException(ioe); } case OBJECT: case POJO: Struct struct = new Struct(schema); Iterable<Map.Entry<String, JsonNode>> fields = value::fields; StreamSupport.stream(fields.spliterator(), false) .forEach(field -> struct.put(field.getKey(), mapValue(extractSchema(field.getValue()), field.getValue())) ); return struct; case ARRAY: Iterable<JsonNode> arrayElements = value::elements; return StreamSupport.stream(arrayElements.spliterator(), false) .map(elm -> mapValue(schema, elm)) .collect(Collectors.toList()); case NULL: case MISSING: default: return null; } } } static class JsonRecord { private final Schema schema; private final JsonNode value; JsonRecord(Schema schema, JsonNode value) { this.schema = schema; this.value = value; } } }
41.193833
132
0.585178
f431756b05ef1ed70bf051373406b24a5f434021
5,888
package cl.tiocomegfas.ubb.loud.controller; import android.content.Context; import android.text.TextUtils; import cl.tiocomegfas.ubb.loud.backend.listeners.OnBuildLoudTreeListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnLoadDataListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnQueryCadenaMandoListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnQueryColegasListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnQueryJefeListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnQuerySubordinadosListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnSearchPersonListener; import cl.tiocomegfas.ubb.loud.backend.listeners.OnTableViewGenerateDataListener; import cl.tiocomegfas.ubb.loud.backend.threads.BuildLoudTreeThread; import cl.tiocomegfas.ubb.loud.backend.threads.LoadDataThread; import cl.tiocomegfas.ubb.loud.backend.threads.QueryCadenaMandoThread; import cl.tiocomegfas.ubb.loud.backend.threads.QueryColegasThread; import cl.tiocomegfas.ubb.loud.backend.threads.QueryJefeThread; import cl.tiocomegfas.ubb.loud.backend.threads.QuerySubordinadosThread; import cl.tiocomegfas.ubb.loud.backend.threads.SearchPersonThread; import cl.tiocomegfas.ubb.loud.backend.threads.TableViewGenerateDataThread; public class Pipe { private static Pipe INSTANCE; private LoadDataThread loadDataThread; private SearchPersonThread searchPersonThread; private BuildLoudTreeThread buildLoudTreeThread; private QueryJefeThread queryJefeThread; private QueryCadenaMandoThread queryCadenaMandoThread; private QueryColegasThread queryColegasThread; private QuerySubordinadosThread querySubordinadosThread; private TableViewGenerateDataThread generateDataThread; private Pipe(){ } public static Pipe getInstance(){ if(INSTANCE == null) INSTANCE = new Pipe(); return INSTANCE; } public void callLoadJson(Context context, int size, OnLoadDataListener listener){ if(context == null) throw new IllegalArgumentException("El contexto es invalido"); if(size <= 0) throw new IllegalArgumentException("size <= 0"); if(listener == null) throw new IllegalArgumentException("El listener es invalido"); loadDataThread = LoadDataThread.getInstance(); loadDataThread. setContext(context). setSize(size). setListener(listener). start(); } public void callSearchPerson(int loudTree, String[] persons, String personSearch, OnSearchPersonListener listener){ if(persons == null || persons.length == 0) throw new IllegalArgumentException("persons is invalid or empty"); if(TextUtils.isEmpty(personSearch)) throw new IllegalArgumentException("personSearch is invalid"); if(listener == null) throw new IllegalArgumentException("El listener es invalido"); searchPersonThread = SearchPersonThread.getInstance(); searchPersonThread. setTreeSelect(loudTree). setPersons(persons). setPersonSearch(personSearch). setListener(listener). start(); } public void callBuildLoud(int loudTree, OnBuildLoudTreeListener listener){ if(loudTree != Manager.LOUD_TREE_1 && loudTree != Manager.LOUD_TREE_2 && loudTree != Manager.LOUD_TREE_3) throw new IllegalArgumentException("El loudTree es invalido"); if(listener == null) throw new IllegalArgumentException("El listener es invalido"); buildLoudTreeThread = BuildLoudTreeThread.getInstance(); buildLoudTreeThread. setLoudTree(loudTree). setListener(listener). start(); } public void callQueryJefe(int loudTree, int position, OnQueryJefeListener listener){ queryJefeThread = QueryJefeThread.getInstance(); queryJefeThread. setLoudTree(loudTree). setPosition(position). setListener(listener). start(); } public void callQuerySubordinado(int loudTree, int position, OnQuerySubordinadosListener listener){ querySubordinadosThread = QuerySubordinadosThread.getInstance(); querySubordinadosThread. setPosition(position). setLoudTree(loudTree). setListener(listener). start(); } public void callQueryCadenaMando(int loudTree, int position, OnQueryCadenaMandoListener listener){ queryCadenaMandoThread = QueryCadenaMandoThread.getInstance(); queryCadenaMandoThread. setPosition(position). setLoudTree(loudTree). setListener(listener). start(); } public void callQueryColegas(int loudTree, int position, OnQueryColegasListener listener){ queryColegasThread = QueryColegasThread.getInstance(); queryColegasThread. setPosition(position). setLoudTree(loudTree). setListener(listener). start(); } public void callTableViewGenerateData(OnTableViewGenerateDataListener listener){ generateDataThread = TableViewGenerateDataThread.getInstance(); generateDataThread. setListener(listener). start(); } public void cancelLoadJson(){ if(loadDataThread == null) throw new IllegalStateException("loadDataThread is invalid"); loadDataThread.stop(); } public void cancelSearchPerson(){ if(searchPersonThread == null) throw new IllegalStateException("searchPersonThread is invalid"); searchPersonThread.stop(); } public void cancelBuildLoudTree(){ if(buildLoudTreeThread == null) throw new IllegalStateException("buildLoudTreeThread is invalid"); buildLoudTreeThread.stop(); } }
41.464789
176
0.709069
bab7c7707f1ec859c60547c8d19fd5494253d7ca
35,569
package com.foryatto.onetoolbox; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import androidx.drawerlayout.widget.DrawerLayout; import android.content.Intent; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.Toast; import com.foryatto.onetoolbox.pojo.Baike; import com.foryatto.onetoolbox.pojo.IpLocation; import com.foryatto.onetoolbox.pojo.NcmRemark; import com.foryatto.onetoolbox.pojo.Poet; import com.foryatto.onetoolbox.pojo.TelNumber; import com.foryatto.onetoolbox.pojo.Translation; import com.foryatto.onetoolbox.pojo.Trash; import com.foryatto.onetoolbox.pojo.Yiyan; import com.foryatto.onetoolbox.utils.HttpUtil; import com.google.gson.Gson; import com.xuexiang.xui.widget.actionbar.TitleBar; import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog; import com.xuexiang.xui.widget.textview.supertextview.SuperButton; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); titleBarInit(); helpfulToolsInit(); wordToolsInit(); picToolsInit(); } // 导航栏的实现 private void titleBarInit() { TitleBar titleBar = (TitleBar) findViewById(R.id.title_bar_main); titleBar.setLeftClickListener(v -> { Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); }).addAction(new TitleBar.ImageAction(R.drawable.ic_navigation_more) { @Override public void performAction(View view) { Intent intent = new Intent(MainActivity.this, AboutActivity.class); startActivity(intent); } }); } // 实用类功能实现 private void helpfulToolsInit() { // 天气查询 功能实现 SuperButton btWeather = (SuperButton) findViewById(R.id.bt_h_weather); btWeather.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/weather.html"); intent.putExtra("mode", 0); startActivity(intent); } }); // App下载 功能实现 SuperButton btAppDown = (SuperButton) findViewById(R.id.bt_h_appdown); btAppDown.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/app.html"); intent.putExtra("mode", 0); startActivity(intent); } }); // 垃圾分类 功能实现 SuperButton btTrash = (SuperButton) findViewById(R.id.bt_h_trash); btTrash.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.ic_expand_web) .title("垃圾分类查询") .content("请输入要查找的关键词:") .inputType( InputType.TYPE_CLASS_TEXT) .input( "", "", false, ((dialog, input) -> { // String query = input.toString(); // Toast.makeText(MainActivity.this, "输入框测试1: "+query, Toast.LENGTH_SHORT).show(); })) .inputRange(1, 100) .positiveText("查询") .negativeText("取消") .onPositive((dialog, which) -> { String query = dialog.getInputEditText().getText().toString(); HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/lajifl?m=" + query, "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("垃圾分类查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); Trash trash = gson.fromJson(requestData, Trash.class); runOnUiThread(new Runnable() { @Override public void run() { if (trash.getCode().equals("200")) { Trash.DataBean dataBean = trash.getData(); Intent intent = new Intent(MainActivity.this, TextShowActivity.class); intent.putExtra("content", "\n关键词: " + query + "\n\n类型:" + dataBean.getType() + "\n\n说明:" + dataBean.getDescription()); startActivity(intent); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("垃圾分类查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); }) .cancelable(false) .show(); } }); // IP查询 功能实现 SuperButton btIp = (SuperButton) findViewById(R.id.bt_h_ip); btIp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.ic_expand_web) .title("IP位置查询") .content("请输入要查找的IP:") .inputType( InputType.TYPE_CLASS_TEXT) .input( "", "", false, ((dialog, input) -> { // String query = input.toString(); // Toast.makeText(MainActivity.this, "输入框测试1: "+query, Toast.LENGTH_SHORT).show(); })) .inputRange(1, 100) .positiveText("查询") .negativeText("取消") .onPositive((dialog, which) -> { String query = dialog.getInputEditText().getText().toString(); HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/ip?ip="+query+"&type=b", "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("IP位置查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); IpLocation ipLocation = gson.fromJson(requestData, IpLocation.class); runOnUiThread(new Runnable() { @Override public void run() { if (ipLocation.getCode().equals("200")) { IpLocation.DataBean dataBean = ipLocation.getData(); Intent intent = new Intent(MainActivity.this, TextShowActivity.class); intent.putExtra("content", "\nIP: " + query + "\n\n位置:" + dataBean.getGeographical_location()); startActivity(intent); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("IP位置查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); }) .cancelable(false) .show(); } }); // 手机号归属地 功能实现 SuperButton btTel = (SuperButton) findViewById(R.id.bt_h_tel); btTel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.ic_expand_web) .title("手机号归属地查询") .content("请输入要查找的手机号:") .inputType( InputType.TYPE_CLASS_TEXT) .input( "", "", false, ((dialog, input) -> { // String query = input.toString(); // Toast.makeText(MainActivity.this, "输入框测试1: "+query, Toast.LENGTH_SHORT).show(); })) .inputRange(1, 100) .positiveText("查询") .negativeText("取消") .onPositive((dialog, which) -> { String query = dialog.getInputEditText().getText().toString(); HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/mobile?phone="+query, "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("手机号归属地查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); TelNumber telNumber = gson.fromJson(requestData, TelNumber.class); runOnUiThread(new Runnable() { @Override public void run() { if (telNumber.getCode().equals("200")) { TelNumber.DataBean dataBean = telNumber.getData(); Intent intent = new Intent(MainActivity.this, TextShowActivity.class); intent.putExtra("content", "\n手机号: " + query + "\n\n归属地:" + dataBean.getProvince()+dataBean.getCity()); startActivity(intent); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("手机号归属地查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); }) .cancelable(false) .show(); } }); // 翻译 功能实现 SuperButton btTrans = (SuperButton) findViewById(R.id.bt_h_trans); btTrans.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.ic_expand_web) .title("翻译") .content("请输入要翻译的内容:") .inputType( InputType.TYPE_CLASS_TEXT) .input( "", "", false, ((dialog, input) -> { // String query = input.toString(); // Toast.makeText(MainActivity.this, "输入框测试1: "+query, Toast.LENGTH_SHORT).show(); })) .inputRange(1, 100) .positiveText("查询") .negativeText("取消") .onPositive((dialog, which) -> { String query = dialog.getInputEditText().getText().toString(); HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/Tn_tencent?text="+query, "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("翻译") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); Translation translation = gson.fromJson(requestData, Translation.class); runOnUiThread(new Runnable() { @Override public void run() { if (translation.getCode().equals("200")) { Translation.DataBean dataBean = translation.getData(); Intent intent = new Intent(MainActivity.this, TextShowActivity.class); intent.putExtra("content", "\n原文: " + query + "\n\n翻译:" + dataBean.getTranslation()); startActivity(intent); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("翻译") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); }) .cancelable(false) .show(); } }); // QQ信息 功能实现 SuperButton btQQ = (SuperButton) findViewById(R.id.bt_h_qq); btQQ.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/qqInfo.html"); intent.putExtra("mode", 0); startActivity(intent); } }); // 匿名邮件 功能实现 SuperButton btEmail = (SuperButton) findViewById(R.id.bt_h_email); btEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/email.html"); intent.putExtra("mode", 0); startActivity(intent); } }); } // 文字类工具的实现 private void wordToolsInit() { // 一言 功能实现 SuperButton btYiyan = (SuperButton) findViewById(R.id.bt_w_yiyan); btYiyan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 不管是使用HttpURLConnection还是OkHttp,最终的回调接口都还是在子线程中运行的,因此我们不可以在这里执行任何的UI操作,除非借助runOnUiThread()方法来进行线程转换。 HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/yiyan", "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("一言") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); Yiyan yiyan = gson.fromJson(requestData, Yiyan.class); runOnUiThread(new Runnable() { @Override public void run() { if (yiyan.getCode().equals("200")) { Yiyan.DataBean dataBean = yiyan.getData(); new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_love) .title("一言") .content(dataBean.getConstant() + "\n\n" + "来自: " + dataBean.getSource()) .positiveText("确定") .show(); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("一言") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); } }); // 网易云音乐热评功能实现。。。 SuperButton btNcmRemark = (SuperButton) findViewById(R.id.bt_w_ncm); btNcmRemark.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 不管是使用HttpURLConnection还是OkHttp,最终的回调接口都还是在子线程中运行的,因此我们不可以在这里执行任何的UI操作,除非借助runOnUiThread()方法来进行线程转换。 HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/163reping", "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("网易云音乐") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); NcmRemark ncmRemark = gson.fromJson(requestData, NcmRemark.class); runOnUiThread(new Runnable() { @Override public void run() { if (ncmRemark.getCode().equals("200")) { NcmRemark.DataBean dataBean = ncmRemark.getData(); new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_love) .title("网易云音乐") .content(dataBean.getContent() + "\n\n" + "用户: " + dataBean.getNickname() + " 在听" + dataBean.getSongName() + "这首歌时留下了此评论!") .positiveText("确定") .show(); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("网易云音乐") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); } }); // 今日古诗词 功能实现 SuperButton btPoet = (SuperButton) findViewById(R.id.bt_w_poet); btPoet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 不管是使用HttpURLConnection还是OkHttp,最终的回调接口都还是在子线程中运行的,因此我们不可以在这里执行任何的UI操作,除非借助runOnUiThread()方法来进行线程转换。 HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/Gushici", "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("今日古诗词") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); Poet poet = gson.fromJson(requestData, Poet.class); runOnUiThread(new Runnable() { @Override public void run() { if (poet.getCode().equals("200")) { Poet.DataBean dataBean = poet.getData(); new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_love) .title("今日古诗词") .content(dataBean.getPoem_title() + "\n\n" + dataBean.getPoetry()) .positiveText("确定") .show(); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("今日古诗词") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); } }); // 历史上的今天 功能实现 SuperButton btToday = (SuperButton) findViewById(R.id.bt_w_today); btToday.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/today.html"); intent.putExtra("mode", 0); startActivity(intent); } }); // 百科 功能实现 SuperButton btBaike = (SuperButton) findViewById(R.id.bt_w_baike); btBaike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.ic_expand_web) .title("百科查询") .content("请输入要查找的关键词:") .inputType( InputType.TYPE_CLASS_TEXT) .input( "", "", false, ((dialog, input) -> { // String query = input.toString(); // Toast.makeText(MainActivity.this, "输入框测试1: "+query, Toast.LENGTH_SHORT).show(); })) .inputRange(1, 100) .positiveText("查询") .negativeText("取消") .onPositive((dialog, which) -> { String query = dialog.getInputEditText().getText().toString(); HttpUtil.sendRequestWithOkHttp("https://api.muxiaoguo.cn/api/Baike?type=Baidu&word=" + query, "get", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("百科查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String requestData = response.body().string(); Gson gson = new Gson(); Baike baike = gson.fromJson(requestData, Baike.class); runOnUiThread(new Runnable() { @Override public void run() { if (baike.getCode() == 200) { Baike.DataBean dataBean = baike.getData(); Intent intent = new Intent(MainActivity.this, TextShowActivity.class); intent.putExtra("content", "\n关键词: " + query + "\n\n" + dataBean.getContent() + "......"); startActivity(intent); } else { new MaterialDialog.Builder(MainActivity.this) .iconRes(R.drawable.icon_warning) .title("百科查询") .content("获取失败,请稍后重试!") .positiveText("确定") .show(); } } }); } }); }) .cancelable(false) .show(); } }); } // 图片相关 功能实现函数 private void picToolsInit() { // Bing美图 功能实现 SuperButton btBing = (SuperButton) findViewById(R.id.bt_p_bing); btBing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/bing.html"); intent.putExtra("mode", 0); startActivity(intent); } }); // 随机壁纸 功能实现 SuperButton btRandom = (SuperButton) findViewById(R.id.bt_p_random); btRandom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/random_img.html"); intent.putExtra("mode", 0); startActivity(intent); } }); // 表情包搜索 功能实现 SuperButton btMeme = (SuperButton) findViewById(R.id.bt_p_meme); btMeme.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, WebActivity.class); intent.putExtra("url", "file:///android_asset/meme_search.html"); intent.putExtra("mode", 0); startActivity(intent); } }); } }
52.077599
167
0.380556
387b1d95d6120888be69f0ce878d418b7e8b4227
1,066
package com.cqupt.master_helper.dao; import com.cqupt.master_helper.entity.VideoRelease; import com.cqupt.master_helper.utils.DruidUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class VideoReleaseDao { /** * 获取用户发布视频列表 * * @param uid 账号 * @return 用户发布视频列表 */ public List<VideoRelease> foundUserVideoRelease(String uid) { List<VideoRelease> videoReleaseList = new ArrayList<>(); QueryRunner queryRunner = new QueryRunner(); try { videoReleaseList = queryRunner.query(DruidUtils.getConnection(), "SELECT * FROM project1.video_release WHERE uid = ?", new BeanListHandler<>(VideoRelease.class), uid); } catch (SQLException e) { e.printStackTrace(); } finally { DruidUtils.closeSource(); } return videoReleaseList; } }
26.65
76
0.644465
50e7295d54e0df4f6639cca943e628090bc12707
962
package com.penglecode.xmodule.common.cloud.hystrix; import java.util.concurrent.Callable; import org.springframework.util.Assert; /** * 代理的Callable * * 解决将主线程的请求上下文参数添加到hystrix执行子线程中去 * * @param <V> * @author pengpeng * @date 2020年2月12日 下午8:54:09 */ public class DelegatingCallable<V> implements Callable<V> { private final Callable<V> delegate; private final HystrixConcurrencyContext context; public DelegatingCallable(Callable<V> delegate, HystrixConcurrencyContext context) { super(); Assert.notNull(delegate, "Parameter 'delegate' can not be null!"); Assert.notNull(context, "Parameter 'context' can not be null!"); this.delegate = delegate; this.context = context; } @Override public V call() throws Exception { try { HystrixConcurrencyContextHolder.setContext(context); return delegate.call(); } finally { HystrixConcurrencyContextHolder.resetContext(); } } }
23.463415
86
0.709979
0bde5ea00836f97fc26400b9b074310fd8964e01
6,474
/* * Copyright (C) 2016 The Android Open Source Project * * 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.example.android.quakereport; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static android.view.View.GONE; public class EarthquakeActivity extends AppCompatActivity implements LoaderCallbacks<List<Earthquake>> { @SuppressWarnings("unused") public static final String LOG_TAG = EarthquakeActivity.class.getName(); // url to request earthquake data from USGS site public static final String REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query"; // unique loader id private static final int LOADER_ID = 0; // references to avoid several calls to findViewById private EarthquakeAdapter mEarthquakeAdapter; private TextView mEmptyListTextView; private ProgressBar mProgressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.earthquake_activity); ListView earthquakeListView = findViewById(R.id.list); mEarthquakeAdapter = new EarthquakeAdapter(this, new ArrayList<Earthquake>()); earthquakeListView.setAdapter(mEarthquakeAdapter); mEmptyListTextView = findViewById(R.id.empty_list); earthquakeListView.setEmptyView(mEmptyListTextView); mProgressBar = findViewById(R.id.loading_spinner); // Check internet connection ConnectivityManager cm = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); // if there is a network connection - query data if (isConnected) { // getSupportLoaderManager is deprecated as of API 28, but it is part of the tutorial // noinspection deprecation getSupportLoaderManager().initLoader(LOADER_ID, null, this); // set clickListener on ListView Item to start intent to open web page with particular url earthquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Earthquake earthquake = mEarthquakeAdapter.getItem(position); Uri uri = Uri.parse(earthquake.getUrl()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }); } else { // if there is no connection show a message // set text for empty list mEmptyListTextView.setText(R.string.no_internet); // hide loading bar mProgressBar.setVisibility(GONE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent); return true; } return super.onOptionsItemSelected(item); } /** * Update the UI. */ private void updateUI(List<Earthquake> earthquakes) { if (earthquakes != null && !earthquakes.isEmpty()) { mEarthquakeAdapter.clear(); mEarthquakeAdapter.addAll(earthquakes); } } @NonNull @Override public Loader<List<Earthquake>> onCreateLoader(int i, @Nullable Bundle bundle) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String orderBy = sharedPreferences.getString( getString(R.string.settings_order_by_key), getString(R.string.settings_order_by_default) ); String minMagnitude = sharedPreferences.getString( getString(R.string.settings_min_magnitude_key), getString(R.string.settings_min_magnitude_default)); Uri baseUri = Uri.parse(REQUEST_URL); Uri.Builder uriBuilder = baseUri.buildUpon(); uriBuilder.appendQueryParameter("format", "geojson"); uriBuilder.appendQueryParameter("eventtype", "earthquake"); uriBuilder.appendQueryParameter("orderby", orderBy); uriBuilder.appendQueryParameter("minmag", minMagnitude); uriBuilder.appendQueryParameter("limit", "10"); return new EarthquakeLoader(this, uriBuilder.toString()); } @Override public void onLoadFinished(@NonNull Loader<List<Earthquake>> loader, List<Earthquake> earthquakes) { // update view with new earthquakes updateUI(earthquakes); // set text for empty list mEmptyListTextView.setText(R.string.no_earthquakes); // hide loading bar mProgressBar.setVisibility(GONE); } @Override public void onLoaderReset(@NonNull Loader<List<Earthquake>> loader) { mEarthquakeAdapter.clear(); } }
37.639535
104
0.694161
5e82f8f0b9d26acf770ad9a33102fabc4bd49959
673
package org.togglz.slack; import org.togglz.core.logging.Log; import org.togglz.core.logging.LogFactory; import org.togglz.core.util.Preconditions; import java.util.LinkedList; import java.util.List; class ChannelsProvider { private static final Log log = LogFactory.getLog(ChannelsProvider.class); private final List<String> channels; ChannelsProvider(List<String> channels) { Preconditions.checkArgument(channels != null, "channels can be empty but not null"); this.channels = new LinkedList<>(channels); log.info("Slack toggles channels: " + channels); } List<String> getRecipients() { return channels; } }
25.884615
92
0.71471
405eacab4a5dcdfc84e2ccd6ef057b2a8b4339c9
2,836
package com.emistoolbox.server.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import com.emistoolbox.server.EmisConfig; import com.emistoolbox.server.ServerUtil; import es.jbauer.lib.io.IOInput; import es.jbauer.lib.io.impl.IOFileInput; public class HtmlServlet extends HttpServlet { private String emisRoot = EmisConfig.get(EmisConfig.EMISTOOLBOX_PATH, ServerUtil.ROOT_PATH); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { IOInput in = getInput(req.getPathInfo()); if (in == null) throw new IllegalArgumentException("Path not found."); resp.setContentType(in.getContentType()); OutputStream os = null; InputStream is = null; try { os = resp.getOutputStream(); is = in.getInputStream(); IOUtils.copy(is, os); os.flush(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } public IOInput getInput(String path) { int offset = 0; if (path.startsWith("/") || path.startsWith("\\")) offset = 1; int pos = path.indexOf("/", offset); if (pos == -1) return null; if (path.indexOf("..") != -1) throw new IllegalArgumentException(); String dataset = path.substring(offset, pos); if (dataset.equals("bin")) throw new IllegalArgumentException("Not allowed."); if (dataset.equals("highcharts") || dataset.equals("reports")) return new IOFileInput(new File(emisRoot, path.substring(offset)), getContentType(path), null); File datasetDir = new File(emisRoot, dataset); if (!datasetDir.exists() || !datasetDir.isDirectory()) return null; return new IOFileInput(new File(datasetDir, path.substring(pos + 1)), getContentType(path), null); } private static String[] exts = new String[] { "js", "json", "html", "txt", "css", "png", "jpg", "jpeg", "zip", }; private static String[] mimes = new String[] { "text/javascript", "application/json", "text/html", "text/plain", "text/css", "image/png", "image/jpeg", "image/jpeg", "application/zip" }; private static Map<String, String> contentTypes = null; private String getContentType(String path) { if (contentTypes == null) { contentTypes = new HashMap<String, String>(); for (int i = 0; i < exts.length; i++) contentTypes.put(exts[i], mimes[i]); } int pos = path.lastIndexOf("."); if (pos == -1) return null; return contentTypes.get(path.substring(pos + 1)); } }
24.448276
101
0.683004
decbd8aec99cc42e216c5b2626f0e7179f7f91db
31,633
package com.racersystems.protege.preferences; import com.racersystems.protege.RacerProInstalledBinaryInfo; import org.protege.editor.core.ui.util.ComponentFactory; import org.protege.editor.owl.ui.preferences.OWLPreferencesPanel; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; /******************************************************************************* * Copyright (c) 2011 by Olaf Noppens. All rights reserved.<br/> * derivo GmbH, Germany. ******************************************************************************/ /** * Author: Olaf Noppens * Date: 14.10.2010 */ public class RacerProPreferencePanel extends OWLPreferencesPanel implements ActionListener { private JRadioButton startRacerPro; private JRadioButton connectRacerPro; private JRadioButton useIntegratedRacerPro; private JRadioButton useExternalRacerPro; protected JTextField binaryField; private JTextField localRacerPort; protected JTextField remoteRacerProAdress; protected JTextField remoteRacerProPort; protected JCheckBox checkForUpdates; protected JCheckBox enableLogging; protected JTextField loggingFile; JCheckBox enableTerminalWindow; JCheckBox enableNavigationInTerminalWindow; private final RacerProPreferences prefs = RacerProPreferences.getInstance(); @Override public void applyChanges() { prefs.setStartRacerEnabled(this.startRacerPro.isSelected()); prefs.setIntegratedRacerEnabled(this.useIntegratedRacerPro.isSelected()); prefs.setExternalRacerBinaryPath(this.binaryField.getText()); if (this.localRacerPort.getText() != null && this.localRacerPort.getText().length() > 0) prefs.setLocalRacerPort(Integer.valueOf(this.localRacerPort.getText())); prefs.setRemoteRacerAddress(this.remoteRacerProAdress.getText()); if (this.remoteRacerProPort.getText() != null && this.remoteRacerProPort.getText().length() > 0) prefs.setRemoteRacerPort(Integer.valueOf(this.remoteRacerProPort.getText())); prefs.setAutoUpdateEnabled(this.checkForUpdates.isSelected()); prefs.setLoggingDirectory(this.loggingFile.getText()); prefs.setLoggingEnabled(this.enableLogging.isSelected()); prefs.setEnableTerminalWindow(this.enableTerminalWindow.isSelected()); prefs.setEnableNavigationInTerminalWindow(this.enableNavigationInTerminalWindow.isSelected()); } public void initialise() throws Exception { JComponent panel = createBinaryPanel(); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); add(panel); // add(createAutoUpdatePanel()); add(createDisposeReasonerOnClosePanel()); add(createOverwriteReasonerConfiguration()); add(createDebugPanel()); } public void dispose() throws Exception { } protected JComponent createAutoUpdatePanel() { JComponent c = createPane(null, BoxLayout.PAGE_AXIS); JCheckBox autoUpdateBox = new JCheckBox("Check for RacerPro updates"); autoUpdateBox.setSelected(prefs.isAutoUpdateEnabled()); autoUpdateBox.setActionCommand("autoupdate"); autoUpdateBox.addActionListener(this); JPanel customPane = new JPanel(); customPane.setLayout(new BoxLayout(customPane, BoxLayout.PAGE_AXIS)); customPane.setAlignmentX(0.0f); customPane.add(autoUpdateBox); c.add(customPane); return c; } protected JComponent createDisposeReasonerOnClosePanel() { JComponent c = createPane("General configuration", BoxLayout.PAGE_AXIS); JCheckBox disposeBox = new JCheckBox("Don't dispose Racer KB on reasoner dispose"); disposeBox.setAlignmentX(LEFT_ALIGNMENT); disposeBox.setAlignmentX(0); disposeBox.setToolTipText("Enable this option if the Racer KB should not be disposed.\nThis is useful if you" + " want to inspect the KB with an external program such as RacerPorter.\n\nPlease note that you are" + " responsible for the disposal of the KB!\n(This only applies to external Racer instances)"); disposeBox.setSelected(!prefs.isDisposeReasonerOnClose()); disposeBox.setActionCommand("disposeReasonerOnClose"); disposeBox.addActionListener(this); JComponent disposeInfoBox = createInfoPanel("If this option is enabled, knowledge bases are not disposed in RacerPro" + " after switching the reasoner in Protege or after closing the ontology. Use this option only if you want to " + "inspect the knowledge base with RacerPorter or a similar application and if you are running an external " + "RacerPro instance that is neither started nor shutdowned automatically by Protege"); disposeInfoBox.setAlignmentX(LEFT_ALIGNMENT); JCheckBox enableMemorySavingMode = new JCheckBox("Enable memory saving mode"); enableMemorySavingMode.setAlignmentX(LEFT_ALIGNMENT); enableMemorySavingMode.setSelected(prefs.isMemorySavingModeEnabled()); enableMemorySavingMode.setActionCommand("enableMemorySavingMode"); enableMemorySavingMode.addActionListener(this); JComponent memorySavingModeInfo = createInfoPanel("If this option is enabled," + " less memory is needed for ontologies in RacerPro but removing axioms" + " might require to transfer the whole ontology to RacerPro" + ""); memorySavingModeInfo.setAlignmentX(LEFT_ALIGNMENT); /* JPanel customPane = new JPanel(); customPane.setLayout(new BoxLayout(customPane, BoxLayout.PAGE_AXIS)); customPane.setAlignmentX(0.0f); customPane.add(disposeBox); customPane.add(disposeInfoBox); customPane.add(enableMemorySavingMode); customPane.add(memorySavingModeInfo); c.add(customPane);*/ Box holder = new Box(BoxLayout.Y_AXIS); c.add(holder); holder.add(disposeBox); holder.add(disposeInfoBox); holder.add(enableMemorySavingMode); holder.add(memorySavingModeInfo); return c; } protected JComponent createOverwriteReasonerConfiguration() { final int HORIZONTAL_SPACE = 35; JComponent c = createPane("ABox Configuration", BoxLayout.PAGE_AXIS); RacerProPreferences prefs = new RacerProPreferences(); JCheckBox disableABoxRealization = new JCheckBox("Disable ABox realization"); disableABoxRealization.setSelected(prefs.isDisableABoxRealization()); disableABoxRealization.setActionCommand("DisableABoxRealization"); disableABoxRealization.addActionListener(this); JPanel disableABoxRealizationDetails = new JPanel(); disableABoxRealizationDetails.setLayout(new BoxLayout(disableABoxRealizationDetails, BoxLayout.PAGE_AXIS)); JComponent disableABoxDetailPanel = new JPanel(); disableABoxDetailPanel.setLayout(new BoxLayout(disableABoxDetailPanel, BoxLayout.LINE_AXIS)); disableABoxDetailPanel.setAlignmentX(0.0f); JLabel warningLabel = new JLabel(); warningLabel.setFont(warningLabel.getFont().deriveFont(Font.ITALIC)); warningLabel.setText("If this option is enabled, Protege Preferences for Reasoner initalization have no effect on ABox realization."); JTextArea warningTA = new JTextArea(); warningTA.setFont(warningTA.getFont().deriveFont(Font.ITALIC)); warningTA.setText("If this option is enabled, Protege Preferences for Reasoner initalization have no effect on ABox realization."); warningTA.setEditable(false); disableABoxDetailPanel.add(warningTA); disableABoxRealizationDetails.add(disableABoxDetailPanel); disableABoxRealizationDetails.setBorder(BorderFactory.createEmptyBorder(0, HORIZONTAL_SPACE, 0, 0)); JCheckBox disableAboxConsistencyTest = new JCheckBox("Disable ABox consistency checks"); disableAboxConsistencyTest.setSelected(prefs.isDisableABoxConsistencyTest()); disableAboxConsistencyTest.setActionCommand("DisableABoxConsistencyTest"); disableAboxConsistencyTest.addActionListener(this); JPanel customPane = new JPanel(); customPane.setLayout(new BoxLayout(customPane, BoxLayout.PAGE_AXIS)); customPane.setAlignmentX(0.0f); customPane.add(disableABoxRealization); customPane.add(disableABoxRealizationDetails); customPane.add(disableAboxConsistencyTest); c.add(customPane); return c; } protected JComponent createDebugPanel() { final int HORIZONTAL_SPACE = 35; JComponent c = createPane("Debug Configuration", BoxLayout.PAGE_AXIS); RacerProPreferences prefs = new RacerProPreferences(); enableTerminalWindow = new JCheckBox("Show Racer terminal window"); enableTerminalWindow.setSelected(prefs.isTerminalWindowEnabled()); enableTerminalWindow.setActionCommand("terminalWindowEnabled"); enableTerminalWindow.addActionListener(this); this.enableTerminalWindow.setEnabled(prefs.isStartRacerEnabled()); JPanel enableTerminalWindowDetails = new JPanel(); enableTerminalWindowDetails.setLayout(new BoxLayout(enableTerminalWindowDetails, BoxLayout.PAGE_AXIS)); JComponent disableABoxDetailPanel = new JPanel(); disableABoxDetailPanel.setLayout(new BoxLayout(disableABoxDetailPanel, BoxLayout.LINE_AXIS)); disableABoxDetailPanel.setAlignmentX(0.0f); JTextArea detailsTA = new JTextArea(); detailsTA.setFont(detailsTA.getFont().deriveFont(Font.ITALIC)); detailsTA.setText("If this option is enabled, a terminal window is openend showing RacerPro's debug and warning messages."); detailsTA.setEditable(false); disableABoxDetailPanel.add(detailsTA); enableTerminalWindowDetails.add(disableABoxDetailPanel); enableTerminalWindowDetails.setBorder(BorderFactory.createEmptyBorder(0, HORIZONTAL_SPACE, 0, 0)); this.enableNavigationInTerminalWindow = new JCheckBox("Enable navigation in terminal window"); this.enableNavigationInTerminalWindow.setSelected(prefs.isNavigationInTerminalWindowEnabeld()); this.enableNavigationInTerminalWindow.setActionCommand("navigationTerminalWindowEnabeled"); this.enableNavigationInTerminalWindow.addActionListener(this); this.enableNavigationInTerminalWindow.setEnabled(this.enableTerminalWindow.isEnabled()); JPanel enableNavigationTerminalWindowDetails = new JPanel(); enableNavigationTerminalWindowDetails.setLayout(new BoxLayout(enableNavigationTerminalWindowDetails, BoxLayout.PAGE_AXIS)); JComponent disableTABoxDetailPanel = new JPanel(); disableTABoxDetailPanel.setLayout(new BoxLayout(disableTABoxDetailPanel, BoxLayout.LINE_AXIS)); disableTABoxDetailPanel.setAlignmentX(0.0f); JTextArea detailsNTA = new JTextArea(); detailsNTA.setFont(detailsNTA.getFont().deriveFont(Font.ITALIC)); detailsNTA.setText("If this option is enabled, clicking on entites in the terminal window displays them in P4"); detailsNTA.setEditable(false); disableTABoxDetailPanel.add(detailsNTA); enableNavigationTerminalWindowDetails.add(disableTABoxDetailPanel); enableNavigationTerminalWindowDetails.setBorder(BorderFactory.createEmptyBorder(0, HORIZONTAL_SPACE, 0, 0)); this.enableNavigationInTerminalWindow.setEnabled(this.enableTerminalWindow.isSelected()); JPanel customPane = new JPanel(); customPane.setLayout(new BoxLayout(customPane, BoxLayout.PAGE_AXIS)); customPane.setAlignmentX(0.0f); customPane.add(enableTerminalWindow); customPane.add(enableTerminalWindowDetails); customPane.add(enableNavigationInTerminalWindow); customPane.add(enableNavigationTerminalWindowDetails); c.add(customPane); return c; } protected JComponent createBinaryPanel() { final int HORIZONTAL_SPACE = 35; JComponent c = createPane("RacerPro", BoxLayout.PAGE_AXIS); this.startRacerPro = new JRadioButton("Start RacerPro automatically"); JPanel startRacerProDetails = new JPanel(); startRacerProDetails.setLayout(new BoxLayout(startRacerProDetails, BoxLayout.PAGE_AXIS)); this.localRacerPort = new JTextField(); JComponent localPortPanel = new JPanel(); localPortPanel.setLayout(new BoxLayout(localPortPanel, BoxLayout.LINE_AXIS)); localPortPanel.setAlignmentX(0.0f); localPortPanel.add(new JLabel("Local Port")); localPortPanel.add(this.localRacerPort); startRacerProDetails.add(localPortPanel); RacerProPreferences prefs = new RacerProPreferences(); if (RacerProInstalledBinaryInfo.getInstance().isBinaryFileAvailable()) this.useIntegratedRacerPro = new JRadioButton("Use integrated RacerPro (" + RacerProInstalledBinaryInfo.getInstance().getInstalledBinaryVersion().toString() + ")"); else this.useIntegratedRacerPro = new JRadioButton("Use integrated RacerPro ( Not Available!)"); startRacerProDetails.add(this.useIntegratedRacerPro); this.useExternalRacerPro = new JRadioButton("Use external RacerPro"); startRacerProDetails.add(this.useExternalRacerPro); startRacerProDetails.setBorder(BorderFactory.createEmptyBorder(0, HORIZONTAL_SPACE, 0, 0)); JPanel binaryPanel = new JPanel(); binaryPanel.setLayout(new BoxLayout(binaryPanel, BoxLayout.LINE_AXIS)); binaryPanel.setAlignmentX(0.0f); binaryPanel.add(Box.createHorizontalStrut(HORIZONTAL_SPACE)); binaryPanel.add(new JLabel("Binary")); this.binaryField = new JTextField(); this.binaryField.setToolTipText("Specify the path to the RacerPro directory."); binaryPanel.add(this.binaryField); JButton binaryFileChooser = new JButton("..."); binaryFileChooser.addActionListener(this); binaryFileChooser.setActionCommand("binaryFileChooser"); binaryPanel.add(binaryFileChooser); startRacerProDetails.add(binaryPanel); JComponent loggingPanel = new JPanel(); loggingPanel.setLayout(new BoxLayout(loggingPanel, BoxLayout.LINE_AXIS)); loggingPanel.setAlignmentX(0.0f); this.enableLogging = new JCheckBox("Enable logging"); loggingPanel.add(this.enableLogging); this.loggingFile = new JTextField(prefs.getLoggingDirectory()); this.loggingFile.setToolTipText("Specify logging directory. Filename will automatically created using the current date (racer-YYYY-MM-DD.log"); loggingPanel.add(this.loggingFile); JButton logginFileChooser = new JButton("..."); logginFileChooser.addActionListener(this); logginFileChooser.setActionCommand("loggingFileChooser"); loggingPanel.add(logginFileChooser); JButton resetButton = new JButton("Reset to default"); resetButton.setActionCommand("loggingFileReset"); resetButton.addActionListener(this); loggingPanel.add(resetButton); startRacerProDetails.add(loggingPanel); this.connectRacerPro = new JRadioButton("Connect to running RacerPro"); JComponent remoteAdressPanel = new JPanel(); remoteAdressPanel.setLayout(new BoxLayout(remoteAdressPanel, BoxLayout.LINE_AXIS)); remoteAdressPanel.setAlignmentX(0.0f); remoteAdressPanel.add(Box.createHorizontalStrut(HORIZONTAL_SPACE)); remoteAdressPanel.add(new JLabel("Remote Adress")); this.remoteRacerProAdress = new JTextField(); remoteAdressPanel.add(this.remoteRacerProAdress); JComponent remotePortPanel = new JPanel(); remotePortPanel.setLayout(new BoxLayout(remotePortPanel, BoxLayout.LINE_AXIS)); remotePortPanel.setAlignmentX(0.0f); remotePortPanel.add(Box.createHorizontalStrut(HORIZONTAL_SPACE)); remotePortPanel.add(new JLabel("Remote Port")); this.remoteRacerProPort = new JTextField(); remotePortPanel.add(this.remoteRacerProPort); this.checkForUpdates = new JCheckBox("Check for RacerPro binary updates"); this.checkForUpdates.setSelected(true); this.checkForUpdates.setToolTipText("Check (and download if available) for newer version of Racer when starting Protege."); JPanel customPane = new JPanel(); customPane.setLayout(new BoxLayout(customPane, BoxLayout.PAGE_AXIS)); customPane.setAlignmentX(0.0f); customPane.add(this.startRacerPro); customPane.add(startRacerProDetails); customPane.add(this.connectRacerPro); customPane.add(remoteAdressPanel); customPane.add(remotePortPanel); c.add(customPane); //some button logics ButtonGroup localRemote = new ButtonGroup(); localRemote.add(this.startRacerPro); localRemote.add(this.connectRacerPro); ButtonGroup internalGroup = new ButtonGroup(); internalGroup.add(this.useIntegratedRacerPro); internalGroup.add(this.useExternalRacerPro); if (prefs.isStartRacerEnabled()) { this.startRacerPro.setSelected(true); this.localRacerPort.setEnabled(true); this.useIntegratedRacerPro.setEnabled(true); this.useExternalRacerPro.setEnabled(true); this.remoteRacerProAdress.setEnabled(false); this.remoteRacerProPort.setEnabled(false); this.loggingFile.setEnabled(true); this.enableLogging.setEnabled(true); } else { this.localRacerPort.setEnabled(false); this.binaryField.setEnabled(false); this.useIntegratedRacerPro.setEnabled(false); this.useExternalRacerPro.setEnabled(false); this.connectRacerPro.setSelected(true); this.remoteRacerProAdress.setEnabled(true); this.remoteRacerProPort.setEnabled(true); this.enableLogging.setEnabled(false); } if (prefs.isIntegratedRacerEnabled()) { this.useIntegratedRacerPro.setSelected(true); this.useExternalRacerPro.setSelected(false); if (this.useIntegratedRacerPro.isEnabled()) this.binaryField.setEnabled(false); } else { this.useExternalRacerPro.setSelected(true); this.useIntegratedRacerPro.setSelected(false); if (this.useExternalRacerPro.isEnabled()) this.binaryField.setEnabled(true); } this.enableLogging.setSelected(prefs.isLoggingEnabled()); this.loggingFile.setEnabled(prefs.isLoggingEnabled() && prefs.isStartRacerEnabled()); this.remoteRacerProAdress.setText(prefs.getRemoteRacerAddress()); this.remoteRacerProPort.setText("" + prefs.getRemoteRacerPort()); this.localRacerPort.setText("" + prefs.getLocalRacerPort()); this.binaryField.setText(prefs.getExternalRacerBinaryPath()); this.loggingFile.setText(prefs.getLoggingDirectory()); this.startRacerPro.addActionListener(this); this.connectRacerPro.addActionListener(this); this.useIntegratedRacerPro.addActionListener(this); this.useExternalRacerPro.addActionListener(this); this.checkForUpdates.addActionListener(this); this.enableLogging.addActionListener(this); return c; } private JComponent createInfoPanel(String text) { final int HORIZONTAL_SPACE = 35; JTextArea infoPanel = new JTextArea(); infoPanel.setLineWrap(true); infoPanel.setWrapStyleWord(true); infoPanel.setFont(infoPanel.getFont().deriveFont(Font.ITALIC)); infoPanel.setText(text); infoPanel.setEditable(false); infoPanel.setBorder(BorderFactory.createEmptyBorder(0, HORIZONTAL_SPACE, 0, 0)); return infoPanel; } private JComponent createPane(String title, int orientation) { JComponent c = new Box(orientation) { public Dimension getMaximumSize() { return new Dimension(super.getMaximumSize().width, getPreferredSize().height); } }; c.setAlignmentX(0.0f); if (title != null) { c.setBorder(ComponentFactory.createTitledBorder(title)); } return c; } public void actionPerformed(ActionEvent event) { if (startRacerPro.isSelected()) { this.localRacerPort.setEnabled(true); this.useIntegratedRacerPro.setEnabled(true); this.useExternalRacerPro.setEnabled(true); this.remoteRacerProAdress.setEnabled(false); this.remoteRacerProPort.setEnabled(false); this.binaryField.setEnabled(this.useExternalRacerPro.isSelected()); this.enableLogging.setEnabled(true); this.loggingFile.setEnabled(true); this.enableTerminalWindow.setEnabled(true); } else { this.remoteRacerProAdress.setEnabled(true); this.remoteRacerProPort.setEnabled(true); this.useIntegratedRacerPro.setEnabled(false); this.useExternalRacerPro.setEnabled(false); this.binaryField.setEnabled(false); this.localRacerPort.setEnabled(false); this.loggingFile.setEnabled(false); this.enableLogging.setEnabled(false); this.enableTerminalWindow.setEnabled(false); } if (useIntegratedRacerPro.isSelected()) { this.binaryField.setEnabled(false); } else { this.binaryField.setEnabled(useExternalRacerPro.isEnabled()); } this.loggingFile.setEnabled(prefs.isLoggingEnabled() && prefs.isStartRacerEnabled()); this.loggingFile.setEnabled(this.enableLogging.isSelected()); if ("autoupdate".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setAutoUpdateEnabled(button.getModel().isSelected()); } else if ("disposeReasonerOnClose".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setDisposeReasonerOnClose(!button.getModel().isSelected()); } if ("terminalWindowEnabled".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setEnableTerminalWindow(button.getModel().isSelected()); } if ("navigationTerminalWindowEnabeled".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setEnableNavigationInTerminalWindow(button.getModel().isSelected()); } if ("DisableABoxRealization".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setDisableABoxRealization(button.getModel().isSelected()); } if ("DisableABoxConsistencyTest".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setDisableABoxConsistencyTest(button.getModel().isSelected()); } if ("binaryFileChooser".equals(event.getActionCommand())) { JFileChooser fileChooser = new JFileChooser((adjustBinaryFilePath(prefs.getExternalRacerBinaryPath()))); fileChooser = new JFileChooser(); fileChooser.setMultiSelectionEnabled(false); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setAcceptAllFileFilterUsed(false); final RacerProInstalledBinaryInfo.OSTYPE ostype = RacerProInstalledBinaryInfo.getInstance().getOSType(); fileChooser.resetChoosableFileFilters(); fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter()); fileChooser.addChoosableFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); //return true; /* System.out.println("accept ? " + f.toString()); if (f.isDirectory()) { System.out.println("f is directory"); String binaryFile = f.toString(); switch (ostype) { case WIN: binaryFile = binaryFile + File.separator +RacerProInstalledBinaryInfo.racerWindowsBinaryName; break; case MAC: binaryFile = binaryFile + File.separator +RacerProInstalledBinaryInfo.racerMacOsXBinaryName; break; case OTHER: case LINUX: binaryFile = binaryFile + File.separator +RacerProInstalledBinaryInfo.racerLinuxBinaryName; } File ff = new File(binaryFile); System.out.println(ff.toString() + " " + ff.exists()); return ff.exists(); } else { System.out.println("f is kein directory"); } System.out.println("not accept " + f); return false; */ } @Override public String getDescription() { if (RacerProInstalledBinaryInfo.getInstance().getOSType() == RacerProInstalledBinaryInfo.OSTYPE.WIN) return "RacerPro folder"; return "RacerPro directory"; } }); if (RacerProInstalledBinaryInfo.getInstance().getOSType() == RacerProInstalledBinaryInfo.OSTYPE.WIN) fileChooser.setDialogTitle("Choose RacerPro folder"); else fileChooser.setDialogTitle("Choose RacerPro directory"); /* fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return (f.getName().startsWith("m")); } @Override public String getDescription() { return "something"; } }); */ //alternative solution: choose the RacerPro binary file name /* JFileChooser binaryFileChooser = new JFileChooser(); binaryFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); binaryFileChooser.setMultiSelectionEnabled(false); binaryFileChooser.setAcceptAllFileFilterUsed(false); binaryFileChooser.setSelectedFile(new File(prefs.getExternalRacerBinaryPath())); binaryFileChooser.setCurrentDirectory(new File(prefs.getExternalRacerBinaryPath())); binaryFileChooser.setDialogTitle("Choose RacerPro binary"); final RacerProInstalledBinaryInfo.OSTYPE ostype = RacerProInstalledBinaryInfo.getInstance().getOSType(); binaryFileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { if (f.isFile()) { switch (ostype) { case WIN: return f.getName().equals(RacerProInstalledBinaryInfo.racerWindowsBinaryName); case MAC: return f.getName().equals(RacerProInstalledBinaryInfo.racerMacOsXBinaryName); case OTHER: case LINUX: return f.getName().equals(RacerProInstalledBinaryInfo.racerLinuxBinaryName); } } return false; } @Override public String getDescription() { return "RacerPro binary file"; } }); if (JFileChooser.APPROVE_OPTION == binaryFileChooser.showDialog(this, null)) { String directory = fileChooser.getSelectedFile().toString(); binaryField.setText(directory); prefs.setExternalRacerBinaryPath(directory); } */ if (JFileChooser.APPROVE_OPTION == fileChooser.showDialog(this, null)) { String directory = fileChooser.getSelectedFile().toString(); String binaryFile = directory + File.separator; switch (ostype) { case WIN: binaryFile += RacerProInstalledBinaryInfo.racerWindowsBinaryName; break; case MAC: binaryFile += RacerProInstalledBinaryInfo.racerMacOsXBinaryName; break; case OTHER: case LINUX: binaryFile += RacerProInstalledBinaryInfo.racerLinuxBinaryName; } File fff = new File(binaryFile); if (!fff.exists()) { JOptionPane.showMessageDialog(null, "The given directory does not contain a racer file", "Racer binary not found", JOptionPane.ERROR_MESSAGE); } else { binaryField.setText(directory); prefs.setExternalRacerBinaryPath(directory); } } } else if ("loggingFileChooser".equals(event.getActionCommand())) { JFileChooser fileChooser = new JFileChooser(prefs.getLoggingDirectory()); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setMultiSelectionEnabled(false); fileChooser.setDialogTitle("Choose logging directory"); fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } @Override public String getDescription() { if (RacerProInstalledBinaryInfo.getInstance().getOSType() == RacerProInstalledBinaryInfo.OSTYPE.WIN) return "folder"; return "directory"; } }); if (JFileChooser.APPROVE_OPTION == fileChooser.showDialog(this, null)) { loggingFile.setText(fileChooser.getSelectedFile().toString()); prefs.setLoggingDirectory(fileChooser.getSelectedFile().toString()); } } else if ("loggingFileReset".equals(event.getActionCommand())) { loggingFile.setText(prefs.getDefaultLoggingDirectory()); prefs.setLoggingDirectory(prefs.getDefaultLoggingDirectory()); } else if ("enableMemorySavingMode".equals(event.getActionCommand())) { AbstractButton button = (AbstractButton) event.getSource(); prefs.setEnableMemorySavingMode(button.getModel().isSelected()); } this.enableNavigationInTerminalWindow.setEnabled(this.enableTerminalWindow.isSelected()); } protected String adjustBinaryFilePath(String path) { String separator = File.separator; int index = path.lastIndexOf(separator); if (index > -1) { path = path.substring(0, index); } return path; } }
47.425787
176
0.668226
0d28dc2c42178dd1b9296821d13968f0a34dd773
6,675
package com.bdxh.system.controller; import com.bdxh.common.utils.BeanMapUtils; import com.bdxh.common.utils.BeanToMapUtil; import com.bdxh.common.utils.ObjectUtil; import com.bdxh.common.utils.SnowflakeIdWorker; import com.bdxh.common.utils.wrapper.WrapMapper; import com.bdxh.system.dto.AddAppConfigSecretDto; import com.bdxh.system.dto.AppConfigSecretQueryDto; import com.bdxh.system.dto.UpdateAppConfigSecretDto; import com.bdxh.system.entity.AppConfigSecret; import com.bdxh.system.service.AppConfigSecretService; import com.github.pagehelper.PageInfo; import com.google.common.base.Preconditions; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @description: 控制器 * @author: xuyuan * @create: 2019-03-21 17:14 **/ @RestController @RequestMapping("/appConfigSecret") @Validated @Slf4j @Api(value = "应用秘钥管理", tags = "应用秘钥管理") public class AppConfigSecretController { @Autowired private AppConfigSecretService appConfigSecretService; @Autowired private SnowflakeIdWorker snowflakeIdWorker; @ApiOperation("增加应用秘钥") @RequestMapping(value = "/addAppConfigSecret",method = RequestMethod.POST) public Object addAppConfigSecret(@Valid @RequestBody AddAppConfigSecretDto addAppConfigSecretDto, BindingResult bindingResult){ //检验参数 if(bindingResult.hasErrors()){ String errors = bindingResult.getFieldErrors().stream().map(u -> u.getDefaultMessage()).collect(Collectors.joining(",")); return WrapMapper.error(errors); } try { Map<String,Object> param = new HashMap<>(); param.put("appId",addAppConfigSecretDto.getAppId()); param.put("mchName",addAppConfigSecretDto.getMchName()); param.put("schoolCode",addAppConfigSecretDto.getSchoolCode()); Integer isAppConfigSecretExist = appConfigSecretService.isAppConfigSecretExist(param); Preconditions.checkArgument(isAppConfigSecretExist==null,"应用秘钥已存在"); AppConfigSecret appConfigSecret = BeanMapUtils.map(addAppConfigSecretDto, AppConfigSecret.class); long mchId = snowflakeIdWorker.nextId(); String appSecret = ObjectUtil.getUuid(); appConfigSecret.setMchId(mchId); appConfigSecret.setAppSecret(appSecret); appConfigSecretService.save(appConfigSecret); return WrapMapper.ok(); }catch (Exception e){ e.printStackTrace(); return WrapMapper.error(e.getMessage()); } } @ApiOperation("根据id删除应用秘钥") @RequestMapping(value = "/delAppConfigSecret",method = RequestMethod.GET) public Object delAppConfigSecret(@RequestParam(name = "id") @NotNull(message = "应用秘钥id不能为空") Long id){ try { appConfigSecretService.deleteByKey(id); return WrapMapper.ok(); }catch (Exception e){ e.printStackTrace(); return WrapMapper.error(e.getMessage()); } } @ApiOperation("根据id更新应用") @RequestMapping(value = "/updateAppConfigSecret",method = RequestMethod.POST) public Object updateAppConfigSecret(@Valid @RequestBody UpdateAppConfigSecretDto updateAppConfigSecretDto, BindingResult bindingResult){ //检验参数 if(bindingResult.hasErrors()){ String errors = bindingResult.getFieldErrors().stream().map(u -> u.getDefaultMessage()).collect(Collectors.joining(",")); return WrapMapper.error(errors); } try { AppConfigSecret appConfigSecret = BeanMapUtils.map(updateAppConfigSecretDto, AppConfigSecret.class); appConfigSecretService.update(appConfigSecret); return WrapMapper.ok(); }catch (Exception e){ e.printStackTrace(); return WrapMapper.error(e.getMessage()); } } @ApiOperation("查询应用秘钥") @RequestMapping(value = "/queryAppConfigSecret",method = RequestMethod.GET) public Object queryAppConfigSecret(@RequestParam(name = "id") @NotNull(message = "应用秘钥id不能为空") Long id){ try { AppConfigSecret appConfigSecret = appConfigSecretService.selectByKey(id); return WrapMapper.ok(appConfigSecret); }catch (Exception e){ e.printStackTrace(); return WrapMapper.error(e.getMessage()); } } @ApiOperation("查询应用秘钥列表") @RequestMapping(value = "/queryAppConfigSecretList",method = RequestMethod.POST) public Object queryAppConfigSecretList(@Valid @RequestBody AppConfigSecretQueryDto appConfigSecretQueryDto, BindingResult bindingResult){ //检验参数 if(bindingResult.hasErrors()){ String errors = bindingResult.getFieldErrors().stream().map(u -> u.getDefaultMessage()).collect(Collectors.joining(",")); return WrapMapper.error(errors); } try { Map<String, Object> param = BeanToMapUtil.objectToMap(appConfigSecretQueryDto); List<AppConfigSecret> appConfigSecrets = appConfigSecretService.getAppConfigSecretList(param); return WrapMapper.ok(appConfigSecrets); }catch (Exception e){ e.printStackTrace(); return WrapMapper.error(e.getMessage()); } } @ApiOperation("分页查询应用列表") @RequestMapping(value = "/queryAppConfigSecretListPage",method = RequestMethod.POST) public Object queryAppConfigSecretListPage(@Valid @RequestBody AppConfigSecretQueryDto appConfigSecretQueryDto, BindingResult bindingResult){ //检验参数 if(bindingResult.hasErrors()){ String errors = bindingResult.getFieldErrors().stream().map(u -> u.getDefaultMessage()).collect(Collectors.joining(",")); return WrapMapper.error(errors); } try { Map<String, Object> param = BeanToMapUtil.objectToMap(appConfigSecretQueryDto); PageInfo<AppConfigSecret> appConfigSecrets = appConfigSecretService.getAppConfigSecretListPage(param, appConfigSecretQueryDto.getPageNum(), appConfigSecretQueryDto.getPageSize()); return WrapMapper.ok(appConfigSecrets); }catch (Exception e){ e.printStackTrace(); return WrapMapper.error(e.getMessage()); } } }
43.064516
191
0.700375
b332d9f95a5e7c9068a1ff29475bcbbf6c0ed50b
429
package com.example.functional; /** * Created by debasishc on 4/9/16. */ public class Address { private String street; private City city; public Address(City city, String street) { this.city = city; this.street = street; } public Option<City> getCity() { return Option.optionOf(city); } public Option<String> getStreet() { return Option.optionOf(street); } }
18.652174
46
0.615385
861db2588a6a7a7d4199482d02966d3e069c1a2d
3,083
package com.diamon.pantalla; import com.diamon.nucleo.Juego; import com.diamon.nucleo.Pantalla; import android.graphics.Bitmap; import android.graphics.Canvas; import android.hardware.SensorEvent; import android.view.KeyEvent; import android.view.MotionEvent; public class PantallaContinuar extends Pantalla { private Bitmap fondo; private Bitmap selector; private float posicionY; private boolean toque; public PantallaContinuar(Juego juego) { super(juego); fondo = this.crearBitmap(recurso.getImagen("continuar.png"), Juego.ANCHO_PANTALLA, Juego.ALTO_PANTALLA); selector = this.crearBitmap(recurso.getImagen("selector2.png"), 16, 16); posicionY = 288; toque = false; } @Override public void pausa() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } @Override public void actualizar(float delta) { // TODO Auto-generated method stub } @Override public void dibujar(Canvas pincel, float delta) { dibujarImagen(pincel, fondo, 0, 0); dibujarImagen(pincel, selector, 202, posicionY); } @Override public void colisiones() { // TODO Auto-generated method stub } @Override public void ocultar() { // TODO Auto-generated method stub } @Override public void mostrar() { // TODO Auto-generated method stub } @Override public void teclaPresionada(KeyEvent ev) { switch (ev.getKeyCode()) { case KeyEvent.KEYCODE_0: if (posicionY == 288) { juego.setPantalla(new PantallaNivel(juego)); } if (posicionY == 322) { juego.setPantalla(new PantallaMenu(juego)); } break; case KeyEvent.KEYCODE_1: posicionY = 288; break; case KeyEvent.KEYCODE_2: posicionY = 322; break; default: break; } } @Override public void teclaLevantada(KeyEvent ev) { // TODO Auto-generated method stub } @Override public void toque(MotionEvent ev) { // TODO Auto-generated method stub } @Override public void multiToque(MotionEvent ev) { int accion = ev.getAction() & MotionEvent.ACTION_MASK; int punteroIndice = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; @SuppressWarnings("unused") int punteroID = ev.getPointerId(punteroIndice); switch (accion) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_POINTER_DOWN: if (posicionY == 288) { juego.setPantalla(new PantallaNivel(juego)); } break; case MotionEvent.ACTION_UP: toque = !toque; if (toque) { posicionY = 288; } else { posicionY = 322; } break; case MotionEvent.ACTION_POINTER_UP: if (posicionY == 322) { juego.setPantalla(new PantallaMenu(juego)); } break; case MotionEvent.ACTION_CANCEL: break; case MotionEvent.ACTION_MOVE: break; default: break; } } @Override public void acelerometro(SensorEvent ev) { // TODO Auto-generated method stub } @Override public void reajustarPantalla(float ancho, float alto) { // TODO Auto-generated method stub } }
15.492462
106
0.698994
9902a9000d9c94722a88e1d6755ef29cc47afb08
2,070
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.kernel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Carbon Constants. * * @since 5.2.0 */ public final class Constants { /** * maven project properties related constants. */ public static final String PROJECT_DEFAULTS_PROPERTY_FILE = "project.defaults.properties"; public static final String MAVEN_PROJECT_VERSION = "MAVEN_PROJECT_VERSION"; public static final String START_TIME = "carbon.start.time"; public static final String LOGIN_MODULE_ENTRY = "CarbonSecurityConfig"; public static final String DEFAULT_TENANT = "default"; public static final String TENANT_NAME = "tenant.name"; public static final String SERVER_PACKAGE = "org.wso2.carbon"; /** * The logger that needs to be used for auditing purposes. * */ public static final Logger AUDIT_LOG = LoggerFactory.getLogger("AUDIT_LOG"); /** * Remove default constructor and make it not available to initialize. */ private Constants() { throw new AssertionError("Trying to a instantiate a constant class"); } /** * Default value if it is not set in sys prop/env. */ public static class PlaceHolders { public static final String SERVER_KEY = "carbon-kernel"; public static final String SERVER_NAME = "WSO2 Carbon Kernel"; public static final String SERVER_VERSION = "5"; } }
33.387097
94
0.701449
bf58008ad7518c743eac0424811fa1c411386528
2,015
package com.github.knightliao.middle.http.sync.utils.helper; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import com.github.knightliao.middle.http.common.constants.HttpConstants; import lombok.extern.slf4j.Slf4j; /** * @author knightliao * @email knightliao@gmail.com * @date 2021/8/23 09:51 */ @Slf4j public class MyHttpRawUtilsHelper { protected static HttpGet getHttpGet(String url, List<NameValuePair> params) { StringBuilder sb = new StringBuilder(url); if (StringUtils.containsNone(url, "?")) { sb.append("?"); } if (params != null) { String paramStr = URLEncodedUtils.format(params, HttpConstants.CHARSET); sb.append(paramStr); } return new HttpGet(sb.toString()); } protected static HttpPost getHttpPost(String url, List<NameValuePair> params, Map<String, String> headers) { try { HttpPost post = new HttpPost(url); if (headers != null && headers.size() > 0) { headers.forEach(post::setHeader); } post.setEntity(new UrlEncodedFormEntity(params, HttpConstants.CHARSET)); return post; } catch (Throwable ex) { log.error(ex.getMessage(), ex); return null; } } protected static HttpPost getHttpPost(String url, String content) { HttpPost post = new HttpPost(url); ContentType contentType = ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), HttpConstants.CHARSET); post.setEntity(new StringEntity(content, contentType)); return post; } }
29.632353
120
0.673945
039d1f82ad16e13d6b9e9b87256da3bdea9435a6
631
package com.sensorsdata.analytics.android.runtime; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; /** * Created by 王灼洲 on 2016/12/1 * TabHost.OnTabChangeListener */ @Aspect public class TabHostOnTabChangedAspectj { private final static String TAG = TabHostOnTabChangedAspectj.class.getCanonicalName(); @After("execution(* android.widget.TabHost.OnTabChangeListener.onTabChanged(String))") public void onTabChangedAOP(final JoinPoint joinPoint) throws Throwable { AopUtil.sendTrackEventToSDK(joinPoint, "onTabHostChanged"); } }
30.047619
90
0.7813
039c94587afac2b224825f9a20a86ed2679fcbeb
836
package com.woayli1.pickerviewdemo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; public class FragmentTestActivity extends AppCompatActivity { private FragmentManager mFragmentManager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragmenttest); mFragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.frame_activity_main, new TestFragment()); fragmentTransaction.commitAllowingStateLoss(); } }
34.833333
86
0.788278
08a9dcbede72680a4d062d4ff9bab636edf17640
372
package com.github.yingzhuo.fastdfs.springboot.exception; /** * 上传图片例外 * * @author tobato */ public class FastDFSUploadImageException extends FastDFSException { protected FastDFSUploadImageException(String message) { super(message); } public FastDFSUploadImageException(String message, Throwable cause) { super(message, cause); } }
19.578947
73
0.717742
c5dcb5ca9b6703650d48915df31edb60154bd6dc
1,857
package com.twu.biblioteca; public class Menu { private final Library library; private ConsoleSimulator consoleSimulator; public Menu(Library library, ConsoleSimulator consoleSimulator) { this.library = library; this.consoleSimulator = consoleSimulator; } public void display() { while (true) { consoleSimulator.display("\nMENU:\n\n1. Display books in library.\n2. Display movies in library\n3. Login. (to avail library facilities)\n4. Quit Application.\n\nEnter your choice : "); int option = consoleSimulator.scanOption(); if (option == 4) break; performAction(option); } } public void performAction(int option) { switch (option) { case 1: library.displayBookList(); break; case 2: library.displayMovieList(); break; case 3: Authenticator authenticator = new Authenticator(); User currentUser; consoleSimulator.display("Enter library number : "); String libraryNumber = consoleSimulator.scanLibraryNumber(); consoleSimulator.display("Enter password : "); String password = consoleSimulator.scanPassword(); if (authenticator.login(libraryNumber, password)) { currentUser = authenticator.retrieveCurrentUser(libraryNumber, password); new PostLoginMenu(library, consoleSimulator, currentUser).displayPostLoginMenu(); } break; case 4: return; // System.exit(1); //todo: system.exit0 default: consoleSimulator.display("Please select a valid option!"); } } }
37.897959
197
0.571352
4381702bdb3f95d1b1643e394c756d9a3aae338f
250
package ifelse; public class Whileloop4 { public static void main(String[] args) { int number = 12; int sum = 0; while (number <= 421) { System.out.println(number); number += number; sum = sum + number; sum = sum + 1; } } }
13.888889
41
0.596
5ac61e8ecf1f746578dd7ff47f3da7c05934e67e
813
package rw.action; import com.intellij.execution.Executor; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.diagnostic.Logger; import rw.icons.Icons; public class RunWithReloadiumRunContext extends ContextPopupAction { private static final Logger LOGGER = Logger.getInstance(RunWithReloadiumRunContext.class); RunWithReloadiumRunContext() { super(); this.runType = RunType.RUN; } void setRunningIcon(AnActionEvent e) { e.getPresentation().setIcon(Icons.Run); } void setNotRunningIcon(AnActionEvent e) { e.getPresentation().setIcon(Icons.Run); } protected Executor getExecutor() { return DefaultRunExecutor.getRunExecutorInstance(); } }
28.034483
94
0.742927
e6e86ae87fd03668a62d07b17a5e01b0be40394c
607
package com.lenovo.compass.sys.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lenovo.compass.sys.service.SysUserService; @RestController @RequestMapping({"/user","/users"}) public class SysUserController { @Autowired SysUserService sysUserService; @GetMapping("/u") // @RequiresPermissions("edit") public String test() { sysUserService.insert(); return "success"; } }
25.291667
62
0.795717
3d7668f4c3ddb3109a9c909909160b3777d5248b
4,515
/* * This file was automatically generated by EvoSuite * Thu Aug 02 17:08:19 GMT 2018 */ package org.mozilla.javascript.ast; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import java.nio.CharBuffer; import java.util.List; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; import org.mozilla.javascript.ast.ArrayLiteral; import org.mozilla.javascript.ast.AstNode; import org.mozilla.javascript.ast.ContinueStatement; import org.mozilla.javascript.ast.FunctionCall; import org.mozilla.javascript.ast.SwitchCase; import org.mozilla.javascript.ast.WithStatement; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class SwitchCase_ESTest extends SwitchCase_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); ArrayLiteral arrayLiteral0 = new ArrayLiteral(13); char[] charArray0 = new char[2]; CharBuffer charBuffer0 = CharBuffer.wrap(charArray0); StringBuilder stringBuilder0 = new StringBuilder(charBuffer0); AstNode.DebugPrintVisitor astNode_DebugPrintVisitor0 = new AstNode.DebugPrintVisitor(stringBuilder0); switchCase0.addStatement(arrayLiteral0); switchCase0.visit(astNode_DebugPrintVisitor0); assertEquals("\u0000\u0000-1\tCASE -1 15\n13\t ARRAYLIT 14 1\n", astNode_DebugPrintVisitor0.toString()); assertEquals(15, switchCase0.getLength()); } @Test(timeout = 4000) public void test1() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); ArrayLiteral arrayLiteral0 = new ArrayLiteral(13); switchCase0.addStatement(arrayLiteral0); switchCase0.toSource(8); assertEquals(15, switchCase0.getLength()); } @Test(timeout = 4000) public void test2() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); ContinueStatement continueStatement0 = new ContinueStatement(); switchCase0.setExpression(continueStatement0); switchCase0.toSource((-2906)); assertFalse(switchCase0.isDefault()); } @Test(timeout = 4000) public void test3() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); WithStatement withStatement0 = new WithStatement(15, 4); switchCase0.setExpression(withStatement0); StringBuilder stringBuilder0 = new StringBuilder("U@pUfG9M4)1lrC7nTcp"); AstNode.DebugPrintVisitor astNode_DebugPrintVisitor0 = new AstNode.DebugPrintVisitor(stringBuilder0); // Undeclared exception! try { switchCase0.visit(astNode_DebugPrintVisitor0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.mozilla.javascript.ast.WithStatement", e); } } @Test(timeout = 4000) public void test4() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); boolean boolean0 = switchCase0.isDefault(); assertTrue(boolean0); assertEquals(116, switchCase0.getType()); } @Test(timeout = 4000) public void test5() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); switchCase0.getStatements(); assertEquals("116", switchCase0.toString()); } @Test(timeout = 4000) public void test6() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); switchCase0.getExpression(); assertEquals("116", switchCase0.toString()); } @Test(timeout = 4000) public void test7() throws Throwable { SwitchCase switchCase0 = new SwitchCase(827, 827); assertEquals("116", switchCase0.toString()); } @Test(timeout = 4000) public void test8() throws Throwable { SwitchCase switchCase0 = new SwitchCase(827); assertEquals("116", switchCase0.toString()); } @Test(timeout = 4000) public void test9() throws Throwable { SwitchCase switchCase0 = new SwitchCase(); FunctionCall functionCall0 = new FunctionCall((-15)); functionCall0.addArgument(switchCase0); List<AstNode> list0 = functionCall0.arguments; switchCase0.setStatements(list0); switchCase0.setStatements(list0); assertEquals(0, switchCase0.getPosition()); } }
36.707317
176
0.717829
70048d2d70014bf7dae084f40d2779e8e70d412e
1,936
/* * 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.commons.jelly.tags.regexp; import org.apache.commons.jelly.XMLOutput; import org.apache.commons.jelly.JellyContext; import junit.framework.TestCase; import org.apache.commons.jelly.tags.regexp.ContainsTag; /*** <p><code>ContainsTagTest</code> a class that is useful to perform regexp matches * in strings.</p> * * @author <a href="mailto:christian@inx-soft.com">Christian Amor Kvalheim</a> * @version $Revision$ */ public class ContainsTagTest extends TestCase { public ContainsTagTest(String name) { super(name); } public void setUp() throws Exception { } public void testDoTag() throws Exception { ContainsTag containsExpTag = new ContainsTag(); XMLOutput xmlOutput = new XMLOutput(); containsExpTag.setText("Hello World"); containsExpTag.setExpr("World"); containsExpTag.setVar("testvar"); containsExpTag.setContext(new JellyContext()); containsExpTag.doTag(xmlOutput); assertEquals("TRUE", containsExpTag.getContext().getVariable("testvar").toString().toUpperCase()); } public void tearDown() { } }
32.266667
104
0.72469
fbc6b74e76f29a9c6997bb4b68a57025a9af121b
823
package com.chunyang.servlet; import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebInitParam; import com.alibaba.druid.support.http.StatViewServlet; /** * Druid监控界面配置 * @author qinxuegang * */ @WebServlet(urlPatterns = "/druid/*", initParams={ @WebInitParam(name="allow",value="172.17.5.250,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问) @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow) @WebInitParam(name="loginUsername",value="admin"),// 用户名 @WebInitParam(name="loginPassword",value="123"),// 密码 @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能 }) public class DruidStatViewServlet extends StatViewServlet{ private static final long serialVersionUID = 1L; }
34.291667
97
0.684083
00f5d2d6e128b160df3eafc58475a44839004b16
3,033
package com.sun.mail.imap.protocol; import javax.mail.*; import com.sun.mail.iap.*; public class MailboxInfo { public Flags availableFlags; public Flags permanentFlags; public int total; public int recent; public int first; public int uidvalidity; public int uidnext; public int mode; public MailboxInfo(final Response[] r) throws ParsingException { this.availableFlags = null; this.permanentFlags = null; this.total = -1; this.recent = -1; this.first = -1; this.uidvalidity = -1; this.uidnext = -1; for (int i = 0; i < r.length; ++i) { if (r[i] != null) { if (r[i] instanceof IMAPResponse) { final IMAPResponse ir = (IMAPResponse)r[i]; if (ir.keyEquals("EXISTS")) { this.total = ir.getNumber(); r[i] = null; } else if (ir.keyEquals("RECENT")) { this.recent = ir.getNumber(); r[i] = null; } else if (ir.keyEquals("FLAGS")) { this.availableFlags = new FLAGS(ir); r[i] = null; } else if (ir.isUnTagged() && ir.isOK()) { ir.skipSpaces(); if (ir.readByte() != 91) { ir.reset(); } else { boolean handled = true; final String s = ir.readAtom(); if (s.equalsIgnoreCase("UNSEEN")) { this.first = ir.readNumber(); } else if (s.equalsIgnoreCase("UIDVALIDITY")) { this.uidvalidity = ir.readNumber(); } else if (s.equalsIgnoreCase("PERMANENTFLAGS")) { this.permanentFlags = new FLAGS(ir); } else if (s.equalsIgnoreCase("UIDNEXT")) { this.uidnext = ir.readNumber(); } else { handled = false; } if (handled) { r[i] = null; } else { ir.reset(); } } } } } } if (this.permanentFlags == null) { if (this.availableFlags != null) { this.permanentFlags = new Flags(this.availableFlags); } else { this.permanentFlags = new Flags(); } } } }
35.682353
76
0.365315
ebad5c9ff41809e382ee13092da7fe96474a79ae
6,286
/* * Copyright 2016 Exorath * * 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.exorath.service.lobbymsg.impl; import com.amazonaws.services.dynamodbv2.document.*; import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec; import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; import com.amazonaws.services.dynamodbv2.model.*; import com.exorath.service.lobbymsg.Message; import com.exorath.service.lobbymsg.Success; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * Created by toonsev on 11/1/2016. */ public class DynamoDBService extends SimpleService { private static final String ID_FIELD = "r"; private static final String ID_VALUE = "prod"; private static final String MSGS_FIELD = "msgs"; private static final String MSG_FIELD = "msg"; private static final String FORMAT_FIELD = "format"; private static final Logger LOG = LoggerFactory.getLogger(DynamoDBService.class); private String tableName; private DynamoDB db; public DynamoDBService(int cacheSeconds, String tableName, DynamoDB db) { super(cacheSeconds); this.tableName = tableName; this.db = db; try { setupTable(); } catch (InterruptedException e) { e.printStackTrace(); } } private void setupTable() throws InterruptedException { try { Table table = db.createTable(new CreateTableRequest() .withTableName(tableName) .withKeySchema(new KeySchemaElement(ID_FIELD, KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition(ID_FIELD, ScalarAttributeType.S)) .withProvisionedThroughput(new ProvisionedThroughput(1l, 1l)) ); LOG.info("Created dynamodb table " + tableName + " with 1r/1w provisioning. Waiting for it to activate"); waitForTableToActivate(); } catch (ResourceInUseException e) {//table exists, let's make sure it's active waitForTableToActivate(); } } private void waitForTableToActivate() throws InterruptedException { db.getTable(tableName).waitForActive(); } @Override public Map<String, Message> fetchMessagesByGameId() throws Exception { Item item = db.getTable(tableName).getItem(getMapMessagesSpec()); if (item == null || !item.hasAttribute(MSGS_FIELD)) return new HashMap<>(); Map<String, Map<String, Object>> messages = item.getMap(MSGS_FIELD); return mapMessages(messages); } public static GetItemSpec getMapMessagesSpec() { return new GetItemSpec().withPrimaryKey(getPrimaryKey()); } private Map<String, Message> mapMessages(Map<String, Map<String, Object>> messages) { Map<String, Message> result = new HashMap<>(); for (Map.Entry<String, Map<String, Object>> msgEntry : messages.entrySet()) { String msg = msgEntry.getValue().containsKey(MSG_FIELD) ? (String) msgEntry.getValue().get(MSG_FIELD) : null; String format = msgEntry.getValue().containsKey(FORMAT_FIELD) ? (String) msgEntry.getValue().get(FORMAT_FIELD) : null; result.put(msgEntry.getKey(), new Message(msg, format)); } return result; } @Override public Success updateMessage(String gameId, Message message) { if (gameId == null || message == null) return new Success(false); try { db.getTable(tableName).updateItem(getCheckMsgsMapExistsSpec()); db.getTable(tableName).updateItem(getCheckMsgMapInMsgsMapExistsSpec(gameId)); db.getTable(tableName).updateItem(getUpdateItemSpec(gameId, message)); } catch (Exception e) { e.printStackTrace(); return new Success(false); } return new Success(true); } public static UpdateItemSpec getCheckMsgsMapExistsSpec() { return new UpdateItemSpec().withPrimaryKey(getPrimaryKey()) .withUpdateExpression("SET " + MSGS_FIELD + " = if_not_exists(" + MSGS_FIELD + ", :empty)") .withValueMap(new ValueMap().withMap(":empty", new HashMap<>())); } public static UpdateItemSpec getCheckMsgMapInMsgsMapExistsSpec(String gameId) { return new UpdateItemSpec().withPrimaryKey(getPrimaryKey()) .withUpdateExpression("SET " + MSGS_FIELD + "." + gameId + " = if_not_exists(" + MSGS_FIELD + "." + gameId + ", :empty)") .withValueMap(new ValueMap().withMap(":empty", new HashMap<>())); } public static UpdateItemSpec getUpdateItemSpec(String gameId, Message message) { String updateExpression; ValueMap valueMap = new ValueMap(); if (message.getMsg() == null) updateExpression = "REMOVE " + MSGS_FIELD + "." + gameId; else { updateExpression = "SET " + MSGS_FIELD + "." + gameId + "=:msgMap"; ValueMap msgMap = new ValueMap().withString(MSG_FIELD, message.getMsg()); if (message.getFormat() != null) msgMap.withString(FORMAT_FIELD, message.getFormat()); valueMap.withMap(":msgMap", msgMap); } if (valueMap.isEmpty()) valueMap = null; System.out.println(updateExpression); return new UpdateItemSpec() .withPrimaryKey(getPrimaryKey()) .withUpdateExpression(updateExpression) .withValueMap(valueMap); } public static KeyAttribute getPrimaryKey() { return new KeyAttribute(ID_FIELD, ID_VALUE); } }
40.818182
137
0.65622
7a441ffd0464c952c2fcf1d761f18d8a9579869d
5,952
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.am.service.http; import io.gravitee.common.util.EnvironmentUtils; import io.vertx.core.net.ProxyOptions; import io.vertx.core.net.ProxyType; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.reactivex.core.Vertx; import io.vertx.reactivex.ext.web.client.WebClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import java.net.URI; import java.net.URL; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com) * @author GraviteeSource Team */ public class WebClientBuilder { private static final Logger LOGGER = LoggerFactory.getLogger(WebClientBuilder.class); private static final String HTTPS_SCHEME = "https"; private static final Pattern WILCARD_PATTERN = Pattern.compile("\\*\\."); @Value("${httpClient.timeout:10000}") private int httpClientTimeout; @Value("${httpClient.proxy.type:HTTP}") private String httpClientProxyType; @Value("${httpClient.proxy.http.host:#{systemProperties['http.proxyHost'] ?: 'localhost'}}") private String httpClientProxyHttpHost; @Value("${httpClient.proxy.http.port:#{systemProperties['http.proxyPort'] ?: 3128}}") private int httpClientProxyHttpPort; @Value("${httpClient.proxy.http.username:#{null}}") private String httpClientProxyHttpUsername; @Value("${httpClient.proxy.http.password:#{null}}") private String httpClientProxyHttpPassword; @Value("${httpClient.proxy.https.host:#{systemProperties['https.proxyHost'] ?: 'localhost'}}") private String httpClientProxyHttpsHost; @Value("${httpClient.proxy.https.port:#{systemProperties['https.proxyPort'] ?: 3128}}") private int httpClientProxyHttpsPort; @Value("${httpClient.proxy.https.username:#{null}}") private String httpClientProxyHttpsUsername; @Value("${httpClient.proxy.https.password:#{null}}") private String httpClientProxyHttpsPassword; @Value("${httpClient.proxy.enabled:false}") private boolean isProxyConfigured; @Autowired private Environment environment; public WebClient createWebClient(Vertx vertx, URL url) { final int port = url.getPort() != -1 ? url.getPort() : (HTTPS_SCHEME.equals(url.getProtocol()) ? 443 : 80); WebClientOptions options = new WebClientOptions() .setDefaultPort(port) .setDefaultHost(url.getHost()) .setKeepAlive(true) .setMaxPoolSize(10) .setTcpKeepAlive(true) .setConnectTimeout(httpClientTimeout) .setSsl(url.getProtocol().equals(HTTPS_SCHEME)); return createWebClient(vertx, options); } public WebClient createWebClient(Vertx vertx, WebClientOptions options) { return createWebClient(vertx, options, null); } public WebClient createWebClient(Vertx vertx, WebClientOptions options, String url) { setProxySettings(options, url); return WebClient.create(vertx, options); } private void setProxySettings(WebClientOptions options, String url) { if (this.isProxyConfigured && !isExcludedHost(url)) { ProxyOptions proxyOptions = new ProxyOptions(); proxyOptions.setType(ProxyType.valueOf(httpClientProxyType)); if (options.isSsl()) { proxyOptions.setHost(httpClientProxyHttpsHost); proxyOptions.setPort(httpClientProxyHttpsPort); proxyOptions.setUsername(httpClientProxyHttpsUsername); proxyOptions.setPassword(httpClientProxyHttpsPassword); } else { proxyOptions.setHost(httpClientProxyHttpHost); proxyOptions.setPort(httpClientProxyHttpPort); proxyOptions.setUsername(httpClientProxyHttpUsername); proxyOptions.setPassword(httpClientProxyHttpPassword); } options.setProxyOptions(proxyOptions); } } private boolean isExcludedHost(String url) { if (url == null) { return false; } try { final List<String> proxyExcludeHosts = EnvironmentUtils .getPropertiesStartingWith((ConfigurableEnvironment) environment, "httpClient.proxy.exclude-hosts") .values() .stream() .map(String::valueOf) .collect(Collectors.toList()); URL uri = URI.create(url).toURL(); String host = uri.getHost(); return proxyExcludeHosts.stream().anyMatch(excludedHost -> { if (excludedHost.startsWith("*.")) { return host.endsWith(WILCARD_PATTERN.matcher(excludedHost).replaceFirst("")); } else { return host.equals(excludedHost); } }); } catch (Exception ex) { LOGGER.error("An error has occurred when calculating proxy excluded hosts", ex); return false; } } }
38.153846
119
0.673723