answer
stringlengths
17
10.2M
package org.lagonette.app.room.statement; import android.support.annotation.IntDef; import org.lagonette.app.room.statement.base.GonetteStatement; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.SOURCE; public abstract class FilterStatement implements GonetteStatement { public static final int VALUE_ROW_CATEGORY = 1; public static final int VALUE_ROW_MAIN_PARTNER = 2; public static final int VALUE_ROW_FOOTER = 3; public static final int VALUE_ROW_ORPHAN_PARTNER = 4; public static final int VALUE_DISPLAY_ORDER_FIRST = -1; public static final int VALUE_ORPHAN_CATEGORY_VISIBILITY = -1; private static final String SQL_ORPHAN_PARTNERS = "SELECT " + VALUE_ROW_ORPHAN_PARTNER + " AS row_type, " + Statement.NO_ID + " AS category_id, " + "NULL AS category_label, " + "NULL AS category_icon, " + VALUE_DISPLAY_ORDER_FIRST + " AS category_display_order, " + VALUE_ORPHAN_CATEGORY_VISIBILITY + " AS category_is_visible, " + "NULL AS category_is_collapsed, " + "NULL AS category_is_partners_visible, " + "location.id AS location_id, " + "location.street AS location_street, " + "location.zip_code AS location_zip_code, " + "location.city AS location_city, " + "location.is_exchange_office AS location_is_exchange_office, " + "location.display_location AS location_display_location, " + "location_metadata.is_visible AS location_is_visible, " + "partner.is_gonette_headquarter AS partner_is_gonette_headquarter, " + "partner.name AS partner_name" + FROM_PARTNER + JOIN_LOCATION_AND_METADATA_ON_PARTNER + " WHERE partner.name LIKE :search" + " AND partner.main_category_id = " + Statement.NO_ID + " " + " AND location.display_location <> 0 "; private static final String SQL_CATEGORIES = "SELECT " + VALUE_ROW_CATEGORY + " AS row_type, " + "category.id AS category_id, " + "category.label AS category_label, " + "category.icon AS category_icon, " + "category.display_order AS category_display_order, " + "category_metadata.is_visible AS category_is_visible, " + "category_metadata.is_collapsed AS category_is_collapsed, " + "TOTAL(main_location_metadata.is_visible) AS category_is_partners_visible, " + "NULL AS location_id, " + "NULL AS location_street, " + "NULL AS location_zip_code, " + "NULL AS location_city, " + "NULL AS location_is_exchange_office, " + "NULL AS location_display_location, " + "NULL AS location_is_visible, " + "NULL AS partner_is_gonette_headquarter, " + "NULL AS partner_name" + FROM_CATEGORY_AND_METADATA + LEFT_JOIN_MAIN_PARTNER_ON_CATEGORY + LEFT_JOIN_MAIN_LOCATION_AND_METADATA_ON_MAIN_PARTNER + " WHERE main_partner.name LIKE :search " + " AND main_location.display_location <> 0 " + " GROUP BY category.id "; private static final String SQL_FOOTERS = "SELECT " + VALUE_ROW_FOOTER + " AS row_type, " + "category.id AS category_id, " + "NULL AS category_label, " + "NULL AS category_icon, " + "category.display_order AS category_display_order, " + "NULL AS category_is_visible, " + "NULL AS category_is_collapsed, " + "NULL AS category_is_partners_visible, " + "NULL AS location_id, " + "NULL AS location_street, " + "NULL AS location_zip_code, " + "NULL AS location_city, " + "NULL AS location_is_exchange_office, " + "NULL AS location_display_location, " + "NULL AS location_is_visible, " + "NULL AS partner_is_gonette_headquarter, " + "NULL AS partner_name" + FROM_CATEGORY + LEFT_JOIN_MAIN_PARTNER_ON_CATEGORY + LEFT_JOIN_MAIN_LOCATION_ON_MAIN_PARTNER + " WHERE main_partner.main_category_id IS NOT NULL " + " AND main_partner.name LIKE :search " + " AND main_location.display_location <> 0 " + " GROUP BY category.id "; private static final String SQL_MAIN_PARTNERS = "SELECT " + VALUE_ROW_MAIN_PARTNER + " AS row_type, " + "category.id AS category_id, " + "NULL AS category_label, " + "NULL AS category_icon, " + "category.display_order AS category_display_order, " + "category_metadata.is_visible AS category_is_visible, " + "NULL AS category_is_collapsed, " + "NULL AS category_is_partners_visible, " + "main_location.id AS location_id, " + "main_location.street AS location_street, " + "main_location.zip_code AS location_zip_code, " + "main_location.city AS location_city, " + "main_location.is_exchange_office AS location_is_exchange_office, " + "main_location.display_location AS location_display_location, " + "main_location_metadata.is_visible AS location_is_visible, " + "main_partner.is_gonette_headquarter AS partner_is_gonette_headquarter, " + "main_partner.name AS partner_name" + FROM_CATEGORY_AND_METADATA + JOIN_MAIN_PARTNER_ON_CATEGORY + LEFT_JOIN_MAIN_LOCATION_AND_METADATA_ON_MAIN_PARTNER + " WHERE main_partner.name LIKE :search " + " AND category_metadata.is_collapsed = 0 " + " AND main_location.display_location <> 0 "; public static final String SQL = SQL_ORPHAN_PARTNERS + " UNION " + SQL_CATEGORIES + " UNION " + SQL_FOOTERS + " UNION " + SQL_MAIN_PARTNERS + " ORDER BY category.display_order ASC, category.id ASC, row_type ASC"; @Retention(SOURCE) @IntDef({ VALUE_ROW_ORPHAN_PARTNER, VALUE_ROW_CATEGORY, VALUE_ROW_MAIN_PARTNER, VALUE_ROW_FOOTER }) public @interface RowType { } }
package tsukurukai.gotoosanbashi.activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import java.util.ArrayList; import java.util.List; import tsukurukai.gotoosanbashi.R; import tsukurukai.gotoosanbashi.models.Spot; public class MapsActivity extends ActionBarActivity implements OnMapReadyCallback { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private List<Spot> spots; public static Intent createIntent(Context context) { Intent intent = new Intent(context, MapsActivity.class); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addCourse(0); setContentView(R.layout.activity_maps); setUpMapIfNeeded(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); final Button button1 = (Button)findViewById(R.id.course_1); final Button button2 = (Button)findViewById(R.id.course_2); final Button button3 = (Button)findViewById(R.id.course_3); final Button courseSave = (Button)findViewById(R.id.course_save); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addCourse(0); setUpMapIfNeeded(); selectedButton(button1); unSelectedButton(button2); unSelectedButton(button3); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addCourse(1); setUpMapIfNeeded(); selectedButton(button2); unSelectedButton(button1); unSelectedButton(button3); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addCourse(2); setUpMapIfNeeded(); selectedButton(button3); unSelectedButton(button1); unSelectedButton(button2); } }); courseSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE); int selectedCourse = sharedPreferences.getInt("selected_course", 0); int spotsCount = sharedPreferences.getInt("course:" + selectedCourse + ":spotsCount", 0); SharedPreferences saveCourseSharedPreferences = getSharedPreferences("saved_courses", MODE_PRIVATE); int savedCourseCount = saveCourseSharedPreferences.getInt("saved_course_count", 0); for (int i = 0; i < spotsCount; i++) { String spotJson = sharedPreferences.getString("course:" + selectedCourse + ":spots:" + i, ""); saveCourseSharedPreferences .edit() .putString("saved_course:" + savedCourseCount + ":spots:" + i, spotJson) .apply(); } saveCourseSharedPreferences .edit() .putLong("saved_course_time:" + savedCourseCount, System.currentTimeMillis()) .apply(); saveCourseSharedPreferences .edit() .putInt("saved_course_count", ++savedCourseCount) .commit(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p/> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p/> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not * have been completely destroyed during this process (it is likely that it would only be * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this * method in {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } private void setUpMap() { mMap.setMyLocationEnabled(true); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(35.469561, 139.599325), 10)); } private void addMarker() { for (Spot spot: spots) { mMap.addMarker(new MarkerOptions().position(new LatLng(spot.getLat(), spot.getLon())).title(spot.getName())); } } private void addPolyLine(GoogleMap googleMap) { PolylineOptions polyLine = new PolylineOptions(); for (Spot spot: spots) { polyLine.geodesic(true).add(new LatLng(spot.getLat(), spot.getLon())); } googleMap.addPolyline(polyLine); } private void addCourse(int courseId) { spots = new ArrayList<>(); SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE); int spotsCount = sharedPreferences.getInt("course:" + courseId + ":spotsCount", 0); for (int i = 0; i < spotsCount; i++) { spots.add(Spot.fromJson(sharedPreferences.getString("course:" + courseId + ":spots:" + i, ""))); } sharedPreferences .edit() .putInt("selected_course", courseId) .commit(); } private void selectedButton(Button button) { button.setBackground(getResources().getDrawable(R.drawable.course_button_selected)); button.setTextColor(getResources().getColor(R.color.white)); } private void unSelectedButton(Button button) { button.setBackground(getResources().getDrawable(R.drawable.course_button)); button.setTextColor(getResources().getColor(R.color.text_color_black_87)); } @Override public void onMapReady(GoogleMap googleMap) { googleMap.clear(); addMarker(); addPolyLine(googleMap); } }
package com.vip.saturn.job.console.service.impl; import com.vip.saturn.job.console.domain.*; import com.vip.saturn.job.console.domain.ExecutionInfo.ExecutionStatus; import com.vip.saturn.job.console.exception.SaturnJobConsoleException; import com.vip.saturn.job.console.mybatis.entity.JobConfig4DB; import com.vip.saturn.job.console.mybatis.service.CurrentJobConfigService; import com.vip.saturn.job.console.repository.zookeeper.CuratorRepository.CuratorFrameworkOp; import com.vip.saturn.job.console.service.RegistryCenterService; import com.vip.saturn.job.console.service.SystemConfigService; import com.vip.saturn.job.console.service.helper.SystemConfigProperties; import com.vip.saturn.job.console.utils.JobNodePath; import com.vip.saturn.job.console.utils.SaturnConstants; import com.vip.saturn.job.sharding.node.SaturnExecutorsNode; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.data.Stat; import org.assertj.core.util.Lists; import org.assertj.core.util.Maps; import org.hamcrest.core.StringContains; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.domain.Pageable; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.vip.saturn.job.console.service.impl.JobServiceImpl.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class JobServiceImplTest { @Mock private CuratorFrameworkOp curatorFrameworkOp; @Mock private CurrentJobConfigService currentJobConfigService; @Mock private RegistryCenterService registryCenterService; @Mock private SystemConfigService systemConfigService; @InjectMocks private JobServiceImpl jobService; private String namespace = "saturn-job-test.vip.com"; private String jobName = "testJob"; private String userName = "weicong01.li"; @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testGetGroup() { when(currentJobConfigService.findConfigsByNamespace(namespace)) .thenReturn(Lists.newArrayList(new JobConfig4DB())); assertEquals(jobService.getGroups(namespace).size(), 1); } @Test public void testGetDependingJobs() throws SaturnJobConsoleException { String dependedJob = "dependedJob"; String dependingJob = "dependingJob"; JobConfig4DB dependedJobConfig = new JobConfig4DB(); dependedJobConfig.setJobName(dependedJob); dependedJobConfig.setDependencies(dependingJob); JobConfig4DB dependingJobConfig = new JobConfig4DB(); dependingJobConfig.setJobName(dependingJob); dependingJobConfig.setEnabled(Boolean.TRUE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, dependedJob)) .thenReturn(dependedJobConfig); when(currentJobConfigService.findConfigsByNamespace(namespace)) .thenReturn(Lists.newArrayList(dependedJobConfig, dependingJobConfig)); List<DependencyJob> dependingJobs = jobService.getDependingJobs(namespace, dependedJob); assertEquals(dependingJobs.size(), 1); assertEquals(dependingJobs.get(0).getJobName(), dependingJob); // test not exist job when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, dependedJob)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", dependedJob)); jobService.getDependingJobs(namespace, dependedJob); } @Test public void testGetDependedJobs() throws SaturnJobConsoleException { String dependedJob = "dependedJob"; String dependingJob = "dependingJob"; JobConfig4DB dependedJobConfig = new JobConfig4DB(); dependedJobConfig.setJobName(dependedJob); dependedJobConfig.setEnabled(Boolean.TRUE); dependedJobConfig.setDependencies(dependingJob); JobConfig4DB dependingJobConfig = new JobConfig4DB(); dependingJobConfig.setJobName(dependingJob); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, dependingJob)) .thenReturn(dependingJobConfig); when(currentJobConfigService.findConfigsByNamespace(namespace)) .thenReturn(Lists.newArrayList(dependedJobConfig, dependingJobConfig)); List<DependencyJob> dependingJobs = jobService.getDependedJobs(namespace, dependingJob); assertEquals(dependingJobs.size(), 1); assertEquals(dependingJobs.get(0).getJobName(), dependedJob); // test not exist job when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, dependingJob)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", dependingJob)); jobService.getDependedJobs(namespace, dependingJob); } @Test public void testEnableJobFailByJobNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", jobName)); jobService.enableJob(namespace, jobName, userName); } @Test public void testEnableJobFailByJobHasEnabled() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.TRUE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", jobName)); jobService.enableJob(namespace, jobName, userName); } @Test public void testEnabledJobFailByJobHasFinished() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.FALSE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "completed")))) .thenReturn(false); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "running")))) .thenReturn(true); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%sSTOPPED", jobName)); jobService.enableJob(namespace, jobName, userName); } @Test public void testEnabledJobSuccess() throws Exception { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.FALSE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "completed")))) .thenReturn(true); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "running")))) .thenReturn(false); jobService.enableJob(namespace, jobName, userName); verify(currentJobConfigService).updateByPrimaryKey(jobConfig4DB); verify(curatorFrameworkOp).update(eq(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_ENABLED)), eq(true)); } @Test public void testDisableJobFailByJobNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", jobName)); jobService.disableJob(namespace, jobName, userName); } @Test public void testDisableJobFailByJobHasDisabled() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.FALSE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", jobName)); jobService.disableJob(namespace, jobName, userName); } @Test public void testDisableJobFailByUpdateError() throws Exception { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.TRUE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(currentJobConfigService.updateByPrimaryKey(jobConfig4DB)) .thenThrow(new SaturnJobConsoleException("update error")); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("update error"); jobService.disableJob(namespace, jobName, userName); } @Test public void testDisableJobSuccess() throws Exception { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.TRUE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); jobService.disableJob(namespace, jobName, userName); verify(currentJobConfigService).updateByPrimaryKey(jobConfig4DB); verify(curatorFrameworkOp).update(eq(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_ENABLED)), eq(false)); } @Test public void testRemoveJobFailByNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", jobName)); jobService.removeJob(namespace, jobName); } @Test public void testRemoveJobFailByNotStopped() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.TRUE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "completed")))) .thenReturn(true); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "running")))) .thenReturn(false); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)STOPPED", jobName)); jobService.removeJob(namespace, jobName); } @Test public void testRemoveJobFailByLimitTime() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.FALSE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "completed")))) .thenReturn(true); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "running")))) .thenReturn(false); Stat stat = new Stat(); stat.setCtime(System.currentTimeMillis()); when(curatorFrameworkOp.getStat(eq(JobNodePath.getJobNodePath(jobName)))).thenReturn(stat); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)%d", jobName, SaturnConstants.JOB_CAN_BE_DELETE_TIME_LIMIT / 60000)); jobService.removeJob(namespace, jobName); } @Test public void testRemoveJobFailByDeleteDBError() throws Exception { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setId(1L); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.FALSE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "completed")))) .thenReturn(true); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "running")))) .thenReturn(false); Stat stat = new Stat(); stat.setCtime(System.currentTimeMillis() - (3 * 60 * 1000)); when(curatorFrameworkOp.getStat(eq(JobNodePath.getJobNodePath(jobName)))).thenReturn(stat); when(currentJobConfigService.deleteByPrimaryKey(jobConfig4DB.getId())) .thenThrow(new SaturnJobConsoleException("delete error")); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("delete error"); jobService.removeJob(namespace, jobName); } @Test public void testRemoveJobSuccess() throws Exception { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setId(1L); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(Boolean.FALSE); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "completed")))) .thenReturn(true); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getExecutionNodePath(jobName, "1", "running")))) .thenReturn(false); Stat stat = new Stat(); stat.setCtime(System.currentTimeMillis() - (3 * 60 * 1000)); when(curatorFrameworkOp.getStat(eq(JobNodePath.getJobNodePath(jobName)))).thenReturn(stat); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getConfigNodePath(jobName, "toDelete")))).thenReturn(true); jobService.removeJob(namespace, jobName); verify(currentJobConfigService).deleteByPrimaryKey(jobConfig4DB.getId()); verify(curatorFrameworkOp).deleteRecursive(eq(JobNodePath.getConfigNodePath(jobName, "toDelete"))); verify(curatorFrameworkOp).create(eq(JobNodePath.getConfigNodePath(jobName, "toDelete"))); } @Test public void testGetCandidateExecutorsFailByNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%sExecutor", jobName)); jobService.getCandidateExecutors(namespace, jobName); } @Test public void testGetCandidaExecutorsByExecutorPathNotExist() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(eq(SaturnExecutorsNode.getExecutorsNodePath()))).thenReturn(false); assertTrue(jobService.getCandidateExecutors(namespace, jobName).isEmpty()); } @Test public void testGetCandidateExecutors() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(eq(SaturnExecutorsNode.getExecutorsNodePath()))).thenReturn(true); String executor = "executor"; when(curatorFrameworkOp.getChildren(eq(SaturnExecutorsNode.getExecutorsNodePath()))) .thenReturn(Lists.newArrayList(executor)); assertEquals(jobService.getCandidateExecutors(namespace, jobName).size(), 1); when(curatorFrameworkOp.checkExists(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_PREFER_LIST))) .thenReturn(true); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_PREFER_LIST))) .thenReturn("preferExecutor2,@preferExecutor3"); assertEquals(jobService.getCandidateExecutors(namespace, jobName).size(), 3); } @Test public void testSetPreferListFailByNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%sExecutor", jobName)); jobService.setPreferList(namespace, jobName, "preferList", userName); } @Test public void testSetPreferListFailByLocalModeNotStop() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); jobConfig4DB.setLocalMode(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)Executor", jobName)); jobService.setPreferList(namespace, jobName, "preferList", userName); } @Test public void testSetPreferListSuccess() throws Exception { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(false); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); String preferList = "preferList"; jobService.setPreferList(namespace, jobName, preferList, userName); verify(currentJobConfigService) .updateNewAndSaveOld2History(any(JobConfig4DB.class), eq(jobConfig4DB), eq(userName)); verify(curatorFrameworkOp) .update(eq(SaturnExecutorsNode.getJobConfigPreferListNodePath(jobName)), eq(preferList)); verify(curatorFrameworkOp).delete(eq(SaturnExecutorsNode.getJobConfigForceShardNodePath(jobName))); verify(curatorFrameworkOp).create(eq(SaturnExecutorsNode.getJobConfigForceShardNodePath(jobName))); } @Test public void testAddJobFailByWithoutJobName() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(""); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByJobNameInvalid() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName("!@ expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("0-9a-zA-Z_"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByDependingJobNameInvalid() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setDependencies("12!@@"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("0-9a-zA-Z_,"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByWithoutJobType() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(""); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByJobTypeInvalid() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType("unknown"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(""); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByJavaJobWithoutClass() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.JAVA_JOB.name()); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("java"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByShellJobWithoutCorn() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.SHELL_JOB.name()); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("JAVA/SHELLcron"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByShellJobCornInvalid() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.SHELL_JOB.name()); jobConfig.setCron("xxxxx"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("cron"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByLocalModeJobWithoutShardingItem() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(true); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(""); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByNoLocalModeJobWithoutShardingItem() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(false); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("1"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByNoLocalModeJoShardingItemInvalid() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(false); jobConfig.setShardingTotalCount(1); jobConfig.setShardingItemParameters("001"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("'%s'", "001")); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByNoLocalModeJoShardingItemInvalidNumber() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(false); jobConfig.setShardingTotalCount(1); jobConfig.setShardingItemParameters("x=x"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("'%s'", "x=x")); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByAddSystemJob() throws SaturnJobConsoleException { JobConfig jobConfig = createValidJob(); jobConfig.setJobMode(JobMode.SYSTEM_PREFIX); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(""); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByJobIsExist() throws SaturnJobConsoleException { JobConfig jobConfig = createValidJob(); JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigByNamespaceAndJobName(eq(namespace), eq(jobName))) .thenReturn(jobConfig4DB); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)", jobName)); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByLimitNum() throws SaturnJobConsoleException { JobConfig jobConfig = createValidJob(); JobConfig4DB jobConfig4DB = new JobConfig4DB(); when(systemConfigService.getIntegerValue(eq(SystemConfigProperties.MAX_JOB_NUM), eq(100))).thenReturn(1); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%d)%s", 1, jobName)); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobSuccess() throws Exception { JobConfig jobConfig = createValidJob(); when(registryCenterService.getCuratorFrameworkOp(eq(namespace))).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getJobNodePath(jobConfig.getJobName())))).thenReturn(true); jobService.addJob(namespace, jobConfig, userName); verify(curatorFrameworkOp).deleteRecursive(eq(JobNodePath.getJobNodePath(jobConfig.getJobName()))); verify(currentJobConfigService).create(any(JobConfig4DB.class)); } @Test public void testCopyJobSuccess() throws Exception { JobConfig jobConfig = createValidJob(); when(registryCenterService.getCuratorFrameworkOp(eq(namespace))).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(eq(JobNodePath.getJobNodePath(jobConfig.getJobName())))).thenReturn(true); JobConfig4DB jobConfig4DB = new JobConfig4DB(); when(currentJobConfigService.findConfigByNamespaceAndJobName(eq(namespace), eq("copyJob"))) .thenReturn(jobConfig4DB); jobService.copyJob(namespace, jobConfig, "copyJob", userName); verify(curatorFrameworkOp).deleteRecursive(eq(JobNodePath.getJobNodePath(jobConfig.getJobName()))); verify(currentJobConfigService).create(any(JobConfig4DB.class)); } private JobConfig createValidJob() { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(false); jobConfig.setShardingTotalCount(1); jobConfig.setShardingItemParameters("0=1"); return jobConfig; } @Test public void testAddJobFailByNoLocalModeJoShardingItemLess() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(false); jobConfig.setShardingTotalCount(2); jobConfig.setShardingItemParameters("0=1"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(""); jobService.addJob(namespace, jobConfig, userName); } @Test public void testAddJobFailByLocalModeJobShardingItemInvalid() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); jobConfig.setJobType(JobType.MSG_JOB.name()); jobConfig.setJobClass("testCLass"); jobConfig.setLocalMode(true); jobConfig.setShardingItemParameters("test"); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("*=xx"); jobService.addJob(namespace, jobConfig, userName); } @Test public void testGetUnSystemJobsWithCondition() throws SaturnJobConsoleException { String namespace = "ns1"; String jobName = "testJob"; int count = 4; Map<String, Object> condition = buildCondition(null); when(currentJobConfigService .findConfigsByNamespaceWithCondition(eq(namespace), eq(condition), Matchers.<Pageable>anyObject())) .thenReturn(buildJobConfig4DBList(namespace, jobName, count)); assertTrue(jobService.getUnSystemJobsWithCondition(namespace, condition, 1, 25).size() == count); } @Test public void testGetMaxJobNum() { assertEquals(jobService.getMaxJobNum(), 100); } @Test public void testJobIncExceeds() throws SaturnJobConsoleException { assertFalse(jobService.jobIncExceeds(namespace, 0, 1)); assertFalse(jobService.jobIncExceeds(namespace, 100, 1)); } @Test public void testGetUnSystemJob() { when(currentJobConfigService.findConfigsByNamespace(namespace)) .thenReturn(Lists.newArrayList(new JobConfig4DB())); assertEquals(jobService.getUnSystemJobs(namespace).size(), 1); } @Test public void testGetUnSystemJobWithConditionAndStatus() throws SaturnJobConsoleException { String namespace = "ns1"; String jobName = "testJob"; int count = 4; List<JobConfig4DB> jobConfig4DBList = buildJobConfig4DBList(namespace, jobName, count); Map<String, Object> condition = buildCondition(JobStatus.READY); when(currentJobConfigService .findConfigsByNamespaceWithCondition(eq(namespace), eq(condition), Matchers.<Pageable>anyObject())) .thenReturn(jobConfig4DBList); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); for (int i = 0; i < count; i++) { JobConfig4DB jobConfig4DB = jobConfig4DBList.get(i); // index job enabled true jobConfig4DB.setEnabled(i % 2 == 1); when(currentJobConfigService.findConfigByNamespaceAndJobName(eq(namespace), eq(jobConfig4DB.getJobName()))) .thenReturn(jobConfig4DB); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobConfig4DB.getJobName()))) .thenReturn(null); } assertTrue(jobService.getUnSystemJobsWithCondition(namespace, condition, 1, 25).size() == (count / 2)); } @Test public void testGetUnSystemJobNames() { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); assertEquals(jobService.getUnSystemJobs(namespace).size(), 1); } @Test public void testGetJobName() { when(currentJobConfigService.findConfigNamesByNamespace(namespace)).thenReturn(null); assertTrue(jobService.getJobNames(namespace).isEmpty()); when(currentJobConfigService.findConfigNamesByNamespace(namespace)).thenReturn(Lists.newArrayList(jobName)); assertEquals(jobService.getJobNames(namespace).size(), 1); } @Test public void testPersistJobFromDb() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); jobService.persistJobFromDB(namespace, jobConfig); jobService.persistJobFromDB(jobConfig, curatorFrameworkOp); } @Test public void testImportFailByWithoutJobName() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByJobNameInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName("!@avb"); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("0-9a-zA-Z_")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByWithoutJobType() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByUnknownJobType() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn("xxx"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByJavaJobWithoutClass() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.JAVA_JOB.name()); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("java")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByShellJobWithoutCron() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.SHELL_JOB.name()); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("croncron")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByShellJobCronInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.SHELL_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_CRON))).thenReturn("xxxx"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("cron")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByWithoutShardingCount() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByShardingCountInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("xxx"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByShardingCountLess4One() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("0"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("1")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByTimeoutSecondsInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_TIMEOUT_SECONDS))) .thenReturn("error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("Kill/")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByLocalJobWithoutShardingParam() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_LOCAL_MODE))) .thenReturn("true"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByLocalJobShardingParamInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_LOCAL_MODE))) .thenReturn("true"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("*=xx")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByShardingParamLess4Count() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("2"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByProcessCountIntervalSecondsInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp .getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_PROCESS_COUNT_INTERVAL_SECONDS))) .thenReturn("error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByLoadLevelInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_LOAD_LEVEL))) .thenReturn("error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByJobDegreeInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_DEGREE))) .thenReturn("error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByJobModeInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_MODE))) .thenReturn(JobMode.SYSTEM_PREFIX); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByDependenciesInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_DEPENDENCIES))) .thenReturn("!@error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("0-9a-zA-Z_,")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByTimeout4AlarmSecondsInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_TIMEOUT_4_ALARM_SECONDS))) .thenReturn("error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByTimeZoneInvalid() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_TIME_ZONE))) .thenReturn("error"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByLocalJobNotSupportFailover() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("*=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_LOCAL_MODE))) .thenReturn("true"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_FAILOVER))) .thenReturn("true"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("failover")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByVMSJobNotSupportFailover() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("*=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_LOCAL_MODE))) .thenReturn("false"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_FAILOVER))) .thenReturn("true"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("failover")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailByVMSJobNotSupportRerun() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_RERUN))).thenReturn("true"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(StringContains.containsString("rerun")); jobService.importJobs(namespace, data, userName); } @Test public void testImportFailTotalCountLimit() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); when(systemConfigService.getIntegerValue(SystemConfigProperties.MAX_JOB_NUM, 100)).thenReturn(1); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%d)", 1)); jobService.importJobs(namespace, data, userName); } @Test public void testImportSuccess() throws SaturnJobConsoleException, IOException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.MSG_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_CLASS))) .thenReturn("vip"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_ITEM_PARAMETERS))) .thenReturn("0=1"); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); when(systemConfigService.getIntegerValue(SystemConfigProperties.MAX_JOB_NUM, 100)).thenReturn(100); jobService.importJobs(namespace, data, userName); } @Test public void testExport() throws SaturnJobConsoleException, IOException, BiffException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigsByNamespace(namespace)).thenReturn(Lists.newArrayList(jobConfig4DB)); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); File file = jobService.exportJobs(namespace); MultipartFile data = new MockMultipartFile("test.xls", new FileInputStream(file)); Workbook workbook = Workbook.getWorkbook(data.getInputStream()); assertNotNull(workbook); Sheet[] sheets = workbook.getSheets(); assertEquals(sheets.length, 1); } @Test public void testIsJobShardingAllocatedExecutor() throws SaturnJobConsoleException { String namespace = "ns1"; String jobName = "testJob"; String executor = "executor1"; when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList(executor)); when(curatorFrameworkOp.getData(JobNodePath.getServerNodePath(jobName, executor, "sharding"))) .thenReturn("true"); assertTrue(jobService.isJobShardingAllocatedExecutor(namespace, jobName)); } @Test public void testGetExecutionStatusSuccessfully() throws Exception { String namespace = "ns1"; String jobName = "jobA"; String executorName = "exec1"; when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)) .thenReturn(buildJobConfig4DB(namespace, jobName)); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); List<String> shardItems = Lists.newArrayList("0", "1", "2", "3", "4"); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))).thenReturn(shardItems); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList(executorName)); when(curatorFrameworkOp.getData(JobNodePath.getServerSharding(jobName, executorName))).thenReturn("0,1,2,3,4"); when(curatorFrameworkOp.checkExists(JobNodePath.getEnabledReportNodePath(jobName))).thenReturn(true); when(curatorFrameworkOp.getData(JobNodePath.getEnabledReportNodePath(jobName))).thenReturn("true"); // 0running mockExecutionStatusNode(true, false, false, false, false, executorName, jobName, "0"); // 1completed mockExecutionStatusNode(false, true, false, false, false, executorName, jobName, "1"); // 2fail mockExecutionStatusNode(false, true, false, true, false, executorName, jobName, "2"); // 3failover mockExecutionStatusNode(true, false, true, false, false, executorName, jobName, "3"); // 4timeout mockExecutionStatusNode(false, true, false, false, true, executorName, jobName, "4"); mockJobMessage(jobName, "0", "this is message"); mockJobMessage(jobName, "1", "this is message"); mockJobMessage(jobName, "2", "this is message"); mockJobMessage(jobName, "3", "this is message"); mockJobMessage(jobName, "4", "this is message"); mockTimezone(jobName, "Asia/Shanghai"); mockExecutionNodeData(jobName, "0", "lastBeginTime", "0"); mockExecutionNodeData(jobName, "0", "nextFireTime", "2000"); mockExecutionNodeData(jobName, "0", "lastCompleteTime", "1000"); mockExecutionNodeData(jobName, "1", "lastBeginTime", "0"); mockExecutionNodeData(jobName, "1", "nextFireTime", "2000"); mockExecutionNodeData(jobName, "1", "lastCompleteTime", "1000"); mockExecutionNodeData(jobName, "2", "lastBeginTime", "0"); mockExecutionNodeData(jobName, "2", "nextFireTime", "2000"); mockExecutionNodeData(jobName, "2", "lastCompleteTime", "1000"); mockExecutionNodeData(jobName, "3", "lastBeginTime", "0"); mockExecutionNodeData(jobName, "3", "nextFireTime", "2000"); mockExecutionNodeData(jobName, "3", "lastCompleteTime", "1000"); mockExecutionNodeData(jobName, "4", "nextFireTime", "2000"); mockExecutionNodeData(jobName, "4", "lastCompleteTime", "1000"); List<ExecutionInfo> result = jobService.getExecutionStatus(namespace, jobName); assertEquals("size should be 5", 5, result.size()); // verify 0 ExecutionInfo executionInfo = result.get(0); assertEquals("executorName not equal", executorName, executionInfo.getExecutorName()); assertEquals("jobName not equal", jobName, executionInfo.getJobName()); assertEquals("status not equal", ExecutionStatus.RUNNING, executionInfo.getStatus()); assertEquals("jobMsg not equal", "this is message", executionInfo.getJobMsg()); assertFalse("failover should be false", executionInfo.getFailover()); assertEquals("lastbeginTime not equal", "1970-01-01 08:00:00", executionInfo.getLastBeginTime()); assertEquals("nextFireTime not equal", "1970-01-01 08:00:02", executionInfo.getNextFireTime()); assertEquals("lastCompleteTime not equal", "1970-01-01 08:00:01", executionInfo.getLastCompleteTime()); // verify 1 executionInfo = result.get(1); assertEquals("executorName not equal", executorName, executionInfo.getExecutorName()); assertEquals("jobName not equal", jobName, executionInfo.getJobName()); assertEquals("status not equal", ExecutionStatus.COMPLETED, executionInfo.getStatus()); assertEquals("jobMsg not equal", "this is message", executionInfo.getJobMsg()); assertFalse("failover should be false", executionInfo.getFailover()); assertEquals("lastbeginTime not equal", "1970-01-01 08:00:00", executionInfo.getLastBeginTime()); assertEquals("nextFireTime not equal", "1970-01-01 08:00:02", executionInfo.getNextFireTime()); assertEquals("lastCompleteTime not equal", "1970-01-01 08:00:01", executionInfo.getLastCompleteTime()); // verify 2 executionInfo = result.get(2); assertEquals("executorName not equal", executorName, executionInfo.getExecutorName()); assertEquals("jobName not equal", jobName, executionInfo.getJobName()); assertEquals("status not equal", ExecutionStatus.FAILED, executionInfo.getStatus()); assertEquals("jobMsg not equal", "this is message", executionInfo.getJobMsg()); assertFalse("failover should be false", executionInfo.getFailover()); assertEquals("lastbeginTime not equal", "1970-01-01 08:00:00", executionInfo.getLastBeginTime()); assertEquals("nextFireTime not equal", "1970-01-01 08:00:02", executionInfo.getNextFireTime()); assertEquals("lastCompleteTime not equal", "1970-01-01 08:00:01", executionInfo.getLastCompleteTime()); // verify 3 executionInfo = result.get(3); assertEquals("executorName not equal", executorName, executionInfo.getExecutorName()); assertEquals("jobName not equal", jobName, executionInfo.getJobName()); assertEquals("status not equal", ExecutionStatus.RUNNING, executionInfo.getStatus()); assertEquals("jobMsg not equal", "this is message", executionInfo.getJobMsg()); assertTrue("failover should be false", executionInfo.getFailover()); assertEquals("lastbeginTime not equal", "1970-01-01 08:00:00", executionInfo.getLastBeginTime()); assertEquals("nextFireTime not equal", "1970-01-01 08:00:02", executionInfo.getNextFireTime()); assertEquals("lastCompleteTime not equal", "1970-01-01 08:00:01", executionInfo.getLastCompleteTime()); // verify 4 executionInfo = result.get(4); assertEquals("executorName not equal", executorName, executionInfo.getExecutorName()); assertEquals("jobName not equal", jobName, executionInfo.getJobName()); assertEquals("status not equal", ExecutionStatus.TIMEOUT, executionInfo.getStatus()); assertEquals("jobMsg not equal", "this is message", executionInfo.getJobMsg()); assertFalse("failover should be false", executionInfo.getFailover()); assertEquals("nextFireTime not equal", "1970-01-01 08:00:02", executionInfo.getNextFireTime()); assertEquals("lastCompleteTime not equal", "1970-01-01 08:00:01", executionInfo.getLastCompleteTime()); } private void mockExecutionNodeData(String jobName, String item, String nodeName, String data) { when(curatorFrameworkOp.getData(JobNodePath.getExecutionNodePath(jobName, item, nodeName))).thenReturn(data); } private void mockJobMessage(String jobName, String item, String msg) { when(curatorFrameworkOp.getData(JobNodePath.getExecutionNodePath(jobName, item, "jobMsg"))).thenReturn(msg); } private void mockTimezone(String jobName, String timezone) { when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, "timeZone"))).thenReturn(timezone); } private void mockExecutionStatusNode(boolean isRunning, boolean isCompleted, boolean isFailover, boolean isFailed, boolean isTimeout, String executorName, String jobName, String jobItem) { if (isRunning) { when(curatorFrameworkOp.getData(JobNodePath.getRunningNodePath(jobName, jobItem))).thenReturn(executorName); } if (isCompleted) { when(curatorFrameworkOp.getData(JobNodePath.getCompletedNodePath(jobName, jobItem))) .thenReturn(executorName); } if (isFailover) { when(curatorFrameworkOp.getData(JobNodePath.getFailoverNodePath(jobName, jobItem))) .thenReturn(executorName); when(curatorFrameworkOp.getMtime(JobNodePath.getFailoverNodePath(jobName, jobItem))).thenReturn(1L); } if (isFailed) { when(curatorFrameworkOp.checkExists(JobNodePath.getFailedNodePath(jobName, jobItem))).thenReturn(true); } if (isTimeout) { when(curatorFrameworkOp.checkExists(JobNodePath.getTimeoutNodePath(jobName, jobItem))).thenReturn(true); } } private JobConfig4DB buildJobConfig4DB(String namespace, String jobName) { JobConfig4DB config = new JobConfig4DB(); config.setNamespace(namespace); config.setJobName(jobName); config.setEnabled(true); config.setEnabledReport(true); config.setJobType(JobType.JAVA_JOB.toString()); return config; } private List<JobConfig4DB> buildJobConfig4DBList(String namespace, String jobName, int count) { List<JobConfig4DB> config4DBList = new ArrayList<>(); for (int i = 0; i < count; i++) { JobConfig4DB config = new JobConfig4DB(); config.setNamespace(namespace); config.setJobName(jobName + i); config.setEnabled(true); config.setEnabledReport(true); config.setJobType(JobType.JAVA_JOB.toString()); config4DBList.add(config); } return config4DBList; } private Map<String, Object> buildCondition(JobStatus jobStatus) { Map<String, Object> condition = new HashMap<>(); condition.put("jobStatus", jobStatus); return condition; } @Test public void testGetJobConfigFromZK() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_JOB_TYPE))) .thenReturn(JobType.SHELL_JOB.name()); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_SHARDING_TOTAL_COUNT))) .thenReturn("1"); when(curatorFrameworkOp .getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_PROCESS_COUNT_INTERVAL_SECONDS))) .thenReturn("100"); when(curatorFrameworkOp.getData(JobNodePath.getConfigNodePath(jobName, CONFIG_ITEM_TIMEOUT_SECONDS))) .thenReturn("100"); assertNotNull(jobService.getJobConfigFromZK(namespace, jobName)); } @Test public void testGetJobConfigFailByJobNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)", jobName)); jobService.getJobConfig(namespace, jobName); } @Test public void testGetJobConfigSuccess() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)) .thenReturn(new JobConfig4DB()); assertNotNull(jobService.getJobConfig(namespace, jobName)); } @Test public void testGetJobStatusFailByJobNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("%s", jobName)); jobService.getJobStatus(namespace, jobName); } @Test public void testGetJobStatusSuccess() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); assertEquals(jobService.getJobStatus(namespace, jobName), JobStatus.READY); JobConfig jobConfig = new JobConfig(); jobConfig.setEnabled(true); assertEquals(jobService.getJobStatus(namespace, jobConfig), JobStatus.READY); } @Test public void testGetServerList() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))).thenReturn(null); assertTrue(jobService.getJobServerList(namespace, jobName).isEmpty()); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList("executor")); assertEquals(jobService.getJobServerList(namespace, jobName).size(), 1); } @Test public void testGetJobConfigVoFailByJobNotExist() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)", jobName)); jobService.getJobConfigVo(namespace, jobName); } @Test public void testGetJobConfigVoSuccess() throws SaturnJobConsoleException { when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)) .thenReturn(new JobConfig4DB()); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); assertNotNull(jobService.getJobConfigVo(namespace, jobName)); } @Test public void testUpdateJobConfigFailByJobNotExist() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobConfig.getJobName())) .thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)", jobName)); jobService.getJobConfigVo(namespace, jobName); } @Test public void testUpdateJobConfigSuccess() throws SaturnJobConsoleException { JobConfig jobConfig = new JobConfig(); jobConfig.setJobName(jobName); JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobConfig.getJobName())) .thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); jobService.getJobConfigVo(namespace, jobName); } @Test public void testGetAllJobNamesFromZK() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.get$JobsNodePath())).thenReturn(null); assertTrue(jobService.getAllJobNamesFromZK(namespace).isEmpty()); when(curatorFrameworkOp.getChildren(JobNodePath.get$JobsNodePath())).thenReturn(Lists.newArrayList(jobName)); when(curatorFrameworkOp.checkExists(JobNodePath.getConfigNodePath(jobName))).thenReturn(true); assertEquals(jobService.getAllJobNamesFromZK(namespace).size(), 1); } @Test public void testUpdateJobCronFailByCronInvalid() throws SaturnJobConsoleException { String cron = "error"; expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("The cron expression is invalid: %s", cron)); jobService.updateJobCron(namespace, jobName, cron, null, userName); } @Test public void testUpdateJobCronFailByJobNotExist() throws SaturnJobConsoleException { String cron = "0 */2 * * * ?"; when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(JobNodePath.getConfigNodePath(jobName))).thenReturn(false); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("The job does not exists: %s", jobName)); jobService.updateJobCron(namespace, jobName, cron, null, userName); } @Test public void testUpdateJobCronSuccess() throws SaturnJobConsoleException { String cron = "0 */2 * * * ?"; Map<String, String> customContext = Maps.newHashMap(); customContext.put("test", "test"); CuratorFramework curatorFramework = mock(CuratorFramework.class); JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); when(curatorFrameworkOp.getCuratorFramework()).thenReturn(curatorFramework); when(curatorFramework.getNamespace()).thenReturn(namespace); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(JobNodePath.getConfigNodePath(jobName))).thenReturn(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); jobService.updateJobCron(namespace, jobName, cron, customContext, userName); } @Test public void testGetJobServers() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList("executor")); when(curatorFrameworkOp.getData(JobNodePath.getLeaderNodePath(jobName, "election/host"))) .thenReturn("127.0.0.1"); JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); assertEquals(jobService.getJobServers(namespace, jobName).size(), 1); } @Test public void testGetJobServerStatus() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList("executor")); assertEquals(jobService.getJobServersStatus(namespace, jobName).size(), 1); } @Test public void testRunAtOneFailByNotReady() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(false); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)READY", jobName)); jobService.runAtOnce(namespace, jobName); } @Test public void testRunAtOnceFailByNoExecutor() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))).thenReturn(null); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("executor(%s)", jobName)); jobService.runAtOnce(namespace, jobName); } @Test public void testRunAtOnceFailByNoOnlineExecutor() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList("executor")); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage("ONLINEexecutor"); jobService.runAtOnce(namespace, jobName); } @Test public void testRunAtOnceSuccess() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); String executor = "executor"; when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList(executor)); when(curatorFrameworkOp.getData(JobNodePath.getServerNodePath(jobName, executor, "status"))).thenReturn("true"); jobService.runAtOnce(namespace, jobName); verify(curatorFrameworkOp).create(JobNodePath.getRunOneTimePath(jobName, executor)); } @Test public void testStopAtOneFailByNotStopping() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("(%s)STOPPING", jobName)); jobService.stopAtOnce(namespace, jobName); } @Test public void testStopAtOnceFailByNoExecutor() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(false); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(JobNodePath.getExecutionNodePath(jobName, "1", "running"))) .thenReturn(true); expectedException.expect(SaturnJobConsoleException.class); expectedException.expectMessage(String.format("executor(%s)", jobName)); jobService.stopAtOnce(namespace, jobName); } @Test public void testStopAtOnceSuccess() throws SaturnJobConsoleException { JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(false); String executor = "executor"; when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); when(curatorFrameworkOp.checkExists(JobNodePath.getExecutionNodePath(jobName, "1", "running"))) .thenReturn(true); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList(executor)); when(curatorFrameworkOp.getData(JobNodePath.getServerNodePath(jobName, executor, "status"))).thenReturn("true"); jobService.stopAtOnce(namespace, jobName); verify(curatorFrameworkOp).create(JobNodePath.getStopOneTimePath(jobName, executor)); } @Test public void testGetExecutionStatusByJobHasStopped() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); // test get execution status by job has stopped JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setJobName(jobName); jobConfig4DB.setEnabled(false); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); assertTrue(jobService.getExecutionStatus(namespace, jobName).isEmpty()); } @Test public void testGetExecutionStatusByWithoutItem() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))).thenReturn(null); assertTrue(jobService.getExecutionStatus(namespace, jobName).isEmpty()); } @Test public void testGetExecutionStatus() throws SaturnJobConsoleException { when(registryCenterService.getCuratorFrameworkOp(namespace)).thenReturn(curatorFrameworkOp); JobConfig4DB jobConfig4DB = new JobConfig4DB(); jobConfig4DB.setEnabled(true); when(currentJobConfigService.findConfigByNamespaceAndJobName(namespace, jobName)).thenReturn(jobConfig4DB); when(curatorFrameworkOp.getChildren(JobNodePath.getExecutionNodePath(jobName))) .thenReturn(Lists.newArrayList("1")); when(curatorFrameworkOp.getChildren(JobNodePath.getServerNodePath(jobName))) .thenReturn(Lists.newArrayList("server")); when(curatorFrameworkOp.getData(JobNodePath.getServerSharding(jobName, "server"))).thenReturn("0"); } }
package com.axelor.apps.crm.service; import java.math.BigDecimal; import javax.persistence.Query; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import com.axelor.apps.base.db.ITarget; import com.axelor.apps.base.db.Team; import com.axelor.auth.db.User; import com.axelor.apps.crm.db.Target; import com.axelor.apps.crm.db.TargetConfiguration; import com.axelor.apps.crm.db.repo.TargetRepository; import com.axelor.apps.crm.exception.IExceptionMessage; import com.axelor.db.JPA; import com.axelor.exception.AxelorException; import com.axelor.exception.db.IException; import com.axelor.i18n.I18n; import com.google.inject.Inject; import com.google.inject.persist.Transactional; public class TargetService extends TargetRepository{ @Inject private EventService eventService; @Inject private OpportunityService opportunityService; public void createsTargets(TargetConfiguration targetConfiguration) throws AxelorException { if(targetConfiguration.getPeriodTypeSelect() == ITarget.NONE) { Target target = this.createTarget(targetConfiguration, targetConfiguration.getFromDate(), targetConfiguration.getToDate()); this.update(target); } else { LocalDate oldDate = targetConfiguration.getFromDate(); for(LocalDate date = oldDate ; date.isBefore(targetConfiguration.getToDate()) || date.isEqual(targetConfiguration.getToDate()); date = this.getNextDate(targetConfiguration.getPeriodTypeSelect(), date)) { Target target2 = all().filter("self.user = ?1 AND self.team = ?2 AND self.periodTypeSelect = ?3 AND self.fromDate >= ?4 AND self.toDate <= ?5 AND " + "((self.callEmittedNumberTarget > 0 AND ?6 > 0) OR (self.meetingNumberTarget > 0 AND ?7 > 0) OR " + "(self.opportunityAmountWonTarget > 0.00 AND ?8 > 0.00) OR (self.opportunityCreatedNumberTarget > 0 AND ?9 > 0) OR (self.opportunityCreatedWonTarget > 0 AND ?10 > 0))", targetConfiguration.getUser(), targetConfiguration.getTeam(), targetConfiguration.getPeriodTypeSelect(), targetConfiguration.getFromDate(), targetConfiguration.getToDate(), targetConfiguration.getCallEmittedNumber(), targetConfiguration.getMeetingNumber(), targetConfiguration.getOpportunityAmountWon().doubleValue(), targetConfiguration.getOpportunityCreatedNumber(), targetConfiguration.getOpportunityCreatedWon()).fetchOne(); if(target2 == null) { Target target = this.createTarget(targetConfiguration, oldDate, date.minusDays(1)); this.update(target); oldDate = date; } else { throw new AxelorException(String.format(I18n.get(IExceptionMessage.TARGET_1), target2.getCode(), targetConfiguration.getCode()), IException.CONFIGURATION_ERROR); } } } } public LocalDate getNextDate(int periodTypeSelect, LocalDate date) { switch (periodTypeSelect) { case ITarget.NONE: return date; case ITarget.MONTHLY: return date.plusMonths(1); case ITarget.WEEKLY: return date.plusWeeks(1); case ITarget.DAILY: return date.plusDays(1); default: return date; } } @Transactional(rollbackOn = {AxelorException.class, Exception.class}) public Target createTarget(TargetConfiguration targetConfiguration, LocalDate fromDate, LocalDate toDate) { Target target = new Target(); target.setCallEmittedNumberTarget(targetConfiguration.getCallEmittedNumber()); target.setMeetingNumberTarget(targetConfiguration.getMeetingNumber()); target.setOpportunityAmountWonTarget(targetConfiguration.getOpportunityAmountWon()); target.setOpportunityCreatedNumberTarget(target.getOpportunityCreatedNumberTarget()); target.setOpportunityCreatedWonTarget(target.getOpportunityCreatedWonTarget()); // target.setSaleOrderAmountWonTarget(targetConfiguration.getSaleOrderAmountWon()); // target.setSaleOrderCreatedNumberTarget(targetConfiguration.getSaleOrderCreatedNumber()); // target.setSaleOrderCreatedWonTarget(targetConfiguration.getSaleOrderCreatedWon()); target.setPeriodTypeSelect(targetConfiguration.getPeriodTypeSelect()); target.setFromDate(fromDate); target.setToDate(toDate); target.setUser(targetConfiguration.getUser()); target.setTeam(targetConfiguration.getTeam()); target.setName(targetConfiguration.getName()); target.setCode(targetConfiguration.getCode()); return save(target); } @Transactional(rollbackOn = {AxelorException.class, Exception.class}) public void update(Target target) { User user = target.getUser(); Team team = target.getTeam(); LocalDate fromDate = target.getFromDate(); LocalDate toDate = target.getToDate(); LocalDateTime fromDateTime = new LocalDateTime(fromDate.getYear(), fromDate.getMonthOfYear(), fromDate.getDayOfMonth(), 0, 0); LocalDateTime toDateTime = new LocalDateTime(toDate.getYear(), toDate.getMonthOfYear(), toDate.getDayOfMonth(), 23, 59); if(user != null) { Query q = JPA.em().createQuery("select SUM(op.amount) FROM Opportunity as op WHERE op.user = ?1 AND op.salesStageSelect = 9 AND op.createdOn >= ?2 AND op.createdOn <= ?3 "); q.setParameter(1, user); q.setParameter(2, fromDateTime); q.setParameter(3, toDateTime); BigDecimal opportunityAmountWon = (BigDecimal) q.getSingleResult(); Long callEmittedNumber = eventService.all().filter("self.typeSelect = ?1 AND self.user = ?2 AND self.startDateTime >= ?3 AND self.endDateTime <= ?4 AND self.callTypeSelect = 2", 1, user, fromDateTime, toDateTime).count(); target.setCallEmittedNumber(callEmittedNumber.intValue()); Long meetingNumber = eventService.all().filter("self.typeSelect = ?1 AND self.user = ?2 AND self.startDateTime >= ?3 AND self.endDateTime <= ?4", 1, user, fromDateTime, toDateTime).count(); target.setMeetingNumber(meetingNumber.intValue()); target.setOpportunityAmountWon(opportunityAmountWon); Long opportunityCreatedNumber = opportunityService.all().filter("self.user = ?1 AND self.createdOn >= ?2 AND self.createdOn <= ?3", user, fromDateTime, toDateTime).count(); target.setOpportunityCreatedNumber(opportunityCreatedNumber.intValue()); Long opportunityCreatedWon = opportunityService.all().filter("self.user = ?1 AND self.createdOn >= ?2 AND self.createdOn <= ?3 AND self.salesStageSelect = 9", user, fromDateTime, toDateTime).count(); target.setOpportunityCreatedWon(opportunityCreatedWon.intValue()); } else if(team != null) { Query q = JPA.em().createQuery("select SUM(op.amount) FROM Opportunity as op WHERE op.team = ?1 AND op.salesStageSelect = 9 AND op.createdOn >= ?2 AND op.createdOn <= ?3 "); q.setParameter(1, team); q.setParameter(2, fromDateTime); q.setParameter(3, toDateTime); BigDecimal opportunityAmountWon = (BigDecimal) q.getSingleResult(); Long callEmittedNumber = eventService.all().filter("self.typeSelect = ?1 AND self.team = ?2 AND self.startDateTime >= ?3 AND self.endDateTime <= ?4 AND self.callTypeSelect = 2", 1, user, fromDateTime, toDateTime).count(); target.setCallEmittedNumber(callEmittedNumber.intValue()); Long meetingNumber = eventService.all().filter("self.typeSelect = ?1 AND self.team = ?2 AND self.startDateTime >= ?3 AND self.endDateTime <= ?4", 1, user, fromDateTime, toDateTime).count(); target.setMeetingNumber(meetingNumber.intValue()); target.setOpportunityAmountWon(opportunityAmountWon); Long opportunityCreatedNumber = opportunityService.all().filter("self.team = ?1 AND self.createdOn >= ?2 AND self.createdOn <= ?3", user, fromDateTime, toDateTime).count(); target.setOpportunityCreatedNumber(opportunityCreatedNumber.intValue()); Long opportunityCreatedWon = opportunityService.all().filter("self.team = ?1 AND self.createdOn >= ?2 AND self.createdOn <= ?3 AND self.salesStageSelect = 9", user, fromDateTime, toDateTime).count(); target.setOpportunityCreatedWon(opportunityCreatedWon.intValue()); } save(target); } }
package com.jfixby.scarabei.red.desktop.sys.settings; import com.jfixby.scarabei.api.collections.Collections; import com.jfixby.scarabei.api.collections.Map; import com.jfixby.scarabei.api.debug.Debug; import com.jfixby.scarabei.api.err.Err; import com.jfixby.scarabei.api.log.L; import com.jfixby.scarabei.api.names.ID; import com.jfixby.scarabei.api.names.Names; import com.jfixby.scarabei.api.sys.settings.ExecutionMode; import com.jfixby.scarabei.api.sys.settings.SystemSettingsComponent; public class DesktopSystemSettings implements SystemSettingsComponent { private ExecutionMode execution_mode = ExecutionMode.EARLY_DEVELOPMENT; final Map<ID, Boolean> flags = Collections.newMap(); final Map<ID, Long> longs = Collections.newMap(); final Map<ID, String> strings = Collections.newMap(); final Map<ID, ID> assets = Collections.newMap(); public DesktopSystemSettings () { final java.util.Map<String, String> list = System.getenv(); for (final String key : list.keySet()) { if (!Names.isValidString(key)) { continue; } final ID id = Names.newID(key); this.strings.put(id, list.get(key)); } } @Override public Map<ID, Object> listAllSettings () { final Map<ID, Object> params = Collections.newMap(); // Err.throwNotImplementedYet(); // params.put("ExecutionMode", "" + this.execution_mode); collect("flag", params, this.flags); collect("long", params, this.longs); collect("string", params, this.strings); collect("assets", params, this.assets); return params; } static private void collect (final String string, final Map<ID, Object> params, final Map<ID, ?> input) { params.putAll(input); } @Override public void setExecutionMode (final ExecutionMode executionMode) { Debug.checkNull("ExecutionMode", executionMode); this.execution_mode = executionMode; } @Override public void setFlag (final ID flag_name, final boolean flag_value) { this.flags.put(flag_name, flag_value); } @Override public boolean getFlag (final ID flag_name) { final Boolean value = this.flags.get(flag_name); if (value == null) { L.d("Flag not found", flag_name); return false; } return value; } @Override public String getStringParameter (final ID parameter_name, final String defaultValue) { final String value = this.strings.get(parameter_name); if (value == null) { return defaultValue; } return value; } @Override public void setStringParameter (final ID parameter_name, final String parameter_value) { this.strings.put(parameter_name, parameter_value); } @Override public void setSystemAssetID (final ID parameter_name, final ID parameter_value) { this.assets.put(parameter_name, parameter_value); } @Override public ID getSystemAssetID (final ID parameter_name) { final ID value = this.assets.get(parameter_name); if (value == null) { L.d("Parameter not found", parameter_name); return null; } return value; } @Override public boolean executionModeIsAtLeast (final ExecutionMode execution_mode) { return this.execution_mode.isAtLeast(execution_mode); } @Override public ExecutionMode getExecutionMode () { return this.execution_mode; } @Override public void setIntParameter (final ID parameterName, final long parameterValue) { this.longs.put(parameterName, parameterValue); } @Override public long getIntParameter (final ID parameterName) { final Long value = this.longs.get(parameterName); if (value == null) { L.d("Parameter not found", parameterName); return 0; } return value; } @Override public void clearAll () { this.flags.clear(); this.longs.clear(); this.strings.clear(); this.assets.clear(); } @Override public boolean saveToStorage () { Err.throwNotImplementedYet(); return false; } @Override public String getRequiredStringParameter (final ID name) { final String value = this.getStringParameter(name, null); Debug.checkNull(name.toString(), value); return value; } }
package com.azure.spring.autoconfigure.aad; import com.nimbusds.jose.JWSObject; import com.nimbusds.jwt.JWTClaimsSet; import java.io.Serializable; import java.util.Map; import java.util.Optional; import java.util.Set; /** * entity class of UserPrincipal */ public class UserPrincipal implements Serializable { private static final long serialVersionUID = -3725690847771476854L; private String aadIssuedBearerToken; // id_token or access_token private final JWSObject jwsObject; private final JWTClaimsSet jwtClaimsSet; /** * All groups in aadIssuedBearerToken. Including the ones not exist in aadAuthenticationProperties.getUserGroup() * .getAllowedGroups() */ private Set<String> groups; /** * All roles in aadIssuedBearerToken. */ private Set<String> roles; private String accessTokenForGraphApi; public UserPrincipal(String aadIssuedBearerToken, JWSObject jwsObject, JWTClaimsSet jwtClaimsSet) { this.aadIssuedBearerToken = aadIssuedBearerToken; this.jwsObject = jwsObject; this.jwtClaimsSet = jwtClaimsSet; } public String getAadIssuedBearerToken() { return aadIssuedBearerToken; } public void setAadIssuedBearerToken(String aadIssuedBearerToken) { this.aadIssuedBearerToken = aadIssuedBearerToken; } public Set<String> getGroups() { return this.groups; } public void setGroups(Set<String> groups) { this.groups = groups; } public Set<String> getRoles() { return roles; } public void setRoles(Set<String> roles) { this.roles = roles; } public String getAccessTokenForGraphApi() { return accessTokenForGraphApi; } public void setAccessTokenForGraphApi(String accessTokenForGraphApi) { this.accessTokenForGraphApi = accessTokenForGraphApi; } public boolean isMemberOf(AADAuthenticationProperties aadAuthenticationProperties, String group) { return aadAuthenticationProperties.isAllowedGroup(group) && Optional.of(groups) .map(g -> g.contains(group)) .orElse(false); } public String getKid() { return jwsObject == null ? null : jwsObject.getHeader().getKeyID(); } public String getIssuer() { return jwtClaimsSet == null ? null : jwtClaimsSet.getIssuer(); } public String getSubject() { return jwtClaimsSet == null ? null : jwtClaimsSet.getSubject(); } public Map<String, Object> getClaims() { return jwtClaimsSet == null ? null : jwtClaimsSet.getClaims(); } public Object getClaim(String name) { return jwtClaimsSet == null ? null : jwtClaimsSet.getClaim(name); } public String getName() { return jwtClaimsSet == null ? null : (String) jwtClaimsSet.getClaim("name"); } public String getUserPrincipalName() { return jwtClaimsSet == null ? null : (String) jwtClaimsSet.getClaim("preferred_username"); } }
package org.simpleflatmapper.reflect.asm; import org.simpleflatmapper.ow2asm.ClassReader; import org.simpleflatmapper.ow2asm.ClassVisitor; import org.simpleflatmapper.ow2asm.Label; import org.simpleflatmapper.ow2asm.MethodVisitor; import org.simpleflatmapper.ow2asm.Opcodes; import org.simpleflatmapper.reflect.instantiator.ExecutableInstantiatorDefinition; import org.simpleflatmapper.reflect.InstantiatorDefinition; import org.simpleflatmapper.reflect.Parameter; import org.simpleflatmapper.util.ErrorHelper; import org.simpleflatmapper.util.TypeHelper; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Member; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class AsmInstantiatorDefinitionFactory { public static List<InstantiatorDefinition> extractDefinitions(final Type target) throws IOException { final List<InstantiatorDefinition> constructors = new ArrayList<InstantiatorDefinition>(); final Class<?> targetClass = TypeHelper.toClass(target); ClassLoader cl = targetClass.getClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } final String fileName = targetClass.getName().replace('.', '/') + ".class"; final InputStream is = cl.getResourceAsStream(fileName); try { if (is == null) { throw new IOException("Cannot find file " + fileName + " in " + cl); } ClassReader classReader = new ClassReader(is); classReader.accept(new ClassVisitor(AsmUtils.API) { List<String> genericTypeNames; @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (signature != null) { genericTypeNames = AsmUtils.extractGenericTypeNames(signature); } else { genericTypeNames = Collections.emptyList(); } super.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, final String methodName, String desc, String signature, String[] exceptions) { final boolean isConstructor = "<init>".equals(methodName); if ((Opcodes.ACC_PUBLIC & access) == Opcodes.ACC_PUBLIC && (isConstructor || ((Opcodes.ACC_STATIC & access) == Opcodes.ACC_STATIC && !desc.endsWith("V")))) { final List<String> descTypes = AsmUtils.extractTypeNamesFromSignature(desc); final List<String> genericTypes; final List<String> names = new ArrayList<String>(); if (signature != null) { genericTypes = AsmUtils.extractTypeNamesFromSignature(signature); if (targetClass.isMemberClass() && isConstructor) { // add outer class param genericTypes.add(0, descTypes.get(0)); } } else { genericTypes = descTypes; } if (!isConstructor) { if (descTypes.size() > 0) { try { final Type genericType = AsmUtils.toGenericType(descTypes.get(descTypes.size() - 1), genericTypeNames, target); if (!targetClass.isAssignableFrom(TypeHelper.toClass(genericType))) { return null; } } catch (ClassNotFoundException e) { return null; } } else return null; } return new MethodVisitor(AsmUtils.API) { Label firstLabel; Label lastLabel; @Override public void visitLabel(Label label) { if (firstLabel == null) { firstLabel = label; } lastLabel = label; } @Override public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { if (start.equals(firstLabel) && end.equals(lastLabel) && ! "this".equals(name)) { names.add(name); } } @Override public void visitEnd() { try { final List<Parameter> parameters = new ArrayList<Parameter>(); int l = descTypes.size() - (isConstructor ? 0 : 1); for(int i = 0; i < l; i ++) { String name = null; if (i < names.size()) { name =names.get(i); } parameters.add(createParameter(i, name, descTypes.get(i), genericTypes.get(i))); } final Member executable; if (isConstructor) { executable = targetClass.getDeclaredConstructor(toTypeArray(parameters)); } else { executable = targetClass.getDeclaredMethod(methodName, toTypeArray(parameters)); } constructors.add(new ExecutableInstantiatorDefinition(executable, parameters.toArray(new Parameter[0]))); } catch(Exception e) { ErrorHelper.rethrow(e); } } private Class<?>[] toTypeArray(List<Parameter> parameters) { Class<?>[] types = new Class<?>[parameters.size()]; for(int i = 0; i < types.length; i++) { types[i] = parameters.get(i).getType(); } return types; } private Parameter createParameter(int index, String name, String desc, String signature) { try { Type basicType = AsmUtils.toGenericType(desc, genericTypeNames, target); Type genericType = basicType; if (signature != null) { Type type = AsmUtils.toGenericType(signature, genericTypeNames, target); if (type != null) { genericType = type; } } return new Parameter(index, name, TypeHelper.toClass(basicType), genericType); } catch (ClassNotFoundException e) { throw new Error("Unexpected error " + e, e); } } }; } else { return null; } } }, 0); } finally { if (is != null) { try { is.close(); } catch (Exception e) { } } } return constructors; } }
package studios.codelight.smartloginlibrary.users; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; public class SmartFacebookUser extends SmartUser implements Parcelable { private String profileName; private String middleName; private Uri profileLink; public SmartFacebookUser() { } protected SmartFacebookUser(Parcel in) { super(in); profileName = in.readString(); middleName = in.readString(); profileLink = in.readParcelable(Uri.class.getClassLoader()); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(profileName); dest.writeString(middleName); dest.writeParcelable(profileLink, flags); } @Override public int describeContents() { return 0; } public static final Creator<SmartFacebookUser> CREATOR = new Creator<SmartFacebookUser>() { @Override public SmartFacebookUser createFromParcel(Parcel in) { return new SmartFacebookUser(in); } @Override public SmartFacebookUser[] newArray(int size) { return new SmartFacebookUser[size]; } }; public String getProfileName() { return profileName; } public void setProfileName(String profileName) { this.profileName = profileName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public Uri getProfileLink() { return profileLink; } public void setProfileLink(Uri profileLink) { this.profileLink = profileLink; } }
package Tamaized.AoV.core.abilities; import java.io.DataOutputStream; import java.io.IOException; import Tamaized.AoV.capabilities.CapabilityList; import Tamaized.AoV.capabilities.aov.IAoVCapability; import io.netty.buffer.ByteBufInputStream; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; public final class Ability { private AbilityBase ability; private int cooldown; private int charges; private int decay; private int tick = 0; public Ability(AbilityBase ability, IAoVCapability cap) { this.ability = ability; reset(cap); } public static Ability construct(IAoVCapability cap, ByteBufInputStream stream) throws IOException { int id = stream.readInt(); if (id < 0) return null; Ability ability = new Ability(AbilityBase.getAbilityFromID(id), cap); ability.decode(stream); return ability; } public static Ability construct(IAoVCapability cap, NBTTagCompound nbt) { int id = nbt.getInteger("id"); if (id < 0) return null; Ability ability = new Ability(AbilityBase.getAbilityFromID(id), cap); ability.decode(nbt); return ability; } public void encode(DataOutputStream stream) throws IOException { stream.writeInt(ability.getID()); stream.writeInt(cooldown); stream.writeInt(charges); stream.writeInt(decay); } public void decode(ByteBufInputStream stream) throws IOException { cooldown = stream.readInt(); charges = stream.readInt(); decay = stream.readInt(); } public NBTTagCompound encode(NBTTagCompound nbt) { nbt.setInteger("id", ability.getID()); nbt.setInteger("cooldown", cooldown); nbt.setInteger("charges", charges); nbt.setInteger("decay", decay); return nbt; } public void decode(NBTTagCompound nbt) { cooldown = nbt.getInteger("cooldown"); charges = nbt.getInteger("charges"); decay = nbt.getInteger("decay"); } public void reset(IAoVCapability cap) { cooldown = 0; charges = ability.getMaxCharges() < 0 ? -1 : ability.getMaxCharges() + cap.getExtraCharges(); decay = 0; } public void cast(EntityPlayer caster, EntityLivingBase target) { IAoVCapability cap = caster.getCapability(CapabilityList.AOV, null); if (cap != null) { if (canUse(cap)) { ability.cast(this, caster, target); charges -= ability.getCost(cap); cooldown = ability.getCoolDown() * ((ability.usesInvoke() && cap.getInvokeMass()) ? 2 : 1); } } } public void castAsAura(EntityPlayer caster, IAoVCapability cap, int life) { if (ability instanceof IAura) ((IAura) ability).castAsAura(caster, cap, life); } public boolean canUse(IAoVCapability cap) { return cooldown <= 0 && (charges == -1 || charges >= ability.getCost(cap)) && cap.slotsContain(this); } public AbilityBase getAbility() { return ability; } public int getCooldown() { return cooldown; } public float getCooldownPerc() { return (float) cooldown / (float) ability.getCoolDown(); } public int getCharges() { return charges; } public int getDecay() { return decay; } public void update() { tick++; if (cooldown > 0) cooldown if (decay > 0 && tick % (20 * 20) == 0) decay } public boolean compare(Ability check) { return check != null && ability == check.ability; } }
package alignment.alignment_v2; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.tinkerpop.rexster.client.RexProException; import com.tinkerpop.rexster.client.RexsterClient; import com.tinkerpop.rexster.client.RexsterClientFactory; import com.tinkerpop.rexster.client.RexsterClientTokens; import com.tinkerpop.rexster.protocol.serializer.msgpack.MsgPackSerializer; import com.tinkerpop.blueprints.*; public class DBConnection { private RexsterClient client = null; private Logger logger = null; private Map<String, String> vertIDCache = null; private String dbType = null; public static RexsterClient createClient(Configuration configOpts){ return createClient(configOpts, 0); } /* * Note that connectionWaitTime is in seconds */ public static RexsterClient createClient(Configuration configOpts, int connectionWaitTime){ RexsterClient client = null; Logger logger = LoggerFactory.getLogger(Align.class); logger.info("connecting to DB..."); try { client = RexsterClientFactory.open(configOpts); //this just throws "Exception." bummer. } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //if wait time given, then wait that long, so the connection can set up. (Mostly needed for travis-ci tests) if(connectionWaitTime > 0){ try { logger.info( "waiting for " + connectionWaitTime + " seconds for connection to establish..." ); Thread.sleep(connectionWaitTime*1000); //in ms. } catch (InterruptedException ie) { // Restore the interrupted status Thread.currentThread().interrupt(); } } return client; } public static Configuration getDefaultConfig(){ Logger logger = LoggerFactory.getLogger(Align.class); logger.info("Loading default DB Config..."); Configuration configOpts = ConfigFileLoader.configFromFile("rexster-config/rexster-default-config"); return configOpts; } public static Configuration getTestConfig(){ Logger logger = LoggerFactory.getLogger(Align.class); logger.info("Loading test DB Config..."); Configuration configOpts = ConfigFileLoader.configFromFile("rexster-config/rexster-test-config"); return configOpts; } public static void closeClient(RexsterClient client){ if(client != null){ try { client.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } client = null; } } public DBConnection(){ this(createClient(getDefaultConfig())); } public DBConnection(RexsterClient c){ //TODO logger = LoggerFactory.getLogger(Align.class); vertIDCache = new HashMap<String, String>(10000); client = c; } private String getDBType(){ if(this.dbType == null){ String type = null; try{ type = client.execute("g.getClass()").get(0).toString(); }catch(Exception e){ logger.error("Could not find graph type!",e); } if( type.equals("class com.tinkerpop.blueprints.impls.tg.TinkerGraph") ){ this.dbType = "TinkerGraph"; }else if( type.equals("class com.thinkaurelius.titan.graphdb.database.StandardTitanGraph") ){ this.dbType = "TitanGraph"; }else{ logger.warn("Could not find graph type, or unknown type! Assuming it is Titan..."); this.dbType = "TitanGraph"; } } return this.dbType; } public void createIndices(){ String graphType = getDBType(); if( graphType.equals("TinkerGraph") ){ createTinkerGraphIndices(); }else if( graphType.equals("TitanGraph") ){ createTitanIndices(); }else{ logger.warn("unknown graph type! Assuming it is Titan..."); createTitanIndices(); } } private void createTinkerGraphIndices(){ List currentRawIndices = null; try { //configure vert indices needed //List currentIndices = client.execute("g.getManagementSystem().getGraphIndexes(Vertex.class)"); currentRawIndices = client.execute("g.getIndices()"); } catch (Exception e) { //this.client = null; logger.error("problem getting indexed keys, assuming there were none..."); logger.error("Exception was: ",e); } List<String> currentIndices = new ArrayList<String>(); for(int i=0; i<currentRawIndices.size(); i++){ String current = ((Index) currentRawIndices.get(i)).getIndexName(); currentIndices.add( current ); } logger.info( "found vertex indices: " + currentIndices ); //TODO: actually create the indices (although for current unit tests, it doesn't matter) } private void createTitanIndices(){ List currentIndices = null; try { //configure vert indices needed //List currentIndices = client.execute("g.getManagementSystem().getGraphIndexes(Vertex.class)"); currentIndices = client.execute("g.getIndexedKeys(Vertex.class)"); } catch (Exception e) { //this.client = null; logger.error("problem getting indexed keys, assuming there were none..."); logger.error("Exception was: ",e); } logger.info( "found vertex indices: " + currentIndices ); try{ // System.out.println("currentIndices = " + currentIndices + " " + "name"); if(currentIndices == null || !currentIndices.contains("name")){ List names = client.execute("mgmt = g.getManagementSystem();mgmt.getPropertyKey(\"name\");"); //logger.info("name found: ", names.get(0)); if(names.get(0) == null){ logger.info("'name' variable and index not found, creating var and index..."); client.execute("mgmt = g.getManagementSystem();" + "name = mgmt.makePropertyKey(\"name\").dataType(String.class).make();" + "mgmt.buildIndex(\"byName\",Vertex.class).addKey(name).unique().buildCompositeIndex();" + "mgmt.commit();g;"); }else{ logger.info("'name' was found, but not indexed. creating index..."); client.execute("mgmt = g.getManagementSystem();" + "name = mgmt.getPropertyKey(\"name\");" + "mgmt.buildIndex(\"byName\",Vertex.class).addKey(name).unique().buildCompositeIndex();" + "mgmt.commit();g;"); } } if(currentIndices == null || !currentIndices.contains("vertexType")){ List names = client.execute("mgmt = g.getManagementSystem();mgmt.getPropertyKey(\"vertexType\");"); //logger.info("vertexType found: ", names.get(0)); if(names.get(0) == null){ logger.info("'vertexType' variable and index not found, creating var and index..."); client.execute("mgmt = g.getManagementSystem();" + "vertexType = mgmt.makePropertyKey(\"vertexType\").dataType(String.class).make();" + "mgmt.buildIndex(\"byVertexType\",Vertex.class).addKey(vertexType).unique().buildCompositeIndex();" + "mgmt.commit();g;"); }else{ logger.info("'vertexType' was found, but not indexed. creating index..."); client.execute("mgmt = g.getManagementSystem();" + "vertexType = mgmt.getPropertyKey(\"vertexType\");" + "mgmt.buildIndex(\"byVertexType\",Vertex.class).addKey(vertexType).unique().buildCompositeIndex();" + "mgmt.commit();g;"); } } /* if(!currentIndices.contains("name") || !currentIndices.contains("vertexType")){ logger.info("name or vertexType index not found, creating combined index..."); client.execute("mgmt = g.getManagementSystem();" + "name = mgmt.getPropertyKey(\"name\");" + "vertexType = mgmt.getPropertyKey(\"vertexType\");" + "mgmt.buildIndex(\"byNameAndVertexType\",Vertex.class).addKey(name).addKey(vertexType).unique().buildCompositeIndex();" + "mgmt.commit();g;"); //TODO: not convinced that this (new) index really works, need to test further. but it's currently unused, so leaving as-is for now. }*/ commit(); logger.info("Connection is good!"); }catch(Exception e){ logger.error("could not configure missing vertex indices!", e); this.client = null; logger.error("Connection is unusable!"); } /* currentIndices = client.execute("g.getIndexedKeys(Edge.class)"); logger.info( "found edge indices: " + currentIndices ); try{ if(!currentIndices.contains("name")){ logger.info("name index not found, creating..."); client.execute("g.makeKey(\"edgeName\").dataType(String.class).indexed(\"standard\",Edge.class).unique().make();g.commit();g;"); } }catch(Exception e){ logger.error("could not configure missing indices!", e); } */ } public void addVertexFromJSON(JSONObject vert){ String graphType = getDBType(); String name = vert.optString("name"); //System.out.println("vertex name is: " + name); String id = vert.optString("_id"); //System.out.println("vertex id is: " + id); if(name == null || name == ""){ name = id; vert.put("name", name); } vert.remove("_id"); //Some graph servers will ignore this ID, some won't. Just remove them so it's consistent. Map<String, Object> param = new HashMap<String, Object>(); param.put("VERT_PROPS", vert); try { Long newID = null; if(graphType == "TitanGraph") newID = (Long)client.execute("v = GraphSONUtility.vertexFromJson(VERT_PROPS, new GraphElementFactory(g), GraphSONMode.NORMAL, null);v.getId()", param).get(0); if(graphType == "TinkerGraph") newID = Long.parseLong((String)client.execute("v = GraphSONUtility.vertexFromJson(VERT_PROPS, new GraphElementFactory(g), GraphSONMode.NORMAL, null);v.getId()", param).get(0)); //System.out.println("new ID is: " + newID); vertIDCache.put(name, newID.toString()); } catch (RexProException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addEdgeFromJSON(JSONObject edge){ Map<String, Object> param = new HashMap<String, Object>(); //System.out.println("edge outV is " + edge.getString("_outV")); String outv_id = findVertId(edge.getString("_outV")); String inv_id = findVertId(edge.getString("_inV")); String edgeName = edge.getString("_id"); //System.out.println("ID = " + edgeName); //String edgeID = findEdgeId(edgeName); if(outv_id == null){ logger.error("Could not find out_v for edge: " + edge); //continue; } if(inv_id == null){ logger.error("Could not find in_v for edge: " + edge); //continue; } String label = edge.optString("_label"); if(edgeExists(inv_id, outv_id, label)){ //TODO need to merge edge props for this case, like verts above... logger.debug("Attempted to add edge with duplicate name. ignoring ..."); //continue; } param.put("ID_OUT", Integer.parseInt(outv_id)); param.put("ID_IN", Integer.parseInt(inv_id)); param.put("LABEL", label); //build your param map obj Map<String, Object> props = new HashMap<String, Object>(); props.put("edgeName", edgeName); edge.remove("_inv"); edge.remove("_outv"); edge.remove("_id"); Iterator<String> k = edge.keys(); String key; while(k.hasNext()){ key = k.next(); props.put(key, edge.get(key)); // System.out.println(key); } param.put("EDGE_PROPS", props); //and now finally add edge to graph execute("g.addEdge(g.v(ID_OUT),g.v(ID_IN),LABEL,EDGE_PROPS)", param); } public void commit(){ String graphType = getDBType(); if(graphType != "TinkerGraph") execute("g.commit()"); } //TODO make private //wrapper to reduce boilerplate //TODO wrapper throws away any return value, // it'd be nice to use this even when we want the query's retval... but then we're back w/ exceptions & don't gain much. public boolean execute(String query, Map<String,Object> params){ if(this.client == null) return false; try { //Adding a trailing return 'g' on everything: // no execute() args can end up returning null, due to known API bug. // returning 'g' everywhere is just the simplest workaround for it, since it is always defined. query += ";g"; client.execute(query, params); } catch (RexProException e) { logger.error("'execute' method caused a rexpro problem (again)"); logger.error("this query was: " + query + " params were: " + params); logger.error("Exception!",e); return false; } catch (IOException e) { logger.error("'execute' method caused something new and unexpected to break!"); logger.error("this query was: " + query + " params were: " + params); logger.error("Exception!",e); return false; } return true; } //likewise. public boolean execute(String query){ return execute(query,null); } //should only use in tests... public RexsterClient getClient(){ return client; } public Map<String, Object> getVertByID(String id){ try { Map<String, Object> param = new HashMap<String, Object>(); param.put("ID", Integer.parseInt(id)); Object query_ret = client.execute("g.v(ID).map();", param); List<Map<String, Object>> query_ret_list = (List<Map<String, Object>>)query_ret; Map<String, Object> query_ret_map = query_ret_list.get(0); return query_ret_map; } catch (RexProException e) { logger.error("Exception!",e); return null; } catch (IOException e) { logger.error("Exception!",e); return null; } catch (ClassCastException e) { logger.error("Exception!",e); return null; } } public Map<String,Object> findVert(String name) throws IOException, RexProException{ if(name == null || name == "") return null; Map<String, Object> param = new HashMap<String, Object>(); param.put("NAME", name); Object query_ret = client.execute("g.query().has(\"name\",NAME).vertices().toList();", param); List<Map<String,Object>> query_ret_list = (List<Map<String,Object>>)query_ret; //logger.info("query returned: " + query_ret_list); if(query_ret_list.size() == 0){ //logger.info("findVert found 0 matching verts for name:" + name); //this is too noisy, the invoking function can complain if it wants to... return null; }else if(query_ret_list.size() > 1){ logger.warn("findVert found more than 1 matching verts for name:" + name); return null; } return query_ret_list.get(0); } /* public Map<String,Object> findEdge(String edgeName) throws IOException, RexProException{ if(edgeName == null || edgeName == "") return null; Map<String, Object> param = new HashMap<String, Object>(); param.put("NAME", edgeName); Object query_ret = client.execute("g.query().has(\"name\",NAME).edges().toList();", param); List<Map<String,Object>> query_ret_list = (List<Map<String,Object>>)query_ret; //logger.info("query returned: " + query_ret_list); if(query_ret_list.size() == 0){ //logger.info("findEdge found 0 matching edges for name:" + name); //this is too noisy, the invoking function can complain if it wants to... return null; }else if(query_ret_list.size() > 1){ logger.warn("findEdge found more than 1 matching edges for name:" + edgeName); return null; } return query_ret_list.get(0); } */ //function is searching vertIDCache first, if id is not in there, then it is calling the findVert funciton public String findVertId(String name){ String id = vertIDCache.get(name); // for (String key: vertIDCache.keySet()){ // System.out.println("key = " + key + " value = " + vertIDCache.get(key)); if(id != null){ return id; }else{ try{ Map<String, Object> vert = findVert(name); if(vert == null) id = null; else id = (String)vert.get("_id"); if(id != null){ //TODO cache eviction, and/or limit caching by vert type. But until vertex count gets higher, it won't matter much. vertIDCache.put(name, id); } return id; }catch(RexProException e){ logger.warn("RexProException in findVertID (with name: " + name + " )", e); return null; }catch(NullPointerException e){ logger.error("NullPointerException in findVertID (with name: " + name + " )", e); return null; }catch(IOException e){ logger.error("IOException in findVertID (with name: " + name + " )", e); return null; } } } public List<Map<String,Object>> findAllVertsByType(String vertexType) throws IOException, RexProException{ if(vertexType == null || vertexType == "") return null; Map<String, Object> properties = new HashMap<String, Object>(); List<String> l = new ArrayList<String>(); l.add("T.eq"); l.add(vertexType); properties.put("vertexType", l); List<Map<String,Object>> query_ret_list = findAllVertsWithProps(properties); if(query_ret_list.size() == 0){ logger.warn("findAllVertsByType found 0 matching verts for type:" + vertexType); return null; } return query_ret_list; } /* * values in the properties map can be any gremlin-friendly type, or a List of [op, value]. * The op given can be any of these supported comparison operations: * T.gt - greater than * T.gte - greater than or equal to * T.eq - equal to * T.neq - not equal to * T.lte - less than or equal to * T.lt - less than * T.in - contained in a list * T.notin - not contained in a list */ public List<Map<String,Object>> findAllVertsWithProps(Map<String, Object> properties) throws IOException, RexProException{ if(properties == null || properties.size() == 0) return null; Map<String, Object> param = new HashMap<String, Object>(); //String query = "g.query()"; String query = "g.V"; Set<String> propKeys = properties.keySet(); for(String key : propKeys){ Object prop = properties.get(key); if(prop instanceof List){ List p = (List)prop; if(p.size() != 2) logger.warn("property " + prop + "has more elements than expected!"); String op = (String)p.get(0); //TODO check op param.put(key.toUpperCase(), p.get(1)); query += ".has(\"" + key + "\"," + op + "," + key.toUpperCase() + ")"; }else{ param.put(key.toUpperCase(), prop); query += ".has(\"" + key + "\"," + key.toUpperCase() + ")"; } } //query += ".vertices().toList();"; query += ";"; Object query_ret = client.execute(query, param); List<Map<String,Object>> query_ret_list = (List<Map<String,Object>>)query_ret; if(query_ret_list.size() == 0){ logger.warn("findAllVertsWithProps found 0 matching verts for properties:" + properties); return null; } return query_ret_list; } /* public String findEdgeId(String edgeName){ String id = null; try{ Map<String, Object> edge = findEdge(edgeName); if(edge == null) id = null; else id = (String)edge.get("_id"); return id; }catch(RexProException e){ logger.warn("RexProException in findEdgeId (with name: " + edgeName + " )", e); return null; }catch(NullPointerException e){ logger.error("NullPointerException in findEdgeId (with name: " + edgeName + " )", e); return null; }catch(IOException e){ logger.error("IOException in findEdgeId (with name: " + edgeName + " )", e); return null; } } */ public boolean edgeExists(String inv_id, String outv_id, String label) { if(inv_id == null || inv_id == "" || outv_id == null || outv_id == "" || label == null || label == "") return false; Map<String, Object> param = new HashMap<String, Object>(); param.put("ID_OUT", Integer.parseInt(outv_id)); param.put("LABEL", label); Object query_ret; try { query_ret = client.execute("g.v(ID_OUT).outE(LABEL).inV();", param); } catch (RexProException e) { logger.error("edgeExists RexProException for args:" + outv_id + ", " + label + ", " + inv_id); e.printStackTrace(); return false; } catch (IOException e) { logger.error("edgeExists IOException for args:" + outv_id + ", " + label + ", " + inv_id); e.printStackTrace(); return false; } List<Map<String, Object>> query_ret_list = (List<Map<String, Object>>)query_ret; //logger.info("query returned: " + query_ret_list); for(Map<String, Object> item : query_ret_list){ if(Integer.parseInt(inv_id) == Integer.parseInt((String)item.get("_id"))) return true; } //logger.info("matching edge not found"); return false; } public void updateVert(String id, Map<String, Object> props){ String[] keys = props.keySet().toArray(new String[0]); for(int i=0; i<keys.length; i++){ updateVertProperty(id, keys[i], props.get(keys[i])); } } public boolean updateVertProperty(String id, String key, Object val){ HashMap<String, Object> param = new HashMap<String, Object>(); param.put("ID", Integer.parseInt(id)); param.put("KEY", key); param.put("VAL", val); boolean ret = execute("g.v(ID)[KEY]=VAL", param); commit(); return ret; } /* * Only use in tests. */ public boolean removeCachedVertices(){ //NB: this query is slow enough that connection can time out if the DB starts with many vertices. if(vertIDCache.isEmpty()) return true; boolean ret = true; //delete the known nodes first, to help prevent timeouts. Map<String,Object> param; Collection<String> ids = vertIDCache.values(); for(String id : ids){ param = new HashMap<String,Object>(); param.put("ID", Integer.parseInt(id)); try{ client.execute("g.v(ID).remove();g", param); }catch(Exception e){ e.printStackTrace(); ret = false; } } try{ commit(); }catch(Exception e){ e.printStackTrace(); ret = false; } //clear the cache now. vertIDCache = new HashMap<String, String>(10000); return ret; } /* public boolean removeAllEdges(RexsterClient client){ return execute("g.E.each{g.removeVertex(it)};g.commit()"); }*/ }
package ankios.blog.service; import ankios.blog.model.Role; import ankios.blog.model.User; import ankios.blog.repository.RoleRepository; import ankios.blog.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Autowired private RoleRepository roleRepository; @Autowired private PasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userRepository.findByUsernameOrEmail(s, s); if (user == null) throw new UsernameNotFoundException("no such user"); List<GrantedAuthority> authorities = new ArrayList<>(); for (Role role : user.getRoles()) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities); } @Override public User findByEmail(String email) { return userRepository.findByEmailIgnoreCase(email); } @Override public User findByUsername(String username) { return userRepository.findByUsernameIgnoreCase(username); } @Override public boolean usernameExists(String username) { return findByUsername(username) != null; } @Override public boolean emailExists(String email) { return findByEmail(email) != null; } @Override public void register(User user) { if(user==null){ return; } user.setPassword(passwordEncoder.encode(user.getPassword())); user.getRoles().add(roleRepository.findByName("ROLE_USER")); user.setEnabled(true); user.setRegistrationDate(LocalDateTime.now()); userRepository.saveAndFlush(user); } @Override public void changeEmail(String newEmail, String currentPassword) throws AuthException { User user = currentUser(); if (!passwordEncoder.matches(currentPassword, user.getPassword())) throw new AuthException("password does not match. Please try again"); user.setEmail(newEmail); userRepository.saveAndFlush(user); } @Override public void changePassword(String newPassword, String currentPassword) throws AuthException { User user = currentUser(); if (!passwordEncoder.matches(currentPassword, user.getPassword())) throw new AuthException("password does not match"); user.setPassword(passwordEncoder.encode(newPassword)); userRepository.saveAndFlush(user); } @Override public void changeProfileInfo(User newProfileInfo) { User user = currentUser(); user.setAboutText(newProfileInfo.getAboutText()); user.setWebsiteLink(newProfileInfo.getWebsiteLink()); userRepository.saveAndFlush(user); } @Override public void changeAvatar(UploadedAvatarInfo uploadedAvatarInfo) { User user = currentUser(); user.setBigAvatarLink(uploadedAvatarInfo.bigImageLink); user.setSmallAvatarLink(uploadedAvatarInfo.smallImageLink); userRepository.saveAndFlush(user); } @Override public void removeAvatar() { User user = currentUser(); user.setBigAvatarLink(null); user.setSmallAvatarLink(null); userRepository.saveAndFlush(user); } @Override public void authenticate(User user) { UserDetails userDetails = loadUserByUsername(user.getUsername()); Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); } @Override public boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication auth = securityContext.getAuthentication(); return auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated(); } @Override public boolean isAdmin() { User user = currentUser(); return user != null && user.hasRole("ROLE_ADMIN"); } @Override public User currentUser() { if (!isAuthenticated()) return null; SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication auth = securityContext.getAuthentication(); return userRepository.findByUsernameIgnoreCase(auth.getName()); } public PasswordEncoder getPasswordEncoder() { return passwordEncoder; } public void setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } }
package aphelion.shared.physics; /** * * @author Joris */ public enum WEAPON_SLOT { GUN(0, "weapon-slot-gun"), GUN_MULTI(1, "weapon-slot-gun-multi"), BOMB(2, "weapon-slot-bomb"), MINE(3, "weapon-slot-mine"), BURST(4, "weapon-slot-burst"), REPEL(5, "weapon-slot-repel"), DECOY(6, "weapon-slot-decoy"), THOR(7, "weapon-slot-thor"), BRICK(8, "weapon-slot-brick"), ROCKET(9, "weapon-slot-rocket"), ; public final int id; // can be used as an array key public final String settingName; private final static WEAPON_SLOT[] values = values(); private WEAPON_SLOT(int id, String settingName) { this.settingName = settingName; this.id = id; } public static WEAPON_SLOT byId(int id) { return values[id]; } public static boolean isValidId(int id) { return id >= 0 && id < values().length; } }
package br.com.tt.cliente; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/cliente") public class ClienteController { @Autowired private ClienteService service; @GetMapping ModelAndView cliente() { ModelAndView mv = new ModelAndView("cliente/cliente.html"); mv.addObject("clientes", service.consulta()); mv.addObject("cpf", "11111111111"); return mv; } @GetMapping("/cadastro") ModelAndView cadastro(Cliente cliente) { ModelAndView mv = new ModelAndView("/cliente/cadastro"); mv.addObject("cliente", cliente); return mv; } @PostMapping("/salvar") ModelAndView salvar(@Valid Cliente cliente, BindingResult result) { if (result.hasErrors()) { return this.cadastro(cliente); } service.salvar(cliente); return this.cliente(); } @GetMapping("/editar/{id}") ModelAndView editar(@PathVariable("id") Long id) { return cadastro(service.buscar(id)); } @GetMapping("/excluir/{id}") ModelAndView excluir(@PathVariable("id") Long id) { service.excluir(id); return cliente(); } }
package ch.fhnw.cantoneditor.views; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import ch.fhnw.cantoneditor.datautils.DB4OConnector; import ch.fhnw.cantoneditor.datautils.NoDataFoundException; import ch.fhnw.cantoneditor.libs.GridBagManager; import ch.fhnw.cantoneditor.model.Canton; import ch.fhnw.command.CommandController; import ch.fhnw.observation.ComputedValue; import ch.fhnw.oop.led.Led; import ch.fhnw.oop.splitflap.SplitFlap; public class Overview { private TranslationManager tm = TranslationManager.getInstance(); public void show() throws IOException { // JFrame.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } JFrame frame = new JFrame(tm.Translate("OverviewTitle")); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { try { DB4OConnector.saveChanges(); DB4OConnector.terminate(); } catch (NoDataFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void windowClosed(WindowEvent arg0) { System.exit(0); } }); JPanel pane = new JPanel(new GridBagLayout()); GridBagManager manager = new GridBagManager(pane); // WHY doesnt it show headers? List<Canton> cantons = DB4OConnector.getAll(Canton.class); JTable table = new JTable(new CantonTableModel(cantons)); table.setMinimumSize(new Dimension(400, 400)); JScrollPane scroller = new JScrollPane(table); JButton undoButton = new JButton(tm.Translate("Undo", "Undo")); JButton redoButton = new JButton(tm.Translate("Redo", "Redo")); new ComputedValue<Boolean>(() -> { return CommandController.getDefault().getDoneCommands().iterator().hasNext(); }).bindTo(undoButton::setEnabled); new ComputedValue<Boolean>(() -> { return CommandController.getDefault().getRedoCommands().iterator().hasNext(); }).bindTo(redoButton::setEnabled); undoButton.addActionListener((e) -> CommandController.getDefault().undo()); redoButton.addActionListener((e) -> CommandController.getDefault().redo()); manager.setWeightX(0).setX(0).setY(0).setComp(undoButton); manager.setWeightX(0).setX(1).setY(0).setComp(redoButton); manager.setWidth(1).setX(0).setY(1).setComp(scroller); manager.setWeightX(1).setWidth(3).setWidth(3).setX(0).setY(2).setComp(initInhabitantsAndAreaDisplay()); frame.add(pane); frame.pack(); frame.setVisible(true); } private JPanel initControlPanel() { JPanel controlPanel = new JPanel(); GridBagManager localGbm = new GridBagManager(controlPanel); return controlPanel; } private JPanel getLedPanel() { List<Canton> cantons = DB4OConnector.getAll(Canton.class); JPanel panel = new JPanel(); // panel.setSize(panel.getWidth(), 5); for (Canton cnt : cantons) { Canton old = cnt.copyToNew(); ComputedValue<Boolean> hasChanged = new ComputedValue<>(() -> { return !cnt.getName().equals(old.getName()) || !cnt.getCapital().equals(old.getCapital()) || !cnt.getShortCut().equals(old.getShortCut()) || !(cnt.getNrInhabitants() == old.getNrInhabitants()) || !(cnt.getArea() == old.getArea()) || !(cnt.getCommunes().equals(old.getCommunes())); }); Led flapper = new Led(); flapper.init(30, 30); flapper.setSize(30, 30); hasChanged.bindTo((vl) -> { flapper.setColor(vl.booleanValue() ? Color.GREEN : Color.RED); }); panel.add(flapper); } return panel; } /** * Creates the lower part of the Frame, which contains the flap display to show the number of * citizen and the area */ private JPanel initInhabitantsAndAreaDisplay() { String[] nums = new String[] { "", "'", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; JPanel inhabPanel = new JPanel(); GridBagManager localGbm = new GridBagManager(inhabPanel); // inhabPanel.setVisible(true); // Lower half of flap SplitFlap areaFlap0 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap0.setSize(20, 20); SplitFlap areaFlap1 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap1.setSize(20, 20); SplitFlap areaFlap2 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap2.setSize(20, 20); SplitFlap areaFlap3 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap3.setSize(20, 20); SplitFlap areaFlap4 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap4.setSize(20, 20); SplitFlap areaFlap5 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap5.setSize(20, 20); SplitFlap areaFlap6 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap6.setSize(20, 20); SplitFlap areaFlap7 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap7.setSize(20, 20); SplitFlap areaFlap8 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap8.setSize(20, 20); SplitFlap areaFlap9 = new SplitFlap(); areaFlap0.setSelection(nums); areaFlap9.setSize(20, 20); int x = 0; int y = 0; localGbm.setWeightX(1.0).setX(x++).setY(y).setComp(new JLabel("")); for (int i = 0; i < 26; i++) { Led led = new Led(); led.init(5, 5); inhabPanel.add(led); } y++; x = 0; localGbm.setWeightX(1.0).setX(x++).setY(y).setComp(new JLabel("")); for (int i = 0; i < nums.length; i++) { // Upper half of flaps SplitFlap InhabitantsFlap0 = new SplitFlap(); InhabitantsFlap0.setSelection(nums); InhabitantsFlap0.setSize(20, 20); localGbm.setX(x++).setY(y).setComp(InhabitantsFlap0); } y++; x = 0; localGbm.setWeightX(1.0).setX(x++).setY(y).setComp(new JLabel("")); localGbm.setX(x++).setY(y).setComp(areaFlap0); localGbm.setX(x++).setY(y).setComp(areaFlap1); localGbm.setX(x++).setY(y).setComp(areaFlap2); localGbm.setX(x++).setY(y).setComp(areaFlap3); localGbm.setX(x++).setY(y).setComp(areaFlap4); localGbm.setX(x++).setY(y).setComp(areaFlap5); localGbm.setX(x++).setY(y).setComp(areaFlap6); localGbm.setX(x++).setY(y).setComp(areaFlap7); localGbm.setX(x++).setY(y).setComp(areaFlap8); localGbm.setX(x++).setY(y).setComp(areaFlap9); return inhabPanel; } }
package co.phoenixlab.discord; import co.phoenixlab.common.lang.SafeNav; import co.phoenixlab.common.localization.Localizer; import co.phoenixlab.discord.api.DiscordApiClient; import co.phoenixlab.discord.api.entities.*; import co.phoenixlab.discord.api.event.*; import co.phoenixlab.discord.commands.tempstorage.TempServerConfig; import co.phoenixlab.discord.dntrack.VersionTracker; import co.phoenixlab.discord.dntrack.event.RegionDescriptor; import co.phoenixlab.discord.dntrack.event.VersionUpdateEvent; import com.google.common.eventbus.Subscribe; import java.time.Duration; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class EventListener { public static final DateTimeFormatter UPDATE_FORMATTER = DateTimeFormatter.ofPattern("M/d HH:mm z"); private final VahrhedralBot bot; private final ScheduledExecutorService executorService; private Map<String, VersionTracker> versionTrackers = new HashMap<>(); public Map<String, Consumer<MemberChangeEvent>> memberChangeEventListener; public Map<String, String> joinMessageRedirect; public Map<String, String> leaveMessageRedirect; public Set<String> ignoredServers; public int excessiveMentionThreshold; public Map<String, Deque<String>> newest = new HashMap<>(); private Map<String, Consumer<Message>> messageListeners; private Map<String, Long> currentDateTimeLastUse = new HashMap<>(); public EventListener(VahrhedralBot bot) { this.bot = bot; executorService = Executors.newSingleThreadScheduledExecutor(); messageListeners = new HashMap<>(); memberChangeEventListener = new HashMap<>(); joinMessageRedirect = new HashMap<>(); leaveMessageRedirect = new HashMap<>(); ignoredServers = new HashSet<>(); messageListeners.put("mention-bot", message -> { User me = bot.getApiClient().getClientUser(); for (User user : message.getMentions()) { if (me.equals(user)) { handleMention(message); return; } } }); excessiveMentionThreshold = 5; messageListeners.put("mention-autotimeout", this::handleExcessiveMentions); messageListeners.put("invite-pm", this::onInviteLinkPrivateMessage); messageListeners.put("other-prefixes", this::onOtherTypesCommand); // messageListeners.put("date-time", this::currentDateTime); } public static String createJoinLeaveMessage(User user, Server server, String fmt) { return fmt. replace("$n", user.getUsername()). replace("$d", user.getDiscriminator()). replace("$i", user.getId()). replace("$s", server.getName()). replace("$t", DateTimeFormatter.ofPattern("HH:mm:ss z").format(ZonedDateTime.now())). replace("$m", "<@" + user.getId() + ">"); } private void currentDateTime(Message message) { if (!bot.getMainCommandDispatcher().active().get()) { return; } String channelId = message.getChannelId(); boolean cd = false; if (currentDateTimeLastUse.containsKey(channelId)) { long time = currentDateTimeLastUse.get(channelId); if (time >= System.currentTimeMillis()) { currentDateTimeLastUse.remove(channelId); } else if (System.currentTimeMillis() - time < TimeUnit.SECONDS.toMillis(30)) { cd = true; } } long time = System.currentTimeMillis(); DiscordApiClient api = bot.getApiClient(); String content = message.getContent().toLowerCase(); if (content.contains("current year")) { if (cd) { return; } api.sendMessage("NOFLIPIt's " + ZonedDateTime.now().getYear() + ", `" + message.getAuthor().getUsername() + "`.", channelId); currentDateTimeLastUse.put(channelId, time); } if (content.contains("current date")) { if (cd) { return; } api.sendMessage("NOFLIPIt's " + DateTimeFormatter.ofPattern("MMM dd uuuu").format(ZonedDateTime.now()) + ", `" + message.getAuthor().getUsername() + "`.", channelId); currentDateTimeLastUse.put(channelId, time); } if (content.contains("current day")) { if (cd) { return; } api.sendMessage("NOFLIPIt's the " + th(ZonedDateTime.now().getDayOfMonth()) + ", `" + message.getAuthor().getUsername() + "`.", channelId); currentDateTimeLastUse.put(channelId, time); } if (content.contains("current time")) { if (cd) { return; } api.sendMessage("NOFLIPIt's " + DateTimeFormatter.ofPattern("HH:mm:ss z").format(ZonedDateTime.now()) + ", `" + message.getAuthor().getUsername() + "`.", channelId); currentDateTimeLastUse.put(channelId, time); } if (content.contains("current president")) { if (cd) { return; } api.sendMessage("NOFLIPIt's Bernie Trump, `" + message.getAuthor().getUsername() + "`.", channelId); currentDateTimeLastUse.put(channelId, time); } } private String th(int i) { switch (i) { case 1: return "1st"; case 2: return "2nd"; case 3: return "3rd"; default: return Integer.toString(i) + "th"; } } @Subscribe public void onVersionChange(VersionUpdateEvent event) { DiscordApiClient api = bot.getApiClient(); for (Server server : api.getServers()) { TempServerConfig config = bot.getCommands().getModCommands().getServerStorage().get(server.getId()); if (config != null) { String chid = config.getDnTrackChannel(); if (chid != null) { Localizer loc = bot.getLocalizer(); api.sendMessage(loc.localize("dn.track.version.updated", loc.localize(event.getRegion().getRegionNameKey()), event.getOldVersion(), event.getNewVersion(), UPDATE_FORMATTER.format(event.getTimestamp())), chid); } } } } @Subscribe public void onMessageRecieved(MessageReceivedEvent messageReceivedEvent) { Message message = messageReceivedEvent.getMessage(); boolean isCommand = message.getContent().startsWith(bot.getConfig().getCommandPrefix()); if (isSelfBot() && isCommand) { if (message.getAuthor().equals(bot.getApiClient().getClientUser())) { bot.getMainCommandDispatcher().handleCommand(message); } return; } if (bot.getConfig().getBlacklist().contains(message.getAuthor().getId())) { return; } Channel channel = bot.getApiClient().getChannelById(message.getChannelId()); if (channel != DiscordApiClient.NO_CHANNEL && channel.getParent() != null) { if (ignoredServers.contains(channel.getParent().getId())) { return; } } if (isCommand && !message.getAuthor().isBot()) { bot.getMainCommandDispatcher().handleCommand(message); return; } messageListeners.values().forEach(c -> c.accept(message)); } private void handleMention(Message message) { if (isSelfBot()) { return; } if (!bot.getMainCommandDispatcher().active().get()) { return; } String otherId = message.getAuthor().getId(); bot.getApiClient().sendMessage(bot.getLocalizer().localize("message.mention.response", message.getAuthor().getUsername()), message.getChannelId(), new String[]{otherId}); } private void handleExcessiveMentions(Message message) { if (isSelfBot()) { return; } if (!bot.getMainCommandDispatcher().active().get()) { return; } User author = message.getAuthor(); if (bot.getConfig().isAdmin(author.getId())) { return; } Channel channel = bot.getApiClient().getChannelById(message.getChannelId()); Server server; if (channel != DiscordApiClient.NO_CHANNEL && channel.getParent() != null) { server = channel.getParent(); } else { return; } if (!server.getId().equals("106293726271246336")) { return; } Member member = bot.getApiClient().getUserMember(author, server); if (member == DiscordApiClient.NO_MEMBER) { return; } // if (Duration.between(ZonedDateTime. // from(Commands.UPDATE_FORMATTER.parse(member.getJoinedAt())), // ZonedDateTime.now()).abs().compareTo(Duration.ofDays(3)) > 0) { // return; Set<User> unique = new HashSet<>(); Collections.addAll(unique, message.getMentions()); if (unique.size() > excessiveMentionThreshold) { bot.getCommands().getModCommands().applyTimeout(bot.getApiClient().getClientUser(), channel, server, author, Duration.ofHours(1)); // bot.getCommands().getModCommands().banImpl(author.getId(), author.getUsername(), // server.getId(), channel.getId()); bot.getApiClient().sendMessage(String.format("`%s#%s` (%s) has been banned for mention spam", author.getUsername(), author.getDiscriminator(), author.getId()), channel); } } @Subscribe public void onServerJoinLeave(ServerJoinLeaveEvent event) { if (isSelfBot()) { return; } if (!bot.getMainCommandDispatcher().active().get()) { return; } if (event.isJoin()) { Server server = event.getServer(); // Default channel has same ID as server Channel channel = bot.getApiClient().getChannelById(server.getId()); if (channel != DiscordApiClient.NO_CHANNEL) { // bot.getApiClient().sendMessage(bot.getLocalizer().localize("message.on_join.response", // bot.getApiClient().getClientUser().getUsername()), // channel.getId()); } } } @Subscribe public void onMemberChangeEvent(MemberChangeEvent event) { if (isSelfBot()) { return; } if (!bot.getMainCommandDispatcher().active().get()) { return; } Server server = event.getServer(); // Default channel has same ID as server Channel channel = bot.getApiClient().getChannelById(server.getId()); if (channel == DiscordApiClient.NO_CHANNEL) { return; } String cid = channel.getId(); String key; if (event.getMemberChange() == MemberChangeEvent.MemberChange.ADDED) { key = "message.new_member.response"; cid = SafeNav.of(joinMessageRedirect.get(server.getId())).orElse(cid); } else if (event.getMemberChange() == MemberChangeEvent.MemberChange.DELETED) { key = "message.member_quit.response"; cid = SafeNav.of(leaveMessageRedirect.get(server.getId())).orElse(cid); } else { return; } User user = event.getMember().getUser(); // 167264528537485312 dnnacd #activity-log // avoid duplicates if (event.getServer().getId().equals("106293726271246336") && !"167264528537485312".equals(cid)) { bot.getApiClient().sendMessage(bot.getLocalizer().localize(key, user.getUsername(), user.getId(), user.getDiscriminator(), DateTimeFormatter.ofPattern("HH:mm:ss z").format(ZonedDateTime.now())), "167264528537485312"); } TempServerConfig config = bot.getCommands().getModCommands().getServerStorage().get(server.getId()); String customWelcomeMessage = SafeNav.of(config).get(TempServerConfig::getCustomWelcomeMessage); String customLeaveMessage = SafeNav.of(config).get(TempServerConfig::getCustomLeaveMessage); if (event.getMemberChange() == MemberChangeEvent.MemberChange.ADDED && customWelcomeMessage != null) { if (!customWelcomeMessage.isEmpty()) { bot.getApiClient().sendMessage(createJoinLeaveMessage(user, server, customWelcomeMessage), cid); } } else if (event.getMemberChange() == MemberChangeEvent.MemberChange.DELETED && customLeaveMessage != null) { if (!customLeaveMessage.isEmpty()) { bot.getApiClient().sendMessage(createJoinLeaveMessage(user, server, customLeaveMessage), cid); } } else { bot.getApiClient().sendMessage(bot.getLocalizer().localize(key, user.getUsername(), user.getId(), user.getDiscriminator(), DateTimeFormatter.ofPattern("HH:mm:ss z").format(ZonedDateTime.now())), cid); } memberChangeEventListener.values().forEach(c -> c.accept(event)); } public boolean isJoin(MemberChangeEvent event) { return event.getMemberChange() == MemberChangeEvent.MemberChange.ADDED; } @Subscribe public void onMemberPresenceUpdate(PresenceUpdateEvent event) { if (isSelfBot()) { return; } // not dnnacd if (!event.getServer().getId().equals("106293726271246336")) { return; } User user = event.getPresenceUpdate().getUser(); if (user.getUsername() != null && !event.getOldUsername().equals(user.getUsername())) { // 167264528537485312 dnnacd #activity-log bot.getApiClient().sendMessage(String.format("`%s` changed name to `%s` (%s)", event.getOldUsername(), user.getUsername(), user.getId()), "167264528537485312"); } } private void onInviteLinkPrivateMessage(Message message) { if (isSelfBot()) { return; } if (!message.isPrivateMessage()) { return; } if (message.getContent().startsWith("https://discord.gg/")) { bot.getApiClient().sendMessage(bot.getLocalizer().localize("message.private.invite"), message.getChannelId()); User author = message.getAuthor(); VahrhedralBot.LOGGER.info("Received invite link from {}#{} ({}), rejecting: {}", author.getUsername(), author.getDiscriminator(), author.getId(), message.getContent()); } } private void onOtherTypesCommand(Message message) { if (isSelfBot()) { return; } if (!message.isPrivateMessage()) { return; } String content = message.getContent().toLowerCase(); if (content.startsWith("~") || content.startsWith("!") || content.startsWith("-")) { bot.getApiClient().sendMessage(bot.getLocalizer().localize("message.private.misc", bot.getConfig().getCommandPrefix()), message.getChannelId()); } } private boolean isSelfBot() { return bot.getConfig().isSelfBot(); } public void registerMessageListner(String name, Consumer<Message> listener) { messageListeners.put(Objects.requireNonNull(name), Objects.requireNonNull(listener)); } public void deleteMessageListener(String name) { messageListeners.remove(Objects.requireNonNull(name)); } @Subscribe public void onLogIn(LogInEvent logInEvent) { if (!bot.getConfig().isSelfBot() && versionTrackers.isEmpty()) { for (RegionDescriptor regionDescriptor : bot.getConfig().getDnRegions()) { VersionTracker tracker = new VersionTracker(regionDescriptor, bot.getApiClient().getEventBus()); versionTrackers.put(regionDescriptor.getRegionCode(), tracker); VahrhedralBot.LOGGER.info("Registered version tracker for " + regionDescriptor.getRegionCode()); executorService.execute(tracker); executorService.schedule(tracker, 1, TimeUnit.MINUTES); } } bot.getCommands().onLogIn(logInEvent); } public Map<String, VersionTracker> getVersionTrackers() { return versionTrackers; } }
package step.grid.agent; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import javax.json.Json; import javax.json.JsonObject; import org.junit.Assert; import org.junit.Test; import step.grid.TokenWrapper; import step.grid.io.OutputMessage; import step.grid.tokenpool.Interest; public class AgentTest extends AbstractGridTest { @Test public void test() throws Exception { Map<String, Interest> interests = new HashMap<>(); interests.put("att1", new Interest(Pattern.compile("val.*"), true)); JsonObject o = newDummyJson(); TokenWrapper token = client.getTokenHandle(null, interests, true); OutputMessage outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 1000); Assert.assertEquals(outputMessage.getPayload(), o);; } @Test public void testNoSession() throws Exception { Map<String, Interest> interests = new HashMap<>(); interests.put("att1", new Interest(Pattern.compile("val.*"), true)); JsonObject o = newDummyJson(); TokenWrapper token = client.getTokenHandle(null, interests, false); OutputMessage outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 1000); Assert.assertEquals(outputMessage.getPayload(), o);; } @Test public void testTimeout() throws Exception { JsonObject o = Json.createObjectBuilder().add("delay", 4000).build(); TokenWrapper token = client.getTokenHandle(null, null, true); OutputMessage outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 100); Assert.assertEquals("Timeout while processing request. Request execution interrupted successfully.",outputMessage.getError()); Assert.assertTrue(outputMessage.getAttachments().get(0).getName().equals("stacktrace_before_interruption.log")); // check if the token has been returned to the pool. In this case the second call should return the same error outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 10); Assert.assertEquals("Timeout while processing request. Request execution interrupted successfully.",outputMessage.getError()); } @Test public void testTimeoutNoTokenReturn() throws Exception { JsonObject o = Json.createObjectBuilder().add("delay", 500).add("notInterruptable", true).build(); TokenWrapper token = client.getTokenHandle(null, null, true); OutputMessage outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 100); Assert.assertEquals("Timeout while processing request. WARNING: Request execution couldn't be interrupted. Subsequent calls to that token may fail!",outputMessage.getError()); Assert.assertTrue(outputMessage.getAttachments().get(0).getName().equals("stacktrace_before_interruption.log")); // check if the token has been returned to the pool. In this case the second call should return the same error outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 10); // we are now allowing for "stuck" tokens to be reused, which means we're potentially letting threads leak on the agent. //Assert.assertTrue(outputMessage.getError().contains("already in use")); Thread.sleep(1000); o = newDummyJson(); // After "delayAfterInterruption" the token should have been returned to the pool outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 10); Assert.assertEquals(outputMessage.getPayload(), o);; } @Test public void testLocalToken() throws Exception { JsonObject o = newDummyJson(); TokenWrapper token = client.getLocalTokenHandle(); OutputMessage outputMessage = client.call(token, "testFunction", o, TestTokenHandler.class.getName(), null, null, 1000); Assert.assertEquals(outputMessage.getPayload(), o);; } }
package com.almasb.fxgl.app; import com.almasb.fxeventbus.EventBus; import com.almasb.fxgl.asset.AssetLoader; import com.almasb.fxgl.audio.AudioPlayer; import com.almasb.fxgl.event.FXGLEvent; import com.almasb.fxgl.gameplay.AchievementManager; import com.almasb.fxgl.gameplay.NotificationService; import com.almasb.fxgl.gameplay.qte.QTE; import com.almasb.fxgl.input.Input; import com.almasb.fxgl.logging.Logger; import com.almasb.fxgl.logging.SystemLogger; import com.almasb.fxgl.net.Net; import com.almasb.fxgl.scene.Display; import com.almasb.fxgl.settings.GameSettings; import com.almasb.fxgl.settings.ReadOnlyGameSettings; import com.almasb.fxgl.time.MasterTimer; import com.almasb.fxgl.util.ExceptionHandler; import com.almasb.fxgl.util.FXGLCheckedExceptionHandler; import com.almasb.fxgl.util.Version; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Rectangle2D; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.stage.Stage; import java.io.IOException; import java.io.InputStream; import java.time.LocalDate; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; import java.util.concurrent.Executor; /** * General FXGL application that configures services for all parts to use. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ abstract class FXGLApplication extends Application { /** * We use system logger because logger service is not yet ready. */ private static final Logger log = SystemLogger.INSTANCE; static { Version.print(); setDefaultCheckedExceptionHandler(new FXGLCheckedExceptionHandler()); } private static ExceptionHandler defaultCheckedExceptionHandler; /** * @return handler for checked exceptions */ public static ExceptionHandler getDefaultCheckedExceptionHandler() { return defaultCheckedExceptionHandler; } /** * Set handler for checked exceptions. * * @param handler exception handler */ public static final void setDefaultCheckedExceptionHandler(ExceptionHandler handler) { defaultCheckedExceptionHandler = error -> { log.warning("Checked Exception:"); log.warning(SystemLogger.INSTANCE.errorTraceAsString(error)); handler.handle(error); }; } @Override public final void init() throws Exception { log.debug("Initializing FXGL"); } @Override public void start(Stage stage) throws Exception { log.debug("Starting FXGL"); long start = System.nanoTime(); initSystemProperties(); initUserProperties(); initAppSettings(); FXGL.configure(this, stage); log.debug("FXGL configuration complete"); log.info("FXGL configuration took: " + (System.nanoTime() - start) / 1000000000.0 + " sec"); if (shouldCheckForUpdate() && getSettings().getApplicationMode() != ApplicationMode.RELEASE) checkForUpdates(); } @Override public final void stop() { log.debug("Exiting FXGL"); } /** * Pause the application. */ protected void pause() { log.debug("Pausing main loop"); getEventBus().fireEvent(FXGLEvent.pause()); } /** * Resume the application. */ protected void resume() { log.debug("Resuming main loop"); getEventBus().fireEvent(FXGLEvent.resume()); } /** * Reset the application. */ protected void reset() { log.debug("Resetting FXGL application"); getEventBus().fireEvent(FXGLEvent.reset()); } /** * Exit the application. * Safe to call this from a paused state. */ protected void exit() { log.debug("Exiting Normally"); getEventBus().fireEvent(FXGLEvent.exit()); FXGL.destroy(); stop(); log.close(); Platform.exit(); System.exit(0); } /** * Load FXGL system properties. */ private void initSystemProperties() { log.debug("Initializing system properties"); ResourceBundle props = ResourceBundle.getBundle("com.almasb.fxgl.app.system"); props.keySet().forEach(key -> { Object value = props.getObject(key); FXGL.setProperty(key, value); log.debug(key + " = " + value); }); } /** * Load user defined properties to override FXGL system properties. */ private void initUserProperties() { log.debug("Initializing user properties"); // services are not ready yet, so load manually try (InputStream is = getClass().getResource("/assets/properties/system.properties").openStream()) { ResourceBundle props = new PropertyResourceBundle(is); props.keySet().forEach(key -> { Object value = props.getObject(key); FXGL.setProperty(key, value); log.debug(key + " = " + value); }); } catch (NullPointerException npe) { log.info("User properties not found. Using system"); } catch (IOException e) { log.warning("Loading user properties failed: " + e.getMessage()); } } /** * Take app settings from user. */ private void initAppSettings() { log.debug("Initializing app settings"); GameSettings localSettings = new GameSettings(); initSettings(localSettings); settings = localSettings.toReadOnly(); } /** * Returns true if first run or required number of days have passed. * * @return whether we need check for updates */ private boolean shouldCheckForUpdate() { if (FXGL.isFirstRun()) return true; LocalDate lastChecked = FXGL.getSystemBundle().get("version.check"); return lastChecked != null && lastChecked.plusDays(FXGL.getInt("version.check.days")).isBefore(LocalDate.now()); } /** * Shows a blocking JavaFX dialog, while it runs an async task * to connect to FXGL repo and find latest version string. */ private void checkForUpdates() { log.debug("Checking for updates"); Dialog<ButtonType> dialog = new Dialog<>(); dialog.setTitle("FXGL Update"); dialog.getDialogPane().setContentText("Checking for updates...\n \n "); dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); Button button = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK); button.setDisable(true); button.setText("Open GitHub"); button.setOnAction(e -> { getNet().openBrowserTask(FXGL.getString("url.github")) .onFailure(error -> log.warning("Error opening browser: " + error)) .execute(); }); getNet().getLatestVersionTask() .onSuccess(version -> { FXGL.getSystemBundle().put("version.check", LocalDate.now()); dialog.getDialogPane().setContentText("Just so you know\n" + "Your version: " + Version.getAsString() + "\n" + "Latest version: " + version); button.setDisable(false); }) .onFailure(error -> { // not important, just log it log.warning("Failed to find updates: " + error); dialog.getDialogPane().setContentText("Failed to find updates: " + error); button.setDisable(false); }) .executeAsyncWithDialogFX(getExecutor()); // blocking call dialog.showAndWait(); } /** * Settings for this game instance. This is an internal copy * of the settings so that they will not be modified during game lifetime. */ private ReadOnlyGameSettings settings; /** * @return read only copy of game settings */ public final ReadOnlyGameSettings getSettings() { return settings; } /** * Initialize app settings. * * @param settings app settings */ protected abstract void initSettings(GameSettings settings); /** * Returns target width of the application. This is the * width that was set using GameSettings. * Note that the resulting * width of the scene might be different due to end user screen, in * which case transformations will be automatically scaled down * to ensure identical image on all screens. * * @return target width */ public final double getWidth() { return getSettings().getWidth(); } /** * Returns target height of the application. This is the * height that was set using GameSettings. * Note that the resulting * height of the scene might be different due to end user screen, in * which case transformations will be automatically scaled down * to ensure identical image on all screens. * * @return target height */ public final double getHeight() { return getSettings().getHeight(); } /** * Returns the visual area within the application window, * excluding window borders. Note that it will return the * rectangle with set target width and height, not actual * screen width and height. Meaning on smaller screens * the area will correctly return the GameSettings' width and height. * <p> * Equivalent to new Rectangle2D(0, 0, getWidth(), getHeight()). * * @return screen bounds */ public final Rectangle2D getScreenBounds() { return new Rectangle2D(0, 0, getWidth(), getHeight()); } /** * @return current tick */ public final long getTick() { return getMasterTimer().getTick(); } /** * @return current time since start of game in nanoseconds */ public final long getNow() { return getMasterTimer().getNow(); } /** * @return event bus */ public final EventBus getEventBus() { return FXGL.getEventBus(); } /** * @return display service */ public final Display getDisplay() { return FXGL.getDisplay(); } /** * @return input service */ public final Input getInput() { return FXGL.getInput(); } /** * @return audio player */ public final AudioPlayer getAudioPlayer() { return FXGL.getAudioPlayer(); } /** * @return asset loader */ public final AssetLoader getAssetLoader() { return FXGL.getAssetLoader(); } /** * @return master timer */ public final MasterTimer getMasterTimer() { return FXGL.getMasterTimer(); } /** * @return executor service */ public final Executor getExecutor() { return FXGL.getExecutor(); } /** * @return notification service */ public final NotificationService getNotificationService() { return FXGL.getNotificationService(); } /** * @return achievement manager */ public final AchievementManager getAchievementManager() { return FXGL.getAchievementManager(); } /** * @return QTE service */ public final QTE getQTE() { return FXGL.getQTE(); } /** * @return net service */ public final Net getNet() { return FXGL.getNet(); } }
package com.almasb.fxgl.app; import com.almasb.easyio.EasyIO; import com.almasb.ents.Entity; import com.almasb.ents.EntityWorldListener; import com.almasb.fxeventbus.EventBus; import com.almasb.fxgl.devtools.DeveloperTools; import com.almasb.fxgl.devtools.profiling.Profiler; import com.almasb.fxgl.event.*; import com.almasb.fxgl.gameplay.GameWorld; import com.almasb.fxgl.gameplay.SaveLoadManager; import com.almasb.fxgl.input.FXGLInputEvent; import com.almasb.fxgl.input.InputModifier; import com.almasb.fxgl.input.UserAction; import com.almasb.fxgl.io.DataFile; import com.almasb.fxgl.io.SaveFile; import com.almasb.fxgl.logging.Logger; import com.almasb.fxgl.logging.SystemLogger; import com.almasb.fxgl.physics.PhysicsWorld; import com.almasb.fxgl.scene.*; import com.almasb.fxgl.scene.menu.MenuEventListener; import com.almasb.fxgl.settings.UserProfile; import com.almasb.fxgl.settings.UserProfileSavable; import com.almasb.fxgl.ui.UIFactory; import com.almasb.fxgl.util.ExceptionHandler; import com.almasb.fxgl.util.FXGLUncaughtExceptionHandler; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.concurrent.Task; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; import java.time.LocalDateTime; /** * To use FXGL extend this class and implement necessary methods. * The initialization process can be seen below (irrelevant phases are omitted): * <p> * <ol> * <li>Instance fields of YOUR subclass of GameApplication</li> * <li>initSettings()</li> * <li>Services configuration (after this you can safely call FXGL.getService())</li> * <li>initAchievements()</li> * <li>initInput()</li> * <li>preInit()</li> * <p>The following phases are NOT executed on UI thread</p> * <li>initAssets()</li> * <li>initGame() OR loadState()</li> * <li>initPhysics()</li> * <li>initUI()</li> * <li>Start of main game loop execution on UI thread</li> * </ol> * <p> * Unless explicitly stated, methods are not thread-safe and must be * executed on JavaFX Application (UI) Thread. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public abstract class GameApplication extends FXGLApplication implements UserProfileSavable { private static Logger log = SystemLogger.INSTANCE; { log.debug("Starting JavaFX"); setDefaultUncaughtExceptionHandler(new FXGLUncaughtExceptionHandler()); } /** * Set handler for runtime uncaught exceptions. * * @param handler exception handler */ public final void setDefaultUncaughtExceptionHandler(ExceptionHandler handler) { Thread.setDefaultUncaughtExceptionHandler((thread, error) -> { pause(); log.fatal("Uncaught Exception:"); log.fatal(SystemLogger.INSTANCE.errorTraceAsString(error)); log.fatal("Application will now exit"); handler.handle(error); exit(); }); } private ObjectProperty<ApplicationState> state = new SimpleObjectProperty<>(ApplicationState.STARTUP); /** * @return current application state */ public final ApplicationState getState() { return state.get(); } private void setState(ApplicationState appState) { log.debug("State: " + getState() + " -> " + appState); state.set(appState); switch (appState) { case INTRO: getDisplay().setScene(introScene); break; case LOADING: getDisplay().setScene(loadingScene); break; case MAIN_MENU: getDisplay().setScene(mainMenuScene); break; case GAME_MENU: getDisplay().setScene(gameMenuScene); break; case PLAYING: getDisplay().setScene(getGameScene()); break; case PAUSED: // no need to do anything break; default: log.warning("Attempted to set illegal state: " + appState); break; } } private GameWorld gameWorld; private PhysicsWorld physicsWorld; private GameScene gameScene; /** * @return game world */ public final GameWorld getGameWorld() { return gameWorld; } /** * @return physics world */ public final PhysicsWorld getPhysicsWorld() { return physicsWorld; } /** * @return game scene */ public final GameScene getGameScene() { return gameScene; } private SceneFactory sceneFactory; /** * Override to provide custom intro/loading/menu scenes. * * @return scene factory */ protected SceneFactory initSceneFactory() { return new SceneFactory(); } /** * Intro scene, this is shown when the application started, * before menus and game. */ private IntroScene introScene; /** * This scene is shown during app initialization, * i.e. when assets / game are loaded on bg thread. */ private LoadingScene loadingScene; /** * Main menu, this is the menu shown at the start of game. */ private FXGLMenu mainMenuScene; /** * In-game menu, this is shown when menu key pressed during the game. */ private FXGLMenu gameMenuScene; /** * Main game profiler. */ private Profiler profiler; /** * Override to register your achievements. * * <pre> * Example: * * AchievementManager am = getAchievementManager(); * am.registerAchievement(new Achievement("Score Master", "Score 20000 points")); * </pre> */ protected void initAchievements() { } /** * Initialize input, i.e. bind key presses, bind mouse buttons. * * <p> * Note: This method is called prior to any game init to * register input mappings in the menus. * </p> * <pre> * Example: * * Input input = getInput(); * input.addAction(new UserAction("Move Left") { * protected void onAction() { * playerControl.moveLeft(); * } * }, KeyCode.A); * </pre> */ protected abstract void initInput(); /** * This is called after core services are initialized * but before any game init. Called only once * per application lifetime. */ protected void preInit() { } /** * Initialize game assets, such as Texture, Sound, Music, etc. */ protected abstract void initAssets(); /** * Called when MenuEvent.SAVE occurs. * Note: if you enable menus, you are responsible for providing * appropriate serialization of your game state, even if it's ad-hoc null. * * @return data with required info about current state * @throws UnsupportedOperationException if was not overridden */ protected DataFile saveState() { log.warning("Called saveState(), but it wasn't overridden!"); throw new UnsupportedOperationException("Default implementation is not available"); } /** * Called when MenuEvent.LOAD occurs. * Note: if you enable menus, you are responsible for providing * appropriate deserialization of your game state, even if it's ad-hoc no-op. * * @param dataFile previously saved data * @throws UnsupportedOperationException if was not overridden */ protected void loadState(DataFile dataFile) { log.warning("Called loadState(), but it wasn't overridden!"); throw new UnsupportedOperationException("Default implementation is not available"); } /** * Initialize game objects. */ protected abstract void initGame(); /** * Initialize collision handlers, physics properties. */ protected abstract void initPhysics(); /** * Initialize UI objects. */ protected abstract void initUI(); /** * Main loop update phase, most of game logic. * * @param tpf time per frame */ protected abstract void onUpdate(double tpf); private void initGlobalEventHandlers() { log.debug("Initializing global event handlers"); EventBus bus = getEventBus(); Font fpsFont = UIFactory.newFont(24); getMasterTimer().setUpdateListener(event -> { getInput().onUpdateEvent(event); getAudioPlayer().onUpdateEvent(event); getGameWorld().onUpdateEvent(event); getPhysicsWorld().onUpdateEvent(event); getGameScene().onUpdateEvent(event); onUpdate(event.tpf()); // notify rest bus.fireEvent(event); if (getSettings().isFPSShown()) { GraphicsContext g = getGameScene().getGraphicsContext(); g.setFont(fpsFont); g.setFill(Color.RED); String text = String.format("FPS: [%d]\nPerformance: [%d]", getMasterTimer().getFPS(), getMasterTimer().getPerformanceFPS()); g.fillText(text, 0, getHeight() - 40); } }); // Save/Load events bus.addEventHandler(SaveEvent.ANY, event -> { getInput().save(event.getProfile()); getDisplay().save(event.getProfile()); getAudioPlayer().save(event.getProfile()); getAchievementManager().save(event.getProfile()); getMasterTimer().save(event.getProfile()); }); bus.addEventHandler(LoadEvent.ANY, event -> { getInput().load(event.getProfile()); getDisplay().load(event.getProfile()); getAudioPlayer().load(event.getProfile()); getAchievementManager().load(event.getProfile()); if (event.getEventType() != LoadEvent.RESTORE_SETTINGS) { getMasterTimer().load(event.getProfile()); } }); bus.addEventHandler(FXGLEvent.PAUSE, event -> { getInput().onPause(); getMasterTimer().onPause(); setState(ApplicationState.PAUSED); }); bus.addEventHandler(FXGLEvent.RESUME, event -> { getInput().onResume(); getMasterTimer().onResume(); setState(ApplicationState.PLAYING); }); bus.addEventHandler(FXGLEvent.RESET, event -> { getGameWorld().reset(); getGameScene().onWorldReset(); getInput().onReset(); getMasterTimer().onReset(); }); bus.addEventHandler(FXGLEvent.EXIT, event -> { saveProfile(); }); getGameWorld().addWorldListener(getPhysicsWorld()); getGameWorld().addWorldListener(getGameScene()); // we need to add this listener // to publish entity events via our event bus getGameWorld().addWorldListener(new EntityWorldListener() { @Override public void onEntityAdded(Entity entity) { bus.fireEvent(WorldEvent.entityAdded(entity)); } @Override public void onEntityRemoved(Entity entity) { bus.fireEvent(WorldEvent.entityRemoved(entity)); } }); // Scene getGameScene().addEventHandler(MouseEvent.ANY, event -> { FXGLInputEvent e = new FXGLInputEvent(event, getGameScene().screenToGame(new Point2D(event.getSceneX(), event.getSceneY()))); getInput().onInputEvent(e); }); getGameScene().addEventHandler(KeyEvent.ANY, event -> { getInput().onInputEvent(new FXGLInputEvent(event, Point2D.ZERO)); }); bus.addEventHandler(NotificationEvent.ANY, event -> { getAudioPlayer().onNotificationEvent(event); }); bus.addEventHandler(AchievementEvent.ANY, event -> { getNotificationService().onAchievementEvent(event); }); // FXGL App bus.addEventHandler(DisplayEvent.CLOSE_REQUEST, e -> exit()); bus.addEventHandler(DisplayEvent.DIALOG_OPENED, e -> { if (getState() == ApplicationState.INTRO || getState() == ApplicationState.LOADING) return; if (!isMenuOpen()) pause(); getInput().onReset(); }); bus.addEventHandler(DisplayEvent.DIALOG_CLOSED, e -> { if (getState() == ApplicationState.INTRO || getState() == ApplicationState.LOADING) return; if (!isMenuOpen()) resume(); }); } /** * @return true if any menu is open */ public boolean isMenuOpen() { return getState() == ApplicationState.GAME_MENU || getState() == ApplicationState.MAIN_MENU; } /** * @return true if game is paused or menu is open */ public boolean isPaused() { return isMenuOpen() || getState() == ApplicationState.PAUSED; } private boolean canSwitchGameMenu = true; private void onMenuKey(boolean pressed) { if (!pressed) { canSwitchGameMenu = true; return; } if (canSwitchGameMenu) { if (getState() == ApplicationState.GAME_MENU) { canSwitchGameMenu = false; resume(); } else if (getState() == ApplicationState.PLAYING) { canSwitchGameMenu = false; pause(); setState(ApplicationState.GAME_MENU); } else { log.warning("Menu key pressed in unknown state: " + getState()); } } } /** * Creates Main and Game menu scenes. * Registers them with the Display service. * Adds key binding so that scenes can be switched on menu key press. */ private void configureMenu() { mainMenuScene = sceneFactory.newMainMenu(this); gameMenuScene = sceneFactory.newGameMenu(this); MenuEventHandler handler = new MenuEventHandler(); mainMenuScene.setListener(handler); gameMenuScene.setListener(handler); getDisplay().registerScene(mainMenuScene); getDisplay().registerScene(gameMenuScene); EventHandler<KeyEvent> menuKeyHandler = event -> { if (event.getCode() == getSettings().getMenuKey()) { onMenuKey(event.getEventType() == KeyEvent.KEY_PRESSED); } }; getGameScene().addEventHandler(KeyEvent.ANY, menuKeyHandler); gameMenuScene.addEventHandler(KeyEvent.ANY, menuKeyHandler); } private class MenuEventHandler implements MenuEventListener { @Override public void onNewGame() { startNewGame(); } @Override public void onContinue() { saveLoadManager.loadLastModifiedSaveFileTask() .then(file -> saveLoadManager.loadTask(file)) .onSuccess(GameApplication.this::startLoadedGame) .executeAsyncWithDialogFX(new ProgressDialog("Loading...")); } @Override public void onResume() { resume(); } private void doSave(String saveFileName) { DataFile dataFile = saveState(); SaveFile saveFile = new SaveFile(saveFileName, LocalDateTime.now()); saveLoadManager.saveTask(dataFile, saveFile) .executeAsyncWithDialogFX(new ProgressDialog("Saving data: " + saveFileName)); } @Override public void onSave() { getDisplay().showInputBox("Enter save file name", DialogPane.ALPHANUM, saveFileName -> { if (saveLoadManager.saveFileExists(saveFileName)) { getDisplay().showConfirmationBox("Overwrite save [" + saveFileName + "]?", yes -> { if (yes) doSave(saveFileName); }); } else { doSave(saveFileName); } }); } @Override public void onLoad(SaveFile saveFile) { getDisplay().showConfirmationBox("Load save [" + saveFile.getName() + "]?\n" + "Unsaved progress will be lost!", yes -> { if (yes) { saveLoadManager.loadTask(saveFile) .onSuccess(GameApplication.this::startLoadedGame) .executeAsyncWithDialogFX(new ProgressDialog("Loading: " + saveFile.getName())); } }); } @Override public void onDelete(SaveFile saveFile) { getDisplay().showConfirmationBox("Delete save [" + saveFile.getName() + "]?", yes -> { if (yes) { saveLoadManager.deleteSaveFileTask(saveFile) .executeAsyncWithDialogFX(new ProgressDialog("Deleting: " + saveFile.getName())); } }); } @Override public void onLogout() { getDisplay().showConfirmationBox("Log out?", yes -> { if (yes) { saveProfile(); showProfileDialog(); } }); } @Override public void onMultiplayer() { showMultiplayerDialog(); } @Override public void onExit() { getDisplay().showConfirmationBox("Exit the game?", yes -> { if (yes) exit(); }); } @Override public void onExitToMainMenu() { getDisplay().showConfirmationBox("Exit to Main Menu?\n" + "All unsaved progress will be lost!", yes -> { if (yes) { pause(); reset(); setState(ApplicationState.MAIN_MENU); } }); } } private void configureIntro() { introScene = sceneFactory.newIntro(); introScene.setOnFinished(this::showGame); getDisplay().registerScene(introScene); } /** * Called right before the main stage is shown. */ private void onStageShow() { if (getSettings().isIntroEnabled()) { configureIntro(); setState(ApplicationState.INTRO); introScene.startIntro(); } else { showGame(); } } private void showGame() { if (getSettings().isMenuEnabled()) { configureMenu(); setState(ApplicationState.MAIN_MENU); // we haven't shown the dialog yet so show now if (getSettings().isIntroEnabled()) showProfileDialog(); } else { startNewGame(); } } private void showMultiplayerDialog() { Button btnHost = UIFactory.newButton("Host..."); btnHost.setOnAction(e -> { getDisplay().showMessageBox("NOT SUPPORTED YET"); }); Button btnConnect = UIFactory.newButton("Connect..."); btnConnect.setOnAction(e -> { getDisplay().showMessageBox("NOT SUPPORTED YET"); }); getDisplay().showBox("Multiplayer Options", UIFactory.newText(""), btnHost, btnConnect); } /** * Show profile dialog so that user selects existing or creates new profile. * The dialog is only dismissed when profile is chosen either way. */ private void showProfileDialog() { ChoiceBox<String> profilesBox = UIFactory.newChoiceBox(FXCollections.observableArrayList()); Button btnNew = UIFactory.newButton("NEW"); Button btnSelect = UIFactory.newButton("SELECT"); btnSelect.disableProperty().bind(profilesBox.valueProperty().isNull()); Button btnDelete = UIFactory.newButton("DELETE"); btnDelete.disableProperty().bind(profilesBox.valueProperty().isNull()); btnNew.setOnAction(e -> { getDisplay().showInputBox("New Profile", DialogPane.ALPHANUM, name -> { profileName = name; saveLoadManager = new SaveLoadManager(profileName); getEventBus().fireEvent(new ProfileSelectedEvent(profileName, false)); saveProfile(); }); }); btnSelect.setOnAction(e -> { profileName = profilesBox.getValue(); saveLoadManager = new SaveLoadManager(profileName); saveLoadManager.loadProfileTask() .onSuccess(profile -> { boolean ok = loadFromProfile(profile); if (!ok) { getDisplay().showErrorBox("Profile is corrupted: " + profileName, this::showProfileDialog); } else { saveLoadManager.loadLastModifiedSaveFileTask() .onSuccess(file -> { getEventBus().fireEvent(new ProfileSelectedEvent(profileName, true)); }) .onFailure(error -> { getEventBus().fireEvent(new ProfileSelectedEvent(profileName, false)); }) .executeAsyncWithDialogFX(new ProgressDialog("Loading last save file")); } }) .onFailure(error -> { getDisplay().showErrorBox("Profile is corrupted: " + profileName + "\nError: " + error.toString(), this::showProfileDialog); }) .executeAsyncWithDialogFX(new ProgressDialog("Loading Profile: "+ profileName)); }); btnDelete.setOnAction(e -> { String name = profilesBox.getValue(); SaveLoadManager.deleteProfileTask(name) .onSuccess(n -> showProfileDialog()) .onFailure(error -> getDisplay().showErrorBox(error.toString(), this::showProfileDialog)) .executeAsyncWithDialogFX(new ProgressDialog("Deleting profile: " + name)); }); SaveLoadManager.loadProfileNamesTask() .onSuccess(names -> { profilesBox.getItems().addAll(names); if (!profilesBox.getItems().isEmpty()) { profilesBox.getSelectionModel().selectFirst(); } getDisplay().showBox("Select profile or create new", profilesBox, btnSelect, btnNew, btnDelete); }) .onFailure(e -> { log.warning(e.toString()); getDisplay().showBox("Select profile or create new", profilesBox, btnSelect, btnNew, btnDelete); }) .executeAsyncWithDialogFX(new ProgressDialog("Loading profiles")); } private void bindScreenshotKey() { getInput().addAction(new UserAction("Screenshot") { @Override protected void onActionBegin() { boolean ok = getDisplay().saveScreenshot(); getNotificationService().pushNotification(ok ? "Screenshot saved" : "Screenshot failed"); } }, KeyCode.P); } private void bindDeveloperKey() { getInput().addAction(new UserAction("Developer Options") { @Override protected void onActionBegin() { log.debug("Scene graph contains " + DeveloperTools.INSTANCE.getChildrenSize(getGameScene().getRoot()) + " nodes"); } }, KeyCode.DIGIT0, InputModifier.CTRL); } private void initFXGL() { initAchievements(); // we call this early to process user input bindings // so we can correctly display them in menus bindScreenshotKey(); bindDeveloperKey(); initInput(); // scan for annotated methods and register them too getInput().scanForUserActions(this); initGlobalEventHandlers(); defaultProfile = createProfile(); preInit(); } @Override public final void start(Stage stage) throws Exception { super.start(stage); // services are now ready, switch to normal logger log = FXGL.getLogger(GameApplication.class); log.debug("Starting Game Application"); EasyIO.INSTANCE.setDefaultExceptionHandler(getDefaultCheckedExceptionHandler()); EasyIO.INSTANCE.setDefaultExecutor(getExecutor()); gameWorld = FXGL.getInstance(GameWorld.class); physicsWorld = FXGL.getInstance(PhysicsWorld.class); gameScene = FXGL.getInstance(GameScene.class); sceneFactory = initSceneFactory(); loadingScene = sceneFactory.newLoadingScene(); getDisplay().registerScene(loadingScene); getDisplay().registerScene(getGameScene()); initFXGL(); onStageShow(); stage.show(); if (getSettings().isMenuEnabled() && !getSettings().isIntroEnabled()) showProfileDialog(); if (getSettings().isProfilingEnabled()) { profiler = FXGL.newProfiler(); profiler.start(); getEventBus().addEventHandler(FXGLEvent.EXIT, e -> { profiler.stop(); profiler.print(); }); } } /** * Initialize user application. */ private void initApp(Task<?> initTask) { log.debug("Initializing App"); // on first run this is no-op, as for rest this ensures // that even without menus and during direct calls to start*Game() // the system is clean pause(); reset(); setState(ApplicationState.LOADING); loadingScene.bind(initTask); log.debug("Starting FXGL Init Thread"); Thread thread = new Thread(initTask, "FXGL Init Thread"); thread.start(); } /** * (Re-)initializes the user application as new and starts the game. */ protected void startNewGame() { log.debug("Starting new game"); initApp(new InitAppTask(this)); } /** * (Re-)initializes the user application from the given data file and starts the game. * * @param dataFile save data to loadTask from */ protected void startLoadedGame(DataFile dataFile) { log.debug("Starting loaded game"); initApp(new InitAppTask(this, dataFile)); } /** * Stores the default profile data. This is used to restore default settings. */ private UserProfile defaultProfile; /** * Stores current selected profile name for this game. */ private String profileName; /** * Create a user profile with current settings. * * @return user profile */ public final UserProfile createProfile() { UserProfile profile = new UserProfile(getSettings().getTitle(), getSettings().getVersion()); save(profile); getEventBus().fireEvent(new SaveEvent(profile)); return profile; } /** * Load from given user profile. * * @param profile the profile * @return true if loaded successfully, false if couldn't load */ public final boolean loadFromProfile(UserProfile profile) { if (!profile.isCompatible(getSettings().getTitle(), getSettings().getVersion())) return false; load(profile); getEventBus().fireEvent(new LoadEvent(LoadEvent.LOAD_PROFILE, profile)); return true; } /** * Restores default settings, e.g. audio, video, controls. */ public final void restoreDefaultSettings() { getEventBus().fireEvent(new LoadEvent(LoadEvent.RESTORE_SETTINGS, defaultProfile)); } private SaveLoadManager saveLoadManager; /** * @return save load manager */ public SaveLoadManager getSaveLoadManager() { if (saveLoadManager == null) { throw new IllegalStateException("SaveLoadManager is not ready"); } return saveLoadManager; } private void saveProfile() { // if it is null then we are running without menus if (profileName != null) { saveLoadManager.saveProfileTask(createProfile()) .onFailure(e -> log.warning("Failed to save profile: " + profileName + " - " + e)) // we execute synchronously to avoid incomplete save since we might be shutting down .execute(); } } @Override public void save(UserProfile profile) { // if there is a need for data save // log.debug("Saving data to profile"); // UserProfile.Bundle bundle = new UserProfile.Bundle("game"); // bundle.put("...", ...); // bundle.log(); // profile.putBundle(bundle); } @Override public void load(UserProfile profile) { // log.debug("Loading data from profile"); // UserProfile.Bundle bundle = profile.getBundle("game"); // bundle.log(); } }
package com.aneeshpu.dpdeppop.schema; import com.aneeshpu.dpdeppop.datatypes.DataType; import org.apache.log4j.Logger; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; public class Column { public static final String COLUMN_NAME = "COLUMN_NAME"; public static final String TYPE_NAME = "TYPE_NAME"; public static final String COLUMN_SIZE = "COLUMN_SIZE"; public static final String IS_NULLABLE = "IS_NULLABLE"; public static final String IS_AUTOINCREMENT = "IS_AUTOINCREMENT"; private String name; private Record record; private DataType dataType; private Column referencingColumn; private YesNo autoIncrement = new YesNo("NO"); private NameValue nameValue; private boolean isPrimaryKey; private static final Logger LOG = Logger.getLogger(Column.class); private Column() { } @Override public String toString() { return name; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Column column = (Column) o; if (name != null ? !name.equals(column.name) : column.name != null) return false; if (record != null ? !record.equals(column.record) : column.record != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (record != null ? record.hashCode() : 0); return result; } public static ColumnBuilder buildColumn() { return new ColumnBuilder(); } public Column getReferencingColumn() { return referencingColumn; } public NameValue nameValue(final Map<String, Map<String, Object>> preassignedValues) { //TODO: How do I get rid of the following if else? if (nameValue != null) { return nameValue; } else if (isPreAssigned(preassignedValues)) { nameValue = new NameValue(name, preassignedValues.get(record.tableName()) .get(name)); } else if (autoIncrement.isTrue()) { nameValue = NameValue.createAutoIncrement(); } else { nameValue = isForeignKey() ? new NameValue(name, referencingColumn.nameValue(preassignedValues).value()) : new NameValue(name, dataType.generateDefaultValue()); } return nameValue; } private boolean isPreAssigned(final Map<String, Map<String, Object>> preassignedValues) { if (!preassignedValues.containsKey(record.tableName())) { if (LOG.isDebugEnabled()) { LOG.debug("No preassigned values for " + record.tableName()); } return false; } return preassignedValues.get(record.tableName()).containsKey(name); } private boolean isForeignKey() { return referencingColumn != null; } public boolean isAutoIncrement() { return autoIncrement.isTrue(); } public void populateGeneratedValue(final ResultSet generatedKeys) throws SQLException { final Object generatedValue = dataType.getGeneratedValue(generatedKeys, name); this.nameValue = new NameValue(name, generatedValue); } public Object value() { return nameValue == null ? null : nameValue.value(); } public boolean isPrimaryKey() { return isPrimaryKey; } public boolean isAssigned() { return nameValue != null && nameValue.isAssigned(); } public String formattedName(final Map<String, Map<String, Object>> preassignedValues) { return nameValue(preassignedValues).formattedName(); } public String formattedValue(final Map<String, Map<String, Object>> preassignedValues) { return nameValue(preassignedValues).formattedValue(); } public static class ColumnBuilder { private final Column column; ColumnBuilder() { column = new Column(); } public ColumnBuilder withName(final String columnName) { column.name = columnName; return this; } public Column create() { return column; } public ColumnBuilder withDataType(final DataType dataType) { column.dataType = dataType; return this; } public ColumnBuilder withIsAutoIncrement(final String autoIncrement) { column.autoIncrement = new YesNo(autoIncrement); return this; } public ColumnBuilder withTable(final Record record) { column.record = record; return this; } public ColumnBuilder withReferencingColumn(final Column referencingColumn) { column.referencingColumn = referencingColumn; return this; } public ColumnBuilder asPrimaryKey(final boolean isPrimaryKey) { column.isPrimaryKey = isPrimaryKey; return this; } } }
package de.najidev.mensaupb.activities; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.widget.TabHost; import java.util.Calendar; import java.util.Date; import de.najidev.mensaupb.R; import de.najidev.mensaupb.helper.DateHelper; public class MensaUPBActivity extends TabActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent = new Intent().setClass(this, DayActivity.class); int resId = 0; for (Date date : DateHelper.getInstance().getDates()) { switch (date.getDay()) { case Calendar.MONDAY: resId = R.drawable.ic_tab_mon; break; case Calendar.TUESDAY: resId = R.drawable.ic_tab_tue; break; case Calendar.WEDNESDAY: resId = R.drawable.ic_tab_wed; break; case Calendar.THURSDAY: resId = R.drawable.ic_tab_thu; break; case Calendar.FRIDAY: resId = R.drawable.ic_tab_fri; break; } spec = tabHost.newTabSpec("tab"+date.getDay()) .setIndicator( date.getDate() + "." + date.getMonth() + ".", res.getDrawable(resId) ) .setContent(intent); tabHost.addTab(spec); } } protected void onResume() { super.onResume(); getTabHost().setCurrentTab(DateHelper.getInstance().getCurrentDateIndex()); } }
package com.cisco.trex.stateless; import com.cisco.trex.ClientBase; import com.cisco.trex.stateless.exception.ServiceModeRequiredException; import com.cisco.trex.stateless.exception.TRexConnectionException; import com.cisco.trex.stateless.model.ApiVersionHandler; import com.cisco.trex.stateless.model.Ipv6Node; import com.cisco.trex.stateless.model.Port; import com.cisco.trex.stateless.model.PortStatus; import com.cisco.trex.stateless.model.Stream; import com.cisco.trex.stateless.model.StreamMode; import com.cisco.trex.stateless.model.StreamModeRate; import com.cisco.trex.stateless.model.StreamRxStats; import com.cisco.trex.stateless.model.StreamVM; import com.cisco.trex.stateless.model.TRexClientResult; import com.cisco.trex.stateless.model.port.PortVlan; import com.cisco.trex.stateless.model.stats.ActivePGIds; import com.cisco.trex.stateless.model.stats.ActivePGIdsRPCResult; import com.cisco.trex.stateless.model.stats.PGIdStatsRPCResult; import com.cisco.trex.stateless.model.vm.VMInstruction; import com.cisco.trex.util.Constants; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.MessageFormat; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.pcap4j.packet.ArpPacket; import org.pcap4j.packet.Dot1qVlanTagPacket; import org.pcap4j.packet.EthernetPacket; import org.pcap4j.packet.IcmpV4CommonPacket; import org.pcap4j.packet.IcmpV4EchoPacket; import org.pcap4j.packet.IcmpV4EchoReplyPacket; import org.pcap4j.packet.IllegalRawDataException; import org.pcap4j.packet.IpV4Packet; import org.pcap4j.packet.IpV4Rfc791Tos; import org.pcap4j.packet.Packet; import org.pcap4j.packet.namednumber.ArpHardwareType; import org.pcap4j.packet.namednumber.ArpOperation; import org.pcap4j.packet.namednumber.EtherType; import org.pcap4j.packet.namednumber.IcmpV4Code; import org.pcap4j.packet.namednumber.IcmpV4Type; import org.pcap4j.packet.namednumber.IpNumber; import org.pcap4j.packet.namednumber.IpVersion; import org.pcap4j.util.ByteArrays; import org.pcap4j.util.MacAddress; /** TRex client for stateless traffic */ public class TRexClient extends ClientBase { private static final String TYPE = "type"; private static final String STREAM = "stream"; private static final String STREAM_ID = "stream_id"; private static final EtherType QInQ = new EtherType((short) 0x88a8, "802.1Q Provider Bridge (Q-in-Q)"); private static final int SESSON_ID = 123456789; TRexClient(TRexTransport transport, Set<String> supportedCommands) { // For unit testing this.transport = transport; this.host = "testHost"; this.port = "testPort"; this.userName = "testUser"; supportedCmds.addAll(supportedCommands); } /** * constructor * * @param host * @param port * @param userName */ public TRexClient(String host, String port, String userName) { this.host = host; this.port = port; this.userName = userName; supportedCmds.add("api_sync_v2"); supportedCmds.add("get_supported_cmds"); EtherType.register(QInQ); } @Override protected void serverAPISync() throws TRexConnectionException { LOGGER.info("Sync API with the TRex"); Map<String, Object> parameters = new HashMap<>(); parameters.put("name", "STL"); parameters.put("major", Constants.STL_API_VERSION_MAJOR); parameters.put("minor", Constants.STL_API_VERSION_MINOR); TRexClientResult<ApiVersionHandler> result = callMethod("api_sync_v2", parameters, ApiVersionHandler.class); if (result.get() == null) { TRexConnectionException e = new TRexConnectionException( MessageFormat.format( "Unable to connect to TRex server. Required API version is {0}.{1}. Error: {2}", Constants.STL_API_VERSION_MAJOR, Constants.STL_API_VERSION_MINOR, result.getError())); LOGGER.error("Unable to sync client with TRex server due to: API_H is null.", e.getMessage()); throw e; } apiH = result.get().getApiH(); LOGGER.info("Received api_H: {}", apiH); } public PortStatus acquirePort(int portIndex, Boolean force) { if (!portHandlers.containsKey(portIndex)) { Map<String, Object> payload = createPayload(portIndex); payload.put("session_id", SESSON_ID); payload.put("user", userName); payload.put("force", force); String json = callMethod("acquire", payload); String handler = getResultFromResponse(json).getAsString(); portHandlers.put(portIndex, handler); } else { LOGGER.debug("Port already acquired, continueing"); } return getPortStatus(portIndex).get(); } /** * Release Port * * @param portIndex * @return PortStatus */ public PortStatus releasePort(int portIndex) { if (!portHandlers.containsKey(portIndex)) { LOGGER.debug("No handler assigned, port is not acquired."); } else { Map<String, Object> payload = createPayload(portIndex); payload.put("user", userName); String result = callMethod("release", payload); if (result.contains("must acquire the context")) { LOGGER.info("Port is not owned by this session, already released or never acquired"); } portHandlers.remove(portIndex); } return getPortStatus(portIndex).get(); } /** * Reset port stop traffic, remove all streams, remove rx queue, disable service mode and release * port * * @param portIndex */ public void resetPort(int portIndex) { acquirePort(portIndex, true); stopTraffic(portIndex); for (String profileId : getProfileIds(portIndex)) { removeAllStreams(portIndex, profileId); } removeRxQueue(portIndex); serviceMode(portIndex, false); releasePort(portIndex); } /** * Set port in service mode, needed to be able to do arp resolution and packet captureing * * @param portIndex * @param isOn * @return PortStatus */ public PortStatus serviceMode(int portIndex, Boolean isOn) { LOGGER.info("Set service mode : {}", isOn ? "on" : "off"); Map<String, Object> payload = createPayload(portIndex); payload.put("enabled", isOn); callMethod("service", payload); return getPortStatus(portIndex).get(); } public void addStream(int portIndex, Stream stream) { addStream(portIndex, "", stream.getId(), stream); } public void addStream(int portIndex, String profileId, Stream stream) { addStream(portIndex, profileId, stream.getId(), stream); } public void addStream(int portIndex, int streamId, JsonObject stream) { addStream(portIndex, "", streamId, stream); } public void addStream(int portIndex, String profileId, int streamId, JsonObject stream) { addStream(portIndex, profileId, streamId, stream); } private void addStream(int portIndex, String profileId, int streamId, Object streamObject) { Map<String, Object> payload = createPayload(portIndex, profileId); payload.put(STREAM_ID, streamId); payload.put(STREAM, streamObject); callMethod("add_stream", payload); } public Stream getStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put("get_pkt", true); payload.put(STREAM_ID, streamId); String json = callMethod("get_stream", payload); JsonObject stream = getResultFromResponse(json).getAsJsonObject().get(STREAM).getAsJsonObject(); return GSON.fromJson(stream, Stream.class); } public void removeStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put(STREAM_ID, streamId); callMethod("remove_stream", payload); } public void removeStream(int portIndex, String profileId, int streamId) { Map<String, Object> payload = createPayload(portIndex, profileId); payload.put(STREAM_ID, streamId); callMethod("remove_stream", payload); } public void removeAllStreams(int portIndex) { removeAllStreams(portIndex, ""); } public void removeAllStreams(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); callMethod("remove_all_streams", payload); } public List<Stream> getAllStreams(int portIndex) { return getAllStreams(portIndex, ""); } public List<Stream> getAllStreams(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); String json = callMethod("get_all_streams", payload); JsonObject streams = getResultFromResponse(json).getAsJsonObject().get("streams").getAsJsonObject(); ArrayList<Stream> streamList = new ArrayList<>(); for (Map.Entry<String, JsonElement> stream : streams.entrySet()) { streamList.add(GSON.fromJson(stream.getValue(), Stream.class)); } return streamList; } public List<Integer> getStreamIds(int portIndex) { return getStreamIds(portIndex, ""); } public List<Integer> getStreamIds(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); String json = callMethod("get_stream_list", payload); JsonArray ids = getResultFromResponse(json).getAsJsonArray(); return StreamSupport.stream(ids.spliterator(), false) .map(JsonElement::getAsInt) .collect(Collectors.toList()); } public void pauseStreams(int portIndex, List<Integer> streams) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_ids", streams); callMethod("pause_streams", payload); } public void resumeStreams(int portIndex, List<Integer> streams) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_ids", streams); callMethod("resume_streams", payload); } public void updateStreams( int portIndex, List<Integer> streams, boolean force, Map<String, Object> multiplier) { Map<String, Object> payload = createPayload(portIndex); payload.put("force", force); payload.put("mul", multiplier); payload.put("stream_ids", streams); callMethod("update_streams", payload); } public List<String> getProfileIds(int portIndex) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_profile_list", payload); JsonArray ids = getResultFromResponse(json).getAsJsonArray(); return StreamSupport.stream(ids.spliterator(), false) .map(JsonElement::getAsString) .collect(Collectors.toList()); } public ActivePGIds getActivePgids() { Map<String, Object> parameters = new HashMap<>(); parameters.put("pgids", ""); return callMethod("get_active_pgids", parameters, ActivePGIdsRPCResult.class).get().getIds(); } public PGIdStatsRPCResult getPgidStats(int[] ids) { Map<String, Object> parameters = new HashMap<>(); parameters.put("pgids", ids); return callMethod("get_pgid_stats", parameters, PGIdStatsRPCResult.class).get(); } public void startTraffic( int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) { startTraffic(portIndex, "", duration, force, mul, coreMask); } public void startTraffic( int portIndex, String profileId, double duration, boolean force, Map<String, Object> mul, int coreMask) { Map<String, Object> payload = createPayload(portIndex, profileId); if (coreMask > 0) { payload.put("core_mask", coreMask); } payload.put("mul", mul); payload.put("duration", duration); payload.put("force", force); callMethod("start_traffic", payload); } public void startAllTraffic( int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) { List<String> profileIds = getProfileIds(portIndex); for (String profileId : profileIds) { startTraffic(portIndex, profileId, duration, force, mul, coreMask); } } public void pauseTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("pause_traffic", payload); } public void resumeTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("resume_traffic", payload); } public void setRxQueue(int portIndex, int size) { Map<String, Object> payload = createPayload(portIndex); payload.put(TYPE, "queue"); payload.put("enabled", true); payload.put("size", size); callMethod("set_rx_feature", payload); } public void removeRxQueue(int portIndex) { Map<String, Object> payload = createPayload(portIndex); payload.put(TYPE, "queue"); payload.put("enabled", false); callMethod("set_rx_feature", payload); } public void removeRxFilters(int portIndex, int profileId) { Map<String, Object> payload = createPayload(portIndex); if (profileId > 0) { payload.put("profile_id", profileId); } callMethod("remove_rx_filters", payload); } /** * Wait until traffic on specified port(s) has ended * * @param timeoutInSecounds * @param rxDelayMs Time to wait (in milliseconds) after last packet was sent, until RX filters * used for measuring flow statistics and latency are removed. This value should reflect the * time it takes packets which were transmitted to arrive to the destination. After this time, * RX filters will be removed, and packets arriving for per flow statistics feature and * latency flows will be counted as errors. * @param ports Ports on which to execute the command */ public void waitOnTrafficToFinish(int timeoutInSecounds, int rxDelayMs, Port... ports) { Map<Port, Boolean> portTrafficMap = new HashMap<>(); long endTime = System.currentTimeMillis() + timeoutInSecounds * 1000; for (Port port : ports) { portTrafficMap.put(port, true); } while (portTrafficMap.containsValue(true)) { for (Entry<Port, Boolean> entry : portTrafficMap.entrySet()) { if (entry.getValue()) { // port is still true, meaning still running traffic // set port to false if traffic is stopped(IDLE) entry.setValue(!getPortStatus(entry.getKey().getIndex()).get().getState().equals("IDLE")); } } if (System.currentTimeMillis() > endTime) { break; } } removeRxFiltersWithDelay(rxDelayMs, ports); } /** * Delay some time to let packets arrive at destination port before removing filters * * @param rxDelayMs * @param ports */ protected void removeRxFiltersWithDelay(int rxDelayMs, Port... ports) { int rxDelayToUse; if (rxDelayMs <= 0) { if (ports[0].is_virtual) { rxDelayToUse = 100; } else { rxDelayToUse = 10; } } else { rxDelayToUse = rxDelayMs; } try { Thread.sleep(rxDelayToUse); } catch (InterruptedException e) { // Do nothing } for (Port port : ports) { removeRxFilters(port.getIndex(), 0); } } /** Set promiscuous mode, Enable interface to receive packets from all mac addresses */ public void setPromiscuousMode(int portIndex, boolean enabled) { Map<String, Object> payload = createPayload(portIndex); Map<String, Object> attributes = new HashMap<>(); Map<String, Object> promiscuousValue = new HashMap<>(); promiscuousValue.put("enabled", enabled); attributes.put("promiscuous", promiscuousValue); payload.put("attr", attributes); callMethod("set_port_attr", payload); } /** Set flow control mode, Flow control: 0 = none, 1 = tx, 2 = rx, 3 = full */ public void setFlowControlMode(int portIndex, int mode) { Map<String, Object> payload = createPayload(portIndex); Map<String, Object> attributes = new HashMap<>(); Map<String, Object> flowCtrlValue = new HashMap<>(); flowCtrlValue.put("enabled", mode); attributes.put("flow_ctrl_mode", flowCtrlValue); payload.put("attr", attributes); callMethod("set_port_attr", payload); } public synchronized void sendPacket(int portIndex, Packet pkt) { Stream stream = build1PktSingleBurstStream(pkt); removeAllStreams(portIndex); addStream(portIndex, stream); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put(TYPE, "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); } public synchronized void startStreamsIntermediate(int portIndex, List<Stream> streams) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); removeAllStreams(portIndex); streams.forEach(s -> addStream(portIndex, s)); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put(TYPE, "percentage"); mul.put("value", 100); startTraffic(portIndex, -1, true, mul, 1); } public synchronized void sendPackets(int portIndex, List<Packet> pkts) { removeAllStreams(portIndex); for (Packet pkt : pkts) { addStream(portIndex, build1PktSingleBurstStream(pkt)); } Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put(TYPE, "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); stopTraffic(portIndex); } public String resolveArp(int portIndex, String srcIp, String dstIp) { String srcMac = getPortByIndex(portIndex).hw_mac; PortVlan vlan = getPortStatus(portIndex).get().getAttr().getVlan(); return resolveArp(portIndex, vlan, srcIp, srcMac, dstIp); } public String resolveArp(int portIndex, String srcIp, String srcMac, String dstIp) { PortVlan vlan = getPortStatus(portIndex).get().getAttr().getVlan(); return resolveArp(portIndex, vlan, srcIp, srcMac, dstIp); } public String resolveArp( int portIndex, PortVlan vlan, String srcIp, String srcMac, String dstIp) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); EthernetPacket pkt = buildArpPkt(srcMac, srcIp, dstIp, vlan); sendPacket(portIndex, pkt); Predicate<EthernetPacket> arpReplyFilter = etherPkt -> { Queue<Integer> vlanTags = new LinkedList<>(vlan.getTags()); Packet nextPkt = etherPkt; boolean vlanOutsideMatches = true; if (etherPkt.getHeader().getType() == QInQ) { try { Dot1qVlanTagPacket qInqPkt = Dot1qVlanTagPacket.newPacket( etherPkt.getRawData(), etherPkt.getHeader().length(), etherPkt.getPayload().length()); vlanOutsideMatches = qInqPkt.getHeader().getVidAsInt() == vlanTags.poll(); nextPkt = qInqPkt.getPayload(); } catch (IllegalRawDataException e) { return false; } } boolean vlanInsideMatches = true; if (nextPkt.contains(Dot1qVlanTagPacket.class)) { Dot1qVlanTagPacket dot1qVlanTagPacket = nextPkt.get(Dot1qVlanTagPacket.class); vlanInsideMatches = dot1qVlanTagPacket.getHeader().getVid() == vlanTags.poll(); } if (nextPkt.contains(ArpPacket.class)) { ArpPacket arp = nextPkt.get(ArpPacket.class); ArpOperation arpOp = arp.getHeader().getOperation(); String replyDstMac = arp.getHeader().getDstHardwareAddr().toString(); boolean arpMatches = ArpOperation.REPLY.equals(arpOp) && replyDstMac.equals(srcMac); return arpMatches && vlanOutsideMatches && vlanInsideMatches; } return false; }; List<org.pcap4j.packet.Packet> pkts = new ArrayList<>(); try { int steps = 10; while (steps > 0) { steps -= 1; Thread.sleep(500); pkts.addAll(getRxQueue(portIndex, arpReplyFilter)); if (!pkts.isEmpty()) { ArpPacket arpPacket = getArpPkt(pkts.get(0)); if (arpPacket != null) { return arpPacket.getHeader().getSrcHardwareAddr().toString(); } } } LOGGER.info("Unable to get ARP reply in {} seconds", steps); } catch (InterruptedException ignored) { } finally { removeRxQueue(portIndex); if (getPortStatus(portIndex).get().getState().equals("TX")) { stopTraffic(portIndex); } removeAllStreams(portIndex); } return null; } private static ArpPacket getArpPkt(Packet pkt) { if (pkt.contains(ArpPacket.class)) { return pkt.get(ArpPacket.class); } try { Dot1qVlanTagPacket unwrapedFromVlanPkt = Dot1qVlanTagPacket.newPacket( pkt.getRawData(), pkt.getHeader().length(), pkt.getPayload().length()); return unwrapedFromVlanPkt.get(ArpPacket.class); } catch (IllegalRawDataException ignored) { } return null; } private static EthernetPacket buildArpPkt( String srcMac, String srcIp, String dstIp, PortVlan vlan) { ArpPacket.Builder arpBuilder = new ArpPacket.Builder(); MacAddress srcMacAddress = MacAddress.getByName(srcMac); try { arpBuilder .hardwareType(ArpHardwareType.ETHERNET) .protocolType(EtherType.IPV4) .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES) .protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES) .operation(ArpOperation.REQUEST) .srcHardwareAddr(srcMacAddress) .srcProtocolAddr(InetAddress.getByName(srcIp)) .dstHardwareAddr(MacAddress.getByName("00:00:00:00:00:00")) .dstProtocolAddr(InetAddress.getByName(dstIp)); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload = new AbstractMap.SimpleEntry<>(EtherType.ARP, arpBuilder); if (!vlan.getTags().isEmpty()) { payload = buildVlan(arpBuilder, vlan); } EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); etherBuilder .dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS) .srcAddr(srcMacAddress) .type(payload.getKey()) .payloadBuilder(payload.getValue()) .paddingAtBuild(true); return etherBuilder.build(); } private static AbstractMap.SimpleEntry<EtherType, Packet.Builder> buildVlan( ArpPacket.Builder arpBuilder, PortVlan vlan) { Queue<Integer> vlanTags = new LinkedList<>(Lists.reverse(vlan.getTags())); Packet.Builder resultPayloadBuilder = arpBuilder; EtherType resultEtherType = EtherType.ARP; if (vlanTags.peek() != null) { Dot1qVlanTagPacket.Builder vlanInsideBuilder = new Dot1qVlanTagPacket.Builder(); vlanInsideBuilder .type(EtherType.ARP) .vid(vlanTags.poll().shortValue()) .payloadBuilder(arpBuilder); resultPayloadBuilder = vlanInsideBuilder; resultEtherType = EtherType.DOT1Q_VLAN_TAGGED_FRAMES; if (vlanTags.peek() != null) { Dot1qVlanTagPacket.Builder vlanOutsideBuilder = new Dot1qVlanTagPacket.Builder(); vlanOutsideBuilder .type(EtherType.DOT1Q_VLAN_TAGGED_FRAMES) .vid(vlanTags.poll().shortValue()) .payloadBuilder(vlanInsideBuilder); resultPayloadBuilder = vlanOutsideBuilder; resultEtherType = QInQ; } } return new AbstractMap.SimpleEntry<>(resultEtherType, resultPayloadBuilder); } private static Stream build1PktSingleBurstStream(Packet pkt) { int streamId = (int) (Math.random() * 1000); return new Stream( streamId, true, 3, 0.0, new StreamMode( 2, 2, 1, 1.0, new StreamModeRate(StreamModeRate.Type.pps, 1.0), StreamMode.Type.single_burst), -1, pkt, new StreamRxStats(true, true, true, streamId), new StreamVM("", Collections.<VMInstruction>emptyList()), true, false, null, -1); } public String resolveIpv6(int portIndex, String dstIp) throws ServiceModeRequiredException { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); EthernetPacket naPacket = new IPv6NeighborDiscoveryService(this).sendNeighborSolicitation(portIndex, 5, dstIp); if (naPacket != null) { return naPacket.getHeader().getSrcAddr().toString(); } return null; } public String resolveIpv6( PortVlan vlan, int portIndex, String srcMac, String srcIp, String dstIp) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); EthernetPacket naPacket = new IPv6NeighborDiscoveryService(this) .sendNeighborSolicitation(vlan, portIndex, 5, srcMac, null, srcIp, dstIp); if (naPacket != null) { return naPacket.getHeader().getSrcAddr().toString(); } return null; } public List<EthernetPacket> getRxQueue(int portIndex, Predicate<EthernetPacket> filter) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_rx_queue_pkts", payload); JsonArray pkts = getResultFromResponse(json).getAsJsonObject().getAsJsonArray("pkts"); return StreamSupport.stream(pkts.spliterator(), false) .map(this::buildEthernetPkt) .filter(filter) .collect(Collectors.toList()); } private EthernetPacket buildEthernetPkt(JsonElement jsonElement) { try { byte[] binary = Base64.getDecoder().decode(jsonElement.getAsJsonObject().get("binary").getAsString()); EthernetPacket pkt = EthernetPacket.newPacket(binary, 0, binary.length); LOGGER.info("Received pkt: {}", pkt.toString()); return pkt; } catch (IllegalRawDataException e) { return null; } } public boolean setL3Mode( int portIndex, String nextHopMac, String sourceIp, String destinationIp) { Map<String, Object> payload = createPayload(portIndex); payload.put("src_addr", sourceIp); payload.put("dst_addr", destinationIp); if (nextHopMac != null) { payload.put("resolved_mac", nextHopMac); } payload.put("block", false); callMethod("set_l3", payload); return true; } public void updatePortHandler(int portID, String handler) { portHandlers.put(portID, handler); } public void invalidatePortHandler(int portID) { portHandlers.remove(portID); } // TODO: move to upper layer public EthernetPacket sendIcmpEcho( int portIndex, String host, int reqId, int seqNumber, long waitResponse) throws UnknownHostException { Port port = getPortByIndex(portIndex); PortStatus portStatus = getPortStatus(portIndex).get(); String srcIp = portStatus.getAttr().getLayerConiguration().getL3Configuration().getSrc(); EthernetPacket icmpRequest = buildIcmpV4Request(port.hw_mac, port.dst_macaddr, srcIp, host, reqId, seqNumber); removeAllStreams(portIndex); setRxQueue(portIndex, 1000); sendPacket(portIndex, icmpRequest); try { Thread.sleep(waitResponse); } catch (InterruptedException ignored) { } try { List<EthernetPacket> receivedPkts = getRxQueue(portIndex, etherPkt -> etherPkt.contains(IcmpV4EchoReplyPacket.class)); if (!receivedPkts.isEmpty()) { return receivedPkts.get(0); } return null; } finally { removeRxQueue(portIndex); } } // TODO: move to upper layer private static EthernetPacket buildIcmpV4Request( String srcMac, String dstMac, String srcIp, String dstIp, int reqId, int seqNumber) throws UnknownHostException { IcmpV4EchoPacket.Builder icmpReqBuilder = new IcmpV4EchoPacket.Builder(); icmpReqBuilder.identifier((short) reqId); icmpReqBuilder.sequenceNumber((short) seqNumber); IcmpV4CommonPacket.Builder icmpv4CommonPacketBuilder = new IcmpV4CommonPacket.Builder(); icmpv4CommonPacketBuilder .type(IcmpV4Type.ECHO) .code(IcmpV4Code.NO_CODE) .correctChecksumAtBuild(true) .payloadBuilder(icmpReqBuilder); IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder(); ipv4Builder .version(IpVersion.IPV4) .tos(IpV4Rfc791Tos.newInstance((byte) 0)) .ttl((byte) 64) .protocol(IpNumber.ICMPV4) .srcAddr((Inet4Address) Inet4Address.getByName(srcIp)) .dstAddr((Inet4Address) Inet4Address.getByName(dstIp)) .correctChecksumAtBuild(true) .correctLengthAtBuild(true) .payloadBuilder(icmpv4CommonPacketBuilder); EthernetPacket.Builder eb = new EthernetPacket.Builder(); eb.srcAddr(MacAddress.getByName(srcMac)) .dstAddr(MacAddress.getByName(dstMac)) .type(EtherType.IPV4) .paddingAtBuild(true) .payloadBuilder(ipv4Builder); return eb.build(); } public void stopTraffic(int portIndex) { stopTraffic(portIndex, ""); } public void stopTraffic(int portIndex, String profileId) { Map<String, Object> payload = createPayload(portIndex, profileId); callMethod("stop_traffic", payload); } public void stopAllTraffic(int portIndex) { List<String> profileIds = getProfileIds(portIndex); for (String profileId : profileIds) { stopTraffic(portIndex, profileId); } } public Map<String, Ipv6Node> scanIPv6(int portIndex) throws ServiceModeRequiredException { return new IPv6NeighborDiscoveryService(this).scan(portIndex, 10, null, null); } public EthernetPacket sendIcmpV6Echo( int portIndex, String dstIp, int icmpId, int icmpSeq, int timeOut) throws ServiceModeRequiredException { return new IPv6NeighborDiscoveryService(this) .sendIcmpV6Echo(portIndex, dstIp, icmpId, icmpSeq, timeOut); } }
package com.cisco.trex.stateless; import com.cisco.trex.stateless.exception.ServiceModeRequiredException; import com.cisco.trex.stateless.exception.TRexConnectionException; import com.cisco.trex.stateless.model.*; import com.cisco.trex.stateless.model.capture.CaptureInfo; import com.cisco.trex.stateless.model.capture.CaptureMonitor; import com.cisco.trex.stateless.model.capture.CaptureMonitorStop; import com.cisco.trex.stateless.model.capture.CapturedPackets; import com.cisco.trex.stateless.model.port.PortStatistics; import com.cisco.trex.stateless.model.port.PortVlan; import com.cisco.trex.stateless.model.vm.VMInstruction; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.gson.*; import org.pcap4j.packet.*; import org.pcap4j.packet.namednumber.*; import org.pcap4j.util.ByteArrays; import org.pcap4j.util.MacAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import static java.lang.Math.abs; public class TRexClient { private static final Logger LOGGER = LoggerFactory.getLogger(TRexClient.class); private static final EtherType QInQ = new EtherType((short)0x88a8, "802.1Q Provider Bridge (Q-in-Q)"); private static String JSON_RPC_VERSION = "2.0"; private static Integer API_VERSION_MAJOR = 4; private static Integer API_VERSION_MINOR = 0; private TRexTransport transport; private Gson gson = new Gson(); private String host; private String port; private String apiH; private String userName = ""; private Integer session_id = 123456789; private Map<Integer, String> portHandlers = new HashMap<>(); private List<String> supportedCmds = new ArrayList<>(); private Random randomizer = new Random(); public TRexClient(String host, String port, String userName) { this.host = host; this.port = port; this.userName = userName; supportedCmds.add("api_sync"); supportedCmds.add("get_supported_cmds"); EtherType.register(QInQ); } public String callMethod(String methodName, Map<String, Object> payload) { LOGGER.info("Call {} method.", methodName); if (!supportedCmds.contains(methodName)) { LOGGER.error("Unsupported {} method.", methodName); throw new UnsupportedOperationException(); } String req = buildRequest(methodName, payload); return call(req); } private String buildRequest(String methodName, Map<String, Object> payload) { if (payload == null) { payload = new HashMap<>(); } Map<String, Object> parameters = new HashMap<>(); parameters.put("id", "aggogxls"); parameters.put("jsonrpc", JSON_RPC_VERSION); parameters.put("method", methodName); payload.put("api_h", apiH); parameters.put("params", payload); return gson.toJson(parameters); } private String call(String json) { return transport.sendJson(json); } public <T> TRexClientResult<T> callMethod(String methodName, Map<String, Object> parameters, Class<T> responseType) { LOGGER.info("Call {} method.", methodName); if (!supportedCmds.contains(methodName)) { LOGGER.error("Unsupported {} method.", methodName); throw new UnsupportedOperationException(); } TRexClientResult<T> result = new TRexClientResult<>(); try { RPCResponse response = transport.sendCommand(buildCommand(methodName, parameters)); if (!response.isFailed()) { T resutlObject = new ObjectMapper().readValue(response.getResult(), responseType); result.set(resutlObject); } else { result.setError(response.getError().getMessage() + " " +response.getError().getSpecificErr()); } } catch (IOException e) { String errorMsg = "Error occurred during processing '"+methodName+"' method with params: " +parameters.toString(); LOGGER.error(errorMsg, e); result.setError(errorMsg); return result; } return result; } public TRexCommand buildCommand(String methodName, Map<String, Object> parameters) { if (parameters == null) { parameters = new HashMap<>(); } parameters.put("api_h", apiH); Map<String, Object> payload = new HashMap<>(); int cmdId = abs(randomizer.nextInt()); payload.put("id", cmdId); payload.put("jsonrpc", JSON_RPC_VERSION); payload.put("method", methodName); if(parameters.containsKey("port_id")) { Integer portId = (Integer) parameters.get("port_id"); String handler = portHandlers.get(portId); if (handler != null) { parameters.put("handler", handler); } } payload.put("params", parameters); return new TRexCommand(cmdId, methodName, payload); } public TRexClientResult<List<RPCResponse>> callMethods(List<TRexCommand> commands) { TRexClientResult<List<RPCResponse>> result = new TRexClientResult<>(); try { RPCResponse[] rpcResponses = transport.sendCommands(commands); result.set(Arrays.asList(rpcResponses)); } catch (IOException e) { String msg = "Unable to send RPC Batch"; result.setError(msg); LOGGER.error(msg, e); } return result; } public void connect() throws TRexConnectionException { transport = new TRexTransport(this.host, this.port, 3000); serverAPISync(); supportedCmds.addAll(getSupportedCommands()); } private String getConnectionAddress() { return "tcp://"+host+":"+port; } private void serverAPISync() throws TRexConnectionException { LOGGER.info("Sync API with the TRex"); Map<String, Object> apiVers = new HashMap<>(); apiVers.put("type", "core"); apiVers.put("major", API_VERSION_MAJOR); apiVers.put("minor", API_VERSION_MINOR); Map<String, Object> parameters = new HashMap<>(); parameters.put("api_vers", Arrays.asList(apiVers)); TRexClientResult<ApiVersion> result = callMethod("api_sync", parameters, ApiVersion.class); if (result.get() == null) { TRexConnectionException e = new TRexConnectionException("Unable to connect to TRex server. Required API version is " +API_VERSION_MAJOR+"."+API_VERSION_MINOR); LOGGER.error("Unable to sync client with TRex server due to: API_H is null.", e.getMessage()); throw e; } apiH = result.get().getApiH(); LOGGER.info("Received api_H: {}", apiH); } public void disconnect() { if (transport != null) { transport.getSocket().close(); transport = null; LOGGER.info("Disconnected"); } else { LOGGER.info("Already disconnected"); } } public void reconnect() throws TRexConnectionException { disconnect(); connect(); } // TODO: move to upper layer public List<Port> getPorts() { LOGGER.info("Getting ports list."); List<Port> ports = getSystemInfo().getPorts(); ports.stream().forEach(port -> { TRexClientResult<PortStatus> result = getPortStatus(port.getIndex()); if (result.isFailed()) { return; } PortStatus status = result.get(); L2Configuration l2config = status.getAttr().getLayerConiguration().getL2Configuration(); port.hw_mac = l2config.getSrc(); port.dst_macaddr = l2config.getDst(); }); return ports; } public Port getPortByIndex(int portIndex) { List<Port> ports = getPorts(); if (ports.stream().noneMatch(p -> p.getIndex() == portIndex)) { LOGGER.error(String.format("Port with index %s was not found. Returning empty port", portIndex)); } return getPorts().stream() .filter(p -> p.getIndex() == portIndex) .findFirst() .orElse(new Port()); } public TRexClientResult<PortStatus> getPortStatus(int portIdx) { Map<String, Object> parameters = new HashMap<>(); parameters.put("port_id", portIdx); parameters.put("block", false); return callMethod("get_port_status", parameters, PortStatus.class); } public PortStatus acquirePort(int portIndex, Boolean force) { Map<String, Object> payload = createPayload(portIndex); payload.put("session_id", session_id); payload.put("user", userName); payload.put("force", force); String json = callMethod("acquire", payload); JsonElement response = new JsonParser().parse(json); String handler = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsString(); portHandlers.put(portIndex, handler); return getPortStatus(portIndex).get(); } public void resetPort(int portIndex) { acquirePort(portIndex, true); stopTraffic(portIndex); removeAllStreams(portIndex); removeRxQueue(portIndex); serviceMode(portIndex, false); releasePort(portIndex); } private Map<String, Object> createPayload(int portIndex) { Map<String, Object> payload = new HashMap<>(); payload.put("port_id", portIndex); payload.put("api_h", apiH); String handler = portHandlers.get(portIndex); if (handler != null) { payload.put("handler", handler); } return payload; } public PortStatus releasePort(int portIndex) { Map<String, Object> payload = createPayload(portIndex); payload.put("user", userName); callMethod("release", payload); portHandlers.remove(portIndex); return getPortStatus(portIndex).get(); } public PortStatistics getPortStatistics(int portIndex) { Map<String, Object> parameters = new HashMap<>(); parameters.put("port_id", portIndex); return callMethod("get_port_stats", parameters, PortStatistics.class).get(); } public List<String> getSupportedCommands() { Map<String, Object> payload = new HashMap<>(); payload.put("api_h", apiH); String json = callMethod("get_supported_cmds", payload); JsonElement response = new JsonParser().parse(json); JsonArray cmds = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray(); return StreamSupport.stream(cmds.spliterator(), false) .map(JsonElement::getAsString) .collect(Collectors.toList()); } public PortStatus serviceMode(int portIndex, Boolean isOn) { LOGGER.info("Set service mode : {}", isOn ? "on" : "off"); Map<String, Object> payload = createPayload(portIndex); payload.put("enabled", isOn); callMethod("service", payload); return getPortStatus(portIndex).get(); } public void addStream(int portIndex, Stream stream) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_id", stream.getId()); payload.put("stream", stream); callMethod("add_stream", payload); } public void addStream(int portIndex, int streamId, JsonObject stream) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_id", streamId); payload.put("stream", stream); callMethod("add_stream", payload); } public Stream getStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put("get_pkt", true); payload.put("stream_id", streamId); String json = callMethod("get_stream", payload); JsonElement response = new JsonParser().parse(json); JsonObject stream = response.getAsJsonArray().get(0) .getAsJsonObject().get("result") .getAsJsonObject().get("stream") .getAsJsonObject(); return gson.fromJson(stream, Stream.class); } public void removeStream(int portIndex, int streamId) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_id", streamId); callMethod("remove_stream", payload); } public void removeAllStreams(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("remove_all_streams", payload); } public List<Integer> getStreamIds(int portIndex) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_stream_list", payload); JsonElement response = new JsonParser().parse(json); JsonArray ids = response.getAsJsonArray().get(0).getAsJsonObject().get("result").getAsJsonArray(); return StreamSupport.stream(ids.spliterator(), false) .map(JsonElement::getAsInt) .collect(Collectors.toList()); } public void pauseStreams(int portIndex, List<Integer> streams) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_ids", streams); callMethod("pause_streams", payload); } public void resumeStreams(int portIndex, List<Integer> streams) { Map<String, Object> payload = createPayload(portIndex); payload.put("stream_ids", streams); callMethod("resume_streams", payload); } public void updateStreams(int portIndex, List<Integer> streams, boolean force, Map<String, Object> multiplier) { Map<String, Object> payload = createPayload(portIndex); payload.put("force", force); payload.put("mul", multiplier); payload.put("stream_ids", streams); callMethod("update_streams", payload); } public SystemInfo getSystemInfo() { String json = callMethod("get_system_info", null); SystemInfoResponse response = gson.fromJson(json, SystemInfoResponse[].class)[0]; return response.getResult(); } public void startTraffic(int portIndex, double duration, boolean force, Map<String, Object> mul, int coreMask) { Map<String, Object> payload = createPayload(portIndex); payload.put("core_mask", coreMask); payload.put("mul", mul); payload.put("duration", duration); payload.put("force", force); callMethod("start_traffic", payload); } public void pauseTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("pause_traffic", payload); } public void resumeTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("resume_traffic", payload); } public void setRxQueue(int portIndex, int size) { Map<String, Object> payload = createPayload(portIndex); payload.put("type", "queue"); payload.put("enabled", true); payload.put("size", size); callMethod("set_rx_feature", payload); } public void removeRxQueue(int portIndex) { Map<String, Object> payload = createPayload(portIndex); payload.put("type", "queue"); payload.put("enabled", false); callMethod("set_rx_feature", payload); } synchronized public void sendPacket(int portIndex, Packet pkt) { Stream stream = build1PktSingleBurstStream(pkt); removeAllStreams(portIndex); addStream(portIndex, stream); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put("type", "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); } synchronized public void startStreamsIntermediate(int portIndex, List<Stream> streams) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); removeAllStreams(portIndex); streams.forEach(s -> addStream(portIndex, s)); Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put("type", "percentage"); mul.put("value", 100); startTraffic(portIndex, -1, true, mul, 1); } synchronized public void sendPackets(int portIndex, List<Packet> pkts) { removeAllStreams(portIndex); for (Packet pkt : pkts) { addStream(portIndex, build1PktSingleBurstStream(pkt)); } Map<String, Object> mul = new HashMap<>(); mul.put("op", "abs"); mul.put("type", "pps"); mul.put("value", 1.0); startTraffic(portIndex, 1, true, mul, 1); stopTraffic(portIndex); } public String resolveArp(int portIndex, String srcIp, String dstIp) { removeRxQueue(portIndex); setRxQueue(portIndex, 1000); String srcMac = getPortByIndex(portIndex).hw_mac; PortVlan vlan = getPortStatus(portIndex).get().getAttr().getVlan(); EthernetPacket pkt = buildArpPkt(srcMac, srcIp, dstIp, vlan); sendPacket(portIndex, pkt); Predicate<EthernetPacket> arpReplyFilter = etherPkt -> { Queue<Integer> vlanTags = new LinkedList<>(vlan.getTags()); Packet next_pkt = etherPkt; boolean vlanOutsideMatches = true; if (etherPkt.getHeader().getType() == QInQ) { try { Dot1qVlanTagPacket QInQPkt = Dot1qVlanTagPacket.newPacket(etherPkt.getRawData(), etherPkt.getHeader().length(), etherPkt.getPayload().length()); vlanOutsideMatches = QInQPkt.getHeader().getVidAsInt() == vlanTags.poll(); next_pkt = QInQPkt.getPayload(); } catch (IllegalRawDataException e) { return false; } } boolean vlanInsideMatches = true; if(next_pkt.contains(Dot1qVlanTagPacket.class)) { Dot1qVlanTagPacket dot1qVlanTagPacket = next_pkt.get(Dot1qVlanTagPacket.class); vlanInsideMatches = dot1qVlanTagPacket.getHeader().getVid() == vlanTags.poll(); } if(next_pkt.contains(ArpPacket.class)) { ArpPacket arp = next_pkt.get(ArpPacket.class); ArpOperation arpOp = arp.getHeader().getOperation(); String replyDstMac = arp.getHeader().getDstHardwareAddr().toString(); boolean arpMatches = ArpOperation.REPLY.equals(arpOp) && replyDstMac.equals(srcMac); return arpMatches && vlanOutsideMatches && vlanInsideMatches; } return false; }; List<org.pcap4j.packet.Packet> pkts = new ArrayList<>(); try { int steps = 10; while (steps > 0) { steps -= 1; Thread.sleep(500); pkts.addAll(getRxQueue(portIndex, arpReplyFilter)); if(!pkts.isEmpty()) { ArpPacket arpPacket = getArpPkt(pkts.get(0)); if (arpPacket != null) return arpPacket.getHeader().getSrcHardwareAddr().toString(); } } LOGGER.info("Unable to get ARP reply in {} seconds", steps); } catch (InterruptedException ignored) {} finally { removeRxQueue(portIndex); if (getPortStatus(portIndex).get().getState().equals("TX")) { stopTraffic(portIndex); } removeAllStreams(portIndex); } return null; } private static ArpPacket getArpPkt(Packet pkt) { if (pkt.contains(ArpPacket.class)) return pkt.get(ArpPacket.class); try { Dot1qVlanTagPacket unwrapedFromVlanPkt = Dot1qVlanTagPacket.newPacket(pkt.getRawData(), pkt.getHeader().length(), pkt.getPayload().length()); return unwrapedFromVlanPkt.get(ArpPacket.class); } catch (IllegalRawDataException ignored) { } return null; } private static EthernetPacket buildArpPkt(String srcMac, String srcIp, String dstIp, PortVlan vlan) { ArpPacket.Builder arpBuilder = new ArpPacket.Builder(); MacAddress srcMacAddress = MacAddress.getByName(srcMac); try { arpBuilder .hardwareType(ArpHardwareType.ETHERNET) .protocolType(EtherType.IPV4) .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES) .protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES) .operation(ArpOperation.REQUEST) .srcHardwareAddr(srcMacAddress) .srcProtocolAddr(InetAddress.getByName(srcIp)) .dstHardwareAddr(MacAddress.getByName("00:00:00:00:00:00")) .dstProtocolAddr(InetAddress.getByName(dstIp)); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } AbstractMap.SimpleEntry<EtherType, Packet.Builder> payload = new AbstractMap.SimpleEntry<>(EtherType.ARP, arpBuilder); if(!vlan.getTags().isEmpty()) payload = buildVlan(arpBuilder, vlan); EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); etherBuilder.dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS) .srcAddr(srcMacAddress) .type(payload.getKey()) .payloadBuilder(payload.getValue()) .paddingAtBuild(true); return etherBuilder.build(); } private static AbstractMap.SimpleEntry<EtherType, Packet.Builder> buildVlan(ArpPacket.Builder arpBuilder, PortVlan vlan) { Queue<Integer> vlanTags = new LinkedList<>(Lists.reverse(vlan.getTags())); Packet.Builder resultPayloadBuilder = arpBuilder; EtherType resultEtherType = EtherType.ARP; if (vlanTags.peek() != null) { Dot1qVlanTagPacket.Builder vlanInsideBuilder = new Dot1qVlanTagPacket.Builder(); vlanInsideBuilder.type(EtherType.ARP) .vid(vlanTags.poll().shortValue()) .payloadBuilder(arpBuilder); resultPayloadBuilder = vlanInsideBuilder; resultEtherType = EtherType.DOT1Q_VLAN_TAGGED_FRAMES; if(vlanTags.peek() != null) { Dot1qVlanTagPacket.Builder vlanOutsideBuilder = new Dot1qVlanTagPacket.Builder(); vlanOutsideBuilder.type(EtherType.DOT1Q_VLAN_TAGGED_FRAMES) .vid(vlanTags.poll().shortValue()) .payloadBuilder(vlanInsideBuilder); resultPayloadBuilder = vlanOutsideBuilder; resultEtherType = QInQ; } } return new AbstractMap.SimpleEntry<>(resultEtherType, resultPayloadBuilder); } private static Stream build1PktSingleBurstStream(Packet pkt) { int stream_id = (int) (Math.random() * 1000); return new Stream( stream_id, true, 3, 0.0, new StreamMode( 2, 2, 1, 1.0, new StreamModeRate( StreamModeRate.Type.pps, 1.0 ), StreamMode.Type.single_burst ), -1, pkt, new StreamRxStats(true, true, true, stream_id), new StreamVM("", Collections.<VMInstruction>emptyList()), true, false, null, -1 ); } public List<EthernetPacket> getRxQueue(int portIndex, Predicate<EthernetPacket> filter) { Map<String, Object> payload = createPayload(portIndex); String json = callMethod("get_rx_queue_pkts", payload); JsonElement response = new JsonParser().parse(json); JsonArray pkts = response.getAsJsonArray().get(0) .getAsJsonObject().get("result") .getAsJsonObject() .getAsJsonArray("pkts"); return StreamSupport.stream(pkts.spliterator(), false) .map(this::buildEthernetPkt) .filter(filter) .collect(Collectors.toList()); } private EthernetPacket buildEthernetPkt(JsonElement jsonElement) { try { byte[] binary = Base64.getDecoder().decode(jsonElement.getAsJsonObject().get("binary").getAsString()); EthernetPacket pkt = EthernetPacket.newPacket(binary, 0, binary.length); LOGGER.info("Received pkt: {}", pkt.toString()); return pkt; } catch (IllegalRawDataException e) { return null; } } public boolean setL3Mode(int portIndex, String nextHopMac, String sourceIp, String destinationIp) { Map<String, Object> payload = createPayload(portIndex); payload.put("src_addr", sourceIp); payload.put("dst_addr", destinationIp); if (nextHopMac != null) { payload.put("resolved_mac", nextHopMac); } payload.put("block", false); callMethod("set_l3", payload); return true; } public void updatePortHandler(int portID, String handler) { portHandlers.put(portID, handler); } public void invalidatePortHandler(int portID) { portHandlers.remove(portID); } // TODO: move to upper layer public EthernetPacket sendIcmpEcho(int portIndex, String host, int reqId, int seqNumber, long waitResponse) throws UnknownHostException { Port port = getPortByIndex(portIndex); PortStatus portStatus = getPortStatus(portIndex).get(); String srcIp = portStatus.getAttr().getLayerConiguration().getL3Configuration().getSrc(); EthernetPacket icmpRequest = buildIcmpV4Request(port.hw_mac, port.dst_macaddr, srcIp, host, reqId, seqNumber); removeAllStreams(portIndex); setRxQueue(portIndex, 1000); sendPacket(portIndex, icmpRequest); try { Thread.sleep(waitResponse); } catch (InterruptedException ignored) {} try { List<EthernetPacket> receivedPkts = getRxQueue(portIndex, etherPkt -> etherPkt.contains(IcmpV4EchoReplyPacket.class)); if (!receivedPkts.isEmpty()) { return receivedPkts.get(0); } return null; } finally { removeRxQueue(portIndex); } } // TODO: move to upper layer private EthernetPacket buildIcmpV4Request(String srcMac, String dstMac, String srcIp, String dstIp, int reqId, int seqNumber) throws UnknownHostException { IcmpV4EchoPacket.Builder icmpReqBuilder = new IcmpV4EchoPacket.Builder(); icmpReqBuilder.identifier((short) reqId); icmpReqBuilder.sequenceNumber((short) seqNumber); IcmpV4CommonPacket.Builder icmpv4CommonPacketBuilder = new IcmpV4CommonPacket.Builder(); icmpv4CommonPacketBuilder.type(IcmpV4Type.ECHO) .code(IcmpV4Code.NO_CODE) .correctChecksumAtBuild(true) .payloadBuilder(icmpReqBuilder); IpV4Packet.Builder ipv4Builder = new IpV4Packet.Builder(); ipv4Builder.version(IpVersion.IPV4) .tos(IpV4Rfc791Tos.newInstance((byte) 0)) .ttl((byte) 64) .protocol(IpNumber.ICMPV4) .srcAddr((Inet4Address) Inet4Address.getByName(srcIp)) .dstAddr((Inet4Address) Inet4Address.getByName(dstIp)) .correctChecksumAtBuild(true) .correctLengthAtBuild(true) .payloadBuilder(icmpv4CommonPacketBuilder); EthernetPacket.Builder eb = new EthernetPacket.Builder(); eb.srcAddr(MacAddress.getByName(srcMac)) .dstAddr(MacAddress.getByName(dstMac)) .type(EtherType.IPV4) .paddingAtBuild(true) .payloadBuilder(ipv4Builder); return eb.build(); } public void stopTraffic(int portIndex) { Map<String, Object> payload = createPayload(portIndex); callMethod("stop_traffic", payload); } public TRexClientResult<CaptureInfo[]> getActiveCaptures() { Map<String, Object> payload = new HashMap<>(); payload.put("command", "status"); return callMethod("capture", payload, CaptureInfo[].class); } public TRexClientResult<CaptureMonitor> captureMonitorStart( List<Integer> rxPorts, List<Integer> txPorts, String filter) { return startCapture(rxPorts, txPorts, "cyclic", 100, filter); } public TRexClientResult<CaptureMonitor> captureRecorderStart( List<Integer> rxPorts, List<Integer> txPorts, String filter, int limit) { return startCapture(rxPorts, txPorts, "fixed", limit, filter); } public TRexClientResult<CaptureMonitor> startCapture( List<Integer> rxPorts, List<Integer> txPorts, String mode, int limit, String filter) { Map<String, Object> payload = new HashMap<>(); payload.put("command", "start"); payload.put("limit", limit); payload.put("mode", mode); payload.put("rx", rxPorts); payload.put("tx", txPorts); payload.put("filter", filter); return callMethod("capture", payload, CaptureMonitor.class); } public TRexClientResult<List<RPCResponse>> removeAllCaptures() { TRexClientResult<CaptureInfo[]> activeCaptures = getActiveCaptures(); List<Integer> captureIds = Arrays.stream(activeCaptures.get()).map(CaptureInfo::getId).collect(Collectors.toList()); List<TRexCommand> commands = buildRemoveCaptureCommand(captureIds); return callMethods(commands); } private List<TRexCommand> buildRemoveCaptureCommand(List<Integer> capture_ids) { return capture_ids.stream() .map(captureId -> { Map<String, Object> parameters = new HashMap<>(); parameters.put("command", "remove"); parameters.put("capture_id", captureId); return buildCommand("capture", parameters); }) .collect(Collectors.toList()); } public TRexClientResult<CaptureMonitorStop> captureMonitorStop(int captureId) { Map<String, Object> payload = new HashMap<>(); payload.put("command", "stop"); payload.put("capture_id", captureId); return callMethod("capture", payload, CaptureMonitorStop.class); } public boolean captureMonitorRemove(int captureId) { List<TRexCommand> commands = buildRemoveCaptureCommand(Collections.singletonList(captureId)); TRexClientResult<List<RPCResponse>> result = callMethods(commands); if (result.isFailed()) { LOGGER.error("Unable to remove recorder due to: {}", result.getError()); return false; } Optional<RPCResponse> failed = result.get().stream().filter(RPCResponse::isFailed).findFirst(); return !failed.isPresent(); } public TRexClientResult<CapturedPackets> captureFetchPkts(int captureId, int chunkSize) { Map<String, Object> payload = new HashMap<>(); payload.put("command", "fetch"); payload.put("capture_id", captureId); payload.put("pkt_limit", chunkSize); return callMethod("capture", payload, CapturedPackets.class); } public Map<String, Ipv6Node> scanIPv6(int portIndex) throws ServiceModeRequiredException { return new IPv6NeighborDiscoveryService(this).scan(portIndex, 10, null, null); } public EthernetPacket sendIcmpV6Echo(int portIndex, String dstIp, int icmpId, int icmpSeq, int timeOut) throws ServiceModeRequiredException { return new IPv6NeighborDiscoveryService(this).sendIcmpV6Echo(portIndex, dstIp, icmpId, icmpSeq, timeOut); } public TRexClientResult<StubResult> setVlan(int portIdx, List<Integer> vlanIds) { Map<String, Object> parameters = new HashMap<>(); parameters.put("port_id", portIdx); parameters.put("vlan", vlanIds); parameters.put("block", false); return callMethod("set_vlan", parameters, StubResult.class); } private class SystemInfoResponse { private String id; private String jsonrpc; private SystemInfo result; public SystemInfo getResult() { return result; } } }
package com.csforge.sstable; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.ByteBuffer; import java.util.List; import java.util.stream.Stream; import com.csforge.reader.Partition; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter.Indenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter.NopIndenter; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.db.*; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.CompositeType; import org.apache.cassandra.db.rows.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class JsonTransformer { private static final Logger logger = LoggerFactory.getLogger(JsonTransformer.class); private static final JsonFactory jsonFactory = new JsonFactory(); private final JsonGenerator json; private final CompactIndenter indenter = new CompactIndenter(); private final CFMetaData metadata; private JsonTransformer(JsonGenerator json, CFMetaData metadata) { this.json = json; this.metadata = metadata; } public static void toJson(Stream<Partition> partitions, CFMetaData metadata, OutputStream out) throws IOException { try(JsonGenerator json = jsonFactory.createGenerator(new OutputStreamWriter(out, "UTF-8"))) { JsonTransformer transformer = new JsonTransformer(json, metadata); DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(); prettyPrinter.indentObjectsWith(transformer.indenter); prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE); json.setPrettyPrinter(prettyPrinter); json.writeStartArray(); partitions.forEach(transformer::serializePartition); json.writeEndArray(); } } public static void keysToJson(Stream<DecoratedKey> keys, CFMetaData metadata, OutputStream out) throws IOException { try(JsonGenerator json = jsonFactory.createGenerator(new OutputStreamWriter(out, "UTF-8"))) { JsonTransformer transformer = new JsonTransformer(json, metadata); DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(); prettyPrinter.indentObjectsWith(transformer.indenter); prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE); json.setPrettyPrinter(prettyPrinter); json.writeStartArray(); keys.forEach(transformer::serializePartitionKey); json.writeEndArray(); } } private void serializePartitionKey(DecoratedKey key) { AbstractType<?> keyValidator = metadata.getKeyValidator(); indenter.setCompact(true); try { json.writeStartArray(); if (keyValidator instanceof CompositeType) { // if a composite type, the partition has multiple keys. CompositeType compositeType = (CompositeType)keyValidator; assert compositeType.getComponents().size() == metadata.partitionKeyColumns().size(); ByteBuffer keyBytes = key.getKey().duplicate(); // Skip static data if it exists. if (keyBytes.remaining() >= 2) { int header = ByteBufferUtil.getShortLength(keyBytes, keyBytes.position()); if ((header & 0xFFFF) == 0xFFFF) { ByteBufferUtil.readShortLength(keyBytes); } } int i = 0; while (keyBytes.remaining() > 0 && i < compositeType.getComponents().size()) { AbstractType<?> colType = compositeType.getComponents().get(i); ColumnDefinition column = metadata.partitionKeyColumns().get(i); json.writeStartObject(); json.writeFieldName("name"); json.writeString(column.name.toString()); json.writeFieldName("value"); ByteBuffer value = ByteBufferUtil.readBytesWithShortLength(keyBytes); String colValue = colType.getString(value); json.writeString(colValue); json.writeEndObject(); byte b = keyBytes.get(); if (b != 0) { break; } ++i; } } else { // if not a composite type, assume a single column partition key. assert metadata.partitionKeyColumns().size() == 1; ColumnDefinition column = metadata.partitionKeyColumns().get(0); json.writeStartObject(); json.writeFieldName("name"); json.writeString(column.name.toString()); json.writeFieldName("value"); json.writeString(keyValidator.getString(key.getKey())); json.writeEndObject(); } json.writeEndArray(); indenter.setCompact(false); } catch(IOException e) { logger.error("Failure serializing partition key.", e); } } private void serializePartition(Partition partition) { String key = metadata.getKeyValidator().getString(partition.getKey().getKey()); try { json.writeStartObject(); json.writeFieldName("partition"); json.writeStartObject(); json.writeFieldName("key"); serializePartitionKey(partition.getKey()); if(!partition.isLive()) { json.writeFieldName("deletion_info"); indenter.setCompact(true); json.writeStartObject(); json.writeFieldName("deletion_time"); json.writeNumber(partition.markedForDeleteAt()); json.writeFieldName("tstamp"); json.writeNumber(partition.localDeletionTime()); json.writeEndObject(); indenter.setCompact(false); json.writeEndObject(); } else { json.writeEndObject(); json.writeFieldName("rows"); json.writeStartArray(); if (!partition.staticRow().isEmpty()) { serializeRow(partition.staticRow()); } partition.rows().forEach(unfiltered -> { if (unfiltered instanceof Row) { serializeRow((Row)unfiltered); } else if (unfiltered instanceof RangeTombstoneMarker) { serializeTombstone((RangeTombstoneMarker)unfiltered); } }); json.writeEndArray(); } json.writeEndObject(); } catch (IOException e) { logger.error("Fatal error parsing partition: {}", key, e); } } private void serializeRow(Row row) { try { json.writeStartObject(); String rowType = row.isStatic() ? "static_block" : "row"; json.writeFieldName("type"); json.writeString(rowType); LivenessInfo liveInfo = row.primaryKeyLivenessInfo(); if (!liveInfo.isEmpty()) { indenter.setCompact(true); json.writeFieldName("tstamp"); json.writeNumber(liveInfo.timestamp()); if (liveInfo.isExpiring()) { json.writeFieldName("ttl"); json.writeNumber(liveInfo.ttl()); json.writeFieldName("ttl_timestamp"); json.writeNumber(liveInfo.localExpirationTime()); json.writeFieldName("expired"); json.writeBoolean(liveInfo.isLive((int)System.currentTimeMillis() / 1000)); } indenter.setCompact(false); } // Only print clustering information for non-static rows. if (!row.isStatic()) { serializeClustering(row.clustering()); } // If this is a deletion, indicate that, otherwise write cells. if(!row.deletion().isLive()) { json.writeFieldName("deletion_info"); indenter.setCompact(true); json.writeStartObject(); json.writeFieldName("deletion_time"); json.writeNumber(row.deletion().time().markedForDeleteAt()); json.writeFieldName("tstamp"); json.writeNumber(row.deletion().time().localDeletionTime()); json.writeEndObject(); indenter.setCompact(false); } else { json.writeFieldName("cells"); json.writeStartArray(); row.cells().forEach(this::serializeCell); json.writeEndArray(); } json.writeEndObject(); } catch(IOException e) { logger.error("Fatal error parsing row.", e); } } private void serializeTombstone(RangeTombstoneMarker tombstone) { try { json.writeStartObject(); json.writeFieldName("type"); if (tombstone instanceof RangeTombstoneBoundMarker) { json.writeString("range_tombstone_bound"); RangeTombstoneBoundMarker bm = (RangeTombstoneBoundMarker)tombstone; serializeBound(bm.clustering(), bm.deletionTime()); } else { assert tombstone instanceof RangeTombstoneBoundaryMarker; json.writeString("range_tombstone_boundary"); RangeTombstoneBoundaryMarker bm = (RangeTombstoneBoundaryMarker)tombstone; serializeBound(bm.openBound(false), bm.openDeletionTime(false)); serializeBound(bm.closeBound(false), bm.closeDeletionTime(false)); } json.writeEndObject(); indenter.setCompact(false); } catch(IOException e) { logger.error("Failure parsing tombstone.", e); } } private void serializeBound(RangeTombstone.Bound bound, DeletionTime deletionTime) throws IOException { json.writeFieldName(bound.isStart() ? "start" : "end"); json.writeStartObject(); json.writeFieldName("type"); json.writeString(bound.isInclusive() ? "inclusive" : "exclusive"); serializeClustering(bound.clustering()); serializeDeletion(deletionTime); json.writeEndObject(); } private void serializeClustering(ClusteringPrefix clustering) throws IOException { if(clustering.size() > 0) { json.writeFieldName("clustering"); json.writeStartArray(); indenter.setCompact(true); List<ColumnDefinition> clusteringColumns = metadata.clusteringColumns(); for (int i = 0; i < clusteringColumns.size(); i++) { ColumnDefinition column = clusteringColumns.get(i); json.writeStartObject(); json.writeFieldName("name"); json.writeString(column.name.toCQLString()); json.writeFieldName("value"); if (i >= clustering.size()) { json.writeString("*"); } else { json.writeString(column.cellValueType().getString(clustering.get(i))); } json.writeEndObject(); } json.writeEndArray(); indenter.setCompact(false); } } private void serializeDeletion(DeletionTime deletion) throws IOException { json.writeFieldName("deletion_info"); indenter.setCompact(true); json.writeStartObject(); json.writeFieldName("deletion_time"); json.writeNumber(deletion.markedForDeleteAt()); json.writeFieldName("tstamp"); json.writeNumber(deletion.localDeletionTime()); json.writeEndObject(); indenter.setCompact(false); } private void serializeCell(Cell cell) { try { json.writeStartObject(); indenter.setCompact(true); json.writeFieldName("name"); json.writeString(cell.column().name.toCQLString()); if (cell.isTombstone()) { json.writeFieldName("deletion_time"); json.writeNumber(cell.localDeletionTime()); } else { json.writeFieldName("value"); json.writeString(cell.column().cellValueType().getString(cell.value())); if (cell.isExpiring()) { json.writeFieldName("ttl"); json.writeNumber(cell.ttl()); json.writeFieldName("deletion_time"); json.writeNumber(cell.localDeletionTime()); json.writeFieldName("expired"); json.writeBoolean(!cell.isLive((int)System.currentTimeMillis() / 1000)); } } json.writeFieldName("tstamp"); json.writeNumber(cell.timestamp()); json.writeEndObject(); indenter.setCompact(false); } catch(IOException e) { logger.error("Failure parsing cell.", e); } } /** * A specialized {@link Indenter} that enables a 'compact' mode which puts all subsequent json * values on the same line. This is manipulated via {@link CompactIndenter#setCompact(boolean)} */ private static final class CompactIndenter extends NopIndenter { private static final int INDENT_LEVELS = 16; private final char[] indents; private final int charsPerLevel; private final String eol; private static final String space = " "; private boolean compact = false; public CompactIndenter() { this(" ", DefaultIndenter.SYS_LF); } public CompactIndenter(String indent, String eol) { this.eol = eol; charsPerLevel = indent.length(); indents = new char[indent.length() * INDENT_LEVELS]; int offset = 0; for (int i=0; i<INDENT_LEVELS; i++) { indent.getChars(0, indent.length(), indents, offset); offset += indent.length(); } } @Override public boolean isInline() { return false; } /** * Configures whether or not subsequent json values should be on the same line delimited by string or not. * @param compact Whether or not to compact. */ public void setCompact(boolean compact) { this.compact = compact; } @Override public void writeIndentation(JsonGenerator jg, int level) throws IOException { if(!compact) { jg.writeRaw(eol); if (level > 0) { // should we err on negative values (as there's some flaw?) level *= charsPerLevel; while (level > indents.length) { // unlike to happen but just in case jg.writeRaw(indents, 0, indents.length); level -= indents.length; } jg.writeRaw(indents, 0, level); } } else { jg.writeRaw(space); } } } }
package edu.washington.escience.myria.parallel; import java.util.ArrayList; import java.util.List; import org.jboss.netty.channel.ChannelFuture; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.MyriaConstants; import edu.washington.escience.myria.MyriaConstants.FTMODE; import edu.washington.escience.myria.TupleBatch; import edu.washington.escience.myria.TupleBatchBuffer; import edu.washington.escience.myria.operator.Operator; import edu.washington.escience.myria.operator.RootOperator; import edu.washington.escience.myria.parallel.ipc.IPCConnectionPool; import edu.washington.escience.myria.parallel.ipc.IPCEvent; import edu.washington.escience.myria.parallel.ipc.IPCEventListener; import edu.washington.escience.myria.parallel.ipc.StreamIOChannelID; import edu.washington.escience.myria.parallel.ipc.StreamOutputChannel; import edu.washington.escience.myria.util.ArrayUtils; /** * A Producer is the counterpart of a consumer. It dispatch data using IPC channels to Consumers. Like network socket, * Each (workerID, operatorID) pair is a logical destination. * */ public abstract class Producer extends RootOperator { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** * The worker this operator is located at. * */ private transient TaskResourceManager taskResourceManager; /** * the netty channels doing the true IPC IO. * */ private transient StreamOutputChannel<TupleBatch>[] ioChannels; /** * if the corresponding ioChannel is available to write again. * */ private transient boolean[] ioChannelsAvail; /** * output buffers. * */ private transient TupleBatchBuffer[] buffers; /** * output buffers. * */ private transient List<List<TupleBatch>> backupBuffers; /** * output channel IDs. * */ private final StreamIOChannelID[] outputIDs; /** * localized output stream channel IDs, with self references dereferenced. * */ private transient StreamIOChannelID[] localizedOutputIDs; /** * if current query execution is in non-blocking mode. * */ private transient boolean nonBlockingExecution; /** * no worker means to the owner worker. * * @param child the child providing data. * @param oIDs operator IDs. * */ public Producer(final Operator child, final ExchangePairID[] oIDs) { this(child, oIDs, ArrayUtils.arrayFillAndReturn(new int[oIDs.length], IPCConnectionPool.SELF_IPC_ID), true); } /** * the same oID to different workers (shuffle or copy). * * @param oID the operator ID. * @param child the child providing data. * @param destinationWorkerIDs worker IDs. * * */ public Producer(final Operator child, final ExchangePairID oID, final int[] destinationWorkerIDs) { this(child, (ExchangePairID[]) ArrayUtils.arrayFillAndReturn(new ExchangePairID[destinationWorkerIDs.length], oID), destinationWorkerIDs, true); } /** * same worker with different oIDs (multiway copy). * * @param oIDs the operator IDs. * @param child the child providing data. * @param destinationWorkerID the worker ID. * */ public Producer(final Operator child, final ExchangePairID[] oIDs, final int destinationWorkerID) { this(child, oIDs, ArrayUtils.arrayFillAndReturn(new int[oIDs.length], Integer.valueOf(destinationWorkerID)), true); } /** * A single oID to a single worker (collect). * * @param oID the operator ID. * @param child the child providing data. * @param destinationWorkerID the worker ID. * */ public Producer(final Operator child, final ExchangePairID oID, final int destinationWorkerID) { this(child, new ExchangePairID[] { oID }, new int[] { destinationWorkerID }, true); } /** * Two modes: * <p> * * <pre> * if (isOne2OneMapping) * Each ( oIDs[i], destinationWorkerIDs[i] ) pair is a producer channel. * It's required that oIDs.length==destinationWorkerIDs.length * The number of producer channels is oID.length==destinationWorkerIDs.length * else * Each combination of oID and workerID is a producer channel. * The number of producer channels is oID.length*destinationWorkerIDs.length * </pre> * * * @param oIDs the operator IDs. * @param child the child providing data. * @param destinationWorkerIDs the worker IDs. * @param isOne2OneMapping choosing the mode. * * */ public Producer(final Operator child, final ExchangePairID[] oIDs, final int[] destinationWorkerIDs, final boolean isOne2OneMapping) { super(child); if (isOne2OneMapping) { // oID and worker pairs. each ( oIDs[i], destinationWorkerIDs[i] ) pair is a logical channel. Preconditions.checkArgument(oIDs.length == destinationWorkerIDs.length); outputIDs = new StreamIOChannelID[oIDs.length]; for (int i = 0; i < oIDs.length; i++) { outputIDs[i] = new StreamIOChannelID(oIDs[i].getLong(), destinationWorkerIDs[i]); } } else { outputIDs = new StreamIOChannelID[oIDs.length * destinationWorkerIDs.length]; int idx = 0; for (int wID : destinationWorkerIDs) { for (ExchangePairID oID : oIDs) { outputIDs[idx] = new StreamIOChannelID(oID.getLong(), wID); idx++; } } } } @SuppressWarnings("unchecked") @Override public final void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { taskResourceManager = (TaskResourceManager) execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_TASK_RESOURCE_MANAGER); ioChannels = new StreamOutputChannel[outputIDs.length]; ioChannelsAvail = new boolean[outputIDs.length]; buffers = new TupleBatchBuffer[outputIDs.length]; backupBuffers = new ArrayList<List<TupleBatch>>(); localizedOutputIDs = new StreamIOChannelID[outputIDs.length]; for (int i = 0; i < outputIDs.length; i++) { if (outputIDs[i].getRemoteID() == IPCConnectionPool.SELF_IPC_ID) { localizedOutputIDs[i] = new StreamIOChannelID(outputIDs[i].getStreamID(), taskResourceManager.getMyWorkerID()); } else { localizedOutputIDs[i] = outputIDs[i]; } } for (int i = 0; i < localizedOutputIDs.length; i++) { createANewChannel(i); } nonBlockingExecution = (taskResourceManager.getExecutionMode() == QueryExecutionMode.NON_BLOCKING); } /** * Does all the jobs needed to create a new channel with index i. * * @param i the index of the channel * */ public void createANewChannel(final int i) { ioChannels[i] = taskResourceManager.startAStream(localizedOutputIDs[i].getRemoteID(), localizedOutputIDs[i].getStreamID()); ioChannels[i].addListener(StreamOutputChannel.OUTPUT_DISABLED, new IPCEventListener() { @Override public void triggered(final IPCEvent event) { taskResourceManager.getOwnerTask().notifyOutputDisabled(localizedOutputIDs[i]); } }); ioChannels[i].addListener(StreamOutputChannel.OUTPUT_RECOVERED, new IPCEventListener() { @Override public void triggered(final IPCEvent event) { taskResourceManager.getOwnerTask().notifyOutputEnabled(localizedOutputIDs[i]); } }); buffers[i] = new TupleBatchBuffer(getSchema()); ioChannelsAvail[i] = true; backupBuffers.add(i, new ArrayList<TupleBatch>()); } /** * @param chIdx the channel to write * @param msg the message. * @return write future * */ protected final ChannelFuture writeMessage(final int chIdx, final TupleBatch msg) { StreamOutputChannel<TupleBatch> ch = ioChannels[chIdx]; if (nonBlockingExecution) { return ch.write(msg); } else { int sleepTime = 1; int maxSleepTime = MyriaConstants.SHORT_WAITING_INTERVAL_MS; while (true) { if (ch.isWritable()) { return ch.write(msg); } else { int toSleep = sleepTime - 1; if (maxSleepTime < sleepTime) { toSleep = maxSleepTime; } try { Thread.sleep(toSleep); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } sleepTime *= 2; } } } } /** * Pop tuple batches from each of the buffers and try to write them to corresponding channels, if possible. * * @param usingTimeout use popAny() or popAnyUsingTimeout() when poping * */ protected final void popTBsFromBuffersAndWrite(final boolean usingTimeout) { final TupleBatchBuffer[] tbb = getBuffers(); FTMODE mode = ownerTask.getOwnerQuery().getFTMode(); for (int i = 0; i < numChannels(); i++) { if (!ioChannelsAvail[i] && (mode.equals(FTMODE.abandon) || mode.equals(FTMODE.rejoin))) { continue; } while (true) { TupleBatch tb = null; if (usingTimeout) { tb = tbb[i].popAnyUsingTimeout(); } else { tb = tbb[i].popAny(); } if (tb == null) { break; } if (mode.equals(FTMODE.rejoin)) { // rejoin, append the TB into the backup buffer in case of recovering backupBuffers.get(i).add(tb); } try { writeMessage(i, tb); } catch (IllegalStateException e) { if (mode.equals(FTMODE.abandon)) { ioChannelsAvail[i] = false; break; } else if (mode.equals(FTMODE.rejoin)) { ioChannelsAvail[i] = false; break; } else { throw e; } } } } } /** * @param chIdx the channel to write * @return channel release future. * */ protected final ChannelFuture channelEnds(final int chIdx) { if (ioChannelsAvail[chIdx]) { return ioChannels[chIdx].release(); } return null; } @Override public final void cleanup() throws DbException { for (int i = 0; i < localizedOutputIDs.length; i++) { ioChannels[i].release(); buffers[i] = null; } buffers = null; ioChannels = null; } /** * @param myWorkerID for parsing self-references. * @return destination worker IDs. * */ public final StreamIOChannelID[] getOutputChannelIDs(final int myWorkerID) { StreamIOChannelID[] result = new StreamIOChannelID[outputIDs.length]; int idx = 0; for (StreamIOChannelID ecID : outputIDs) { if (ecID.getRemoteID() != IPCConnectionPool.SELF_IPC_ID) { result[idx++] = ecID; } else { result[idx++] = new StreamIOChannelID(ecID.getStreamID(), myWorkerID); } } return result; } /** * @return number of output channels. * */ public final int numChannels() { return ioChannels.length; } /** * @return the buffers. * */ protected final TupleBatchBuffer[] getBuffers() { return buffers; } /** * @return The resource manager of the running task. * */ protected TaskResourceManager getTaskResourceManager() { return taskResourceManager; } /** * enable/disable output channels that belong to the worker. * * @param workerId the worker that changed its status. * @param enable enable/disable all the channels that belong to the worker. * */ public final void updateChannelAvailability(final int workerId, final boolean enable) { List<Integer> indices = getChannelIndicesOfAWorker(workerId); for (int i : indices) { ioChannelsAvail[i] = enable; } } /** * return the backup buffers. * * @return backup buffers. */ public final List<List<TupleBatch>> getBackupBuffers() { return backupBuffers; } /** * return the indices of the channels that belong to the worker. * * @param workerId the id of the worker. * @return the list of channel indices. * */ public final List<Integer> getChannelIndicesOfAWorker(final int workerId) { List<Integer> ret = new ArrayList<Integer>(); for (int i = 0; i < numChannels(); ++i) { if (ioChannels[i].getID().getRemoteID() == workerId) { ret.add(i); } } return ret; } /** * @return the channel availability array. */ public boolean[] getChannelsAvail() { return ioChannelsAvail; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.image.BinaryImage; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; import edu.wpi.first.wpilibj.image.CriteriaCollection; import edu.wpi.first.wpilibj.image.NIVision.MeasurementType; /** * * @author Rajath * find targets */ public class ImageProcessing { ParticleAnalysisReport particles[]; Physics imageCalculations; CriteriaCollection criteriaCollection = new CriteriaCollection(); ParticleAnalysisReport bottomTarget, topTarget, middleTargetLeft, middleTargetRight; final double numberOfDegreesInVerticalFieldOfView = 33; final double numberOfPixelsVerticalInFieldOfView = 240; final double numberOfPixelsHorizontalInFieldOfView = 640; double targetHeight = 18; final double heightToTopOfTopTarget = 100; final double heightToBottomOfTopTarget = heightToTopOfTopTarget + targetHeight; final double heightToBottomOfBottomTarget = 30; final double heightToTopOfBottomTarget = heightToBottomOfBottomTarget + targetHeight; final double heightToBottomOfMiddleTarget = 56; final double heightToTopOfMiddleTarget = heightToBottomOfMiddleTarget + targetHeight; final double cameraAngleOffset = 12; final double cameraHeight = 45; public ImageProcessing() { criteriaCollection.addCriteria( MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, 30, 400, false); criteriaCollection.addCriteria( MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, 40, 400, false); imageCalculations = new Physics(true); } public double pixlesToAngles(double pixles) { return pixles*numberOfDegreesInVerticalFieldOfView /numberOfPixelsVerticalInFieldOfView; } public double getPixelsFromLevelToBottomOfATarget( ParticleAnalysisReport particle) { double PixelsFromLevelToBottomOfTopTarget = numberOfPixelsVerticalInFieldOfView - particle.center_mass_y - (particle.boundingRectHeight / 2); System.out.println("PixelsFromLevelToBottomOfTopTarget"+ PixelsFromLevelToBottomOfTopTarget); return PixelsFromLevelToBottomOfTopTarget; } public double getPixelsFromLevelToTopOfATarget( ParticleAnalysisReport particle) { /*TODO take into account the fact that level is not * always at the bottom of the field of view */ /*TODO don't use global variable PixelsFromLevelToBottomOfTopTarget, * instead use local variables, return values, and parameters */ double PixelsFromLevelToTopOfTopTarget = numberOfPixelsVerticalInFieldOfView - particle.center_mass_y + (particle.boundingRectHeight / 2); System.out.println("PixelsFromLevelToTopOfTopTarget" + PixelsFromLevelToTopOfTopTarget); return PixelsFromLevelToTopOfTopTarget; } public double getPhi(double PixelsFromLevelToTopOfTopTarget) { /* TODO: consider simply returning the calculated value, * instead of assigning it to a variable and then returning that * variable */ return pixlesToAngles(PixelsFromLevelToTopOfTopTarget) + cameraAngleOffset; } public double getTheta(double PixelsFromLevelToBottomOfATarget) { return pixlesToAngles(PixelsFromLevelToBottomOfATarget) + cameraAngleOffset; } public static ParticleAnalysisReport getTopMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport greatest = particles[0]; for (int i=0;i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if(particle.center_mass_y > greatest.center_mass_y){ greatest = particle; } } return greatest; } public static ParticleAnalysisReport getBottomMost (ParticleAnalysisReport[] particles) { ParticleAnalysisReport lowest = particles[0]; for (int i=0;i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if(particle.center_mass_y < lowest.center_mass_y){ lowest = particle; } } return lowest; } public static ParticleAnalysisReport getLeftMost (ParticleAnalysisReport[] particles) { ParticleAnalysisReport leftist = particles[0]; for (int i=0;i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if(particle.center_mass_x < leftist.center_mass_x){ leftist = particle; } } return leftist; } public static ParticleAnalysisReport getRightMost (ParticleAnalysisReport[] particles) { ParticleAnalysisReport rightist = particles[0]; for (int i=0;i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if(particle.center_mass_x > rightist.center_mass_x){ rightist = particle; } } return rightist; } public void setTargets(ParticleAnalysisReport[] particles) { topTarget = getTopMost(particles); bottomTarget = getBottomMost(particles); } public double getHypotneuse0(double angle, int ref) { //ref-reference number //1 Top //2 Middle double opposite0 = 0; //3 Bottom switch (ref){ case 1: opposite0 = heightToBottomOfTopTarget - cameraHeight; break; case 2: opposite0 = heightToBottomOfMiddleTarget - cameraHeight; break; case 3: opposite0 = heightToBottomOfBottomTarget - cameraHeight; break; } double hypotneuse_0 = opposite0 / MathX.sin(getTheta(angle)); System.out.println("Phi " + getTheta(angle)); return hypotneuse_0; } public double getHypotneuse1(double angle, int targetSelector) { //ref-reference number //1 Top //2 Middle double opposite1 = 0; //3 Bottom switch (targetSelector){ case 1: opposite1 = heightToTopOfTopTarget - cameraHeight; break; case 2: opposite1 = heightToTopOfMiddleTarget - cameraHeight; break; case 3: opposite1 = heightToTopOfBottomTarget - cameraHeight; break; } double hypotneuse_1 = opposite1 / MathX.sin(getPhi(angle)); System.out.println("Phi " + getPhi(angle)); return hypotneuse_1; } public double getAdjacent1(double phiAngle,double hypotneuse){ return MathX.cos(phiAngle) * hypotneuse; } public double getAdjacent0(double thetaAngle,double hypotneuse){ return MathX.cos(thetaAngle) * hypotneuse; } public void idTarget(ParticleAnalysisReport particle) { double phi = getPhi(getPixelsFromLevelToTopOfATarget(particle)); double theta = getTheta (getPixelsFromLevelToBottomOfATarget(particle)); double adjacent1 = getAdjacent1(phi,getHypotneuse1(phi,1)); double adjacent0 = getAdjacent0(theta,getHypotneuse0(theta,1)); double disparity = Math.abs(adjacent1 - adjacent0); System.out.println("Bottom Adjacent0 : " + adjacent0); System.out.println("Bottom Adjacent1 : " + adjacent1); System.out.println("The disperity is " + disparity); System.out.println(" } public void getTheParticles(AxisCamera camera) throws Exception { int erosionCount = 2; // true means use connectivity 8, true means connectivity 4 boolean connectivity8Or4 = false; ColorImage colorImage; BinaryImage binaryImage; BinaryImage cleanImage; BinaryImage convexHullImage; BinaryImage filteredImage; colorImage = camera.getImage(); //seperate the light and dark image binaryImage = colorImage.thresholdRGB(0, 42, 71, 255, 0, 255); cleanImage = binaryImage.removeSmallObjects( connectivity8Or4, erosionCount); //fill the rectangles that were created convexHullImage = cleanImage.convexHull(connectivity8Or4); filteredImage = convexHullImage.particleFilter(criteriaCollection); particles = filteredImage.getOrderedParticleAnalysisReports(); colorImage.free(); binaryImage.free(); cleanImage.free(); convexHullImage.free(); filteredImage.free(); } public double CameraCorrection(ParticleAnalysisReport particle,String target){ if("top".equals(target)){ targetHeight = 109; } if("middle".equals(target)){ targetHeight = 72; } if("bottom".equals(target)){ targetHeight = 39; } double delta = targetHeight - cameraHeight; double lambda = numberOfPixelsVerticalInFieldOfView/ numberOfDegreesInVerticalFieldOfView; double pixelHeightBetweenReflectiveTape = getPixelsFromLevelToTopOfATarget(particle) - getPixelsFromLevelToBottomOfATarget(particle); double ph_fixed = pixelHeightBetweenReflectiveTape; double R = 18/MathX.tan(ph_fixed/lambda); double Distance = 0; for(int i =1; i<= 4; i++) { double theta = MathX.asin(delta/R); double ph_new = ph_fixed/MathX.cos(theta); R = 18/MathX.tan(ph_new/lambda); Distance = MathX.sqrt(R*R-delta*delta); } return Distance; } }
package com.facebook.litho; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.pm.ApplicationInfo; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v4.util.LongSparseArray; import android.support.v4.view.accessibility.AccessibilityManagerCompat; import android.text.TextUtils; import android.view.View; import android.view.accessibility.AccessibilityManager; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.displaylist.DisplayList; import com.facebook.litho.displaylist.DisplayListException; import com.facebook.litho.reference.BorderColorDrawableReference; import com.facebook.litho.reference.Reference; import com.facebook.infer.annotation.ThreadSafe; import com.facebook.yoga.YogaConstants; import com.facebook.yoga.YogaDirection; import com.facebook.yoga.YogaEdge; import static android.content.Context.ACCESSIBILITY_SERVICE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; import static android.os.Build.VERSION_CODES.M; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO; import static com.facebook.litho.Component.isHostSpec; import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec; import static com.facebook.litho.Component.isMountSpec; import static com.facebook.litho.Component.isMountViewSpec; import static com.facebook.litho.ComponentContext.NULL_LAYOUT; import static com.facebook.litho.ComponentLifecycle.MountType.NONE; import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS; import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS; import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT; import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT; import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG; import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED; import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE; import static com.facebook.litho.MountState.ROOT_HOST_ID; import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE; import static com.facebook.litho.SizeSpec.EXACTLY; /** * The main role of {@link LayoutState} is to hold the output of layout calculation. This includes * mountable outputs and visibility outputs. A centerpiece of the class is {@link * #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs * based on the provided {@link InternalNode} for later use in {@link MountState}. */ class LayoutState { static final Comparator<LayoutOutput> sTopsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsTop = lhs.getBounds().top; final int rhsTop = rhs.getBounds().top; return lhsTop < rhsTop ? -1 : lhsTop > rhsTop ? 1 // Hosts should be higher for tops so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? -1 : 1; } }; static final Comparator<LayoutOutput> sBottomsComparator = new Comparator<LayoutOutput>() { @Override public int compare(LayoutOutput lhs, LayoutOutput rhs) { final int lhsBottom = lhs.getBounds().bottom; final int rhsBottom = rhs.getBounds().bottom; return lhsBottom < rhsBottom ? -1 : lhsBottom > rhsBottom ? 1 // Hosts should be lower for bottoms so that they are mounted first if possible. : isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent()) ? 0 : isHostSpec(lhs.getComponent()) ? 1 : -1; } }; private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled}; private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{}; private ComponentContext mContext; private TransitionContext mTransitionContext; private Component<?> mComponent; private int mWidthSpec; private int mHeightSpec; private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8); private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8); private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8); private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator; private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>(); private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>(); private final List<TestOutput> mTestOutputs; private InternalNode mLayoutRoot; private DiffNode mDiffTreeRoot; // Reference count will be initialized to 1 in init(). private final AtomicInteger mReferenceCount = new AtomicInteger(-1); private int mWidth; private int mHeight; private int mCurrentX; private int mCurrentY; private int mCurrentLevel = 0; // Holds the current host marker in the layout tree. private long mCurrentHostMarker = -1; private int mCurrentHostOutputPosition = -1; private boolean mShouldDuplicateParentState = true; private boolean mShouldGenerateDiffTree = false; private int mComponentTreeId = -1; private AccessibilityManager mAccessibilityManager; private boolean mAccessibilityEnabled = false; private StateHandler mStateHandler; LayoutState() { mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator(); mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null; } /** * Acquires a new layout output for the internal node and its associated component. It returns * null if there's no component associated with the node as the mount pass only cares about nodes * that will potentially mount content into the component host. */ @Nullable private static LayoutOutput createGenericLayoutOutput( InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); // Skip empty nodes and layout specs because they don't mount anything. if (component == null || component.getLifecycle().getMountType() == NONE) { return null; } return createLayoutOutput( component, layoutState, node, true /* useNodePadding */, node.getImportantForAccessibility(), layoutState.mShouldDuplicateParentState); } private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) { final LayoutOutput hostOutput = createLayoutOutput( HostComponent.create(), layoutState, node, false /* useNodePadding */, node.getImportantForAccessibility(), node.isDuplicateParentStateEnabled()); hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey()); return hostOutput; } private static LayoutOutput createDrawableLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node) { return createLayoutOutput( component, layoutState, node, false /* useNodePadding */, IMPORTANT_FOR_ACCESSIBILITY_NO, layoutState.mShouldDuplicateParentState); } private static LayoutOutput createLayoutOutput( Component<?> component, LayoutState layoutState, InternalNode node, boolean useNodePadding, int importantForAccessibility, boolean duplicateParentState) { final boolean isMountViewSpec = isMountViewSpec(component); final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput(); layoutOutput.setComponent(component); layoutOutput.setImportantForAccessibility(importantForAccessibility); // The mount operation will need both the marker for the target host and its matching // parent host to ensure the correct hierarchy when nesting the host views. layoutOutput.setHostMarker(layoutState.mCurrentHostMarker); if (layoutState.mCurrentHostOutputPosition >= 0) { final LayoutOutput hostOutput = layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition); final Rect hostBounds = hostOutput.getBounds(); layoutOutput.setHostTranslationX(hostBounds.left); layoutOutput.setHostTranslationY(hostBounds.top); } int l = layoutState.mCurrentX + node.getX(); int t = layoutState.mCurrentY + node.getY(); int r = l + node.getWidth(); int b = t + node.getHeight(); final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0; final int paddingTop = useNodePadding ? node.getPaddingTop() : 0; final int paddingRight = useNodePadding ? node.getPaddingRight() : 0; final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0; // View mount specs are able to set their own attributes when they're mounted. // Non-view specs (drawable and layout) always transfer their view attributes // to their respective hosts. // Moreover, if the component mounts a view, then we apply padding to the view itself later on. // Otherwise, apply the padding to the bounds of the layout output. if (isMountViewSpec) { layoutOutput.setNodeInfo(node.getNodeInfo()); // Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput. final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire(); viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom); viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection()); viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b); layoutOutput.setViewNodeInfo(viewNodeInfo); viewNodeInfo.release(); } else { l += paddingLeft; t += paddingTop; r -= paddingRight; b -= paddingBottom; } layoutOutput.setBounds(l, t, r, b); int flags = 0; if (duplicateParentState) { flags |= FLAG_DUPLICATE_PARENT_STATE; } layoutOutput.setFlags(flags); return layoutOutput; } /** * Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information * stored in the {@link InternalNode}. */ private static VisibilityOutput createVisibilityOutput( InternalNode node, LayoutState layoutState) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final EventHandler visibleHandler = node.getVisibleHandler(); final EventHandler focusedHandler = node.getFocusedHandler(); final EventHandler fullImpressionHandler = node.getFullImpressionHandler(); final EventHandler invisibleHandler = node.getInvisibleHandler(); final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput(); final Component<?> handlerComponent; // Get the component from the handler that is not null. If more than one is not null, then // getting the component from any of them works. if (visibleHandler != null) { handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher; } else if (focusedHandler != null) { handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher; } else if (fullImpressionHandler != null) { handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher; } else { handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher; } visibilityOutput.setComponent(handlerComponent); visibilityOutput.setBounds(l, t, r, b); visibilityOutput.setVisibleEventHandler(visibleHandler); visibilityOutput.setFocusedEventHandler(focusedHandler); visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler); visibilityOutput.setInvisibleEventHandler(invisibleHandler); return visibilityOutput; } private static TestOutput createTestOutput( InternalNode node, LayoutState layoutState, LayoutOutput layoutOutput) { final int l = layoutState.mCurrentX + node.getX(); final int t = layoutState.mCurrentY + node.getY(); final int r = l + node.getWidth(); final int b = t + node.getHeight(); final TestOutput output = ComponentsPools.acquireTestOutput(); output.setTestKey(node.getTestKey()); output.setBounds(l, t, r, b); output.setHostMarker(layoutState.mCurrentHostMarker); if (layoutOutput != null) { output.setLayoutOutputId(layoutOutput.getId()); } return output; } private static boolean isLayoutDirectionRTL(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if ((SDK_INT >= JELLY_BEAN_MR1) && (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) { int layoutDirection = getLayoutDirection(context); return layoutDirection == View.LAYOUT_DIRECTION_RTL; } return false; } @TargetApi(JELLY_BEAN_MR1) private static int getLayoutDirection(Context context) { return context.getResources().getConfiguration().getLayoutDirection(); } /** * Determine if a given {@link InternalNode} within the context of a given {@link LayoutState} * requires to be wrapped inside a view. * * @see #needsHostView(InternalNode, LayoutState) */ private static boolean hasViewContent(InternalNode node, LayoutState layoutState) { final Component<?> component = node.getComponent(); final NodeInfo nodeInfo = node.getNodeInfo(); final boolean implementsAccessibility = (nodeInfo != null && nodeInfo.hasAccessibilityHandlers()) || (component != null && component.getLifecycle().implementsAccessibility()); final int importantForAccessibility = node.getImportantForAccessibility(); // A component has accessibility content if: // 1. Accessibility is currently enabled. // 2. Accessibility hasn't been explicitly disabled on it // i.e. IMPORTANT_FOR_ACCESSIBILITY_NO. // 3. Any of these conditions are true: // - It implements accessibility support. // - It has a content description. // - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES // or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS. // IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host // so that such flag is applied in the resulting view hierarchy after the component // tree is mounted. Click handling is also considered accessibility content but // this is already covered separately i.e. click handler is not null. final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled && importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO && (implementsAccessibility || (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription())) || importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO); final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers()); final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null); final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null); final boolean isFocusableSetTrue = (nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE); return hasTouchEventHandlers || hasViewTag || hasViewTags || hasAccessibilityContent || isFocusableSetTrue; } /** * Collects layout outputs and release the layout tree. The layout outputs hold necessary * information to be used by {@link MountState} to mount components into a {@link ComponentHost}. * <p/> * Whenever a component has view content (view tags, click handler, etc), a new host 'marker' * is added for it. The mount pass will use the markers to decide which host should be used * for each layout output. The root node unconditionally generates a layout output corresponding * to the root host. * <p/> * The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts * will be created at the right order when mounting. The host markers will be define which host * each mounted artifacts will be attached to. * <p/> * At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled * will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the * host and the contents (including background/foreground). In all other cases instead we'll only * try to re-use the hosts. In some cases the host's structure might change between two updates * even if the component is of the same type. This can happen for example when a click listener is * added. To avoid trying to re-use the wrong host type we explicitly check that after all the * children for a subtree have been added (this is when the actual host type is resolved). If the * host type changed compared to the one in the DiffNode we need to refresh the ids for the whole * subtree in order to ensure that the MountState will unmount the subtree and mount it again on * the correct host. * <p/> * * @param node InternalNode to process. * @param layoutState the LayoutState currently operating. * @param parentDiffNode whether this method also populates the diff tree and assigns the root * to mDiffTreeRoot. */ private static void collectResults( InternalNode node, LayoutState layoutState, DiffNode parentDiffNode) { if (node.hasNewLayout()) { node.markLayoutSeen(); } final Component<?> component = node.getComponent(); // Early return if collecting results of a node holding a nested tree. if (node.isNestedTreeHolder()) { // If the nested tree is defined, it has been resolved during a measure call during // layout calculation. InternalNode nestedTree = resolveNestedTree( node, SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY), SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY)); if (nestedTree == NULL_LAYOUT) { return; } // Account for position of the holder node. layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); collectResults(nestedTree, layoutState, parentDiffNode); layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); return; } final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree; final DiffNode currentDiffNode = node.getDiffNode(); final boolean shouldUseCachedOutputs = isMountSpec(component) && currentDiffNode != null; final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid(); final DiffNode diffNode; if (shouldGenerateDiffTree) { diffNode = createDiffNode(node, parentDiffNode); if (parentDiffNode == null) { layoutState.mDiffTreeRoot = diffNode; } } else { diffNode = null; } final boolean needsHostView = needsHostView(node, layoutState); final long currentHostMarker = layoutState.mCurrentHostMarker; final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition; int hostLayoutPosition = -1; // 1. Insert a host LayoutOutput if we have some interactive content to be attached to. if (needsHostView) { hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode); layoutState.mCurrentLevel++; layoutState.mCurrentHostMarker = layoutState.mMountableOutputs.get(hostLayoutPosition).getId(); layoutState.mCurrentHostOutputPosition = hostLayoutPosition; } // We need to take into account flattening when setting duplicate parent state. The parent after // flattening may no longer exist. Therefore the value of duplicate parent state should only be // true if the path between us (inclusive) and our inner/root host (exclusive) all are // duplicate parent state. final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState; layoutState.mShouldDuplicateParentState = needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled()); // Generate the layoutOutput for the given node. final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState); if (layoutOutput != null) { final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( layoutOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_CONTENT, previousId, isCachedOutputUpdated); } // If we don't need to update this output we can safely re-use the display list from the // previous output. if (isCachedOutputUpdated) { layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList()); } // 2. Add background if defined. final Reference<? extends Drawable> background = node.getBackground(); if (background != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) { layoutOutput.getViewNodeInfo().setBackground(background); } else { final LayoutOutput convertBackground = (currentDiffNode != null) ? currentDiffNode.getBackground() : null; final LayoutOutput backgroundOutput = addDrawableComponent( node, layoutState, convertBackground, background, LayoutOutput.TYPE_BACKGROUND); if (diffNode != null) { diffNode.setBackground(backgroundOutput); } } } // 3. Now add the MountSpec (either View or Drawable) to the Outputs. if (isMountSpec(component)) { // Notify component about its final size. component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component); addMountableOutput(layoutState, layoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, layoutOutput, layoutState.mMountableOutputs.size() - 1); if (diffNode != null) { diffNode.setContent(layoutOutput); } } // 4. Add border color if defined. if (node.shouldDrawBorders()) { final LayoutOutput convertBorder = (currentDiffNode != null) ? currentDiffNode.getBorder() : null; final LayoutOutput borderOutput = addDrawableComponent( node, layoutState, convertBorder, getBorderColorDrawable(node), LayoutOutput.TYPE_BORDER); if (diffNode != null) { diffNode.setBorder(borderOutput); } } // 5. Extract the Transitions. if (SDK_INT >= ICE_CREAM_SANDWICH) { if (node.getTransitionKey() != null) { layoutState .getOrCreateTransitionContext() .addTransitionKey(node.getTransitionKey()); } if (component != null) { Transition transition = component.getLifecycle().onLayoutTransition( layoutState.mContext, component); if (transition != null) { layoutState.getOrCreateTransitionContext().add(transition); } } } layoutState.mCurrentX += node.getX(); layoutState.mCurrentY += node.getY(); // We must process the nodes in order so that the layout state output order is correct. for (int i = 0, size = node.getChildCount(); i < size; i++) { collectResults( node.getChildAt(i), layoutState, diffNode); } layoutState.mCurrentX -= node.getX(); layoutState.mCurrentY -= node.getY(); // 6. Add foreground if defined. final Reference<? extends Drawable> foreground = node.getForeground(); if (foreground != null) { if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) { layoutOutput.getViewNodeInfo().setForeground(foreground); } else { final LayoutOutput convertForeground = (currentDiffNode != null) ? currentDiffNode.getForeground() : null; final LayoutOutput foregroundOutput = addDrawableComponent( node, layoutState, convertForeground, foreground, LayoutOutput.TYPE_FOREGROUND); if (diffNode != null) { diffNode.setForeground(foregroundOutput); } } } // 7. Add VisibilityOutputs if any visibility-related event handlers are present. if (node.hasVisibilityHandlers()) { final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState); final long previousId = shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1; layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId( visibilityOutput, layoutState.mCurrentLevel, previousId); layoutState.mVisibilityOutputs.add(visibilityOutput); if (diffNode != null) { diffNode.setVisibilityOutput(visibilityOutput); } } // 8. If we're in a testing environment, maintain an additional data structure with // information about nodes that we can query later. if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) { final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput); layoutState.mTestOutputs.add(testOutput); } // All children for the given host have been added, restore the previous // host, level, and duplicate parent state value in the recursive queue. if (layoutState.mCurrentHostMarker != currentHostMarker) { layoutState.mCurrentHostMarker = currentHostMarker; layoutState.mCurrentHostOutputPosition = currentHostOutputPosition; layoutState.mCurrentLevel } layoutState.mShouldDuplicateParentState = shouldDuplicateParentState; Collections.sort(layoutState.mMountableOutputTops, sTopsComparator); Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator); } private static void calculateAndSetHostOutputIdAndUpdateState( InternalNode node, LayoutOutput hostOutput, LayoutState layoutState, boolean isCachedOutputUpdated) { if (layoutState.isLayoutRoot(node)) { // The root host (ComponentView) always has ID 0 and is unconditionally // set as dirty i.e. no need to use shouldComponentUpdate(). hostOutput.setId(ROOT_HOST_ID); // Special case where the host marker of the root host is pointing to itself. hostOutput.setHostMarker(ROOT_HOST_ID); hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY); } else { layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( hostOutput, layoutState.mCurrentLevel, LayoutOutput.TYPE_HOST, -1, isCachedOutputUpdated); } } private static LayoutOutput addDrawableComponent( InternalNode node, LayoutState layoutState, LayoutOutput recycle, Reference<? extends Drawable> reference, @LayoutOutput.LayoutOutputType int type) { final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference); drawableComponent.setScopedContext( ComponentContext.withComponentScope(node.getContext(), drawableComponent)); final boolean isOutputUpdated; if (recycle != null) { isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate( recycle.getComponent(), drawableComponent); } else { isOutputUpdated = false; } final long previousId = recycle != null ? recycle.getId() : -1; final LayoutOutput output = addDrawableLayoutOutput( drawableComponent, layoutState, node, type, previousId, isOutputUpdated); return output; } private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) { if (!node.shouldDrawBorders()) { throw new RuntimeException("This node does not support drawing border color"); } return BorderColorDrawableReference.create(node.getContext()) .color(node.getBorderColor()) .borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT))) .borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP))) .borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT))) .borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM))) .build(); } private static void addLayoutOutputIdToPositionsMap( LongSparseArray outputsIdToPositionMap, LayoutOutput layoutOutput, int position) { if (outputsIdToPositionMap != null) { outputsIdToPositionMap.put(layoutOutput.getId(), position); } } private static LayoutOutput addDrawableLayoutOutput( Component<DrawableComponent> drawableComponent, LayoutState layoutState, InternalNode node, @LayoutOutput.LayoutOutputType int layoutOutputType, long previousId, boolean isCachedOutputUpdated) { drawableComponent.getLifecycle().onBoundsDefined( layoutState.mContext, node, drawableComponent); final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput( drawableComponent, layoutState, node); layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState( drawableLayoutOutput, layoutState.mCurrentLevel, layoutOutputType, previousId, isCachedOutputUpdated); addMountableOutput(layoutState, drawableLayoutOutput); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, drawableLayoutOutput, layoutState.mMountableOutputs.size() - 1); return drawableLayoutOutput; } static void releaseNodeTree(InternalNode node, boolean isNestedTree) { if (node == NULL_LAYOUT) { throw new IllegalArgumentException("Cannot release a null node tree"); } for (int i = node.getChildCount() - 1; i >= 0; i final InternalNode child = node.getChildAt(i); if (isNestedTree && node.hasNewLayout()) { node.markLayoutSeen(); } // A node must be detached from its parent *before* being released (otherwise the parent would // retain a reference to a node that may get re-used by another thread) node.removeChildAt(i); releaseNodeTree(child, isNestedTree); } if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) { releaseNodeTree(node.getNestedTree(), true); } ComponentsPools.release(node); } /** * If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an * HostComponent in the Outputs such as it will be used as a HostView at Mount time. View * MountSpec are not allowed. * * @return The position the HostLayoutOutput was inserted. */ private static int addHostLayoutOutput( InternalNode node, LayoutState layoutState, DiffNode diffNode) { final Component<?> component = node.getComponent(); // Only the root host is allowed to wrap view mount specs as a layout output // is unconditionally added for it. if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) { throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View"); } final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node); // The component of the hostLayoutOutput will be set later after all the // children got processed. addMountableOutput(layoutState, hostLayoutOutput); final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1; if (diffNode != null) { diffNode.setHost(hostLayoutOutput); } calculateAndSetHostOutputIdAndUpdateState( node, hostLayoutOutput, layoutState, false); addLayoutOutputIdToPositionsMap( layoutState.mOutputsIdToPositionMap, hostLayoutOutput, hostOutputPosition); return hostOutputPosition; } static <T extends ComponentLifecycle> LayoutState calculate( ComponentContext c, Component<T> component, int componentTreeId, int widthSpec, int heightSpec, boolean shouldGenerateDiffTree, DiffNode previousDiffTreeRoot) { // Detect errors internal to components component.markLayoutStarted(); LayoutState layoutState = ComponentsPools.acquireLayoutState(c); layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree; layoutState.mComponentTreeId = componentTreeId; layoutState.mAccessibilityManager = (AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE); layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager); layoutState.mComponent = component; layoutState.mWidthSpec = widthSpec; layoutState.mHeightSpec = heightSpec; component.applyStateUpdates(c); final InternalNode root = createAndMeasureTreeForComponent( component.getScopedContext(), component, null, // nestedTreeHolder is null because this is measuring the root component tree. widthSpec, heightSpec, previousDiffTreeRoot); switch (SizeSpec.getMode(widthSpec)) { case SizeSpec.EXACTLY: layoutState.mWidth = SizeSpec.getSize(widthSpec); break; case SizeSpec.AT_MOST: layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mWidth = root.getWidth(); break; } switch (SizeSpec.getMode(heightSpec)) { case SizeSpec.EXACTLY: layoutState.mHeight = SizeSpec.getSize(heightSpec); break; case SizeSpec.AT_MOST: layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec)); break; case SizeSpec.UNSPECIFIED: layoutState.mHeight = root.getHeight(); break; } layoutState.mLayoutStateOutputIdCalculator.clear(); // Reset markers before collecting layout outputs. layoutState.mCurrentHostMarker = -1; final ComponentsLogger logger = c.getLogger(); if (root == NULL_LAYOUT) { return layoutState; } layoutState.mLayoutRoot = root; ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName()); if (logger != null) { logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag()); } collectResults(root, layoutState, null); if (logger != null) { logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS); } ComponentsSystrace.endSection(); if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) { releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */); layoutState.mLayoutRoot = null; }
package com.finitejs.modules.core; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import com.finitejs.system.FiniteJS; /** * Utility class for file related operations. * */ public class FileUtils { /** * Reads a text file, given path as string. * * @param filePath path of the file to read * @return file contents * @throws IOException */ public static String readTextFile(String filePath) throws IOException{ byte[] fileBytes = Files.readAllBytes(Paths.get(filePath)); return new String(fileBytes, StandardCharsets.UTF_8); } /** * Reads a text file, given {@code File} as argument. * * @param file file to read * @return file contents * @throws IOException */ public static String readTextFile(File file) throws IOException{ byte[] fileBytes = Files.readAllBytes(Paths.get(file.toURI())); return new String(fileBytes, StandardCharsets.UTF_8); } /** * Get current working directory. * * @return absolute path of working directory */ public static String getWorkingDir(){ Path dir = Paths.get(""); return dir.toAbsolutePath().toString(); } public static String getRootPath() { // main class Class<FiniteJS> aclass = FiniteJS.class; URL url; // get the URL try { url = aclass.getProtectionDomain().getCodeSource().getLocation(); } catch (SecurityException ex) { url = aclass.getResource(aclass.getSimpleName() + ".class"); } // convert to external form String extURL = url.toExternalForm(); // prune for various cases if (extURL.endsWith(".jar")) // from getCodeSource extURL = extURL.substring(0, extURL.lastIndexOf("/")); else { // from getResource String suffix = "/"+(aclass.getName()).replace(".", "/")+".class"; extURL = extURL.replace(suffix, ""); if (extURL.startsWith("jar:") && extURL.endsWith(".jar!")){ extURL = extURL.substring(4, extURL.lastIndexOf("/")); } } // convert back to URL try { url = new URL(extURL); } catch (MalformedURLException mux) { // leave URL unchanged; probably does not happen } File file; // convert URL to File try { file = new File(url.toURI()); } catch(URISyntaxException ex) { file = new File(url.getPath()); } return file.getAbsolutePath(); } }
package com.frostwire.jlibtorrent; /** * This is a limited capability data point series backed by * a circular buffer logic. Used to hold equally timed sample * of statistics. * * @author aldenml * @author gubatron */ public final class IntSeries { private final int[] buffer; private int head; private int end; private int size; IntSeries(int[] buffer) { if (buffer == null) { throw new IllegalArgumentException("buffer to hold data can't be null"); } if (buffer.length == 0) { throw new IllegalArgumentException("buffer to hold data can't be of size 0"); } this.buffer = buffer; head = -1; end = -1; size = 0; } IntSeries(int capacity) { this(new int[capacity]); } void add(int value) { if (head == -1) { // first element add head = end = 0; buffer[end] = value; size = 1; return; } // update buffer and pointers end = (end + 1) % buffer.length; buffer[end] = value; if (end <= head) { head = (head + 1) % buffer.length; } // update size if (head <= end) { size = 1 + (end - head); } else { size = buffer.length; } } /** * This method will always returns a value, but keep in mind that * due to the nature of the circular buffer internal logic, if you pass * past the size, you will get the sames values again. * Use {@link #size()} for a proper boundary check. * * <br/>Usage example: * <pre><code> * for (int i = min(series.size(), desired_count); i >= 0; i--) { * plotMyValueAt(i, series.get(i)); * }</code></pre> * * @param index the value's index * @return the value in the series */ public int get(int index) { return buffer[(head + index) % size]; } public int size() { return size; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[ "); for (int i = 0; i < buffer.length; i++) { sb.append(buffer[i]); if (i != buffer.length - 1) { sb.append(", "); } } sb.append(" ]"); return "{ head: " + head + ", end: " + end + ", size: " + size() + ", buffer: " + sb.toString() + " }"; } }
package com.github.davidmoten.rx; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import rx.Observable; import rx.Observable.Operator; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.observables.AbstractOnSubscribe; public final class Serialized { private static final int DEFAULT_BUFFER_SIZE = 8192; public static <T extends Serializable> Observable<T> read(final InputStream is) { return Observable.create(new AbstractOnSubscribe<T, ObjectInputStream>() { @Override protected ObjectInputStream onSubscribe(Subscriber<? super T> subscriber) { try { return new ObjectInputStream(is); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void next(SubscriptionState<T, ObjectInputStream> state) { ObjectInputStream ois = state.state(); try { @SuppressWarnings("unchecked") T t = (T) ois.readObject(); state.onNext(t); } catch (ClassNotFoundException e) { state.onError(e); return; } catch (EOFException e) { state.onCompleted(); } catch (IOException e) { state.onError(e); return; } } }); } public static <T extends Serializable> Observable<T> read(final File file, final int bufferSize) { Func0<InputStream> resourceFactory = new Func0<InputStream>() { @Override public InputStream call() { try { return new BufferedInputStream(new FileInputStream(file), bufferSize); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }; Func1<InputStream, Observable<? extends T>> observableFactory = new Func1<InputStream, Observable<? extends T>>() { @Override public Observable<? extends T> call(InputStream is) { return read(is); } }; Action1<InputStream> disposeAction = new Action1<InputStream>() { @Override public void call(InputStream is) { try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } }; return Observable.using(resourceFactory, observableFactory, disposeAction, true); } public static <T extends Serializable> Observable<T> read(final File file) { return read(file, DEFAULT_BUFFER_SIZE); } public static <T extends Serializable> Observable<T> write(Observable<T> source, final OutputStream os) { return source.lift(new Operator<T, T>() { @Override public Subscriber<? super T> call(final Subscriber<? super T> child) { try { final ObjectOutputStream ois = new ObjectOutputStream(os); return new Subscriber<T>(child) { @Override public void onCompleted() { child.onCompleted(); } @Override public void onError(Throwable e) { child.onError(e); } @Override public void onNext(T t) { try { ois.writeObject(t); } catch (IOException e) { onError(e); return; } child.onNext(t); } }; } catch (IOException e) { // ignore everything that the parent does // but ensure gets unsubscribed Subscriber<T> parent = new Subscriber<T>(child) { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(T t) { } }; child.add(parent); child.onError(e); return parent; } } }); } public static <T extends Serializable> Observable<T> write(final Observable<T> source, final File file, final boolean append, final int bufferSize) { Func0<OutputStream> resourceFactory = new Func0<OutputStream>() { @Override public OutputStream call() { try { return new BufferedOutputStream(new FileOutputStream(file, append), bufferSize); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }; Func1<OutputStream, Observable<? extends T>> observableFactory = new Func1<OutputStream, Observable<? extends T>>() { @Override public Observable<? extends T> call(OutputStream os) { return write(source, os); } }; Action1<OutputStream> disposeAction = new Action1<OutputStream>() { @Override public void call(OutputStream os) { try { os.close(); } catch (IOException e) { throw new RuntimeException(e); } } }; return Observable.using(resourceFactory, observableFactory, disposeAction, true); } public static <T extends Serializable> Observable<T> write(final Observable<T> source, final File file, final boolean append) { return write(source, file, append, DEFAULT_BUFFER_SIZE); } }
package com.github.jhpoelen.fbob; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.Pair; import ucar.ma2.InvalidRangeException; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; public class ConfigUtil { private static final Logger LOG = Logger.getLogger(ConfigUtil.class.getName()); public static final String OUTPUT_DEFAULTS = "output.start.year;0;;\n" + "output.file.prefix;osm;;\n" + "output.dir.path;output;;\n" + "output.recordfrequency.ndt;12;;\n" + ";;;\n" + "# CSV separator (COMA, SEMICOLON, EQUALS, COLON, TAB);;;\n" + "output.csv.separator;COMA;;\n" + ";;;\n" + "# Save restart file;;;\n" + "output.restart.enabled;false;;\n" + "output.restart.recordfrequency.ndt;60;;\n" + "output.restart.spinup;114;;\n" + ";;;\n" + "# Biomass;;;\n" + "output.biomass.enabled;true;;\n" + "output.biomass.bysize.enabled;false;;\n" + "output.biomass.byage.enabled;false;;\n" + "# Abundance;;;\n" + "output.abundance.enabled;false;;\n" + "output.abundance.bysize.enabled;false;;\n" + "output.abundance.byage.enabled;true;;\n" + "# Mortality;;;\n" + "output.mortality.enabled;true;;\n" + "output.mortality.perSpecies.byAge.enabled;true;;\n" + "output.mortality.perSpecies.bySize.enabled;false;;\n" + "# Yield;;;\n" + "output.yield.biomass.enabled;true;;\n" + "output.yield.abundance.enabled;false;;\n" + "output.yieldN.bySize.enabled;false;;\n" + "output.yield.bySize.enabled;false;;\n" + "output.yieldN.byAge.enabled;false;;\n" + "output.yield.byAge.enabled;false;;\n" + "# Size;;;\n" + "output.size.enabled;true ;;\n" + "output.size.catch.enabled;true ;;\n" + "output.meanSize.byAge.enabled;false;;\n" + "# TL;;;\n" + "output.TL.enabled;true;;\n" + "output.TL.catch.enabled;true;;\n" + "output.biomass.byTL.enabled;true;;\n" + "output.meanTL.bySize.enabled;false;;\n" + "output.meanTL.byAge.enabled;false;;\n" + "# Predation;;;\n" + "output.diet.composition.enabled;true;;\n" + "output.diet.composition.byAge.enabled;false;;\n" + "output.diet.composition.bySize.enabled;false;;\n" + "output.diet.pressure.enabled;true;;\n" + "output.diet.pressure.byAge.enabled;false;;\n" + "output.diet.pressure.bySize.enabled;false;;\n" + "# Spatial;;;\n" + "output.spatial.enabled;false;;\n" + "output.spatial.ltl.enabled;false;;\n" + ";;;\n" + "# Advanced parameters;;;\n" + "# Whether to include step 0 of the simulation in the outputs;;;\n" + "output.step0.include;false;;\n" + "# Cutoff for biomass, abundance, mean size and mean trophic level outputs;;;"; public static void writeLine(OutputStream os, List<String> values, boolean leadingNewline) throws IOException { List<String> escapedValues = new ArrayList<String>(); for (String value : values) { escapedValues.add(StringEscapeUtils.escapeCsv(value)); } String row = StringUtils.join(escapedValues, ";"); String line = leadingNewline ? ("\n" + row) : row; IOUtils.copy(IOUtils.toInputStream(line, "UTF-8"), os); } public static void writeLine(OutputStream os, List<String> values) throws IOException { writeLine(os, values, true); } public static void generateSeasonalReproductionFor(List<Group> groups, StreamFactory factory, ValueFactory valueFactory, Integer numberOfTimestepsPerYear) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-reproduction.csv"); for (int i = 0; i < groups.size(); i++) { String reproductionFilename = reproductionFilename(i); String paramName = "reproduction.season.file.sp" + i; writeLine(os, Arrays.asList(paramName, reproductionFilename), i > 0); } List<Pair<Double, String>> months = Arrays.asList( Pair.of(1.0 / 12.0, "Jan"), Pair.of(2.0 / 12.0, "Feb"), Pair.of(3.0 / 12.0, "Mar"), Pair.of(4.0 / 12.0, "Apr"), Pair.of(5.0 / 12.0, "May"), Pair.of(6.0 / 12.0, "Jun"), Pair.of(7.0 / 12.0, "Jul"), Pair.of(8.0 / 12.0, "Aug"), Pair.of(9.0 / 12.0, "Sep"), Pair.of(10.0 / 12.0, "Oct"), Pair.of(11.0 / 12.0, "Nov"), Pair.of(12.0 / 12.0, "Dec")); for (int i = 0; i < groups.size(); i++) { double values[] = new double[numberOfTimestepsPerYear]; Arrays.fill(values, 0); double valuesSum = 0.0; OutputStream reprodOs = factory.outputStreamFor(reproductionFilename(i)); final Group group = groups.get(i); writeLine(reprodOs, Arrays.asList("Time (year)", group.getName()), false); for (int timeStep = 0; timeStep < numberOfTimestepsPerYear; timeStep++) { for (Pair<Double, String> month : months) { double upper = (double) (timeStep + 1) / numberOfTimestepsPerYear; if (upper <= month.getLeft()) { String reproductionForSpawningMonth = valueFactory.groupValueFor("spawning." + month.getRight(), group); if (NumberUtils.isParsable(reproductionForSpawningMonth)) { double value = Double.parseDouble(reproductionForSpawningMonth); valuesSum += value; values[timeStep] = value; } break; } } } if (values.length > 0) { for (int timeStep = 0; timeStep < numberOfTimestepsPerYear; timeStep++) { double valueNormalized = valuesSum == 0 ? (1.0 / numberOfTimestepsPerYear) : (values[timeStep] / valuesSum); writeLine(reprodOs, Arrays.asList(formatTimeStep(numberOfTimestepsPerYear, timeStep), String.format("%.3f", valueNormalized))); } } } } private static String formatTimeStep(Integer numberOfTimestepsPerYear, int stepNumber) { return String.format("%.3f", (double) stepNumber / numberOfTimestepsPerYear); } public static String reproductionFilename(int i) { return "reproduction-seasonality-sp" + i + ".csv"; } public static void generateFishingParametersFor(List<Group> groupNames, StreamFactory factory, Integer timeStepsPerYear) throws IOException { generateFishingSeasonalityConfig(groupNames, factory); generateFishingSeasonalityTables(groupNames, factory, timeStepsPerYear); } public static void generateFishingSeasonalityTables(List<Group> groups, StreamFactory factory, Integer timeStepsPerYear) throws IOException { for (Group group : groups) { OutputStream seasonalityOs = factory.outputStreamFor(finishingSeasonalityFilename(group)); writeLine(seasonalityOs, Arrays.asList("Time", "Season"), false); for (int i = 0; i < timeStepsPerYear; i++) { writeLine(seasonalityOs, Arrays.asList(formatTimeStep(timeStepsPerYear, i), "")); } } } public static void generateFishingSeasonalityConfig(List<Group> groups, StreamFactory factory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-fishing.csv"); writeZerosFor(groups, "mortality.fishing.rate.sp", os); writeZerosFor(groups, "mortality.fishing.recruitment.age.sp", os); writeZerosFor(groups, "mortality.fishing.recruitment.size.sp", os); for (Group group : groups) { String paramName = "mortality.fishing.season.distrib.file.sp" + groups.indexOf(group); String fishingSeasonality = finishingSeasonalityFilename(group); writeLine(os, Arrays.asList(paramName, fishingSeasonality)); } } public static String finishingSeasonalityFilename(Group groupName) { return "fishing/fishing-seasonality-" + groupName.getName() + ".csv"; } public static void writeZerosFor(List<Group> groupNames, String paramName, OutputStream os) throws IOException { for (Group groupName : groupNames) { writeLine(os, Arrays.asList(paramName + groupNames.indexOf(groupName), "0.0")); } } public static void generateStarvationFor(List<Group> groupNames, StreamFactory factory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-starvation.csv"); for (int i = 0; i < groupNames.size(); i++) { String paramName = "mortality.starvation.rate.max.sp" + i; writeLine(os, Arrays.asList(paramName, "0.3"), i > 0); } } public static void generateSpecies(List<Group> groups, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-species.csv"); for (Group groupName : groups) { int i = groups.indexOf(groupName); writeLine(os, Arrays.asList("species.name.sp" + i, groupName.getName()), i > 0); } writeParamLines(groups, "species.egg.size.sp", valueFactory, os); writeParamLines(groups, "species.egg.weight.sp", valueFactory, os); writeParamLines(groups, "species.K.sp", valueFactory, os); writeParamLines(groups, "species.length2weight.allometric.power.sp", valueFactory, os); writeParamLines(groups, "species.length2weight.condition.factor.sp", valueFactory, os); writeParamLines(groups, "species.lifespan.sp", valueFactory, os); writeParamLines(groups, "species.lInf.sp", valueFactory, os); writeParamLines(groups, "species.maturity.size.sp", valueFactory, os); writeParamLines(groups, "species.maturity.age.sp", valueFactory, os); writeParamLines(groups, "species.relativefecundity.sp", valueFactory, os); writeParamLines(groups, "species.sexratio.sp", (name, group) -> { String someValue = valueFactory.groupValueFor(name, group); return NumberUtils.isParsable(someValue) ? String.format("%.2f", Double.parseDouble(someValue)) : someValue; }, os); writeParamLines(groups, "species.t0.sp", valueFactory, os); writeParamLines(groups, "species.vonbertalanffy.threshold.age.sp", valueFactory, os); } public static void generateLtlForGroups(List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-ltl.csv"); for (Group groupName : groupsBackground) { int i = groupsBackground.indexOf(groupName); writeLine(os, Arrays.asList("plankton.name.plk" + i, groupName.getName()), i > 0); } writeParamLines(groupsBackground, "plankton.accessibility2fish.plk", valueFactory, os); writeParamLines(groupsBackground, "plankton.conversion2tons.plk", valueFactory, os); writeParamLines(groupsBackground, "plankton.size.max.plk", valueFactory, os); writeParamLines(groupsBackground, "plankton.size.min.plk", valueFactory, os); writeParamLines(groupsBackground, "plankton.TL.plk", valueFactory, os); } public static void writeParamLines(List<Group> groups, String paramPrefix, ValueFactory valueFactory, OutputStream os) throws IOException { for (Group group : groups) { final String paramName = paramPrefix + groups.indexOf(group); writeLine(os, Arrays.asList(paramName, valueFactory.groupValueFor(paramPrefix, group))); } } public static void writeParamLinesDup(List<Group> groups, String paramPrefix, ValueFactory valueFactory, OutputStream os) throws IOException { for (Group group : groups) { final String paramName = paramPrefix + groups.indexOf(group); String value = valueFactory.groupValueFor(paramPrefix, group); writeLine(os, Arrays.asList(paramName, value, value)); } } public static void writeParamLines(List<Group> groupNames, String paramPrefix, List<String> paramValues, OutputStream os) throws IOException { for (Group group : groupNames) { List<String> values = new ArrayList<String>() {{ add(paramPrefix + groupNames.indexOf(group)); addAll(paramValues); }}; writeLine(os, values); } } public static void generatePredationFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-predation.csv"); writeLine(os, Arrays.asList("predation.accessibility.file", "predation-accessibility.csv"), false); writeLine(os, Arrays.asList("predation.accessibility.stage.structure", "age")); writeParamLines(groupNames, "predation.accessibility.stage.threshold.sp", valueFactory, os); writeParamLines(groupNames, "predation.efficiency.critical.sp", valueFactory, os); writeParamLines(groupNames, "predation.ingestion.rate.max.sp", valueFactory, os); writeParamLinesDup(groupNames, "predation.predPrey.sizeRatio.max.sp", valueFactory, os); writeParamLinesDup(groupNames, "predation.predPrey.sizeRatio.min.sp", valueFactory, os); writeLine(os, Arrays.asList("predation.predPrey.stage.structure", "size")); writeParamLines(groupNames, "predation.predPrey.stage.threshold.sp", valueFactory, os); } public static void generateAllParametersFor(Integer timeStepsPerYear, List<Group> groupFocal, List<Group> groupsBackground, StreamFactory factory) throws IOException { OutputStream os = factory.outputStreamFor("osm_all-parameters.csv"); writeLine(os, Arrays.asList("simulation.time.ndtPerYear", timeStepsPerYear.toString())); writeLine(os, Arrays.asList("simulation.time.nyear", "134")); writeLine(os, Arrays.asList("simulation.restart.file", "null")); writeLine(os, Arrays.asList("output.restart.recordfrequency.ndt", "60")); writeLine(os, Arrays.asList("output.restart.spinup", "114")); writeLine(os, Arrays.asList("simulation.nschool", "20")); writeLine(os, Arrays.asList("simulation.ncpu", "8")); writeLine(os, Arrays.asList("simulation.nplankton", Integer.toString(groupsBackground.size()))); writeLine(os, Arrays.asList("simulation.nsimulation", "10")); writeLine(os, Arrays.asList("simulation.nspecies", Integer.toString(groupFocal.size()))); writeLine(os, Arrays.asList("mortality.algorithm", "stochastic")); writeLine(os, Arrays.asList("mortality.subdt", "10")); writeLine(os, Arrays.asList("osmose.configuration.output", "osm_param-output.csv")); writeLine(os, Arrays.asList("osmose.configuration.movement", "osm_param-movement.csv")); writeLine(os, Arrays.asList("osmose.configuration.mortality.fishing", "osm_param-fishing.csv")); writeLine(os, Arrays.asList("osmose.configuration.mortality.natural", "osm_param-natural-mortality.csv")); writeLine(os, Arrays.asList("osmose.configuration.mortality.predation", "osm_param-predation.csv")); writeLine(os, Arrays.asList("osmose.configuration.mortality.starvation", "osm_param-starvation.csv")); writeLine(os, Arrays.asList("osmose.configuration.reproduction", "osm_param-reproduction.csv")); writeLine(os, Arrays.asList("osmose.configuration.species", "osm_param-species.csv")); writeLine(os, Arrays.asList("osmose.configuration.plankton", "osm_param-ltl.csv")); writeLine(os, Arrays.asList("osmose.configuration.grid", "osm_param-grid.csv")); writeLine(os, Arrays.asList("osmose.configuration.initialization", "osm_param-init-pop.csv")); } public static void generateOutputParamsFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-output.csv"); IOUtils.copy(IOUtils.toInputStream(OUTPUT_DEFAULTS, "UTF-8"), os); writeLine(os, Arrays.asList("output.cutoff.enabled", "true")); writeParamLines(groupNames, "output.cutoff.age.sp", valueFactory, os); writeLine(os, Arrays.asList("output.distrib.bySize.min", "0")); writeLine(os, Arrays.asList("output.distrib.bySize.max", "205")); writeLine(os, Arrays.asList("output.distrib.bySize.incr", "10")); writeLine(os, Arrays.asList("output.distrib.byAge.min", "0")); writeLine(os, Arrays.asList("output.distrib.byAge.max", "10")); writeLine(os, Arrays.asList("output.distrib.byAge.incr", "1")); writeLine(os, Arrays.asList("output.diet.stage.structure", "age")); writeParamLines(groupNames, "output.diet.stage.threshold.sp", Arrays.asList("0", "1", "2"), os); } public static void generateNaturalMortalityFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-natural-mortality.csv"); writeLine(os, Arrays.asList("mortality.natural.larva.rate.file", "null"), false); writeParamLines(groupNames, "mortality.natural.larva.rate.sp", valueFactory, os); writeLine(os, Arrays.asList("mortality.natural.rate.file", "null")); writeParamLines(groupNames, "mortality.natural.rate.sp", valueFactory, os); } public static void generateInitBiomassFor(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-init-pop.csv"); writeParamLines(groupNames, "population.seeding.biomass.sp", valueFactory, os); } public static void generateStatic(StreamFactory factory) throws IOException { generateFromTemplate(factory, "osm_param-grid.csv"); generateFromTemplate(factory, "README.xlsx"); } public static void generateFromTemplate(StreamFactory factory, String staticTemplate) throws IOException { OutputStream os = factory.outputStreamFor(staticTemplate); IOUtils.copy(ConfigUtil.class.getResourceAsStream("osmose_config/" + staticTemplate), os); } public static void generateMaps(List<Group> groupNames, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream maskOs = factory.outputStreamFor("grid-mask.csv"); IOUtils.copy(ConfigUtil.class.getResourceAsStream("osmose_config/grid-mask.csv"), maskOs); generateMovementConfig(groupNames, factory, valueFactory); generateMovementMapTemplates(groupNames, factory); } public static void generateMovementMapTemplates(List<Group> groups, StreamFactory factory) throws IOException { int nMaps = 1; for (Group group : groups) { OutputStream mapOutputStream = factory.outputStreamFor(getMapName(group)); IOUtils.copy(ConfigUtil.class.getResourceAsStream("osmose_config/maps/Amberjacks_1.csv"), mapOutputStream); nMaps++; } } public static void generateMovementConfig(List<Group> groups, StreamFactory factory, ValueFactory valueFactory) throws IOException { OutputStream os = factory.outputStreamFor("osm_param-movement.csv"); writeParamLines(groups, "movement.distribution.method.sp", valueFactory, os); writeParamLines(groups, "movement.randomwalk.range.sp", valueFactory, os); int nMaps = 1; for (Group group : groups) { addMapForGroup(os, nMaps, group, getMapName(group)); nMaps++; } } public static String getMapName(Group group) { return "maps/" + group.getName() + "_1.csv"; } public static void addMapForGroup(OutputStream os, int nMaps, Group group, String mapName) throws IOException { String prefix = "movement.map" + nMaps; writeLine(os, Arrays.asList(prefix + ".age.max", "2")); writeLine(os, Arrays.asList(prefix + ".age.min", "0")); writeLine(os, Arrays.asList(prefix + ".file", mapName)); writeLine(os, Arrays.asList(prefix + ".season", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11")); writeLine(os, Arrays.asList(prefix + ".species", group.getName())); } public static void generateConfigFor(Config config, StreamFactory factory, ValueFactory valueFactory) throws IOException { generateConfigFor(config.getTimeStepsPerYear(), config.getGroups() .stream() .filter(group -> group.getType() == GroupType.FOCAL) .collect(Collectors.toList()), config.getGroups() .stream() .filter(group -> group.getType() == GroupType.BACKGROUND) .collect(Collectors.toList()), factory, valueFactory); } public static void generateConfigFor(Integer timeStepsPerYear, List<Group> groupsFocal, List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException { generateAllParametersFor(timeStepsPerYear, groupsFocal, groupsBackground, factory); generateFishingParametersFor(groupsFocal, factory, timeStepsPerYear); generateInitBiomassFor(groupsFocal, factory, valueFactory); generateMaps(groupsFocal, factory, valueFactory); generateNaturalMortalityFor(groupsFocal, factory, valueFactory); generateOutputParamsFor(groupsFocal, factory, valueFactory); generatePredationFor(groupsFocal, factory, valueFactory); generatePredationAccessibilityFor(groupsFocal, groupsBackground, factory, valueFactory); generateSeasonalReproductionFor(groupsFocal, factory, valueFactory, timeStepsPerYear); generateSpecies(groupsFocal, factory, valueFactory); generateStarvationFor(groupsFocal, factory); generateLtlForGroups(groupsBackground, factory, valueFactory); generateLtlBiomassForGroups(groupsBackground, factory, valueFactory); generateStatic(factory); generateFunctionGroupList(new ArrayList<Group>() {{ addAll(groupsFocal); addAll(groupsBackground); }}, factory); } protected static void generateFunctionGroupList(List<Group> groups, StreamFactory factory) throws IOException { OutputStream outputStream = factory.outputStreamFor("functional_groups.csv"); IOUtils.write("functional group name,functional group type,species name,species url", outputStream); for (Group group : groups) { for (Taxon taxon : group.getTaxa()) { if (!StringUtils.equalsIgnoreCase("implicit", taxon.getSelectionCriteria())) { List<String> row = Arrays.asList(group.getName(), group.getType().getLabel(), taxon.getName(), taxon.getUrl()); IOUtils.write("\n", outputStream); IOUtils.write(StringUtils.join(row, ","), outputStream); } } } } private static void generateLtlBiomassForGroups(List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException { final String resourceName = "osm_ltlbiomass.nc"; OutputStream os = factory.outputStreamFor(resourceName); try { final File ltlbiomass = File.createTempFile("ltlbiomass", ".nc"); ltlbiomass.deleteOnExit(); LtlBiomassUtil.generateLtlBiomassNC(ltlbiomass, groupsBackground.size()); IOUtils.copy(FileUtils.openInputStream(ltlbiomass), os); } catch (InvalidRangeException e) { throw new IOException("failed to generate [" + resourceName + "]", e); } } public static ValueFactory getProxyValueFactory(List<ValueFactory> valueFactories) { return new ValueFactoryProxy(valueFactories); } enum Overlap { small(0.125), moderate(0.5), strong(1.0); private final double value; Overlap(double value) { this.value = value; } } enum EcologicalRegion { benthic } public static void generatePredationAccessibilityFor(List<Group> groupsFocal, List<Group> groupsBackground, StreamFactory factory, ValueFactory valueFactory) throws IOException { List<Group> groupList = new ArrayList<Group>() {{ addAll(groupsFocal); addAll(groupsBackground); }}; List<Pair<Group, String>> focal = groupsFocal .stream() .map(group -> Pair.of(group, valueFactory.groupValueFor("predation.accessibility.stage.threshold.sp", group))) .flatMap(groupJuvenile -> { if (StringUtils.isBlank(groupJuvenile.getRight())) { return Stream.of(groupJuvenile); } else { Pair<Group, String> juvenile = Pair.of(groupJuvenile.getLeft(), groupJuvenile.getLeft().getName() + " < " + groupJuvenile.getRight() + " year"); Pair<Group, String> adult = Pair.of(groupJuvenile.getLeft(), groupJuvenile.getLeft().getName() + " > " + groupJuvenile.getRight() + " year"); return Stream.of(juvenile, adult); } }).collect(Collectors.toList()); Stream<Pair<Group, String>> back = groupsBackground.stream().map(group -> Pair.of(group, group.getName())); Stream<Stream<String>> rows = Stream.concat(focal.stream(), back) .map(row -> { Stream<String> values = focal.stream().map(column -> { double accessbilityCoefficient = 1.0d; if (notPlankton(row)) { accessbilityCoefficient = 0.8; if (GroupType.FOCAL == row.getLeft().getType()) { Overlap overlap = calculateOverlap(valueFactory, row.getLeft(), column.getLeft()); accessbilityCoefficient = 0.8 * overlap.value; } } return String.format("%.2f", accessbilityCoefficient); }); return Stream.concat(Stream.of(row.getRight()), values); }); Stream<Stream<String>> header = Stream.of(Stream.concat(Stream.of("v Prey / Predator >"), focal.stream().map(Pair::getRight))); List<List<String>> rowsOfValues = Stream.concat(header, rows) .map(row -> row.collect(Collectors.toList())) .collect(Collectors.toList()); OutputStream outputStream = factory.outputStreamFor("predation-accessibility.csv"); for (List<String> rowsOfValue : rowsOfValues) { writeLine(outputStream, rowsOfValue, rowsOfValues.indexOf(rowsOfValue) != 0); } } private static boolean notPlankton(Pair<Group, String> row) { return Stream.of("zooplankton", "phytoplankton") .noneMatch(name -> StringUtils.equalsIgnoreCase(row.getLeft().getName(), name)); } private static Overlap calculateOverlap(ValueFactory valueFactory, Group groupA, Group groupB) { Overlap overlap; if (groupA.equals(groupB)) { overlap = Overlap.strong; } else { EcologicalRegion regionA = ecologicalRegionFor(valueFactory, groupA); EcologicalRegion regionB = ecologicalRegionFor(valueFactory, groupB); overlap = determineOverlap(Pair.of(regionA, regionB)); } return overlap; } private static EcologicalRegion ecologicalRegionFor(ValueFactory valueFactory, Group group) { EcologicalRegion region = null; if (ecoRegionMatches(valueFactory, "Benthic", group)) { region = EcologicalRegion.benthic; } return region; } private static Overlap determineOverlap(Pair<EcologicalRegion, EcologicalRegion> region) { Overlap overlap; if (sameEcoRegions(region)) { overlap = Overlap.strong; } else { overlap = Overlap.moderate; } return overlap; } private static boolean sameEcoRegions(Pair<EcologicalRegion, EcologicalRegion> regionPair) { return regionPair.getLeft() == regionPair.getRight(); } private static boolean ecoRegionMatches(ValueFactory valueFactory, String ecologyFieldName, Group group) { return !StringUtils.equals("0", valueFactory.groupValueFor("ecology." + ecologyFieldName, group)); } }
package org.rstudio.studio.client.workbench.views.source.editors.data; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import org.rstudio.core.client.Debug; import org.rstudio.core.client.Size; import org.rstudio.core.client.widget.SimplePanelWithProgress; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.filetypes.FileIconResources; import org.rstudio.studio.client.common.satellite.SatelliteManager; import org.rstudio.studio.client.dataviewer.DataViewerSatellite; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.views.source.editors.urlcontent.UrlContentEditingTarget; import org.rstudio.studio.client.workbench.views.source.events.DataViewChangedEvent; import org.rstudio.studio.client.workbench.views.source.model.DataItem; import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations; import java.util.HashMap; public class DataEditingTarget extends UrlContentEditingTarget implements DataViewChangedEvent.Handler { @Inject public DataEditingTarget(SourceServerOperations server, Commands commands, GlobalDisplay globalDisplay, EventBus events, SatelliteManager satelliteManager) { super(server, commands, globalDisplay, events); satelliteManager_ = satelliteManager; events.addHandler(DataViewChangedEvent.TYPE, this); } @Override protected Display createDisplay() { progressPanel_ = new SimplePanelWithProgress(); progressPanel_.setSize("100%", "100%"); reloadDisplay(); return new Display() { public void print() { ((Display)progressPanel_.getWidget()).print(); } public Widget asWidget() { return progressPanel_; } }; } @Override public void onDataViewChanged(DataViewChangedEvent event) { if (event.getData().getCacheKey().equals(getDataItem().getCacheKey())) { view_.refreshData(event.getData().structureChanged()); } } @Override public void onActivate() { super.onActivate(); if (view_ != null) view_.applySizeChange(); } private void clearDisplay() { progressPanel_.showProgress(1); } private void reloadDisplay() { view_ = new DataEditingTargetWidget( commands_, getDataItem()); view_.setSize("100%", "100%"); progressPanel_.setWidget(view_); } @Override public String getPath() { return getDataItem().getURI(); } @Override public ImageResource getIcon() { return FileIconResources.INSTANCE.iconCsv(); } private DataItem getDataItem() { return doc_.getProperties().cast(); } @Override protected String getContentTitle() { return getDataItem().getCaption(); } @Override protected String getContentUrl() { return getDataItem().getContentUrl(); } @Override public void popoutDoc() { DataItem item = getDataItem(); if (item.getCacheKey() != null && item.getCacheKey().length() > 0) { // if we have a cache key, duplicate it server_.duplicateDataView(item.getCaption(), item.getEnvironment(), item.getObject(), item.getCacheKey(), new ServerRequestCallback<DataItem>() { @Override public void onResponseReceived(DataItem item) { satelliteManager_.openSatellite(DataViewerSatellite.NAME, item, new Size(750, 850)); } @Override public void onError(ServerError error) { globalDisplay_.showErrorMessage("View Failed", error.getMessage()); } }); } else { // no cache key, just show the content directly globalDisplay_.showHtmlFile(item.getContentUrl()); } } protected String getCacheKey() { return getDataItem().getCacheKey(); } public void updateData(final DataItem data) { final Widget originalWidget = progressPanel_.getWidget(); clearDisplay(); final String oldCacheKey = getCacheKey(); HashMap<String, String> props = new HashMap<String, String>(); data.fillProperties(props); server_.modifyDocumentProperties( doc_.getId(), props, new SimpleRequestCallback<Void>("Error") { @Override public void onResponseReceived(Void response) { server_.removeCachedData( oldCacheKey, new ServerRequestCallback<Void>() { @Override public void onError(ServerError error) { Debug.logError(error); } }); data.fillProperties(doc_.getProperties()); reloadDisplay(); } @Override public void onError(ServerError error) { super.onError(error); progressPanel_.setWidget(originalWidget); } }); } @Override public void onDismiss() { server_.removeCachedData(getCacheKey(), new ServerRequestCallback<org.rstudio.studio.client.server.Void>() { @Override public void onError(ServerError error) { Debug.logError(error); } }); } private SimplePanelWithProgress progressPanel_; private DataEditingTargetWidget view_; private final SatelliteManager satelliteManager_; }
package com.gmail.favorlock.bonesqlib; import com.gmail.favorlock.bonesqlib.delegates.HostnameDatabase; import com.gmail.favorlock.bonesqlib.delegates.HostnameDatabaseImpl; import com.jolbox.bonecp.BoneCPConfig; import java.sql.SQLException; import java.util.Properties; import java.util.logging.Logger; /** * @author Evan Lindsay * @date 8/23/13 * @time 2:09 AM */ public class MySQL extends Database { private HostnameDatabase delegate = new HostnameDatabaseImpl(); public MySQL(Logger log, String prefix, String database, String username, String password) { super(log, prefix, "[MySQL] "); setHostname("localhost"); setPort(3306); setDatabase(database); setUsername(username); setPassword(password); } public MySQL(Logger log, String prefix, String hostname, int port, String database, String username, String password) { super(log, prefix, "[MySQL] "); setHostname(hostname); setPort(port); setDatabase(database); setUsername(username); setPassword(password); } public String getHostname() { return delegate.getHostname(); } public void setHostname(String hostname) { delegate.setHostname(hostname); } public int getPort() { return delegate.getPort(); } public void setPort(int port) { delegate.setPort(port); } public String getUsername() { return delegate.getUsername(); } public void setUsername(String username) { delegate.setUsername(username); } public String getPassword() { return delegate.getPassword(); } public void setPassword(String password) { delegate.setPassword(password); } public String getDatabase() { return delegate.getDatabase(); } public void setDatabase(String database) { delegate.setDatabase(database); } @Override protected boolean initialize() { try { Class.forName("com.mysql.jdbc.Driver"); return true; } catch (ClassNotFoundException e) { this.writeError("MySQL driver class missing: " + e.getMessage() + ".", true); return false; } } @Override public boolean open() { if (initialize()) { initConfig(); BoneCPConfig config = getConfig(); config.setJdbcUrl("jdbc:mysql://" + getHostname() + ":" + getPort() + "/" + getDatabase()); config.setUsername(getUsername()); config.setPassword(getPassword()); config.setMinConnectionsPerPartition(5); config.setMaxConnectionsPerPartition(10); config.setPartitionCount(1); config.setDefaultAutoCommit(true); config.setDefaultReadOnly(false); Properties properties = new Properties(); properties.setProperty("zeroDateTimeBehavior", "convertToNull"); config.setDriverProperties(properties); try { initCP(config); return true; } catch (SQLException e) { this.writeError("Not connected to the database: " + e.getMessage() + ".", true); return false; } } else { return false; } } }
package org.rstudio.studio.client.workbench.views.source.editors.text; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceEditorNative; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Anchor; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.Timer; public class ChunkRowExecState { public ChunkRowExecState(final AceEditorNative editor, int row, int state, Command onRemoved) { anchor_ = Anchor.createAnchor(editor.getSession().getDocument(), row, 0); editor_ = editor; row_ = row; state_ = state; onRemoved_ = onRemoved; anchor_.addOnChangeHandler(new Command() { @Override public void execute() { // no work if anchor hasn't changed rows if (getRow() == anchor_.getRow()) return; // if we're just cleaning up this line, finish the cleanup // immediately rather than trying to shift if (state_ == LINE_RESTING) { detach(); return; } // remove all cumulative state from the old line and reapply to // the new line removeClazz(); row_ = anchor_.getRow(); if (state_ == LINE_ERROR) { addClazz(state_); } else { for (int i = LINE_QUEUED; i <= state_; i++) { addClazz(i); } } } }); addClazz(state_); } public int getRow() { return row_; } public void setRow(int row) { row_ = row; } public void detach() { resetTimer(); removeClazz(); anchor_.detach(); if (onRemoved_ != null) onRemoved_.execute(); } public int getState() { return state_; } public static String getClazz(int state) { switch (state) { case LINE_QUEUED: return LINE_QUEUED_CLASS; case LINE_EXECUTED: return LINE_EXECUTED_CLASS; case LINE_RESTING: return LINE_RESTING_CLASS; case LINE_ERROR: return LINE_ERROR_CLASS; } return ""; } public void setState(int state) { // ignore if already at this state if (state_ == state) return; // if the moving to the error state, clean other states if (state == LINE_ERROR) removeClazz(); // if this is the error state, there's no transition to the resting state if (state_ == LINE_ERROR && state == LINE_RESTING) return; state_ = state; if (state_ == LINE_RESTING) { timer_ = new Timer() { @Override public void run() { addClazz(state_); scheduleDismiss(); } }; timer_.schedule(LINGER_MS); } else { addClazz(state_); } } private void addClazz(int state) { editor_.getRenderer().addGutterDecoration(getRow() - 1, getClazz(state)); } private void removeClazz() { for (int i = LINE_QUEUED; i <= state_; i++) { editor_.getRenderer().removeGutterDecoration( getRow() - 1, getClazz(i)); } } private void scheduleDismiss() { resetTimer(); timer_ = new Timer() { @Override public void run() { detach(); } }; timer_.schedule(FADE_MS); } private void resetTimer() { if (timer_ != null && timer_.isRunning()) { timer_.cancel(); timer_ = null; } } private int row_; private int state_; private final Anchor anchor_; private final AceEditorNative editor_; private final Command onRemoved_; private Timer timer_; private final static int LINGER_MS = 250; private final static int FADE_MS = 400; public final static String LINE_QUEUED_CLASS = "ace_chunk-queued-line"; public final static String LINE_EXECUTED_CLASS = "ace_chunk-executed-line"; public final static String LINE_RESTING_CLASS = "ace_chunk-resting-line"; public final static String LINE_ERROR_CLASS = "ace_chunk-error-line"; public final static int LINE_QUEUED = 0; public final static int LINE_EXECUTED = 1; public final static int LINE_RESTING = 2; public final static int LINE_ERROR = 3; public final static int LINE_NONE = 4; }
package org.voltdb.compiler; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.voltdb.BackendTarget; import org.voltdb.ProcInfoData; import org.voltdb.utils.NotImplementedException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * Alternate (programmatic) interface to VoltCompiler. Give the class all of * the information a user would put in a VoltDB project file and it will go * and build the project file and run the compiler on it. * * It will also create a deployment.xml file and apply its changes to the catalog. */ public class VoltProjectBuilder { final LinkedHashSet<String> m_schemas = new LinkedHashSet<String>(); public static final class ProcedureInfo { private final String groups[]; private final Class<?> cls; private final String name; private final String sql; private final String partitionInfo; private final String joinOrder; public ProcedureInfo(final String groups[], final Class<?> cls) { this.groups = groups; this.cls = cls; this.name = cls.getSimpleName(); this.sql = null; this.joinOrder = null; this.partitionInfo = null; assert(this.name != null); } public ProcedureInfo( final String groups[], final String name, final String sql, final String partitionInfo) { this(groups, name, sql, partitionInfo, null); } public ProcedureInfo( final String groups[], final String name, final String sql, final String partitionInfo, final String joinOrder) { assert(name != null); this.groups = groups; this.cls = null; this.name = name; this.sql = sql; this.partitionInfo = partitionInfo; this.joinOrder = joinOrder; assert(this.name != null); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(final Object o) { if (o instanceof ProcedureInfo) { final ProcedureInfo oInfo = (ProcedureInfo)o; return name.equals(oInfo.name); } return false; } } public static final class UserInfo { public final String name; public final String password; private final String groups[]; public UserInfo (final String name, final String password, final String groups[]){ this.name = name; this.password = password; this.groups = groups; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(final Object o) { if (o instanceof UserInfo) { final UserInfo oInfo = (UserInfo)o; return name.equals(oInfo.name); } return false; } } public static final class GroupInfo { private final String name; private final boolean adhoc; private final boolean sysproc; public GroupInfo(final String name, final boolean adhoc, final boolean sysproc){ this.name = name; this.adhoc = adhoc; this.sysproc = sysproc; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(final Object o) { if (o instanceof GroupInfo) { final GroupInfo oInfo = (GroupInfo)o; return name.equals(oInfo.name); } return false; } } /** An export/tables/table entry */ public static final class ExportTableInfo { final public String m_tablename; final public boolean m_export_only; ExportTableInfo(String tablename, boolean append) { m_tablename = tablename; m_export_only = append; } } final ArrayList<ExportTableInfo> m_exportTables = new ArrayList<ExportTableInfo>(); final LinkedHashSet<UserInfo> m_users = new LinkedHashSet<UserInfo>(); final LinkedHashSet<GroupInfo> m_groups = new LinkedHashSet<GroupInfo>(); final LinkedHashSet<ProcedureInfo> m_procedures = new LinkedHashSet<ProcedureInfo>(); final LinkedHashSet<Class<?>> m_supplementals = new LinkedHashSet<Class<?>>(); final LinkedHashMap<String, String> m_partitionInfos = new LinkedHashMap<String, String>(); String m_elloader = null; // loader package.Classname private boolean m_elenabled; // true if enabled; false if disabled List<String> m_elAuthGroups; // authorized groups int m_httpdPortNo = 0; // zero defaults to first open port >= 8080 boolean m_jsonApiEnabled = true; BackendTarget m_target = BackendTarget.NATIVE_EE_JNI; PrintStream m_compilerDebugPrintStream = null; boolean m_securityEnabled = false; final Map<String, ProcInfoData> m_procInfoOverrides = new HashMap<String, ProcInfoData>(); private String m_snapshotPath = null; private int m_snapshotRetain = 0; private String m_snapshotPrefix = null; private String m_snapshotFrequency = null; private String m_pathToDeployment = null; /** * Produce all catalogs this project builder knows how to produce. * Written to allow BenchmarkController to cause compilation of multiple * catalogs for benchmarks that need to update running appplications and * consequently need multiple benchmark controlled catalog jars. * @param sitesPerHost * @param length * @param kFactor * @param string * @return a list of jar filenames that were compiled. The benchmark will * be started using the filename at index 0. */ public String[] compileAllCatalogs( int sitesPerHost, int length, int kFactor, String string) { throw new NotImplementedException("This project builder does not support compileAllCatalogs"); } public void addAllDefaults() { // does nothing in the base class } public void addUsers(final UserInfo users[]) { for (final UserInfo info : users) { final boolean added = m_users.add(info); if (!added) { assert(added); } } } public void addGroups(final GroupInfo groups[]) { for (final GroupInfo info : groups) { final boolean added = m_groups.add(info); if (!added) { assert(added); } } } public void addSchema(final URL schemaURL) { assert(schemaURL != null); addSchema(schemaURL.getPath()); } /** * This is test code written by Ryan, even though it was * committed by John. */ public void addLiteralSchema(String ddlText) throws IOException { File temp = File.createTempFile("literalschema", "sql"); temp.deleteOnExit(); FileWriter out = new FileWriter(temp); out.write(ddlText); out.close(); addSchema(URLEncoder.encode(temp.getAbsolutePath(), "UTF-8")); } public void addSchema(String schemaPath) { try { schemaPath = URLDecoder.decode(schemaPath, "UTF-8"); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); System.exit(-1); } assert(m_schemas.contains(schemaPath) == false); final File schemaFile = new File(schemaPath); assert(schemaFile != null); assert(schemaFile.isDirectory() == false); // this check below fails in some valid cases (like when the file is in a jar) //assert schemaFile.canRead() // : "can't read file: " + schemaPath; m_schemas.add(schemaPath); } public void addStmtProcedure(String name, String sql) { addStmtProcedure(name, sql, null, null); } public void addStmtProcedure(String name, String sql, String partitionInfo) { addStmtProcedure( name, sql, partitionInfo, null); } public void addStmtProcedure(String name, String sql, String partitionInfo, String joinOrder) { addProcedures(new ProcedureInfo(new String[0], name, sql, partitionInfo, joinOrder)); } public void addProcedures(final Class<?>... procedures) { final ArrayList<ProcedureInfo> procArray = new ArrayList<ProcedureInfo>(); for (final Class<?> procedure : procedures) procArray.add(new ProcedureInfo(new String[0], procedure)); addProcedures(procArray); } /* * List of groups permitted to invoke the procedure */ public void addProcedures(final ProcedureInfo... procedures) { final ArrayList<ProcedureInfo> procArray = new ArrayList<ProcedureInfo>(); for (final ProcedureInfo procedure : procedures) procArray.add(procedure); addProcedures(procArray); } public void addProcedures(final Iterable<ProcedureInfo> procedures) { // check for duplicates and existings final HashSet<ProcedureInfo> newProcs = new HashSet<ProcedureInfo>(); for (final ProcedureInfo procedure : procedures) { assert(newProcs.contains(procedure) == false); assert(m_procedures.contains(procedure) == false); newProcs.add(procedure); } // add the procs for (final ProcedureInfo procedure : procedures) { m_procedures.add(procedure); } } public void addSupplementalClasses(final Class<?>... supplementals) { final ArrayList<Class<?>> suppArray = new ArrayList<Class<?>>(); for (final Class<?> supplemental : supplementals) suppArray.add(supplemental); addSupplementalClasses(suppArray); } public void addSupplementalClasses(final Iterable<Class<?>> supplementals) { // check for duplicates and existings final HashSet<Class<?>> newSupps = new HashSet<Class<?>>(); for (final Class<?> supplemental : supplementals) { assert(newSupps.contains(supplemental) == false); assert(m_supplementals.contains(supplemental) == false); newSupps.add(supplemental); } // add the supplemental classes for (final Class<?> supplemental : supplementals) m_supplementals.add(supplemental); } public void addPartitionInfo(final String tableName, final String partitionColumnName) { assert(m_partitionInfos.containsKey(tableName) == false); m_partitionInfos.put(tableName, partitionColumnName); } public void setHTTPDPort(int port) { m_httpdPortNo = port; } public void setJSONAPIEnabled(final boolean enabled) { m_jsonApiEnabled = enabled; } public void setSecurityEnabled(final boolean enabled) { m_securityEnabled = enabled; } public void setSnapshotSettings( String frequency, int retain, String path, String prefix) { assert(frequency != null); assert(prefix != null); m_snapshotFrequency = frequency; m_snapshotRetain = retain; m_snapshotPrefix = prefix; m_snapshotPath = path; } public void addExport(final String loader, boolean enabled, List<String> groups) { m_elloader = loader; m_elenabled = enabled; m_elAuthGroups = groups; } public void addExportTable(String name, boolean exportonly) { ExportTableInfo info = new ExportTableInfo(name, exportonly); m_exportTables.add(info); } public void setCompilerDebugPrintStream(final PrintStream out) { m_compilerDebugPrintStream = out; } /** * Override the procedure annotation with the specified values for a * specified procedure. * * @param procName The name of the procedure to override the annotation. * @param info The values to use instead of the annotation. */ public void overrideProcInfoForProcedure(final String procName, final ProcInfoData info) { assert(procName != null); assert(info != null); m_procInfoOverrides.put(procName, info); } public boolean compile(final String jarPath) { return compile(jarPath, 1, 1, 0, "localhost"); } public boolean compile(final String jarPath, final int sitesPerHost, final int replication) { return compile(jarPath, sitesPerHost, 1, replication, "localhost"); } public boolean compile(final String jarPath, final int sitesPerHost, final int hostCount, final int replication, final String leaderAddress) { VoltCompiler compiler = new VoltCompiler(); String voltRootPath = "/tmp/" + System.getProperty("user.name"); java.io.File voltRootFile = new java.io.File(voltRootPath); if (!voltRootFile.exists()) { if (!voltRootFile.mkdir()) { throw new RuntimeException("Unable to create voltroot \"" + voltRootPath + "\" for test"); } } if (!voltRootFile.isDirectory()) { throw new RuntimeException("voltroot \"" + voltRootPath + "\" for test exists but is not a directory"); } if (!voltRootFile.canRead()) { throw new RuntimeException("voltroot \"" + voltRootPath + "\" for test exists but is not readable"); } if (!voltRootFile.canWrite()) { throw new RuntimeException("voltroot \"" + voltRootPath + "\" for test exists but is not writable"); } if (!voltRootFile.canExecute()) { throw new RuntimeException("voltroot \"" + voltRootPath + "\" for test exists but is not writable"); } return compile(compiler, jarPath, sitesPerHost, hostCount, replication, leaderAddress, voltRootPath, false, null, "none"); } public boolean compile( final String jarPath, final int sitesPerHost, final int hostCount, final int replication, final String leaderAddress, final String voltRoot, final boolean ppdEnabled, final String ppdPath, final String ppdPrefix) { VoltCompiler compiler = new VoltCompiler(); return compile(compiler, jarPath, sitesPerHost, hostCount, replication, leaderAddress, voltRoot, ppdEnabled, ppdPath, ppdPrefix); } public boolean compile(final VoltCompiler compiler, final String jarPath, final int sitesPerHost, final int hostCount, final int replication, final String leaderAddress, final String voltRoot, final boolean ppdEnabled, final String ppdPath, final String ppdPrefix) { assert(jarPath != null); assert(sitesPerHost >= 1); assert(hostCount >= 1); assert(leaderAddress != null); // this stuff could all be converted to org.voltdb.compiler.projectfile.* // jaxb objects and (WE ARE!) marshaled to XML. Just needs some elbow grease. DocumentBuilderFactory docFactory; DocumentBuilder docBuilder; Document doc; try { docFactory = DocumentBuilderFactory.newInstance(); docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); } catch (final ParserConfigurationException e) { e.printStackTrace(); return false; } // <project> final Element project = doc.createElement("project"); doc.appendChild(project); // <security> final Element security = doc.createElement("security"); security.setAttribute("enabled", new Boolean(m_securityEnabled).toString()); project.appendChild(security); // <database> final Element database = doc.createElement("database"); database.setAttribute("name", "database"); project.appendChild(database); buildDatabaseElement(doc, database); // boilerplate to write this DOM object to file. StreamResult result; try { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); result = new StreamResult(new StringWriter()); final DOMSource domSource = new DOMSource(doc); transformer.transform(domSource, result); } catch (final TransformerConfigurationException e) { e.printStackTrace(); return false; } catch (final TransformerFactoryConfigurationError e) { e.printStackTrace(); return false; } catch (final TransformerException e) { e.printStackTrace(); return false; } String xml = result.getWriter().toString(); System.out.println(xml); final File projectFile = writeStringToTempFile(result.getWriter().toString()); final String projectPath = projectFile.getPath(); boolean success = compiler.compile(projectPath, jarPath, m_compilerDebugPrintStream, m_procInfoOverrides); m_pathToDeployment = writeDeploymentFile( hostCount, sitesPerHost, leaderAddress, replication, voltRoot, ppdEnabled, ppdPath, ppdPrefix); return success; } /** * After compile() has been called, a deployment file will be written. This method exposes its location so it can be * passed to org.voltdb.VoltDB on startup. * @return Returns the deployment file location. */ public String getPathToDeployment() { if (m_pathToDeployment == null) { System.err.println("ERROR: Call compile() before trying to get the deployment path."); return null; } else { return m_pathToDeployment; } } private void buildDatabaseElement(Document doc, final Element database) { // /project/database/groups final Element groups = doc.createElement("groups"); database.appendChild(groups); // groups/group if (m_groups.isEmpty()) { final Element group = doc.createElement("group"); group.setAttribute("name", "default"); group.setAttribute("sysproc", "true"); group.setAttribute("adhoc", "true"); groups.appendChild(group); } else { for (final GroupInfo info : m_groups) { final Element group = doc.createElement("group"); group.setAttribute("name", info.name); group.setAttribute("sysproc", info.sysproc ? "true" : "false"); group.setAttribute("adhoc", info.adhoc ? "true" : "false"); groups.appendChild(group); } } // /project/database/schemas final Element schemas = doc.createElement("schemas"); database.appendChild(schemas); // schemas/schema for (final String schemaPath : m_schemas) { final Element schema = doc.createElement("schema"); schema.setAttribute("path", schemaPath); schemas.appendChild(schema); } // /project/database/procedures final Element procedures = doc.createElement("procedures"); database.appendChild(procedures); // procedures/procedure for (final ProcedureInfo procedure : m_procedures) { if (procedure.cls == null) continue; assert(procedure.sql == null); final Element proc = doc.createElement("procedure"); proc.setAttribute("class", procedure.cls.getName()); // build up @groups. This attribute should be redesigned if (procedure.groups.length > 0) { final StringBuilder groupattr = new StringBuilder(); for (final String group : procedure.groups) { if (groupattr.length() > 0) groupattr.append(","); groupattr.append(group); } proc.setAttribute("groups", groupattr.toString()); } procedures.appendChild(proc); } // procedures/procedures (that are stmtprocedures) for (final ProcedureInfo procedure : m_procedures) { if (procedure.sql == null) continue; assert(procedure.cls == null); final Element proc = doc.createElement("procedure"); proc.setAttribute("class", procedure.name); if (procedure.partitionInfo != null); proc.setAttribute("partitioninfo", procedure.partitionInfo); // build up @groups. This attribute should be redesigned if (procedure.groups.length > 0) { final StringBuilder groupattr = new StringBuilder(); for (final String group : procedure.groups) { if (groupattr.length() > 0) groupattr.append(","); groupattr.append(group); } proc.setAttribute("groups", groupattr.toString()); } final Element sql = doc.createElement("sql"); if (procedure.joinOrder != null) { sql.setAttribute("joinorder", procedure.joinOrder); } proc.appendChild(sql); final Text sqltext = doc.createTextNode(procedure.sql); sql.appendChild(sqltext); procedures.appendChild(proc); } if (m_partitionInfos.size() > 0) { // /project/database/partitions final Element partitions = doc.createElement("partitions"); database.appendChild(partitions); // partitions/table for (final Entry<String, String> partitionInfo : m_partitionInfos.entrySet()) { final Element table = doc.createElement("partition"); table.setAttribute("table", partitionInfo.getKey()); table.setAttribute("column", partitionInfo.getValue()); partitions.appendChild(table); } } // /project/database/classdependencies final Element classdeps = doc.createElement("classdependencies"); database.appendChild(classdeps); // classdependency for (final Class<?> supplemental : m_supplementals) { final Element supp= doc.createElement("classdependency"); supp.setAttribute("class", supplemental.getName()); classdeps.appendChild(supp); } // project/database/exports if (m_elloader != null) { final Element exports = doc.createElement("exports"); database.appendChild(exports); final Element conn = doc.createElement("connector"); conn.setAttribute("class", m_elloader); conn.setAttribute("enabled", m_elenabled ? "true" : "false"); // turn list into stupid comma separated attribute list String groupsattr = ""; if (m_elAuthGroups != null) { for (String s : m_elAuthGroups) { if (groupsattr.isEmpty()) { groupsattr += s; } else { groupsattr += "," + s; } } conn.setAttribute("groups", groupsattr); } exports.appendChild(conn); if (m_exportTables.size() > 0) { final Element tables = doc.createElement("tables"); conn.appendChild(tables); for (ExportTableInfo info : m_exportTables) { final Element table = doc.createElement("table"); table.setAttribute("name", info.m_tablename); table.setAttribute("exportonly", info.m_export_only ? "true" : "false"); tables.appendChild(table); } } } } /** * Utility method to take a string and put it in a file. This is used by * this class to write the project file to a temp file, but it also used * by some other tests. * * @param content The content of the file to create. * @return A reference to the file created or null on failure. */ public static File writeStringToTempFile(final String content) { File tempFile; try { tempFile = File.createTempFile("myApp", ".tmp"); // tempFile.deleteOnExit(); final FileWriter writer = new FileWriter(tempFile); writer.write(content); writer.flush(); writer.close(); return tempFile; } catch (final IOException e) { e.printStackTrace(); return null; } } /** * Writes deployment.xml file to a temporary file. It is constructed from the passed parameters and the m_users * field. * @param hostCount Number of hosts. * @param sitesPerHost Sites per host. * @param leader Leader address. * @param kFactor Replication factor. * @return Returns the path the temporary file was written to. */ private String writeDeploymentFile( int hostCount, int sitesPerHost, String leader, int kFactor, String voltRoot, boolean ppdEnabled, String ppdPath, String ppdPrefix) { DocumentBuilderFactory docFactory; DocumentBuilder docBuilder; Document doc; try { docFactory = DocumentBuilderFactory.newInstance(); docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); } catch (final ParserConfigurationException e) { e.printStackTrace(); return null; } // <deployment> final Element deployment = doc.createElement("deployment"); doc.appendChild(deployment); // <cluster> final Element cluster = doc.createElement("cluster"); cluster.setAttribute("hostcount", new Integer(hostCount).toString()); cluster.setAttribute("sitesperhost", new Integer(sitesPerHost).toString()); cluster.setAttribute("leader", leader); cluster.setAttribute("kfactor", new Integer(kFactor).toString()); deployment.appendChild(cluster); // <paths> final Element paths = doc.createElement("paths"); final Element voltroot = doc.createElement("voltroot"); voltroot.setAttribute("path", voltRoot); paths.appendChild(voltroot); if (ppdPath != null) { final Element ppdPathElement = doc.createElement("partitiondetectionsnapshot"); ppdPathElement.setAttribute("path", ppdPath); paths.appendChild(ppdPathElement); } if (m_snapshotPath != null) { final Element snapshotPathElement = doc.createElement("snapshots"); snapshotPathElement.setAttribute("path", m_snapshotPath); paths.appendChild(snapshotPathElement); } deployment.appendChild(paths); if (m_snapshotPrefix != null) { final Element snapshot = doc.createElement("snapshot"); snapshot.setAttribute("frequency", m_snapshotFrequency); snapshot.setAttribute("prefix", m_snapshotPrefix); snapshot.setAttribute("retain", Integer.toString(m_snapshotRetain)); deployment.appendChild(snapshot); } // <cluster>/<partition-detection>/<snapshot> if (ppdEnabled) { final Element ppd = doc.createElement("partition-detection"); cluster.appendChild(ppd); ppd.setAttribute("enabled", "true"); final Element ss = doc.createElement("snapshot"); ss.setAttribute("prefix", ppdPrefix); ppd.appendChild(ss); } // <users> Element users = null; if (m_users.size() > 0) { users = doc.createElement("users"); deployment.appendChild(users); } // <user> for (final UserInfo info : m_users) { final Element user = doc.createElement("user"); user.setAttribute("name", info.name); user.setAttribute("password", info.password); // build up user/@groups. This attribute must be redesigned if (info.groups.length > 0) { final StringBuilder groups = new StringBuilder(); for (final String group : info.groups) { if (groups.length() > 0) groups.append(","); groups.append(group); } user.setAttribute("groups", groups.toString()); } users.appendChild(user); } // <httpd> final Element httpd = doc.createElement("httpd"); httpd.setAttribute("port", new Integer(m_httpdPortNo).toString()); final Element jsonapi = doc.createElement("jsonapi"); jsonapi.setAttribute("enabled", new Boolean(m_jsonApiEnabled).toString()); httpd.appendChild(jsonapi); deployment.appendChild(httpd); // boilerplate to write this DOM object to file. StreamResult result; try { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); result = new StreamResult(new StringWriter()); final DOMSource domSource = new DOMSource(doc); transformer.transform(domSource, result); } catch (final TransformerConfigurationException e) { e.printStackTrace(); return null; } catch (final TransformerFactoryConfigurationError e) { e.printStackTrace(); return null; } catch (final TransformerException e) { e.printStackTrace(); return null; } String xml = result.getWriter().toString(); System.out.println(xml); final File deploymentFile = writeStringToTempFile(result.getWriter().toString()); final String deploymentPath = deploymentFile.getPath(); return deploymentPath; } }
package org.rstudio.studio.client.workbench.views.source.editors.text; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Style.FontWeight; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.http.client.URL; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.*; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.command.KeyboardHelper; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.events.EnsureHeightHandler; import org.rstudio.core.client.events.EnsureVisibleHandler; import org.rstudio.core.client.events.HasEnsureHeightHandlers; import org.rstudio.core.client.events.HasEnsureVisibleHandlers; import org.rstudio.core.client.files.FileSystemContext; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsUtil; import org.rstudio.core.client.regex.Match; import org.rstudio.core.client.regex.Pattern; import org.rstudio.core.client.widget.*; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.ChangeFontSizeEvent; import org.rstudio.studio.client.application.events.ChangeFontSizeHandler; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.*; import org.rstudio.studio.client.common.debugging.BreakpointManager; import org.rstudio.studio.client.common.debugging.events.BreakpointsSavedEvent; import org.rstudio.studio.client.common.debugging.model.Breakpoint; import org.rstudio.studio.client.common.filetypes.DocumentMode; import org.rstudio.studio.client.common.filetypes.FileType; import org.rstudio.studio.client.common.filetypes.FileTypeCommands; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.SweaveFileType; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.common.r.roxygen.RoxygenHelper; import org.rstudio.studio.client.common.rnw.RnwWeave; import org.rstudio.studio.client.common.synctex.Synctex; import org.rstudio.studio.client.common.synctex.SynctexUtils; import org.rstudio.studio.client.common.synctex.model.SourceLocation; import org.rstudio.studio.client.htmlpreview.events.ShowHTMLPreviewEvent; import org.rstudio.studio.client.htmlpreview.model.HTMLPreviewParams; import org.rstudio.studio.client.notebook.CompileNotebookOptions; import org.rstudio.studio.client.notebook.CompileNotebookOptionsDialog; import org.rstudio.studio.client.notebook.CompileNotebookPrefs; import org.rstudio.studio.client.notebook.CompileNotebookResult; import org.rstudio.studio.client.rmarkdown.events.ConvertToShinyDocEvent; import org.rstudio.studio.client.rmarkdown.events.RmdOutputFormatChangedEvent; import org.rstudio.studio.client.rmarkdown.model.RMarkdownContext; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter; import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatterOutputOptions; import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat; import org.rstudio.studio.client.rmarkdown.model.RmdTemplateFormat; import org.rstudio.studio.client.rmarkdown.model.RmdYamlData; import org.rstudio.studio.client.rmarkdown.model.YamlFrontMatter; import org.rstudio.studio.client.rmarkdown.ui.RmdTemplateOptionsDialog; import org.rstudio.studio.client.rsconnect.events.RSConnectActionEvent; import org.rstudio.studio.client.rsconnect.events.RSConnectDeployInitiatedEvent; import org.rstudio.studio.client.rsconnect.model.RSConnectPublishSettings; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.shiny.events.ShinyApplicationStatusEvent; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.SessionInfo; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor; import org.rstudio.studio.client.workbench.snippets.SnippetHelper; import org.rstudio.studio.client.workbench.ui.FontSizeManager; import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition; import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection; import org.rstudio.studio.client.workbench.views.files.events.FileChangeEvent; import org.rstudio.studio.client.workbench.views.files.events.FileChangeHandler; import org.rstudio.studio.client.workbench.views.files.model.FileChange; import org.rstudio.studio.client.workbench.views.help.events.ShowHelpEvent; import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfEvent; import org.rstudio.studio.client.workbench.views.output.lint.LintManager; import org.rstudio.studio.client.workbench.views.presentation.events.SourceFileSaveCompletedEvent; import org.rstudio.studio.client.workbench.views.presentation.model.PresentationState; import org.rstudio.studio.client.workbench.views.source.SourceBuildHelper; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetCodeExecution; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay.AnchoredSelection; import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeList.ContainsFoldPredicate; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper.RmdSelectedTemplate; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceFold; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Mode.InsertChunkInfo; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range; import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionContext; import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionOperation; import org.rstudio.studio.client.workbench.views.source.editors.text.events.*; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupRequest; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.ChooseEncodingDialog; import org.rstudio.studio.client.workbench.views.source.events.CollabEditStartParams; import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent; import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler; import org.rstudio.studio.client.workbench.views.source.events.SourceFileSavedEvent; import org.rstudio.studio.client.workbench.views.source.events.SourceNavigationEvent; import org.rstudio.studio.client.workbench.views.source.model.*; import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsDiffEvent; import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsHistoryEvent; import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRevertFileEvent; import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsViewOnGitHubEvent; import org.rstudio.studio.client.workbench.views.vcs.common.model.GitHubViewRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; public class TextEditingTarget implements EditingTarget, EditingTargetCodeExecution.CodeExtractor { interface MyCommandBinder extends CommandBinder<Commands, TextEditingTarget> { } private static final String NOTEBOOK_TITLE = "notebook_title"; private static final String NOTEBOOK_AUTHOR = "notebook_author"; private static final String NOTEBOOK_TYPE = "notebook_type"; private static final MyCommandBinder commandBinder = GWT.create(MyCommandBinder.class); public interface Display extends TextDisplay, WarningBarDisplay, HasEnsureVisibleHandlers, HasEnsureHeightHandlers { HasValue<Boolean> getSourceOnSave(); void ensureVisible(); void showFindReplace(boolean defaultForward); void findNext(); void findPrevious(); void findSelectAll(); void findFromSelection(); void replaceAndFind(); StatusBar getStatusBar(); boolean isAttached(); void adaptToExtendedFileType(String extendedType); void onShinyApplicationStateChanged(String state); void debug_dumpContents(); void debug_importDump(); void setIsShinyFormat(boolean isPresentation); void setFormatOptions(TextFileType fileType, List<String> options, List<String> values, List<String> extensions, String selected); void setFormatOptionsVisible(boolean visible); HandlerRegistration addRmdFormatChangedHandler( RmdOutputFormatChangedEvent.Handler handler); void setPublishPath(String type, String publishPath); } private class SaveProgressIndicator implements ProgressIndicator { public SaveProgressIndicator(FileSystemItem file, TextFileType fileType, Command executeOnSuccess) { file_ = file; newFileType_ = fileType; executeOnSuccess_ = executeOnSuccess; } public void onProgress(String message) { } public void clearProgress() { } public void onCompleted() { // don't need to check again soon because we just saved // (without this and when file monitoring is active we'd // end up immediately checking for external edits) externalEditCheckInterval_.reset(250); if (newFileType_ != null) fileType_ = newFileType_; if (file_ != null) { ignoreDeletes_ = false; forceSaveCommandActive_ = false; commands_.reopenSourceDocWithEncoding().setEnabled(true); name_.setValue(file_.getName(), true); // Make sure tooltip gets updated, even if name hasn't changed name_.fireChangeEvent(); // If we were dirty prior to saving, clean up the debug state so // we don't continue highlighting after saving. (There are cases // in which we want to restore highlighting after the dirty state // is marked clean--i.e. when unwinding the undo stack.) if (dirtyState_.getValue()) endDebugHighlighting(); dirtyState_.markClean(); } if (newFileType_ != null) { // Make sure the icon gets updated, even if name hasn't changed name_.fireChangeEvent(); updateStatusBarLanguage(); view_.adaptToFileType(newFileType_); events_.fireEvent(new FileTypeChangedEvent()); if (!fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { view_.getSourceOnSave().setValue(false, true); } } if (executeOnSuccess_ != null) executeOnSuccess_.execute(); } public void onError(final String message) { // in case the error occured saving a document that wasn't // in the foreground view_.ensureVisible(); // command to show the error final Command showErrorCommand = new Command() { @Override public void execute() { globalDisplay_.showErrorMessage("Error Saving File", message); } }; // check whether the file exists and isn't writeable if (file_ != null) { server_.isReadOnlyFile(file_.getPath(), new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean isReadOnly) { if (isReadOnly) { String message = "This source file is read-only " + "so changes cannot be saved"; view_.showWarningBar(message); String saveAsPath = file_.getParentPath().completePath( file_.getStem() + "-copy" + file_.getExtension()); saveNewFile( saveAsPath, null, CommandUtil.join(postSaveCommand(), new Command() { @Override public void execute() { view_.hideWarningBar(); } })); } else { showErrorCommand.execute(); } } @Override public void onError(ServerError error) { Debug.logError(error); showErrorCommand.execute(); } }); } else { showErrorCommand.execute(); } } private final FileSystemItem file_; private final TextFileType newFileType_; private final Command executeOnSuccess_; } @Inject public TextEditingTarget(Commands commands, SourceServerOperations server, EventBus events, GlobalDisplay globalDisplay, FileDialogs fileDialogs, FileTypeRegistry fileTypeRegistry, FileTypeCommands fileTypeCommands, ConsoleDispatcher consoleDispatcher, WorkbenchContext workbenchContext, Session session, Synctex synctex, FontSizeManager fontSizeManager, DocDisplay docDisplay, UIPrefs prefs, BreakpointManager breakpointManager, SourceBuildHelper sourceBuildHelper) { commands_ = commands; server_ = server; events_ = events; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileTypeRegistry_ = fileTypeRegistry; fileTypeCommands_ = fileTypeCommands; consoleDispatcher_ = consoleDispatcher; workbenchContext_ = workbenchContext; session_ = session; synctex_ = synctex; fontSizeManager_ = fontSizeManager; breakpointManager_ = breakpointManager; sourceBuildHelper_ = sourceBuildHelper; docDisplay_ = docDisplay; dirtyState_ = new DirtyState(docDisplay_, false); lintManager_ = new LintManager(this, cppCompletionContext_); prefs_ = prefs; codeExecution_ = new EditingTargetCodeExecution(docDisplay_, this); compilePdfHelper_ = new TextEditingTargetCompilePdfHelper(docDisplay_); rmarkdownHelper_ = new TextEditingTargetRMarkdownHelper(); cppHelper_ = new TextEditingTargetCppHelper(cppCompletionContext_, docDisplay_); presentationHelper_ = new TextEditingTargetPresentationHelper( docDisplay_); reformatHelper_ = new TextEditingTargetReformatHelper(docDisplay_); snippets_ = new SnippetHelper((AceEditor) docDisplay_); docDisplay_.setRnwCompletionContext(compilePdfHelper_); docDisplay_.setCppCompletionContext(cppCompletionContext_); docDisplay_.setRCompletionContext(rContext_); scopeHelper_ = new TextEditingTargetScopeHelper(docDisplay_); addRecordNavigationPositionHandler(releaseOnDismiss_, docDisplay_, events_, this); docDisplay_.addKeyDownHandler(new KeyDownHandler() { @SuppressWarnings("deprecation") public void onKeyDown(KeyDownEvent event) { NativeEvent ne = event.getNativeEvent(); int mod = KeyboardShortcut.getModifierValue(ne); if ((mod == KeyboardShortcut.META || (mod == KeyboardShortcut.CTRL && !BrowseCap.hasMetaKey())) && ne.getKeyCode() == 'F') { event.preventDefault(); event.stopPropagation(); commands_.findReplace().execute(); } else if (BrowseCap.hasMetaKey() && (mod == KeyboardShortcut.META) && (ne.getKeyCode() == 'E')) { event.preventDefault(); event.stopPropagation(); commands_.findFromSelection().execute(); } else if (mod == KeyboardShortcut.ALT && KeyboardHelper.isHyphenKeycode(ne.getKeyCode())) { event.preventDefault(); event.stopPropagation(); if (Character.isSpace(docDisplay_.getCharacterBeforeCursor()) || (!docDisplay_.hasSelection() && docDisplay_.getCursorPosition().getColumn() == 0)) docDisplay_.insertCode("<- ", false); else docDisplay_.insertCode(" <- ", false); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_UP && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToPreviousFunction(); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_DOWN && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToNextFunction(); } else if ((ne.getKeyCode() == KeyCodes.KEY_ESCAPE) && !prefs_.useVimMode().getValue()) { event.preventDefault(); event.stopPropagation(); // Don't send an interrupt if a popup is visible if (docDisplay_.isPopupVisible()) return; if (commands_.interruptR().isEnabled()) commands_.interruptR().execute(); } else if (ne.getKeyCode() == KeyCodes.KEY_M && ( (BrowseCap.hasMetaKey() && mod == (KeyboardShortcut.META + KeyboardShortcut.SHIFT)) || (!BrowseCap.hasMetaKey() && mod == (KeyboardShortcut.CTRL + KeyboardShortcut.SHIFT)))) { event.preventDefault(); event.stopPropagation(); if (Character.isSpace(docDisplay_.getCharacterBeforeCursor()) || (!docDisplay_.hasSelection() && docDisplay_.getCursorPosition().getColumn() == 0)) docDisplay_.insertCode("%>% ", false); else docDisplay_.insertCode(" %>% ", false); } else if ( prefs_.continueCommentsOnNewline().getValue() && !docDisplay_.isPopupVisible() && ne.getKeyCode() == KeyCodes.KEY_ENTER && mod == 0 && (fileType_.isC() || isCursorInRMode() || isCursorInTexMode())) { String line = docDisplay_.getCurrentLineUpToCursor(); Pattern pattern = null; if (isCursorInRMode()) pattern = Pattern.create("^(\\s* else if (isCursorInTexMode()) pattern = Pattern.create("^(\\s*%+'?\\s*)"); else if (fileType_.isC()) { // bail on attributes if (!line.matches("^\\s* pattern = Pattern.create("^(\\s* } if (pattern != null) { Match match = pattern.match(line, 0); if (match != null) { event.preventDefault(); event.stopPropagation(); docDisplay_.insertCode("\n" + match.getGroup(1)); docDisplay_.ensureCursorVisible(); } } } else if ( prefs_.continueCommentsOnNewline().getValue() && !docDisplay_.isPopupVisible() && ne.getKeyCode() == KeyCodes.KEY_ENTER && mod == KeyboardShortcut.SHIFT) { event.preventDefault(); event.stopPropagation(); String indent = docDisplay_.getNextLineIndent(); docDisplay_.insertCode("\n" + indent); } } }); docDisplay_.addCommandClickHandler(new CommandClickEvent.Handler() { @Override public void onCommandClick(CommandClickEvent event) { if (fileType_.canCompilePDF() && commands_.synctexSearch().isEnabled()) { // warn firefox users that this doesn't really work in Firefox if (BrowseCap.isFirefox() && !BrowseCap.isMacintosh()) SynctexUtils.maybeShowFirefoxWarning("PDF preview"); doSynctexSearch(true); } else { docDisplay_.goToFunctionDefinition(); } } }); docDisplay_.addFindRequestedHandler(new FindRequestedEvent.Handler() { @Override public void onFindRequested(FindRequestedEvent event) { view_.showFindReplace(event.getDefaultForward()); } }); events_.addHandler( ShinyApplicationStatusEvent.TYPE, new ShinyApplicationStatusEvent.Handler() { @Override public void onShinyApplicationStatus( ShinyApplicationStatusEvent event) { // If the document appears to be inside the directory // associated with the event, update the view to match the // new state. if (getPath() != null && getPath().startsWith(event.getParams().getPath())) { view_.onShinyApplicationStateChanged( event.getParams().getState()); } } }); events_.addHandler( BreakpointsSavedEvent.TYPE, new BreakpointsSavedEvent.Handler() { @Override public void onBreakpointsSaved(BreakpointsSavedEvent event) { // if this document isn't ready for breakpoints, stop now if (docUpdateSentinel_ == null) { return; } for (Breakpoint breakpoint: event.breakpoints()) { // discard the breakpoint if it's not related to the file this // editor instance is concerned with if (!breakpoint.isInFile(getPath())) { continue; } // if the breakpoint was saved successfully, enable it on the // editor surface; otherwise, just remove it. if (event.successful()) { docDisplay_.addOrUpdateBreakpoint(breakpoint); } else { // Show a warning for breakpoints that didn't get set (unless // the reason the breakpoint wasn't set was that it's being // removed) if (breakpoint.getState() != Breakpoint.STATE_REMOVING) { view_.showWarningBar("Breakpoints can only be set inside "+ "the body of a function. "); } docDisplay_.removeBreakpoint(breakpoint); } } updateBreakpointWarningBar(); } }); events_.addHandler(ConvertToShinyDocEvent.TYPE, new ConvertToShinyDocEvent.Handler() { @Override public void onConvertToShinyDoc(ConvertToShinyDocEvent event) { if (getPath() != null && getPath().equals(event.getPath())) { String yaml = getRmdFrontMatter(); if (yaml == null) return; String newYaml = rmarkdownHelper_.convertYamlToShinyDoc(yaml); applyRmdFrontMatter(newYaml); renderRmd(); } } }); events_.addHandler(RSConnectDeployInitiatedEvent.TYPE, new RSConnectDeployInitiatedEvent.Handler() { @Override public void onRSConnectDeployInitiated( RSConnectDeployInitiatedEvent event) { // no need to process this event if this target doesn't have a // path, or if the event's contents don't include additional // files. if (getPath() == null) return; // see if the event corresponds to a deployment of this file if (!getPath().equals(event.getSource().getSourceFile())) return; RSConnectPublishSettings settings = event.getSettings(); if (settings == null) return; // ignore deployments of static content generated from this // file if (settings.getAsStatic()) return; if (settings.getAdditionalFiles() != null && settings.getAdditionalFiles().size() > 0) { addAdditionalResourceFiles(settings.getAdditionalFiles()); } } }); } @Override public void recordCurrentNavigationPosition() { docDisplay_.recordCurrentNavigationPosition(); } @Override public void navigateToPosition(SourcePosition position, boolean recordCurrent) { docDisplay_.navigateToPosition(position, recordCurrent); } @Override public void navigateToPosition(SourcePosition position, boolean recordCurrent, boolean highlightLine) { docDisplay_.navigateToPosition(position, recordCurrent, highlightLine); } @Override public void restorePosition(SourcePosition position) { docDisplay_.restorePosition(position); } @Override public boolean isAtSourceRow(SourcePosition position) { return docDisplay_.isAtSourceRow(position); } @Override public void setCursorPosition(Position position) { docDisplay_.setCursorPosition(position); } @Override public void ensureCursorVisible() { docDisplay_.ensureCursorVisible(); } @Override public void forceLineHighlighting() { docDisplay_.setHighlightSelectedLine(true); } @Override public void highlightDebugLocation( SourcePosition startPos, SourcePosition endPos, boolean executing) { debugStartPos_ = startPos; debugEndPos_ = endPos; docDisplay_.highlightDebugLocation(startPos, endPos, executing); updateDebugWarningBar(); } @Override public void endDebugHighlighting() { docDisplay_.endDebugHighlighting(); debugStartPos_ = null; debugEndPos_ = null; updateDebugWarningBar(); } @Override public void beginCollabSession(CollabEditStartParams params) { if (commandHandlerReg_ != null) { // if we're the active doc, begin the collab session right away beginQueuedCollabSession(params); } else { // otherwise, save the params for when the doc is activated queuedCollabParams_ = params; } } @Override public void endCollabSession() { if (docDisplay_.hasActiveCollabSession()) docDisplay_.endCollabSession(); // a collaboration session may have come and gone while the tab was not // focused queuedCollabParams_ = null; } private void beginQueuedCollabSession(final CollabEditStartParams params) { // do nothing if we don't have an active path if (docUpdateSentinel_ == null || docUpdateSentinel_.getPath() == null) return; // if we have local changes, and we're not the master copy, we need to // prompt the user if (dirtyState().getValue() && !params.isMaster()) { String filename = FilePathUtils.friendlyFileName(docUpdateSentinel_.getPath()); globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_QUESTION, "Join Edit Session", "You have unsaved changes to " + filename + ", but another " + "user is editing the file. Do you want to discard your " + "changes and join their edit session, or make your own copy " + "of the file to work on?", false, // includeCancel new Operation() { @Override public void execute() { docDisplay_.beginCollabSession(params, dirtyState_); } }, new Operation() { @Override public void execute() { events_.fireEvent(new NewWorkingCopyEvent(fileType_, docUpdateSentinel_.getPath(), docUpdateSentinel_.getContents())); } }, null, // cancelOperation, "Join Edit Session", "Work on a Copy", true // yesIsDefault ); } else { // just begin the session right away docDisplay_.beginCollabSession(params, dirtyState_); } } private void updateDebugWarningBar() { // show the warning bar if we're debugging and the document is dirty if (debugStartPos_ != null && dirtyState().getValue() && !isDebugWarningVisible_) { view_.showWarningBar("Debug lines may not match because the file contains unsaved changes."); isDebugWarningVisible_ = true; } // hide the warning bar if the dirty state or debug state change else if (isDebugWarningVisible_ && (debugStartPos_ == null || dirtyState().getValue() == false)) { view_.hideWarningBar(); // if we're still debugging, start highlighting the line again if (debugStartPos_ != null) { docDisplay_.highlightDebugLocation( debugStartPos_, debugEndPos_, false); } isDebugWarningVisible_ = false; } } private void jumpToPreviousFunction() { Scope jumpTo = scopeHelper_.getPreviousFunction( docDisplay_.getCursorPosition()); if (jumpTo != null) docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true); } private void jumpToNextFunction() { Scope jumpTo = scopeHelper_.getNextFunction( docDisplay_.getCursorPosition()); if (jumpTo != null) docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true); } public void initialize(SourceDocument document, FileSystemContext fileContext, FileType type, Provider<String> defaultNameProvider) { id_ = document.getId(); fileContext_ = fileContext; fileType_ = (TextFileType) type; extendedType_ = document.getExtendedType(); extendedType_ = rmarkdownHelper_.detectExtendedType(document.getContents(), extendedType_, fileType_); view_ = new TextEditingTargetWidget(commands_, prefs_, fileTypeRegistry_, docDisplay_, fileType_, extendedType_, events_, session_); docUpdateSentinel_ = new DocUpdateSentinel( server_, docDisplay_, document, globalDisplay_.getProgressIndicator("Save File"), dirtyState_, events_); roxygenHelper_ = new RoxygenHelper(docDisplay_, view_); // ensure that Makefile and Makevars always use tabs name_.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { if ("Makefile".equals(event.getValue()) || "Makevars".equals(event.getValue()) || "Makevars.win".equals(event.getValue())) { docDisplay_.setUseSoftTabs(false); } } }); name_.setValue(getNameFromDocument(document, defaultNameProvider), true); docDisplay_.setCode(document.getContents(), false); final ArrayList<Fold> folds = Fold.decode(document.getFoldSpec()); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { for (Fold fold : folds) docDisplay_.addFold(fold.getRange()); } }); registerPrefs(releaseOnDismiss_, prefs_, docDisplay_, document); // Initialize sourceOnSave, and keep it in sync view_.getSourceOnSave().setValue(document.sourceOnSave(), false); view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { docUpdateSentinel_.setSourceOnSave( event.getValue(), globalDisplay_.getProgressIndicator("Error Saving Setting")); } }); if (document.isDirty()) dirtyState_.markDirty(false); else dirtyState_.markClean(); docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>() { public void onValueChange(ValueChangeEvent<Void> event) { dirtyState_.markDirty(true); docDisplay_.clearSelectionHistory(); } }); docDisplay_.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { if (queuedCollabParams_ != null) { // join an in-progress collab session if we aren't already part // of one if (docDisplay_ != null && !docDisplay_.hasActiveCollabSession()) { beginQueuedCollabSession(queuedCollabParams_); } // clear queued params so we don't try to join again queuedCollabParams_ = null; } else { // check to see if the file's been saved externally Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { public boolean execute() { if (view_.isAttached()) checkForExternalEdit(); return false; } }, 500); } } }); if (fileType_.isR()) { docDisplay_.addBreakpointSetHandler(new BreakpointSetEvent.Handler() { @Override public void onBreakpointSet(BreakpointSetEvent event) { if (event.isSet()) { Breakpoint breakpoint = null; // don't try to set breakpoints in unsaved code if (isNewDoc()) { view_.showWarningBar("Breakpoints cannot be set until " + "the file is saved."); return; } // don't try to set breakpoints if the R version is too old if (!session_.getSessionInfo().getHaveSrcrefAttribute()) { view_.showWarningBar("Editor breakpoints require R 2.14 " + "or newer."); return; } Position breakpointPosition = Position.create(event.getLineNumber() - 1, 1); // if we're not in function scope, or this is a Shiny file, // set a top-level (aka. Shiny-deferred) breakpoint ScopeFunction innerFunction = null; if (!extendedType_.equals("shiny")) innerFunction = docDisplay_.getFunctionAtPosition( breakpointPosition, false); if (innerFunction == null || !innerFunction.isFunction() || StringUtil.isNullOrEmpty(innerFunction.getFunctionName())) { breakpoint = breakpointManager_.setTopLevelBreakpoint( getPath(), event.getLineNumber()); } // the scope tree will find nested functions, but in R these // are addressable only as substeps of the parent function. // keep walking up the scope tree until we've reached the top // level function. else { while (innerFunction.getParentScope() != null && innerFunction.getParentScope().isFunction()) { innerFunction = (ScopeFunction) innerFunction.getParentScope(); } String functionName = innerFunction.getFunctionName(); breakpoint = breakpointManager_.setBreakpoint( getPath(), functionName, event.getLineNumber(), dirtyState().getValue() == false); } docDisplay_.addOrUpdateBreakpoint(breakpoint); } else { breakpointManager_.removeBreakpoint(event.getBreakpointId()); } updateBreakpointWarningBar(); } }); docDisplay_.addBreakpointMoveHandler(new BreakpointMoveEvent.Handler() { @Override public void onBreakpointMove(BreakpointMoveEvent event) { breakpointManager_.moveBreakpoint(event.getBreakpointId()); } }); } // validate required components (e.g. Tex, knitr, C++ etc.) checkCompilePdfDependencies(); rmarkdownHelper_.verifyPrerequisites(view_, fileType_); syncFontSize(releaseOnDismiss_, events_, view_, fontSizeManager_); final String rTypeId = FileTypeRegistry.R.getTypeId(); releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler( new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> evt) { if (fileType_.getTypeId().equals(rTypeId)) view_.adaptToFileType(fileType_); } } )); releaseOnDismiss_.add(events_.addHandler(FileChangeEvent.TYPE, new FileChangeHandler() { @Override public void onFileChange(FileChangeEvent event) { // screen out adds and events that aren't for our path FileChange fileChange = event.getFileChange(); if (fileChange.getType() == FileChange.ADD) return; else if (!fileChange.getFile().getPath().equals(getPath())) return; // always check for changes if this is the active editor if (commandHandlerReg_ != null) { checkForExternalEdit(); } // also check for changes on modifications if we are not dirty // note that we don't check for changes on removed files because // this will show a confirmation dialog else if (event.getFileChange().getType() == FileChange.MODIFIED && dirtyState().getValue() == false) { checkForExternalEdit(); } } })); spelling_ = new TextEditingTargetSpelling(docDisplay_, docUpdateSentinel_); // show/hide the debug toolbar when the dirty state changes. (note: // this doesn't yet handle the case where the user saves the document, // in which case we should still show some sort of warning.) dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> evt) { updateDebugWarningBar(); } } ); // find all of the debug breakpoints set in this document and replay them // onto the edit surface ArrayList<Breakpoint> breakpoints = breakpointManager_.getBreakpointsInFile(getPath()); for (Breakpoint breakpoint: breakpoints) { docDisplay_.addOrUpdateBreakpoint(breakpoint); } // for R Markdown docs, populate the popup menu with a list of available // formats if (extendedType_.equals("rmarkdown")) updateRmdFormatList(); view_.addRmdFormatChangedHandler(new RmdOutputFormatChangedEvent.Handler() { @Override public void onRmdOutputFormatChanged(RmdOutputFormatChangedEvent event) { setRmdFormat(event.getFormat()); } }); syncPublishPath(document.getPath()); initStatusBar(); } private void updateBreakpointWarningBar() { // check to see if there are any inactive breakpoints in this file boolean hasInactiveBreakpoints = false; boolean hasDebugPendingBreakpoints = false; boolean hasPackagePendingBreakpoints = false; String pendingPackageName = ""; ArrayList<Breakpoint> breakpoints = breakpointManager_.getBreakpointsInFile(getPath()); for (Breakpoint breakpoint: breakpoints) { if (breakpoint.getState() == Breakpoint.STATE_INACTIVE) { if (breakpoint.isPendingDebugCompletion()) { hasDebugPendingBreakpoints = true; } else if (breakpoint.isPackageBreakpoint()) { hasPackagePendingBreakpoints = true; pendingPackageName = breakpoint.getPackageName(); } else { hasInactiveBreakpoints = true; } break; } } boolean showWarning = hasDebugPendingBreakpoints || hasInactiveBreakpoints || hasPackagePendingBreakpoints; if (showWarning && !isBreakpointWarningVisible_) { String message = ""; if (hasDebugPendingBreakpoints) { message = "Breakpoints will be activated when the file or " + "function is finished executing."; } else if (isPackageFile()) { message = "Breakpoints will be activated when the package is " + "built and reloaded."; } else if (hasPackagePendingBreakpoints) { message = "Breakpoints will be activated when an updated version " + "of the " + pendingPackageName + " package is loaded"; } else { message = "Breakpoints will be activated when this file is " + "sourced."; } view_.showWarningBar(message); isBreakpointWarningVisible_ = true; } else if (!showWarning && isBreakpointWarningVisible_) { hideBreakpointWarningBar(); } } private void hideBreakpointWarningBar() { if (isBreakpointWarningVisible_) { view_.hideWarningBar(); isBreakpointWarningVisible_ = false; } } private boolean isPackageFile() { // not a package file if we're not in package development mode String type = session_.getSessionInfo().getBuildToolsType(); if (!type.equals(SessionInfo.BUILD_TOOLS_PACKAGE)) { return false; } // get the directory associated with the project and see if the file is // inside that directory FileSystemItem projectDir = session_.getSessionInfo() .getActiveProjectDir(); return getPath().startsWith(projectDir.getPath() + "/R"); } private boolean isPackageDocumentationFile() { if (getPath() == null) { return false; } String type = session_.getSessionInfo().getBuildToolsType(); if (!type.equals(SessionInfo.BUILD_TOOLS_PACKAGE)) { return false; } FileSystemItem srcFile = FileSystemItem.createFile(getPath()); FileSystemItem projectDir = session_.getSessionInfo() .getActiveProjectDir(); if (srcFile.getPath().startsWith(projectDir.getPath() + "/vignettes")) return true; else if (srcFile.getParentPathString().equals(projectDir.getPath()) && srcFile.getExtension().toLowerCase().equals(".md")) return true; else return false; } private void checkCompilePdfDependencies() { compilePdfHelper_.checkCompilers(view_, fileType_); } private void initStatusBar() { statusBar_ = view_.getStatusBar(); docDisplay_.addCursorChangedHandler(new CursorChangedHandler() { public void onCursorChanged(CursorChangedEvent event) { updateStatusBarPosition(); } }); updateStatusBarPosition(); updateStatusBarLanguage(); // build file type menu dynamically (so it can change according // to whether e.g. knitr is installed) statusBar_.getLanguage().addMouseDownHandler(new MouseDownHandler() { @Override public void onMouseDown(MouseDownEvent event) { // build menu with all file types - also track whether we need // to add the current type (may be the case for types which we // support but don't want to expose on the menu -- e.g. Rmd // files when knitr isn't installed) boolean addCurrentType = true; final StatusBarPopupMenu menu = new StatusBarPopupMenu(); TextFileType[] fileTypes = fileTypeCommands_.statusBarFileTypes(); for (TextFileType type : fileTypes) { menu.addItem(createMenuItemForType(type)); if (addCurrentType && type.equals(fileType_)) addCurrentType = false; } // add the current type if isn't on the menu if (addCurrentType) menu.addItem(createMenuItemForType(fileType_)); // show the menu menu.showRelativeToUpward((UIObject) statusBar_.getLanguage()); } }); statusBar_.getScope().addMouseDownHandler(new MouseDownHandler() { public void onMouseDown(MouseDownEvent event) { // Unlike the other status bar elements, the function outliner // needs its menu built on demand JsArray<Scope> tree = docDisplay_.getScopeTree(); final StatusBarPopupMenu menu = new StatusBarPopupMenu(); MenuItem defaultItem = null; if (fileType_.isRpres()) { String path = docUpdateSentinel_.getPath(); if (path != null) { presentationHelper_.buildSlideMenu( docUpdateSentinel_.getPath(), dirtyState_.getValue(), TextEditingTarget.this, new CommandWithArg<StatusBarPopupRequest>() { @Override public void execute(StatusBarPopupRequest request) { showStatusBarPopupMenu(request); } }); } } else { defaultItem = addFunctionsToMenu( menu, tree, "", docDisplay_.getCurrentScope(), true); showStatusBarPopupMenu(new StatusBarPopupRequest(menu, defaultItem)); } } }); } private void showStatusBarPopupMenu(StatusBarPopupRequest popupRequest) { final StatusBarPopupMenu menu = popupRequest.getMenu(); MenuItem defaultItem = popupRequest.getDefaultMenuItem(); if (defaultItem != null) { menu.selectItem(defaultItem); Scheduler.get().scheduleFinally(new RepeatingCommand() { public boolean execute() { menu.ensureSelectedIsVisible(); return false; } }); } menu.showRelativeToUpward((UIObject) statusBar_.getScope()); } private MenuItem createMenuItemForType(final TextFileType type) { SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder(); labelBuilder.appendEscaped(type.getLabel()); MenuItem menuItem = new MenuItem( labelBuilder.toSafeHtml(), new Command() { public void execute() { docUpdateSentinel_.changeFileType( type.getTypeId(), new SaveProgressIndicator(null, type, null)); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { focus(); } }); } }); return menuItem; } private void addScopeStyle(MenuItem item, Scope scope) { if (scope.isSection()) item.getElement().getStyle().setFontWeight(FontWeight.BOLD); } private MenuItem addFunctionsToMenu(StatusBarPopupMenu menu, final JsArray<Scope> funcs, String indent, Scope defaultFunction, boolean includeNoFunctionsMessage) { MenuItem defaultMenuItem = null; if (funcs.length() == 0 && includeNoFunctionsMessage) { String type = fileType_.canExecuteChunks() ? "chunks" : "functions"; MenuItem noFunctions = new MenuItem("(No " + type + " defined)", false, (Command) null); noFunctions.setEnabled(false); noFunctions.getElement().addClassName("disabled"); menu.addItem(noFunctions); } for (int i = 0; i < funcs.length(); i++) { final Scope func = funcs.get(i); String childIndent = indent; if (!StringUtil.isNullOrEmpty(func.getLabel())) { SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder(); labelBuilder.appendHtmlConstant(indent); labelBuilder.appendEscaped(func.getLabel()); final MenuItem menuItem = new MenuItem( labelBuilder.toSafeHtml(), new Command() { public void execute() { docDisplay_.navigateToPosition(toSourcePosition(func), true); } }); addScopeStyle(menuItem, func); menu.addItem(menuItem); childIndent = indent + "&nbsp;&nbsp;"; if (defaultFunction != null && defaultMenuItem == null && func.getLabel().equals(defaultFunction.getLabel()) && func.getPreamble().getRow() == defaultFunction.getPreamble().getRow() && func.getPreamble().getColumn() == defaultFunction.getPreamble().getColumn()) { defaultMenuItem = menuItem; } } MenuItem childDefaultMenuItem = addFunctionsToMenu( menu, func.getChildren(), childIndent, defaultMenuItem == null ? defaultFunction : null, false); if (childDefaultMenuItem != null) defaultMenuItem = childDefaultMenuItem; } return defaultMenuItem; } private void updateStatusBarLanguage() { statusBar_.getLanguage().setValue(fileType_.getLabel()); boolean canShowScope = fileType_.canShowScopeTree(); statusBar_.setScopeVisible(canShowScope); if (canShowScope) updateCurrentScope(); } private void updateStatusBarPosition() { Position pos = docDisplay_.getCursorPosition(); statusBar_.getPosition().setValue((pos.getRow() + 1) + ":" + (pos.getColumn() + 1)); if (fileType_.canShowScopeTree()) updateCurrentScope(); } private void updateCurrentScope() { Scheduler.get().scheduleDeferred( new ScheduledCommand() { public void execute() { // special handing for presentations since we extract // the slide structure in a different manner than // the editor scope trees if (fileType_.isRpres()) { statusBar_.getScope().setValue( presentationHelper_.getCurrentSlide()); statusBar_.setScopeType(StatusBar.SCOPE_SLIDE); } else { Scope scope = docDisplay_.getCurrentScope(); String label = scope != null ? scope.getLabel() : null; statusBar_.getScope().setValue(label); if (scope != null) { boolean useChunk = scope.isChunk() || (fileType_.isRnw() && scope.isTopLevel()); if (useChunk) statusBar_.setScopeType(StatusBar.SCOPE_CHUNK); else if (scope.isNamespace()) statusBar_.setScopeType(StatusBar.SCOPE_NAMESPACE); else if (scope.isClass()) statusBar_.setScopeType(StatusBar.SCOPE_CLASS); else if (scope.isSection()) statusBar_.setScopeType(StatusBar.SCOPE_SECTION); else if (scope.isTopLevel()) statusBar_.setScopeType(StatusBar.SCOPE_TOP_LEVEL); else if (scope.isFunction()) statusBar_.setScopeType(StatusBar.SCOPE_FUNCTION); else if (scope.isLambda()) statusBar_.setScopeType(StatusBar.SCOPE_LAMBDA); else if (scope.isAnon()) statusBar_.setScopeType(StatusBar.SCOPE_ANON); } } } }); } private String getNameFromDocument(SourceDocument document, Provider<String> defaultNameProvider) { if (document.getPath() != null) return FileSystemItem.getNameFromPath(document.getPath()); String name = document.getProperties().getString("tempName"); if (!StringUtil.isNullOrEmpty(name)) return name; String defaultName = defaultNameProvider.get(); docUpdateSentinel_.setProperty("tempName", defaultName, null); return defaultName; } public long getFileSizeLimit() { return 5 * 1024 * 1024; } public long getLargeFileSize() { return 2 * 1024 * 1024; } public void insertCode(String source, boolean blockMode) { docDisplay_.insertCode(source, blockMode); } public HashSet<AppCommand> getSupportedCommands() { return fileType_.getSupportedCommands(commands_); } @Override public boolean canCompilePdf() { return fileType_.canCompilePDF(); } @Override public void verifyCppPrerequisites() { // NOTE: will be a no-op for non-c/c++ file types cppHelper_.checkBuildCppDependencies(this, view_, fileType_); } public void focus() { docDisplay_.focus(); } public String getSelectedText() { if (docDisplay_.hasSelection()) return docDisplay_.getSelectionValue(); else return ""; } public HandlerRegistration addEnsureVisibleHandler(EnsureVisibleHandler handler) { return view_.addEnsureVisibleHandler(handler); } public HandlerRegistration addEnsureHeightHandler(EnsureHeightHandler handler) { return view_.addEnsureHeightHandler(handler); } public HandlerRegistration addCloseHandler(CloseHandler<java.lang.Void> handler) { return handlers_.addHandler(CloseEvent.getType(), handler); } public void fireEvent(GwtEvent<?> event) { handlers_.fireEvent(event); } public void onActivate() { // IMPORTANT NOTE: most of this logic is duplicated in // CodeBrowserEditingTarget (no straightforward way to create a // re-usable implementation) so changes here need to be synced // If we're already hooked up for some reason, unhook. // This shouldn't happen though. if (commandHandlerReg_ != null) { Debug.log("Warning: onActivate called twice without intervening onDeactivate"); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; } commandHandlerReg_ = commandBinder.bind(commands_, this); Scheduler.get().scheduleFinally(new ScheduledCommand() { public void execute() { // This has to be executed in a scheduleFinally because // Source.manageCommands gets called after this.onActivate, // and if we're going from a non-editor (like data view) to // an editor, setEnabled(true) will be called on the command // in manageCommands. commands_.reopenSourceDocWithEncoding().setEnabled( docUpdateSentinel_.getPath() != null); } }); view_.onActivate(); } public void onDeactivate() { // IMPORTANT NOTE: most of this logic is duplicated in // CodeBrowserEditingTarget (no straightforward way to create a // re-usable implementation) so changes here need to be synced externalEditCheckInvalidation_.invalidate(); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; // switching tabs is a navigation action try { docDisplay_.recordCurrentNavigationPosition(); } catch(Exception e) { Debug.log("Exception recording nav position: " + e.toString()); } } @Override public void onInitiallyLoaded() { checkForExternalEdit(); } public boolean onBeforeDismiss() { Command closeCommand = new Command() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }; if (dirtyState_.getValue()) saveWithPrompt(closeCommand, null); else closeCommand.execute(); return false; } public void save() { save(new Command() { @Override public void execute() { }}); } public void save(Command onCompleted) { saveThenExecute(null, CommandUtil.join(postSaveCommand(), onCompleted)); } public void saveWithPrompt(final Command command, final Command onCancelled) { view_.ensureVisible(); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, getName().getValue() + " - Unsaved Changes", "The document '" + getName().getValue() + "' has unsaved changes.\n\n" + "Do you want to save these changes?", true, new Operation() { public void execute() { saveThenExecute(null, command); } }, new Operation() { public void execute() { command.execute(); } }, new Operation() { public void execute() { if (onCancelled != null) onCancelled.execute(); } }, "Save", "Don't Save", true); } public void revertChanges(Command onCompleted) { docUpdateSentinel_.revert(onCompleted); } private void saveThenExecute(String encodingOverride, final Command command) { checkCompilePdfDependencies(); final String path = docUpdateSentinel_.getPath(); if (path == null) { saveNewFile(null, encodingOverride, command); return; } withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { fixupCodeBeforeSaving(); docUpdateSentinel_.save(path, null, encoding, new SaveProgressIndicator( FileSystemItem.createFile(path), null, command )); } }); } private void saveNewFile(final String suggestedPath, String encodingOverride, final Command executeOnSuccess) { withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { saveNewFileWithEncoding(suggestedPath, encoding, executeOnSuccess); } }); } private void withEncodingRequiredUnlessAscii( final String encodingOverride, final CommandWithArg<String> command) { final String encoding = StringUtil.firstNotNullOrEmpty(new String[] { encodingOverride, docUpdateSentinel_.getEncoding(), prefs_.defaultEncoding().getValue() }); if (StringUtil.isNullOrEmpty(encoding)) { if (docUpdateSentinel_.isAscii()) { // Don't bother asking when it's just ASCII command.execute(null); } else { withChooseEncoding(session_.getSessionInfo().getSystemEncoding(), new CommandWithArg<String>() { public void execute(String newEncoding) { command.execute(newEncoding); } }); } } else { command.execute(encoding); } } private void withChooseEncoding(final String defaultEncoding, final CommandWithArg<String> command) { view_.ensureVisible();; server_.iconvlist(new SimpleRequestCallback<IconvListResult>() { @Override public void onResponseReceived(IconvListResult response) { // Stupid compiler. Use this Value shim to make the dialog available // in its own handler. final HasValue<ChooseEncodingDialog> d = new Value<ChooseEncodingDialog>(null); d.setValue(new ChooseEncodingDialog( response.getCommon(), response.getAll(), defaultEncoding, false, true, new OperationWithInput<String>() { public void execute(String newEncoding) { if (newEncoding == null) return; if (d.getValue().isSaveAsDefault()) { prefs_.defaultEncoding().setGlobalValue(newEncoding); prefs_.writeUIPrefs(); } command.execute(newEncoding); } })); d.getValue().showModal(); } }); } private void saveNewFileWithEncoding(String suggestedPath, final String encoding, final Command executeOnSuccess) { view_.ensureVisible(); FileSystemItem fsi; if (suggestedPath != null) fsi = FileSystemItem.createFile(suggestedPath); else fsi = getSaveFileDefaultDir(); fileDialogs_.saveFile( "Save File - " + getName().getValue(), fileContext_, fsi, fileType_.getDefaultExtension(), false, new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem saveItem, ProgressIndicator indicator) { if (saveItem == null) return; try { workbenchContext_.setDefaultFileDialogDir( saveItem.getParentPath()); final TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(saveItem); final Command saveCommand = new Command() { @Override public void execute() { if (!getPath().equals(saveItem.getPath())) { // breakpoints are file-specific, so when saving // as a different file, clear the display of // breakpoints from the old file name docDisplay_.removeAllBreakpoints(); // update publish settings syncPublishPath(saveItem.getPath()); } fixupCodeBeforeSaving(); docUpdateSentinel_.save( saveItem.getPath(), fileType.getTypeId(), encoding, new SaveProgressIndicator(saveItem, fileType, executeOnSuccess)); events_.fireEvent( new SourceFileSavedEvent(saveItem.getPath())); } }; // if we are switching from an R file type // to a non-R file type then confirm if (fileType_.isR() && !fileType.isR()) { globalDisplay_.showYesNoMessage( MessageDialog.WARNING, "Confirm Change File Type", "This file was created as an R script however " + "the file extension you specified will change " + "it into another file type that will no longer " + "open as an R script.\n\n" + "Are you sure you want to change the type of " + "the file so that it is no longer an R script?", new Operation() { @Override public void execute() { saveCommand.execute(); } }, false); } else { saveCommand.execute(); } } catch (Exception e) { indicator.onError(e.toString()); return; } indicator.onCompleted(); } }); } private void fixupCodeBeforeSaving() { int lineCount = docDisplay_.getRowCount(); if (lineCount < 1) return; if (prefs_.stripTrailingWhitespace().getValue() && !fileType_.isMarkdown()) { String code = docDisplay_.getCode(); Pattern pattern = Pattern.create("[ \t]+$"); String strippedCode = pattern.replaceAll(code, ""); if (!strippedCode.equals(code)) docDisplay_.setCode(strippedCode, true); } if (prefs_.autoAppendNewline().getValue() || fileType_.isPython()) { String lastLine = docDisplay_.getLine(lineCount - 1); if (lastLine.length() != 0) docDisplay_.insertCode(docDisplay_.getEnd().getEnd(), "\n"); } } private FileSystemItem getSaveFileDefaultDir() { FileSystemItem fsi = null; SessionInfo si = session_.getSessionInfo(); if (si.getBuildToolsType() == SessionInfo.BUILD_TOOLS_PACKAGE) { FileSystemItem pkg = FileSystemItem.createDir(si.getBuildTargetDir()); if (fileType_.isR()) { fsi = FileSystemItem.createDir(pkg.completePath("R")); } else if (fileType_.isC() && si.getHasPackageSrcDir()) { fsi = FileSystemItem.createDir(pkg.completePath("src")); } else if (fileType_.isRd()) { fsi = FileSystemItem.createDir(pkg.completePath("man")); } else if ((fileType_.isRnw() || fileType_.isRmd()) && si.getHasPackageVignetteDir()) { fsi = FileSystemItem.createDir(pkg.completePath("vignettes")); } } if (fsi == null) fsi = workbenchContext_.getDefaultFileDialogDir(); return fsi; } public void onDismiss() { docUpdateSentinel_.stop(); if (spelling_ != null) spelling_.onDismiss(); while (releaseOnDismiss_.size() > 0) releaseOnDismiss_.remove(0).removeHandler(); docDisplay_.endCollabSession(); codeExecution_.detachLastExecuted(); } public ReadOnlyValue<Boolean> dirtyState() { return dirtyState_; } @Override public boolean isSaveCommandActive() { return // force active? forceSaveCommandActive_ || // standard check of dirty state (dirtyState().getValue() == true) || // empty untitled document (allow for immediate save) ((getPath() == null) && docDisplay_.getCode().isEmpty()) || // source on save is active (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()); } @Override public void forceSaveCommandActive() { forceSaveCommandActive_ = true; } public Widget asWidget() { return (Widget) view_; } public String getId() { return id_; } @Override public void adaptToExtendedFileType(String extendedType) { view_.adaptToExtendedFileType(extendedType); if (extendedType.equals("rmarkdown")) updateRmdFormatList(); extendedType_ = extendedType; } @Override public String getExtendedFileType() { return extendedType_; } public HasValue<String> getName() { return name_; } public String getTitle() { return getName().getValue(); } public String getPath() { if (docUpdateSentinel_ == null) return null; return docUpdateSentinel_.getPath(); } public String getContext() { return null; } public ImageResource getIcon() { return fileType_.getDefaultIcon(); } public String getTabTooltip() { return getPath(); } @Override public TextFileType getTextFileType() { return fileType_; } @Handler void onReformatCode() { // Only allow if entire selection in R mode for now if (!DocumentMode.isSelectionInRMode(docDisplay_)) { showRModeWarning("Reformat Code"); return; } reformatHelper_.insertPrettyNewlines(); } @Handler void onInsertRoxygenSkeleton() { roxygenHelper_.insertRoxygenSkeleton(); } @Handler void onExpandSelection() { docDisplay_.expandSelection(); } @Handler void onShrinkSelection() { docDisplay_.shrinkSelection(); } @Handler void onInsertSnippet() { // NOTE: Bound to Shift + Tab so we delegate back there // if this isn't dispatched if (!snippets_.onInsertSnippet()) docDisplay_.blockOutdent(); } @Handler void onShowDiagnosticsActiveDocument() { lintManager_.lint(true, true, false); } public void withSavedDoc(Command onsaved) { docUpdateSentinel_.withSavedDoc(onsaved); } @Handler void onCheckSpelling() { spelling_.checkSpelling(); } @Handler void onDebugDumpContents() { view_.debug_dumpContents(); } @Handler void onDebugImportDump() { view_.debug_importDump(); } @Handler void onReopenSourceDocWithEncoding() { withChooseEncoding( docUpdateSentinel_.getEncoding(), new CommandWithArg<String>() { public void execute(String encoding) { docUpdateSentinel_.reopenWithEncoding(encoding); } }); } @Handler void onSaveSourceDoc() { saveThenExecute(null, postSaveCommand()); } @Handler void onSaveSourceDocAs() { saveNewFile(docUpdateSentinel_.getPath(), null, postSaveCommand()); } @Handler void onSaveSourceDocWithEncoding() { withChooseEncoding( StringUtil.firstNotNullOrEmpty(new String[] { docUpdateSentinel_.getEncoding(), prefs_.defaultEncoding().getValue(), session_.getSessionInfo().getSystemEncoding() }), new CommandWithArg<String>() { public void execute(String encoding) { saveThenExecute(encoding, postSaveCommand()); } }); } @Handler void onPrintSourceDoc() { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { docDisplay_.print(); } }); } @Handler void onVcsFileDiff() { Command showDiffCommand = new Command() { @Override public void execute() { events_.fireEvent(new ShowVcsDiffEvent( FileSystemItem.createFile(docUpdateSentinel_.getPath()))); } }; if (dirtyState_.getValue()) saveWithPrompt(showDiffCommand, null); else showDiffCommand.execute(); } @Handler void onVcsFileLog() { events_.fireEvent(new ShowVcsHistoryEvent( FileSystemItem.createFile(docUpdateSentinel_.getPath()))); } @Handler void onVcsFileRevert() { events_.fireEvent(new VcsRevertFileEvent( FileSystemItem.createFile(docUpdateSentinel_.getPath()))); } @Handler void onVcsViewOnGitHub() { fireVcsViewOnGithubEvent(GitHubViewRequest.ViewType.View); } @Handler void onVcsBlameOnGitHub() { fireVcsViewOnGithubEvent(GitHubViewRequest.ViewType.Blame); } private void fireVcsViewOnGithubEvent(GitHubViewRequest.ViewType type) { FileSystemItem file = FileSystemItem.createFile(docUpdateSentinel_.getPath()); if (docDisplay_.getSelectionValue().length() > 0) { int start = docDisplay_.getSelectionStart().getRow() + 1; int end = docDisplay_.getSelectionEnd().getRow() + 1; events_.fireEvent(new VcsViewOnGitHubEvent( new GitHubViewRequest(file, type, start, end))); } else { events_.fireEvent(new VcsViewOnGitHubEvent( new GitHubViewRequest(file, type))); } } @Handler void onExtractLocalVariable() { if (!isCursorInRMode()) { showRModeWarning("Extract Variable"); return; } docDisplay_.focus(); String initialSelection = docDisplay_.getSelectionValue(); final String refactoringName = "Extract local variable"; final String pleaseSelectCodeMessage = "Please select the code to " + "extract into a variable."; if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, initialSelection)) return; docDisplay_.fitSelectionToLines(false); final String code = docDisplay_.getSelectionValue(); if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, code)) return; // get the first line of the selection and calculate it's indentation String firstLine = docDisplay_.getLine( docDisplay_.getSelectionStart().getRow()); final String indentation = extractIndentation(firstLine); // used to parse the code server_.detectFreeVars(code, new RefactorServerRequestCallback(refactoringName) { @Override void doExtract(JsArrayString response) { globalDisplay_.promptForText( refactoringName, "Variable Name", "", new OperationWithInput<String>() { public void execute(String input) { final String extractedCode = indentation + input.trim() + " <- " + code + "\n"; InputEditorPosition insertPosition = docDisplay_ .getSelection() .extendToLineStart() .getStart(); docDisplay_.replaceSelection( input.trim()); docDisplay_.insertCode( insertPosition, extractedCode); } } ); } } ); } private void showRModeWarning(String command) { globalDisplay_.showMessage(MessageDisplay.MSG_WARNING, "Command Not Available", "The "+ command + " command is " + "only valid for R code chunks."); return; } @Handler void onExtractFunction() { if (!isCursorInRMode()) { showRModeWarning("Extract Function"); return; } docDisplay_.focus(); String initialSelection = docDisplay_.getSelectionValue(); final String refactoringName = "Extract Function"; final String pleaseSelectCodeMessage = "Please select the code to " + "extract into a function."; if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, initialSelection)) return; docDisplay_.fitSelectionToLines(false); final String code = docDisplay_.getSelectionValue(); if (checkSelectionAndAlert(refactoringName, pleaseSelectCodeMessage, code)) return; final String indentation = extractIndentation(code); server_.detectFreeVars(code, new RefactorServerRequestCallback(refactoringName) { @Override void doExtract(final JsArrayString response) { globalDisplay_.promptForText( refactoringName, "Function Name", "", new OperationWithInput<String>() { public void execute(String input) { String prefix; if (docDisplay_.getSelectionOffset(true) == 0) prefix = ""; else prefix = "\n"; String args = response != null ? response.join(", ") : ""; docDisplay_.replaceSelection( prefix + indentation + input.trim() + " <- " + "function (" + args + ") {\n" + StringUtil.indent(code, " ") + "\n" + indentation + "}"); } } ); } } ); } private boolean checkSelectionAndAlert(String refactoringName, String pleaseSelectCodeMessage, String selection) { if (isSelectionValueEmpty(selection)) { globalDisplay_.showErrorMessage(refactoringName, pleaseSelectCodeMessage); return true; } return false; } private String extractIndentation(String code) { Pattern leadingWhitespace = Pattern.create("^(\\s*)"); Match match = leadingWhitespace.match(code, 0); return match == null ? "" : match.getGroup(1); } private boolean isSelectionValueEmpty(String selection) { return selection == null || selection.trim().length() == 0; } @Handler void onJumpToMatching() { docDisplay_.jumpToMatching(); docDisplay_.ensureCursorVisible(); } @Handler void onSelectToMatching() { docDisplay_.selectToMatching(); docDisplay_.ensureCursorVisible(); } @Handler void onExpandToMatching() { docDisplay_.expandToMatching(); docDisplay_.ensureCursorVisible(); } @Handler void onSplitIntoLines() { docDisplay_.splitIntoLines(); } @Handler void onCommentUncomment() { if (isCursorInTexMode()) doCommentUncomment("%"); else if (isCursorInRMode()) doCommentUncomment(" else if (fileType_.isCpp() || fileType_.isStan()) doCommentUncomment(" } private void doCommentUncomment(String c) { InputEditorSelection initialSelection = docDisplay_.getSelection(); String indent = ""; boolean singleLineAction = initialSelection.isEmpty() || initialSelection.getStart().getLine().equals( initialSelection.getEnd().getLine()); if (singleLineAction) { String currentLine = docDisplay_.getCurrentLine(); Match firstCharMatch = Pattern.create("([^\\s])").match(currentLine, 0); if (firstCharMatch != null) { indent = currentLine.substring(0, firstCharMatch.getIndex()); } else { indent = currentLine; } } boolean selectionCollapsed = docDisplay_.isSelectionCollapsed(); docDisplay_.fitSelectionToLines(true); String selection = docDisplay_.getSelectionValue(); // If any line's first non-whitespace character is not #, then the whole // selection should be commented. Exception: If the whole selection is // whitespace, then we comment out the whitespace. Match match = Pattern.create("^\\s*[^" + c + "\\s]").match(selection, 0); boolean uncomment = match == null && selection.trim().length() != 0; if (uncomment) { String prefix = c + "'?"; selection = selection.replaceAll("((^|\\n)\\s*)" + prefix + " ?", "$1"); } else { // Check to see if we're commenting something that looks like Roxygen Pattern pattern = Pattern.create("(^\\s*@)|(\\n\\s*@)"); boolean isRoxygen = pattern.match(selection, 0) != null; if (isRoxygen) c = c + "'"; if (singleLineAction) selection = indent + c + " " + selection.replaceAll("^\\s*", ""); else { selection = c + " " + selection.replaceAll("\\n", "\n" + c + " "); // If the selection ends at the very start of a line, we don't want // to comment out that line. This enables Shift+DownArrow to select // one line at a time. if (selection.endsWith("\n" + c + " ")) selection = selection.substring(0, selection.length() - 1 - c.length()); } } docDisplay_.replaceSelection(selection); if (selectionCollapsed) docDisplay_.collapseSelection(true); if (singleLineAction) { int offset = c.length() + 1; String line = docDisplay_.getCurrentLine(); Match matchPos = Pattern.create("([^\\s])").match(line, 0); InputEditorSelection newSelection; if (uncomment) { if (initialSelection.isEmpty()) { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(-offset, true), initialSelection.getStart().movePosition(-offset, true)); } else { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(matchPos.getIndex(), false), initialSelection.getEnd().movePosition(-offset, true)); } } else { if (initialSelection.isEmpty()) { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(offset, true), initialSelection.getStart().movePosition(offset, true)); } else { newSelection = new InputEditorSelection( initialSelection.getStart().movePosition(matchPos.getIndex() + offset, false), initialSelection.getEnd().movePosition(offset, true)); } } docDisplay_.setSelection(newSelection); } docDisplay_.focus(); } @Handler void onReindent() { docDisplay_.reindent(); docDisplay_.focus(); } @Handler void onReflowComment() { if (DocumentMode.isSelectionInRMode(docDisplay_)) doReflowComment("( else if (DocumentMode.isSelectionInCppMode(docDisplay_)) { String currentLine = docDisplay_.getLine( docDisplay_.getCursorPosition().getRow()); if (currentLine.startsWith(" *")) doReflowComment("( \\*[^/])", false); else doReflowComment("( } else if (DocumentMode.isSelectionInTexMode(docDisplay_)) doReflowComment("(%)"); else if (DocumentMode.isSelectionInMarkdownMode(docDisplay_)) doReflowComment("()"); else if (docDisplay_.getFileType().isText()) doReflowComment("()"); } public void reflowText() { if (docDisplay_.getSelectionValue().isEmpty()) docDisplay_.setSelectionRange( Range.fromPoints( Position.create(docDisplay_.getCursorPosition().getRow(), 0), Position.create(docDisplay_.getCursorPosition().getRow(), docDisplay_.getCurrentLine().length()))); onReflowComment(); docDisplay_.setCursorPosition( Position.create( docDisplay_.getSelectionEnd().getRow(), 0)); } public void showHelpAtCursor() { docDisplay_.goToHelp(); } @Handler void onDebugBreakpoint() { docDisplay_.toggleBreakpointAtCursor(); } @Handler void onRsconnectDeploy() { if (docUpdateSentinel_ == null) return; // only Shiny files get the deploy command, so we can be confident we're // deploying an app here events_.fireEvent(RSConnectActionEvent.DeployAppEvent( docUpdateSentinel_.getPath(), null)); } @Handler void onRsconnectConfigure() { events_.fireEvent(RSConnectActionEvent.ConfigureAppEvent( docUpdateSentinel_.getPath())); } @Handler void onEditRmdFormatOptions() { rmarkdownHelper_.withRMarkdownPackage( "Editing R Markdown options", false, new CommandWithArg<RMarkdownContext>() { @Override public void execute(RMarkdownContext arg) { showFrontMatterEditor(); } }); } private void showFrontMatterEditor() { final String yaml = getRmdFrontMatter(); if (yaml == null) { globalDisplay_.showErrorMessage("Edit Format Failed", "Can't find the YAML front matter for this document. Make " + "sure the front matter is enclosed by lines containing only " + "three dashes: return; } rmarkdownHelper_.convertFromYaml(yaml, new CommandWithArg<RmdYamlData>() { @Override public void execute(RmdYamlData arg) { String errCaption = "Edit Format Failed"; String errMsg = "The YAML front matter in this document could not be " + "successfully parsed. This parse error needs to be " + "resolved before format options can be edited."; if (arg == null) { globalDisplay_.showErrorMessage(errCaption, errMsg); } else if (!arg.parseSucceeded()) { // try to find where the YAML segment begins in the document // so we can show an adjusted line number for the error int numLines = docDisplay_.getRowCount(); int offsetLine = 0; String separator = RmdFrontMatter.FRONTMATTER_SEPARATOR.trim(); for (int i = 0; i < numLines; i++) { if (docDisplay_.getLine(i).equals(separator)) { offsetLine = i + 1; break; } } globalDisplay_.showErrorMessage(errCaption, errMsg + "\n\n" + arg.getOffsetParseError(offsetLine)); } else { showFrontMatterEditorDialog(yaml, arg); } } }); } private void showFrontMatterEditorDialog(String yaml, RmdYamlData data) { RmdSelectedTemplate selTemplate = rmarkdownHelper_.getTemplateFormat(yaml); if (selTemplate == null) { // we don't expect this to happen since we disable the dialog // entry point when we can't find an associated template globalDisplay_.showErrorMessage("Edit Format Failed", "Couldn't determine the format options from the YAML front " + "matter. Make sure the YAML defines a supported output " + "format in its 'output' field."); return; } RmdTemplateOptionsDialog dialog = new RmdTemplateOptionsDialog(selTemplate.template, selTemplate.format, data.getFrontMatter(), getPath() == null ? null : FileSystemItem.createFile(getPath()), selTemplate.isShiny, new OperationWithInput<RmdTemplateOptionsDialog.Result>() { @Override public void execute(RmdTemplateOptionsDialog.Result in) { // when the dialog is completed successfully, apply the new // front matter applyRmdFormatOptions(in.format, in.outputOptions); } }, new Operation() { @Override public void execute() { // when the dialog is cancelled, update the view's format list // (to cancel in-place changes) updateRmdFormatList(); } }); dialog.showModal(); } private void applyRmdFormatOptions(String format, RmdFrontMatterOutputOptions options) { rmarkdownHelper_.replaceOutputFormatOptions( getRmdFrontMatter(), format, options, new OperationWithInput<String>() { @Override public void execute(String input) { applyRmdFrontMatter(input); } }); } private String getRmdFrontMatter() { return YamlFrontMatter.getFrontMatter(docDisplay_.getCode()); } private void applyRmdFrontMatter(String yaml) { String code = docDisplay_.getCode(); String newCode = YamlFrontMatter.applyFrontMatter(code, yaml); if (!code.equals(newCode)) { docDisplay_.setCode(newCode, true); updateRmdFormatList(); } } private RmdSelectedTemplate getSelectedTemplate() { // try to extract the front matter and ascertain the template to which // it refers String yaml = getRmdFrontMatter(); if (yaml == null) return null; return rmarkdownHelper_.getTemplateFormat(yaml); } private void updateRmdFormatList() { RmdSelectedTemplate selTemplate = getSelectedTemplate(); if (selTemplate == null) { view_.setFormatOptionsVisible(false); return; } else if (selTemplate.isShiny) { view_.setIsShinyFormat(selTemplate.format != null && selTemplate.format.endsWith( RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX)); return; } // we know which template this doc is using--populate the format list // with the formats available in the template String formatUiName = ""; JsArray<RmdTemplateFormat> formats = selTemplate.template.getFormats(); List<String> formatList = new ArrayList<String>(); List<String> valueList = new ArrayList<String>(); List<String> extensionList = new ArrayList<String>(); for (int i = 0; i < formats.length(); i++) { String uiName = formats.get(i).getUiName(); formatList.add(uiName); valueList.add(formats.get(i).getName()); extensionList.add(formats.get(i).getExtension()); if (formats.get(i).getName().equals(selTemplate.format)) { formatUiName = uiName; } } view_.setFormatOptions(fileType_, formatList, valueList, extensionList, formatUiName); } private void setRmdFormat(String formatName) { RmdSelectedTemplate selTemplate = getSelectedTemplate(); if (selTemplate == null) return; // if this is the current format, we don't need to change the front matter if (selTemplate.format.equals(formatName)) { renderRmd(); return; } rmarkdownHelper_.setOutputFormat(getRmdFrontMatter(), formatName, new CommandWithArg<String>() { @Override public void execute(String yaml) { if (yaml != null) applyRmdFrontMatter(yaml); // re-knit the document renderRmd(); } }); } void doReflowComment(String commentPrefix) { doReflowComment(commentPrefix, true); } void doReflowComment(String commentPrefix, boolean multiParagraphIndent) { docDisplay_.focus(); InputEditorSelection originalSelection = docDisplay_.getSelection(); InputEditorSelection selection = originalSelection; if (selection.isEmpty()) { selection = selection.growToIncludeLines("^\\s*" + commentPrefix + ".*$"); } else { selection = selection.shrinkToNonEmptyLines(); selection = selection.extendToLineStart(); selection = selection.extendToLineEnd(); } if (selection.isEmpty()) return; reflowComments(commentPrefix, multiParagraphIndent, selection, originalSelection.isEmpty() ? originalSelection.getStart() : null); } private Position selectionToPosition(InputEditorPosition pos) { return docDisplay_.selectionToPosition(pos); } private void reflowComments(String commentPrefix, final boolean multiParagraphIndent, InputEditorSelection selection, final InputEditorPosition cursorPos) { String code = docDisplay_.getCode(selection); String[] lines = code.split("\n"); String prefix = StringUtil.getCommonPrefix(lines, true); Pattern pattern = Pattern.create("^\\s*" + commentPrefix + "+('?)\\s*"); Match match = pattern.match(prefix, 0); // Selection includes non-comments? Abort. if (match == null) return; prefix = match.getValue(); final boolean roxygen = match.hasGroup(1); int cursorRowIndex = 0; int cursorColIndex = 0; if (cursorPos != null) { cursorRowIndex = selectionToPosition(cursorPos).getRow() - selectionToPosition(selection.getStart()).getRow(); cursorColIndex = Math.max(0, cursorPos.getPosition() - prefix.length()); } final WordWrapCursorTracker wwct = new WordWrapCursorTracker( cursorRowIndex, cursorColIndex); int maxLineLength = prefs_.printMarginColumn().getValue() - prefix.length(); WordWrap wordWrap = new WordWrap(maxLineLength, false) { @Override protected boolean forceWrapBefore(String line) { String trimmed = line.trim(); if (roxygen && trimmed.startsWith("@") && !trimmed.startsWith("@@")) { // Roxygen tags always need to be at the start of a line. If // there is content immediately following the roxygen tag, then // content should be wrapped until the next roxygen tag is // encountered. indent_ = ""; if (TAG_WITH_CONTENTS.match(line, 0) != null) { indentRestOfLines_ = true; } return true; } // empty line disables indentation else if (!multiParagraphIndent && (line.trim().length() == 0)) { indent_ = ""; indentRestOfLines_ = false; } return super.forceWrapBefore(line); } @Override protected void onChunkWritten(String chunk, int insertionRow, int insertionCol, int indexInOriginalString) { if (indentRestOfLines_) { indentRestOfLines_ = false; indent_ = " "; // TODO: Use real indent from settings } wwct.onChunkWritten(chunk, insertionRow, insertionCol, indexInOriginalString); } private boolean indentRestOfLines_ = false; private Pattern TAG_WITH_CONTENTS = Pattern.create("@\\w+\\s+[^\\s]"); }; for (String line : lines) { String content = line.substring(Math.min(line.length(), prefix.length())); if (content.matches("^\\s*\\@examples\\b.*$")) wordWrap.setWrappingEnabled(false); else if (content.trim().startsWith("@")) wordWrap.setWrappingEnabled(true); wwct.onBeginInputRow(); wordWrap.appendLine(content); } String wrappedString = wordWrap.getOutput(); StringBuilder finalOutput = new StringBuilder(); for (String line : StringUtil.getLineIterator(wrappedString)) finalOutput.append(prefix).append(line).append("\n"); // Remove final \n if (finalOutput.length() > 0) finalOutput.deleteCharAt(finalOutput.length()-1); String reflowed = finalOutput.toString(); docDisplay_.setSelection(selection); if (!reflowed.equals(code)) { docDisplay_.replaceSelection(reflowed); } if (cursorPos != null) { if (wwct.getResult() != null) { int row = wwct.getResult().getY(); int col = wwct.getResult().getX(); row += selectionToPosition(selection.getStart()).getRow(); col += prefix.length(); Position pos = Position.create(row, col); docDisplay_.setSelection(docDisplay_.createSelection(pos, pos)); } else { docDisplay_.collapseSelection(false); } } } @Handler void onExecuteCodeWithoutFocus() { codeExecution_.executeSelection(false); } @Handler void onExecuteCodeWithoutMovingCursor() { if (docDisplay_.isFocused()) codeExecution_.executeSelection(true, false); else if (view_.isAttached()) view_.findSelectAll(); } @Handler void onExecuteCode() { codeExecution_.executeSelection(true); } @Override public String extractCode(DocDisplay docDisplay, Range range) { Scope sweaveChunk = null; if (fileType_.canExecuteChunks()) sweaveChunk = scopeHelper_.getCurrentSweaveChunk(range.getStart()); String code = sweaveChunk != null ? scopeHelper_.getSweaveChunkText(sweaveChunk, range) : docDisplay_.getCode(range.getStart(), range.getEnd()); return code; } @Handler void onExecuteAllCode() { sourceActiveDocument(true); } @Handler void onExecuteToCurrentLine() { docDisplay_.focus(); int row = docDisplay_.getSelectionEnd().getRow(); int col = docDisplay_.getLength(row); codeExecution_.executeRange(Range.fromPoints(Position.create(0, 0), Position.create(row, col))); } @Handler void onExecuteFromCurrentLine() { docDisplay_.focus(); int startRow = docDisplay_.getSelectionStart().getRow(); int startColumn = 0; Position start = Position.create(startRow, startColumn); codeExecution_.executeRange(Range.fromPoints(start, endPosition())); } @Handler void onExecuteCurrentFunction() { docDisplay_.focus(); // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); Scope currentFunction = docDisplay_.getCurrentFunction(false); // Check if we're at the top level (i.e. not in a function), or in // an unclosed function if (currentFunction == null || currentFunction.getEnd() == null) return; Position start = currentFunction.getPreamble(); Position end = currentFunction.getEnd(); codeExecution_.executeRange(Range.fromPoints(start, end)); } @Handler void onExecuteCurrentSection() { docDisplay_.focus(); // Determine the current section. docDisplay_.getScopeTree(); Scope currentSection = docDisplay_.getCurrentSection(); if (currentSection == null) return; // Determine the start and end of the section Position start = currentSection.getBodyStart(); if (start == null) start = Position.create(0, 0); Position end = currentSection.getEnd(); if (end == null) end = endPosition(); codeExecution_.executeRange(Range.fromPoints(start, end)); } private Position endPosition() { int endRow = Math.max(0, docDisplay_.getRowCount() - 1); int endColumn = docDisplay_.getLength(endRow); return Position.create(endRow, endColumn); } @Handler void onInsertChunk() { Position pos = moveCursorToNextInsertLocation(); InsertChunkInfo insertChunkInfo = docDisplay_.getInsertChunkInfo(); if (insertChunkInfo != null) { docDisplay_.insertCode(insertChunkInfo.getValue(), false); Position cursorPosition = insertChunkInfo.getCursorPosition(); docDisplay_.setCursorPosition(Position.create( pos.getRow() + cursorPosition.getRow(), cursorPosition.getColumn())); docDisplay_.focus(); } else { assert false : "Mode did not have insertChunkInfo available"; } } @Handler void onInsertSection() { globalDisplay_.promptForText( "Insert Section", "Section label:", "", new OperationWithInput<String>() { @Override public void execute(String label) { // move cursor to next insert location Position pos = moveCursorToNextInsertLocation(); // truncate length to print margin - 5 int printMarginColumn = prefs_.printMarginColumn().getValue(); int length = printMarginColumn - 5; // truncate label to maxLength - 10 (but always allow at // least 20 chars for the label) int maxLabelLength = length - 10; maxLabelLength = Math.max(maxLabelLength, 20); if (label.length() > maxLabelLength) label = label.substring(0, maxLabelLength-1); // prefix String prefix = "# " + label + " "; // fill to maxLength (bit ensure at least 4 fill characters // so the section parser is sure to pick it up) StringBuffer sectionLabel = new StringBuffer(); sectionLabel.append("\n"); sectionLabel.append(prefix); int fillChars = length - prefix.length(); fillChars = Math.max(fillChars, 4); for (int i=0; i<fillChars; i++) sectionLabel.append("-"); sectionLabel.append("\n\n"); // insert code and move cursor docDisplay_.insertCode(sectionLabel.toString(), false); docDisplay_.setCursorPosition(Position.create(pos.getRow() + 3, 0)); docDisplay_.focus(); } }); } private Position moveCursorToNextInsertLocation() { docDisplay_.collapseSelection(true); if (!docDisplay_.moveSelectionToBlankLine()) { int lastRow = docDisplay_.getRowCount(); int lastCol = docDisplay_.getLength(lastRow); Position endPos = Position.create(lastRow, lastCol); docDisplay_.setCursorPosition(endPos); docDisplay_.insertCode("\n", false); } return docDisplay_.getCursorPosition(); } public void executeChunk(Position position) { docDisplay_.getScopeTree(); executeSweaveChunk(scopeHelper_.getCurrentSweaveChunk(position), false); } @Handler void onExecuteCurrentChunk() { // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); executeSweaveChunk(scopeHelper_.getCurrentSweaveChunk(), false); } @Handler void onExecuteNextChunk() { // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); executeSweaveChunk(scopeHelper_.getNextSweaveChunk(), true); } @Handler void onExecutePreviousChunks() { withPreservedSelection(new Command() { @Override public void execute() { // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentScope() returns // a Scope with an end. docDisplay_.getScopeTree(); // see if there is a region of code in the current chunk to execute Range currentChunkRange = null; Scope currentScope = scopeHelper_.getCurrentSweaveChunk(); if (currentScope != null) { // get end position (always execute the current line unless // the cursor is at the beginning of it) Position endPos = docDisplay_.getCursorPosition(); if (endPos.getColumn() >0) endPos = Position.create(endPos.getRow()+1, 0); currentChunkRange = Range.fromPoints(currentScope.getBodyStart(), endPos); } // execute the previous chunks Scope[] previousScopes = scopeHelper_.getPreviousSweaveChunks(); for (Scope scope : previousScopes) executeSweaveChunk(scope, false); // execute code from the current chunk if we have it if (currentChunkRange != null) codeExecution_.executeRange(currentChunkRange); } }); } private void withPreservedSelection(Command command) { // save the selection and scroll position for restoration int scrollPosition = docDisplay_.getScrollTop(); Position start = docDisplay_.getSelectionStart(); Position end = docDisplay_.getSelectionEnd(); AnchoredSelection anchoredSelection = docDisplay_.createAnchoredSelection(start,end); // execute the command command.execute(); // restore the selection and scroll position anchoredSelection.apply(); docDisplay_.scrollToY(scrollPosition); } private void executeSweaveChunk(final Scope chunk, final boolean scrollNearTop) { if (chunk == null) return; // command used to execute chunk (we may need to defer it if this // is an Rmd document as populating params might be necessary) final Command executeChunk = new Command() { @Override public void execute() { Range range = scopeHelper_.getSweaveChunkInnerRange(chunk); if (scrollNearTop) { docDisplay_.navigateToPosition( SourcePosition.create(range.getStart().getRow(), range.getStart().getColumn()), true); } docDisplay_.setSelection( docDisplay_.createSelection(range.getStart(), range.getEnd())); if (!range.isEmpty()) { codeExecution_.setLastExecuted(range.getStart(), range.getEnd()); String code = scopeHelper_.getSweaveChunkText(chunk); events_.fireEvent(new SendToConsoleEvent(code, true)); docDisplay_.collapseSelection(true); } } }; // Rmd allows server-side prep for chunk execution if (fileType_.isRmd()) { // ensure source is synced with server docUpdateSentinel_.withSavedDoc(new Command() { @Override public void execute() { // allow server to prepare for chunk execution // (e.g. by populating 'params' in the global environment) rmarkdownHelper_.prepareForRmdChunkExecution( docUpdateSentinel_.getId(), docUpdateSentinel_.getContents(), executeChunk); } }); } else { executeChunk.execute(); } } @Handler void onJumpTo() { statusBar_.getScope().click(); } @Handler void onGoToLine() { globalDisplay_.promptForInteger( "Go to Line", "Enter line number:", null, new ProgressOperationWithInput<Integer>() { @Override public void execute(Integer line, ProgressIndicator indicator) { indicator.onCompleted(); line = Math.max(1, line); line = Math.min(docDisplay_.getRowCount(), line); docDisplay_.navigateToPosition( SourcePosition.create(line-1, 0), true); } }, null); } @Handler void onCodeCompletion() { docDisplay_.codeCompletion(); } @Handler void onGoToHelp() { docDisplay_.goToHelp(); } @Handler void onGoToFunctionDefinition() { docDisplay_.goToFunctionDefinition(); } @Handler void onFindUsages() { cppHelper_.findUsages(); } @Handler public void onSetWorkingDirToActiveDoc() { // get path String activeDocPath = docUpdateSentinel_.getPath(); if (activeDocPath != null) { FileSystemItem wdPath = FileSystemItem.createFile(activeDocPath).getParentPath(); consoleDispatcher_.executeSetWd(wdPath, true); } else { globalDisplay_.showMessage( MessageDialog.WARNING, "Source File Not Saved", "The currently active source file is not saved so doesn't " + "have a directory to change into."); return; } } @SuppressWarnings("unused") private String stangle(String sweaveStr) { ScopeList chunks = new ScopeList(docDisplay_); chunks.selectAll(ScopeList.CHUNK); StringBuilder code = new StringBuilder(); for (Scope chunk : chunks) { String text = scopeHelper_.getSweaveChunkText(chunk); code.append(text); if (text.length() > 0 && text.charAt(text.length()-1) != '\n') code.append('\n'); } return code.toString(); } @Handler void onSourceActiveDocument() { sourceActiveDocument(false); } @Handler void onSourceActiveDocumentWithEcho() { sourceActiveDocument(true); } private void sourceActiveDocument(final boolean echo) { docDisplay_.focus(); // If the document being sourced is a Shiny file, run the app instead. if (fileType_.isR() && extendedType_.equals("shiny")) { runShinyApp(); return; } // If the document being sourced is a script then use that codepath if (fileType_.isScript()) { runScript(); return; } // If the document is previewable if (fileType_.canPreviewFromR()) { previewFromR(); return; } String code = docDisplay_.getCode(); if (code != null && code.trim().length() > 0) { // R 2.14 prints a warning when sourcing a file with no trailing \n if (!code.endsWith("\n")) code = code + "\n"; boolean sweave = fileType_.canCompilePDF() || fileType_.canKnitToHTML() || fileType_.isRpres(); RnwWeave rnwWeave = compilePdfHelper_.getActiveRnwWeave(); final boolean forceEcho = sweave && (rnwWeave != null) ? rnwWeave.forceEchoOnExec() : false; // NOTE: we always set echo to true for knitr because knitr doesn't // require print statements so if you don't echo to the console // then you don't see any of the output boolean saveWhenSourcing = fileType_.isCpp() || docDisplay_.hasBreakpoints() || (prefs_.saveBeforeSourcing().getValue() && (getPath() != null) && !sweave); if ((dirtyState_.getValue() || sweave) && !saveWhenSourcing) { server_.saveActiveDocument(code, sweave, compilePdfHelper_.getActiveRnwWeaveName(), new SimpleRequestCallback<Void>() { @Override public void onResponseReceived(Void response) { consoleDispatcher_.executeSourceCommand( "~/.active-rstudio-document", fileType_, "UTF-8", activeCodeIsAscii(), forceEcho ? true : echo, true, docDisplay_.hasBreakpoints()); } }); } else { Command sourceCommand = new Command() { @Override public void execute() { if (docDisplay_.hasBreakpoints()) { hideBreakpointWarningBar(); } consoleDispatcher_.executeSourceCommand( getPath(), fileType_, docUpdateSentinel_.getEncoding(), activeCodeIsAscii(), forceEcho ? true : echo, true, docDisplay_.hasBreakpoints()); } }; if (saveWhenSourcing && (dirtyState_.getValue() || (getPath() == null))) saveThenExecute(null, sourceCommand); else sourceCommand.execute(); } } // update pref if necessary if (prefs_.sourceWithEcho().getValue() != echo) { prefs_.sourceWithEcho().setGlobalValue(echo, true); prefs_.writeUIPrefs(); } } private void runShinyApp() { sourceBuildHelper_.withSaveFilesBeforeCommand(new Command() { @Override public void execute() { RStudioGinjector.INSTANCE.getShinyApplication() .launchShinyApplication(getPath()); } }, "Run Shiny Application"); } private void runScript() { saveThenExecute(null, new Command() { @Override public void execute() { String interpreter = fileType_.getScriptInterpreter(); server_.getScriptRunCommand( interpreter, getPath(), new SimpleRequestCallback<String>() { @Override public void onResponseReceived(String cmd) { events_.fireEvent(new SendToConsoleEvent(cmd, true)); } }); } }); } private void previewFromR() { saveThenExecute(null, new Command() { @Override public void execute() { server_.getMinimalSourcePath( getPath(), new SimpleRequestCallback<String>() { @Override public void onResponseReceived(String path) { String cmd = fileType_.createPreviewCommand(path); if (cmd != null) events_.fireEvent(new SendToConsoleEvent(cmd, true)); } }); } }); } private boolean activeCodeIsAscii() { String code = docDisplay_.getCode(); for (int i=0; i< code.length(); i++) { if (code.charAt(i) > 127) return false; } return true; } @Handler void onExecuteLastCode() { docDisplay_.focus(); codeExecution_.executeLastCode(); } @Handler void onKnitDocument() { onPreviewHTML(); } @Handler void onUsingRMarkdownHelp() { if (extendedType_.equals("rmarkdown")) globalDisplay_.openRStudioLink("using_rmarkdown"); else globalDisplay_.openRStudioLink("using_markdown"); } @Handler void onPreviewHTML() { // last ditch extended type detection String extendedType = extendedType_; extendedType = rmarkdownHelper_.detectExtendedType(docDisplay_.getCode(), extendedType, fileType_); if (extendedType == "rmarkdown") renderRmd(); else if (fileType_.isRd()) previewRd(); else if (fileType_.isRpres()) previewRpresentation(); else if (fileType_.isR()) onCompileNotebook(); else previewHTML(); } void previewRpresentation() { SessionInfo sessionInfo = session_.getSessionInfo(); if (!fileTypeCommands_.getHTMLCapabiliites().isRMarkdownSupported()) { globalDisplay_.showMessage( MessageDisplay.MSG_WARNING, "Unable to Preview", "R Presentations require the knitr package " + "(version 1.2 or higher)"); return; } PresentationState state = sessionInfo.getPresentationState(); // if we are showing a tutorial then don't allow preview if (state.isTutorial()) { globalDisplay_.showMessage( MessageDisplay.MSG_WARNING, "Unable to Preview", "R Presentations cannot be previewed when a Tutorial " + "is active"); return; } // if this presentation is already showing then just activate if (state.isActive() && state.getFilePath().equals(docUpdateSentinel_.getPath())) { commands_.activatePresentation().execute(); save(); } // otherwise reload else { saveThenExecute(null, new Command() { @Override public void execute() { server_.showPresentationPane(docUpdateSentinel_.getPath(), new VoidServerRequestCallback()); } }); } } void previewRd() { saveThenExecute(null, new Command() { @Override public void execute() { String previewURL = "help/preview?file="; previewURL += URL.encodeQueryString(docUpdateSentinel_.getPath()); events_.fireEvent(new ShowHelpEvent(previewURL)) ; } }); } void renderRmd() { saveThenExecute(null, new Command() { @Override public void execute() { boolean asTempfile = isPackageDocumentationFile(); rmarkdownHelper_.renderRMarkdown( docUpdateSentinel_.getPath(), docDisplay_.getCursorPosition().getRow() + 1, null, docUpdateSentinel_.getEncoding(), asTempfile, isShinyDoc(), false); } }); } private boolean isShinyDoc() { try { RmdSelectedTemplate template = getSelectedTemplate(); return (template != null) && template.isShiny; } catch(Exception e) { Debug.log(e.getMessage()); return false; } } void previewHTML() { // validate pre-reqs if (!rmarkdownHelper_.verifyPrerequisites(view_, fileType_)) return; doHtmlPreview(new Provider<HTMLPreviewParams>() { @Override public HTMLPreviewParams get() { return HTMLPreviewParams.create(docUpdateSentinel_.getPath(), docUpdateSentinel_.getEncoding(), fileType_.isMarkdown(), fileType_.requiresKnit(), false); } }); } private void doHtmlPreview(final Provider<HTMLPreviewParams> pParams) { // command to show the preview window final Command showPreviewWindowCommand = new Command() { @Override public void execute() { HTMLPreviewParams params = pParams.get(); events_.fireEvent(new ShowHTMLPreviewEvent(params)); } }; // command to run the preview final Command runPreviewCommand = new Command() { @Override public void execute() { final HTMLPreviewParams params = pParams.get(); server_.previewHTML(params, new SimpleRequestCallback<Boolean>()); } }; if (pParams.get().isNotebook()) { saveThenExecute(null, new Command() { @Override public void execute() { generateNotebook(new Command() { @Override public void execute() { showPreviewWindowCommand.execute(); runPreviewCommand.execute(); } }); } }); } // if the document is new and unsaved, then resolve that and then // show the preview window -- it won't activate in web mode // due to popup activation rules but at least it will show up else if (isNewDoc()) { saveThenExecute(null, CommandUtil.join(showPreviewWindowCommand, runPreviewCommand)); } // otherwise if it's dirty then show the preview window first (to // beat the popup blockers) then save & run else if (dirtyState().getValue()) { showPreviewWindowCommand.execute(); saveThenExecute(null, runPreviewCommand); } // otherwise show the preview window then run the preview else { showPreviewWindowCommand.execute(); runPreviewCommand.execute(); } } private void generateNotebook(final Command executeOnSuccess) { // default title String defaultTitle = docUpdateSentinel_.getProperty(NOTEBOOK_TITLE); if (StringUtil.isNullOrEmpty(defaultTitle)) defaultTitle = FileSystemItem.getNameFromPath(docUpdateSentinel_.getPath()); // default author String defaultAuthor = docUpdateSentinel_.getProperty(NOTEBOOK_AUTHOR); if (StringUtil.isNullOrEmpty(defaultAuthor)) { defaultAuthor = prefs_.compileNotebookOptions().getValue().getAuthor(); if (StringUtil.isNullOrEmpty(defaultAuthor)) defaultAuthor = session_.getSessionInfo().getUserIdentity(); } // default type String defaultType = docUpdateSentinel_.getProperty(NOTEBOOK_TYPE); if (StringUtil.isNullOrEmpty(defaultType)) { defaultType = prefs_.compileNotebookOptions().getValue().getType(); if (StringUtil.isNullOrEmpty(defaultType)) defaultType = CompileNotebookOptions.TYPE_DEFAULT; } CompileNotebookOptionsDialog dialog = new CompileNotebookOptionsDialog( getId(), defaultTitle, defaultAuthor, defaultType, new OperationWithInput<CompileNotebookOptions>() { @Override public void execute(CompileNotebookOptions input) { server_.createNotebook( input, new SimpleRequestCallback<CompileNotebookResult>() { @Override public void onResponseReceived(CompileNotebookResult response) { if (response.getSucceeded()) { executeOnSuccess.execute(); } else { globalDisplay_.showErrorMessage( "Unable to Compile Notebook", response.getFailureMessage()); } } }); // save options for this document HashMap<String, String> changedProperties = new HashMap<String, String>(); changedProperties.put(NOTEBOOK_TITLE, input.getNotebookTitle()); changedProperties.put(NOTEBOOK_AUTHOR, input.getNotebookAuthor()); changedProperties.put(NOTEBOOK_TYPE, input.getNotebookType()); docUpdateSentinel_.modifyProperties(changedProperties, null); // save global prefs CompileNotebookPrefs prefs = CompileNotebookPrefs.create( input.getNotebookAuthor(), input.getNotebookType()); if (!CompileNotebookPrefs.areEqual( prefs, prefs_.compileNotebookOptions().getValue())) { prefs_.compileNotebookOptions().setGlobalValue(prefs); prefs_.writeUIPrefs(); } } } ); dialog.showModal(); } @Handler void onCompileNotebook() { if (session_.getSessionInfo().getRMarkdownPackageAvailable()) { saveThenExecute(null, new Command() { @Override public void execute() { rmarkdownHelper_.renderNotebookv2(docUpdateSentinel_); } }); } else { if (!rmarkdownHelper_.verifyPrerequisites("Compile Notebook", view_, FileTypeRegistry.RMARKDOWN)) { return; } doHtmlPreview(new Provider<HTMLPreviewParams>() { @Override public HTMLPreviewParams get() { return HTMLPreviewParams.create(docUpdateSentinel_.getPath(), docUpdateSentinel_.getEncoding(), true, true, true); } }); } } @Handler void onCompilePDF() { String pdfPreview = prefs_.pdfPreview().getValue(); boolean showPdf = !pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_NONE); boolean useInternalPreview = pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_RSTUDIO); boolean useDesktopSynctexPreview = pdfPreview.equals(UIPrefsAccessor.PDF_PREVIEW_DESKTOP_SYNCTEX) && Desktop.isDesktop(); String action = new String(); if (showPdf && !useInternalPreview && !useDesktopSynctexPreview) action = "view_external"; handlePdfCommand(action, useInternalPreview, null); } @Handler void onSynctexSearch() { doSynctexSearch(true); } private void doSynctexSearch(boolean fromClick) { SourceLocation sourceLocation = getSelectionAsSourceLocation(fromClick); if (sourceLocation == null) return; // compute the target pdf FileSystemItem editorFile = FileSystemItem.createFile( docUpdateSentinel_.getPath()); FileSystemItem targetFile = compilePdfHelper_.getTargetFile(editorFile); String pdfFile = targetFile.getParentPath().completePath(targetFile.getStem() + ".pdf"); synctex_.forwardSearch(pdfFile, sourceLocation); } private SourceLocation getSelectionAsSourceLocation(boolean fromClick) { // get doc path (bail if the document is unsaved) String file = docUpdateSentinel_.getPath(); if (file == null) return null; Position selPos = docDisplay_.getSelectionStart(); int line = selPos.getRow() + 1; int column = selPos.getColumn() + 1; return SourceLocation.create(file, line, column, fromClick); } @Handler void onFindReplace() { view_.showFindReplace(true); } @Handler void onFindNext() { view_.findNext(); } @Handler void onFindPrevious() { view_.findPrevious(); } @Handler void onFindSelectAll() { view_.findSelectAll(); } @Handler void onFindFromSelection() { view_.findFromSelection(); docDisplay_.focus(); } @Handler void onReplaceAndFind() { view_.replaceAndFind(); } @Override public Position search(String regex) { return search(Position.create(0, 0), regex); } @Override public Position search(Position startPos, String regex) { InputEditorSelection sel = docDisplay_.search(regex, false, false, false, false, startPos, null, true); if (sel != null) return docDisplay_.selectionToPosition(sel.getStart()); else return null; } @Handler void onFold() { if (useScopeTreeFolding()) { Range range = Range.fromPoints(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); if (range.isEmpty()) { // If no selection, fold the innermost non-anonymous scope ScopeList scopeList = new ScopeList(docDisplay_); scopeList.removeAll(ScopeList.ANON_BRACE); Scope scope = scopeList.findLast(new ContainsFoldPredicate( Range.fromPoints(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()))); if (scope == null) return; docDisplay_.addFoldFromRow(scope.getFoldStart().getRow()); } else { // If selection, fold the selection docDisplay_.addFold(range); } } else { int row = docDisplay_.getSelectionStart().getRow(); docDisplay_.addFoldFromRow(row); } } @Handler void onUnfold() { if (useScopeTreeFolding()) { Range range = Range.fromPoints(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); if (range.isEmpty()) { // If no selection, unfold the closest fold on the current row Position pos = range.getStart(); AceFold startCandidate = null; AceFold endCandidate = null; for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds())) { if (startCandidate == null && f.getStart().getRow() == pos.getRow() && f.getStart().getColumn() >= pos.getColumn()) { startCandidate = f; } if (f.getEnd().getRow() == pos.getRow() && f.getEnd().getColumn() <= pos.getColumn()) { endCandidate = f; } } if (startCandidate == null ^ endCandidate == null) { docDisplay_.unfold(startCandidate != null ? startCandidate : endCandidate); } else if (startCandidate != null) { // Both are candidates; see which is closer int startDelta = startCandidate.getStart().getColumn() - pos.getColumn(); int endDelta = pos.getColumn() - endCandidate.getEnd().getColumn(); docDisplay_.unfold(startDelta <= endDelta? startCandidate : endCandidate); } } else { // If selection, unfold the selection docDisplay_.unfold(range); } } else { int row = docDisplay_.getSelectionStart().getRow(); docDisplay_.unfold(row); } } @Handler void onFoldAll() { if (useScopeTreeFolding()) { // Fold all except anonymous braces HashSet<Integer> rowsFolded = new HashSet<Integer>(); for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds())) rowsFolded.add(f.getStart().getRow()); ScopeList scopeList = new ScopeList(docDisplay_); scopeList.removeAll(ScopeList.ANON_BRACE); for (Scope scope : scopeList) { int row = scope.getFoldStart().getRow(); if (!rowsFolded.contains(row)) docDisplay_.addFoldFromRow(row); } } else { docDisplay_.foldAll(); } } @Handler void onUnfoldAll() { if (useScopeTreeFolding()) { for (AceFold f : JsUtil.asIterable(docDisplay_.getFolds())) docDisplay_.unfold(f); } else { docDisplay_.unfoldAll(); } } boolean useScopeTreeFolding() { return docDisplay_.hasScopeTree() && !fileType_.isRmd(); } void handlePdfCommand(final String completedAction, final boolean useInternalPreview, final Command onBeforeCompile) { if (fileType_.isRnw() && prefs_.alwaysEnableRnwConcordance().getValue()) compilePdfHelper_.ensureRnwConcordance(); // if the document has been previously saved then we should execute // the onBeforeCompile command immediately final boolean isNewDoc = isNewDoc(); if (!isNewDoc && (onBeforeCompile != null)) onBeforeCompile.execute(); saveThenExecute(null, new Command() { public void execute() { // if this was a new doc then we still need to execute the // onBeforeCompile command if (isNewDoc && (onBeforeCompile != null)) onBeforeCompile.execute(); String path = docUpdateSentinel_.getPath(); if (path != null) { String encoding = StringUtil.notNull( docUpdateSentinel_.getEncoding()); fireCompilePdfEvent(path, encoding, completedAction, useInternalPreview); } } }); } private void fireCompilePdfEvent(String path, String encoding, String completedAction, boolean useInternalPreview) { // first validate the path to make sure it doesn't contain spaces FileSystemItem file = FileSystemItem.createFile(path); if (file.getName().indexOf(' ') != -1) { globalDisplay_.showErrorMessage( "Invalid Filename", "The file '" + file.getName() + "' cannot be compiled to " + "a PDF because TeX does not understand paths with spaces. " + "If you rename the file to remove spaces then " + "PDF compilation will work correctly."); return; } CompilePdfEvent event = new CompilePdfEvent( compilePdfHelper_.getTargetFile(file), encoding, getSelectionAsSourceLocation(false), completedAction, useInternalPreview); events_.fireEvent(event); } private Command postSaveCommand() { return new Command() { public void execute() { // fire source document saved event FileSystemItem file = FileSystemItem.createFile( docUpdateSentinel_.getPath()); events_.fireEvent(new SourceFileSaveCompletedEvent( file, docUpdateSentinel_.getContents(), docDisplay_.getCursorPosition())); // check for source on save if (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { if (fileType_.isRd()) { previewRd(); } else if (fileType_.canPreviewFromR()) { previewFromR(); } else { if (docDisplay_.hasBreakpoints()) { hideBreakpointWarningBar(); } consoleDispatcher_.executeSourceCommand( docUpdateSentinel_.getPath(), fileType_, docUpdateSentinel_.getEncoding(), activeCodeIsAscii(), false, false, docDisplay_.hasBreakpoints()); } } } }; } public void checkForExternalEdit() { if (!externalEditCheckInterval_.hasElapsed()) return; externalEditCheckInterval_.reset(); externalEditCheckInvalidation_.invalidate(); // If the doc has never been saved, don't even bother checking if (getPath() == null) return; // If we're in a collaborative session, we rely on it to sync contents // (including saved/unsaved state); otherwise we'd need to (a) distinguish // between "external edits" caused by other people in the session saving // the file (already synced) and true external edits from other // programs/processes, and (b) and figure out what to when > 1 person // gets the "file has changed externally" prompt (even at best this // creates a "last writer wins" race condition) if (docDisplay_ != null && docDisplay_.hasActiveCollabSession()) return; final Invalidation.Token token = externalEditCheckInvalidation_.getInvalidationToken(); server_.checkForExternalEdit( id_, new ServerRequestCallback<CheckForExternalEditResult>() { @Override public void onResponseReceived(CheckForExternalEditResult response) { if (token.isInvalid()) return; if (response.isDeleted()) { if (ignoreDeletes_) return; globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Deleted", "The file " + StringUtil.notNull(docUpdateSentinel_.getPath()) + " has been deleted or moved. " + "Do you want to close this file now?", false, new Operation() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); ignoreDeletes_ = true; // Make sure it stays dirty dirtyState_.markDirty(false); } }, true ); } else if (response.isModified()) { ignoreDeletes_ = false; // Now we know it exists // Use StringUtil.formatDate(response.getLastModified())? if (!dirtyState_.getValue()) { docUpdateSentinel_.revert(); } else { externalEditCheckInterval_.reset(); globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Changed", "The file " + name_.getValue() + " has changed " + "on disk. Do you want to reload the file from " + "disk and discard your unsaved changes?", false, new Operation() { public void execute() { docUpdateSentinel_.revert(); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); docUpdateSentinel_.ignoreExternalEdit(); // Make sure it stays dirty dirtyState_.markDirty(false); } }, true ); } } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private SourcePosition toSourcePosition(Scope func) { Position pos = func.getPreamble(); return SourcePosition.create(pos.getRow(), pos.getColumn()); } private boolean isCursorInTexMode() { if (fileType_.canCompilePDF()) { if (fileType_.isRnw()) { return SweaveFileType.TEX_LANG_MODE.equals( docDisplay_.getLanguageMode(docDisplay_.getCursorPosition())); } else { return true; } } else { return false; } } private boolean isCursorInRMode() { String mode = docDisplay_.getLanguageMode(docDisplay_.getCursorPosition()); if (mode == null) return true; if (mode.equals(TextFileType.R_LANG_MODE)) return true; return false; } private boolean isNewDoc() { return docUpdateSentinel_.getPath() == null; } private CppCompletionContext cppCompletionContext_ = new CppCompletionContext() { @Override public boolean isCompletionEnabled() { return session_.getSessionInfo().getClangAvailable() && (docUpdateSentinel_.getPath() != null) && fileType_.isC(); } @Override public void withUpdatedDoc(final CommandWithArg<String> onUpdated) { docUpdateSentinel_.withSavedDoc(new Command() { @Override public void execute() { onUpdated.execute(docUpdateSentinel_.getPath()); } }); } @Override public void cppCompletionOperation(final CppCompletionOperation operation) { if (isCompletionEnabled()) { withUpdatedDoc(new CommandWithArg<String>() { @Override public void execute(String docPath) { Position pos = docDisplay_.getSelectionStart(); operation.execute(docPath, pos.getRow() + 1, pos.getColumn() + 1); } }); } } @Override public String getDocPath() { if (docUpdateSentinel_ == null) return ""; return docUpdateSentinel_.getPath(); } }; private RCompletionContext rContext_ = new RCompletionContext() { @Override public String getPath() { if (docUpdateSentinel_ == null) return null; else return docUpdateSentinel_.getPath(); } @Override public String getId() { if (docUpdateSentinel_ == null) return null; else return docUpdateSentinel_.getId(); } }; // these methods are public static so that other editing targets which // display source code (but don't inherit from TextEditingTarget) can share // their implementation public static interface PrefsContext { FileSystemItem getActiveFile(); } public static void registerPrefs( ArrayList<HandlerRegistration> releaseOnDismiss, UIPrefs prefs, DocDisplay docDisplay, final SourceDocument sourceDoc) { registerPrefs(releaseOnDismiss, prefs, docDisplay, new PrefsContext() { @Override public FileSystemItem getActiveFile() { String path = sourceDoc.getPath(); if (path != null) return FileSystemItem.createFile(path); else return null; } }); } public static void registerPrefs( ArrayList<HandlerRegistration> releaseOnDismiss, UIPrefs prefs, final DocDisplay docDisplay, final PrefsContext context) { releaseOnDismiss.add(prefs.highlightSelectedLine().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setHighlightSelectedLine(arg); }})); releaseOnDismiss.add(prefs.highlightSelectedWord().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setHighlightSelectedWord(arg); }})); releaseOnDismiss.add(prefs.showLineNumbers().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowLineNumbers(arg); }})); releaseOnDismiss.add(prefs.useSpacesForTab().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { // Makefile always uses tabs FileSystemItem file = context.getActiveFile(); if ((file != null) && ("Makefile".equals(file.getName()) || "Makevars".equals(file.getName()) || "Makevars.win".equals(file.getName()))) { docDisplay.setUseSoftTabs(false); } else { docDisplay.setUseSoftTabs(arg); } }})); releaseOnDismiss.add(prefs.numSpacesForTab().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.setTabSize(arg); }})); releaseOnDismiss.add(prefs.showMargin().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowPrintMargin(arg); }})); releaseOnDismiss.add(prefs.blinkingCursor().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setBlinkingCursor(arg); }})); releaseOnDismiss.add(prefs.printMarginColumn().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.setPrintMarginColumn(arg); }})); releaseOnDismiss.add(prefs.showInvisibles().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowInvisibles(arg); }})); releaseOnDismiss.add(prefs.showIndentGuides().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setShowIndentGuides(arg); }})); releaseOnDismiss.add(prefs.useVimMode().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.setUseVimMode(arg); }})); releaseOnDismiss.add(prefs.codeCompleteOther().bind( new CommandWithArg<String>() { public void execute(String arg) { docDisplay.syncCompletionPrefs(); }})); releaseOnDismiss.add(prefs.alwaysCompleteCharacters().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.syncCompletionPrefs(); }})); releaseOnDismiss.add(prefs.alwaysCompleteDelayMs().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.syncCompletionPrefs(); }})); releaseOnDismiss.add(prefs.enableSnippets().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.syncCompletionPrefs(); }})); releaseOnDismiss.add(prefs.showDiagnosticsOther().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.syncDiagnosticsPrefs(); }})); releaseOnDismiss.add(prefs.diagnosticsOnSave().bind( new CommandWithArg<Boolean>() { @Override public void execute(Boolean arg) { docDisplay.syncDiagnosticsPrefs(); }})); releaseOnDismiss.add(prefs.backgroundDiagnosticsDelayMs().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay.syncDiagnosticsPrefs(); }})); releaseOnDismiss.add(prefs.showInlineToolbarForRCodeChunks().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay.forceImmediateRender(); }})); } public static void syncFontSize( ArrayList<HandlerRegistration> releaseOnDismiss, EventBus events, final TextDisplay view, FontSizeManager fontSizeManager) { releaseOnDismiss.add(events.addHandler( ChangeFontSizeEvent.TYPE, new ChangeFontSizeHandler() { public void onChangeFontSize(ChangeFontSizeEvent event) { view.setFontSize(event.getFontSize()); } })); view.setFontSize(fontSizeManager.getSize()); } public static void onPrintSourceDoc(final DocDisplay docDisplay) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { docDisplay.print(); } }); } public static void addRecordNavigationPositionHandler( ArrayList<HandlerRegistration> releaseOnDismiss, final DocDisplay docDisplay, final EventBus events, final EditingTarget target) { releaseOnDismiss.add(docDisplay.addRecordNavigationPositionHandler( new RecordNavigationPositionHandler() { @Override public void onRecordNavigationPosition( RecordNavigationPositionEvent event) { SourcePosition pos = SourcePosition.create( target.getContext(), event.getPosition().getRow(), event.getPosition().getColumn(), docDisplay.getScrollTop()); events.fireEvent(new SourceNavigationEvent( SourceNavigation.create( target.getId(), target.getPath(), pos))); } })); } public Position screenCoordinatesToDocumentPosition(int pageX, int pageY) { return docDisplay_.screenCoordinatesToDocumentPosition(pageX, pageY); } public DocDisplay getDocDisplay() { return docDisplay_; } private void addAdditionalResourceFiles(ArrayList<String> additionalFiles) { // it does--get the YAML front matter and modify it to include // the additional files named in the deployment String yaml = getRmdFrontMatter(); if (yaml == null) return; rmarkdownHelper_.addAdditionalResourceFiles(yaml, additionalFiles, new CommandWithArg<String>() { @Override public void execute(String yamlOut) { if (yamlOut != null) { applyRmdFrontMatter(yamlOut); } } }); } private void syncPublishPath(String path) { // if we have a view, a type, and a path, sync the view's content publish // path to the new content path--note that we need to do this even if the // document isn't currently of a publishable type, since it may become // publishable once saved. if (view_ != null && path != null) { view_.setPublishPath(extendedType_, path); } } private StatusBar statusBar_; private final DocDisplay docDisplay_; private final UIPrefs prefs_; private Display view_; private final Commands commands_; private SourceServerOperations server_; private EventBus events_; private final GlobalDisplay globalDisplay_; private final FileDialogs fileDialogs_; private final FileTypeRegistry fileTypeRegistry_; private final FileTypeCommands fileTypeCommands_; private final ConsoleDispatcher consoleDispatcher_; private final WorkbenchContext workbenchContext_; private final Session session_; private final Synctex synctex_; private final FontSizeManager fontSizeManager_; private final SourceBuildHelper sourceBuildHelper_; private DocUpdateSentinel docUpdateSentinel_; private Value<String> name_ = new Value<String>(null); private TextFileType fileType_; private String id_; private HandlerRegistration commandHandlerReg_; private ArrayList<HandlerRegistration> releaseOnDismiss_ = new ArrayList<HandlerRegistration>(); private final DirtyState dirtyState_; private HandlerManager handlers_ = new HandlerManager(this); private FileSystemContext fileContext_; private final TextEditingTargetCompilePdfHelper compilePdfHelper_; private final TextEditingTargetRMarkdownHelper rmarkdownHelper_; private final TextEditingTargetCppHelper cppHelper_; private final TextEditingTargetPresentationHelper presentationHelper_; private final TextEditingTargetReformatHelper reformatHelper_; private RoxygenHelper roxygenHelper_; private boolean ignoreDeletes_; private boolean forceSaveCommandActive_ = false; private final TextEditingTargetScopeHelper scopeHelper_; private TextEditingTargetSpelling spelling_; private BreakpointManager breakpointManager_; private final LintManager lintManager_; private final SnippetHelper snippets_; private CollabEditStartParams queuedCollabParams_; // Allows external edit checks to supercede one another private final Invalidation externalEditCheckInvalidation_ = new Invalidation(); // Prevents external edit checks from happening too soon after each other private final IntervalTracker externalEditCheckInterval_ = new IntervalTracker(1000, true); private final EditingTargetCodeExecution codeExecution_; private SourcePosition debugStartPos_ = null; private SourcePosition debugEndPos_ = null; private boolean isDebugWarningVisible_ = false; private boolean isBreakpointWarningVisible_ = false; private String extendedType_; private abstract class RefactorServerRequestCallback extends ServerRequestCallback<JsArrayString> { private final String refactoringName_; public RefactorServerRequestCallback(String refactoringName) { refactoringName_ = refactoringName; } @Override public void onResponseReceived(final JsArrayString response) { doExtract(response); } @Override public void onError(ServerError error) { globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, refactoringName_, "The selected code could not be " + "parsed.\n\n" + "Are you sure you want to continue?", new Operation() { public void execute() { doExtract(null); } }, false); } abstract void doExtract(final JsArrayString response); } }
package com.gooddata.connector; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.gooddata.connector.AbstractConnector; import org.gooddata.connector.Connector; import org.gooddata.connector.backend.ConnectorBackend; import com.gooddata.exception.ModelException; import com.gooddata.exception.ProcessingException; import com.gooddata.modeling.model.SourceColumn; import com.gooddata.modeling.model.SourceSchema; import com.gooddata.processor.CliParams; import com.gooddata.processor.Command; import com.gooddata.processor.ProcessingContext; import com.gooddata.util.FileUtil; import com.gooddata.util.StringUtil; /** * GoodData CSV Connector * * @author zd <zd@gooddata.com> * @version 1.0 */ public class CsvConnector extends AbstractConnector implements Connector { // data file private File dataFile; private boolean hasHeader; /** * Creates GoodData CSV connector * @param backend connector backend */ protected CsvConnector(ConnectorBackend backend) { super(backend); } /** * Create a new GoodData CSV connector. This constructor creates the connector from a config file * @param backend connector backend * @return new CSV Connector */ public static CsvConnector createConnector(ConnectorBackend backend) { return new CsvConnector(backend); } /** * Saves a template of the config file * @param configFileName the new config file name * @param dataFileName the data file * @throws IOException in case of an IO error */ public static void saveConfigTemplate(String configFileName, String dataFileName) throws IOException { saveConfigTemplate(configFileName, dataFileName, null, null); } /** * Saves a template of the config file * @param configFileName the new config file name * @param dataFileName the data file * @param defaultLdmType default LDM type * @param folder default folder * @throws IOException in case of an IO issue */ public static void saveConfigTemplate(String configFileName, String dataFileName, String defaultLdmType, String folder) throws IOException { File dataFile = new File(dataFileName); String name = dataFile.getName().split("\\.")[0]; String[] headers = FileUtil.getCsvHeader(dataFile); int i = 0; final SourceSchema s; File configFile = new File(configFileName); if (configFile.exists()) { s = SourceSchema.createSchema(configFile); } else { s = SourceSchema.createSchema(name); } final int knownColumns = s.getColumns().size(); NameTransformer idGen = new NameTransformer(new NameTransformerCallback() { public String transform(String str) { return StringUtil.csvHeaderToIdentifier(str); } }); NameTransformer titleGen = new NameTransformer(new NameTransformerCallback() { public String transform(String str) { return StringUtil.csvHeaderToTitle(str); } }); for(int j = knownColumns; j < headers.length; j++) { final String header = headers[j]; final SourceColumn sc; final String identifier = idGen.transform(header); final String title = titleGen.transform(header); if (defaultLdmType != null) { sc = new SourceColumn(identifier, defaultLdmType, title, folder); } else { switch (i %3) { case 0: sc = new SourceColumn(identifier, SourceColumn.LDM_TYPE_ATTRIBUTE, title, "folder"); break; case 1: sc = new SourceColumn(identifier, SourceColumn.LDM_TYPE_FACT, title, "folder"); break; case 2: sc = new SourceColumn(identifier, SourceColumn.LDM_TYPE_LABEL, title, "folder", "existing-attribute-name"); break; default: throw new AssertionError("i % 3 outside {0, 1, 2} - this cannot happen"); } } s.addColumn(sc); i++; } s.writeConfig(new File(configFileName)); } /** * Data CSV file getter * @return the data CSV file */ public File getDataFile() { return dataFile; } /** * Data CSV file setter * @param dataFile the data CSV file */ public void setDataFile(File dataFile) { this.dataFile = dataFile; } /** * Extracts the source data CSV to the Derby database where it is going to be transformed * @throws ModelException in case of PDM schema issues */ public void extract() throws ModelException, IOException { if(getHasHeader()) { File tmp = FileUtil.stripCsvHeader(getDataFile()); getConnectorBackend().extract(tmp); tmp.delete(); } } /** * hasHeader getter * @return hasHeader flag */ public boolean getHasHeader() { return hasHeader; } /** * hasHeader setter * @param hasHeader flag value */ public void setHasHeader(boolean hasHeader) { this.hasHeader = hasHeader; } /** * {@inheritDoc} */ public boolean processCommand(Command c, CliParams cli, ProcessingContext ctx) throws ProcessingException { try { if(c.match("GenerateCsvConfig")) { generateCsvConfig(c, cli, ctx); } else if(c.match("LoadCsv")) { loadCsv(c, cli, ctx); } else return super.processCommand(c, cli, ctx); } catch (IOException e) { throw new ProcessingException(e); } return true; } /** * Loads new CSV file command processor * @param c command * @param p command line arguments * @param ctx current processing context * @throws IOException in case of IO issues */ private void loadCsv(Command c, CliParams p, ProcessingContext ctx) throws IOException { String configFile = c.getParamMandatory("configFile"); String csvDataFile = c.getParamMandatory("csvDataFile"); String hdr = c.getParamMandatory("header"); File conf = FileUtil.getFile(configFile); File csvf = FileUtil.getFile(csvDataFile); boolean hasHeader = false; if(hdr.equalsIgnoreCase("true")) hasHeader = true; initSchema(conf.getAbsolutePath()); setDataFile(new File(csvf.getAbsolutePath())); setHasHeader(hasHeader); // sets the current connector ctx.setConnector(this); setProjectId(ctx); } /** * Generate new config file from CSV command processor * @param c command * @param p command line arguments * @param ctx current processing context * @throws IOException in case of IO issues */ private void generateCsvConfig(Command c, CliParams p, ProcessingContext ctx) throws IOException { String configFile = c.getParamMandatory("configFile"); String csvHeaderFile = c.getParamMandatory("csvHeaderFile"); File cf = new File(configFile); File csvf = FileUtil.getFile(csvHeaderFile); CsvConnector.saveConfigTemplate(configFile, csvHeaderFile); } private static class NameTransformer { private final NameTransformerCallback cb; private final Set<String> seen = new HashSet<String>(); public NameTransformer(NameTransformerCallback cb) { this.cb = cb; } public String transform(String str) { int index = 0; String transformed = cb.transform(str); while (true) { String result = transformed; if (index > 0) { result += " " + index; } index++; if (!seen.contains(result)) { seen.add(result); return result; } } } } private interface NameTransformerCallback { public String transform(String str); } }
package com.github.onsdigital.babbage.template.handlebars.helpers.resolve; import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Options; import com.github.onsdigital.babbage.api.util.SearchUtils; import com.github.onsdigital.babbage.content.client.ContentClient; import com.github.onsdigital.babbage.content.client.ContentFilter; import com.github.onsdigital.babbage.content.client.ContentResponse; import com.github.onsdigital.babbage.request.handler.TimeseriesLandingRequestHandler; import com.github.onsdigital.babbage.search.model.SearchResult; import com.github.onsdigital.babbage.template.handlebars.helpers.base.BabbageHandlebarsHelper; import com.github.onsdigital.babbage.util.URIUtil; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.github.onsdigital.babbage.content.client.ContentClient.depth; import static com.github.onsdigital.babbage.content.client.ContentClient.filter; import static com.github.onsdigital.babbage.util.json.JsonUtil.toList; import static com.github.onsdigital.babbage.util.json.JsonUtil.toMap; public enum DataHelpers implements BabbageHandlebarsHelper<Object> { /** * usage: {{#resolve "uri" [filter=] [assign=variableName]}} * <p> * If variableName is not empty data is assigned to given variable name */ resolve { @Override public CharSequence apply(Object uri, Options options) throws IOException { ContentResponse contentResponse; try { validateUri(uri); String uriString = (String) uri; if (TimeseriesLandingRequestHandler.isTimeseriesLandingUri(uriString)) { uriString = TimeseriesLandingRequestHandler.getLatestTimeseriesUri(uriString); } ContentFilter filter = null; String filterVal = options.<String>hash("filter"); if (filterVal != null) { filter = ContentFilter.valueOf(filterVal.toUpperCase()); } contentResponse = ContentClient.getInstance().getContent(uriString, filter(filter)); InputStream data = contentResponse.getDataStream(); Map<String, Object> context = toMap(data); assign(options, context); return options.fn(context); } catch (Exception e) { logResolveError(uri, e); return options.inverse(); } } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }, /** * usage: {{#resolve "uri" [filter=] [assign=variableName]}} * <p> * If variableName is not empty data is assigned to given variable name */ resolveTimeSeriesList { @Override public CharSequence apply(Object uri, Options options) throws IOException { try { validateUri(uri); String uriString = (String) uri; HashMap<String, SearchResult> results = SearchUtils.searchTimeseriesForUri(uriString); LinkedHashMap<String, Object> data = SearchUtils.buildResults("list", results); assign(options, data); return options.fn(data); } catch (Exception e) { logResolveError(uri, e); return options.inverse(); } } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }, //Resolve latest article or bulletin with given uri resolveLatest { @Override public CharSequence apply(Object uri, Options options) throws IOException { ContentResponse contentResponse = null; try { validateUri(uri); String uriString = (String) uri; String s = URIUtil.removeLastSegment(uriString) + "/latest"; ContentFilter filter = null; String filterVal = options.<String>hash("filter"); if (filterVal != null) { filter = ContentFilter.valueOf(filterVal.toUpperCase()); } contentResponse = ContentClient.getInstance().getContent(s, filter(filter)); InputStream data = contentResponse.getDataStream(); Map<String, Object> context = toMap(data); assign(options, context); return options.fn(context); } catch (Exception e) { logResolveError(uri, e); return options.inverse(); } } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }, /** * usage: {{#resolveTaxonomy [depth=depthvalue] [assign=variableName]} * <p> * If assign is not empty data is assigned to given variable name */ resolveTaxonomy { @Override public CharSequence apply(Object uri, Options options) throws IOException { ContentResponse stream = null; try { Integer depth = options.<Integer>hash("depth"); stream = ContentClient.getInstance().getTaxonomy(depth(depth)); InputStream data = stream.getDataStream(); List<Map<String, Object>> context = toList(data); assign(options, context); return options.fn(context); } catch (Exception e) { logResolveError(uri, e); return options.inverse(); } } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }, /** * Resolves resource file as string, if a file can not be resolved as a string, this will not work * usage: {{#resolveResource [depth=depthvalue] [assign=variableName]} * <p> * If assign is not empty data is assigned to given variable name */ resolveResource { @Override public CharSequence apply(Object uri, Options options) throws IOException { ContentResponse contentResponse = null; try { validateUri(uri); String uriString = (String) uri; contentResponse = ContentClient.getInstance().getResource(uriString); String data = contentResponse.getAsString(); Map<String, Object> context = new LinkedHashMap<>(); context.put("resource", data); assign(options, context); return options.fn(context); } catch (Exception e) { logResolveError(uri, e); return options.inverse(); } } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }, /** * usage: {{#resolveParents "variableName" "uri"}} * <p> * If variableName is not empty data is assigned to given variable name */ resolveParents { @Override public CharSequence apply(Object uri, Options options) throws IOException { ContentResponse stream = null; try { validateUri(uri); String uriString = (String) uri; stream = ContentClient.getInstance().getParents(uriString); InputStream data = stream.getDataStream(); List<Map<String, Object>> context = toList(data); assign(options, context); return options.fn(context); } catch (Exception e) { logResolveError(uri, e); return options.inverse(); } } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }, /** * File size helper reads file size from content service */ fs { @Override public CharSequence apply(Object uri, Options options) throws IOException { if (options.isFalsy(uri)) { return null; } String uriString = (String) uri; try { ContentResponse stream = ContentClient.getInstance().getFileSize(uriString); Map<String, Object> size = toMap(stream.getDataStream()); return humanReadableByteCount(((Number) size.get("fileSize")).longValue(), true); } catch (Exception e) { System.err.printf("Failed reading file size from content service, uri: %s cause: %s", uri, e.getMessage()); e.printStackTrace(); return null; } } private String humanReadableByteCount(Long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } @Override public void register(Handlebars handlebars) { handlebars.registerHelper(this.name(), this); } }; //gets first parameter as uri, throws exception if not valid private static void validateUri(Object uri) throws IOException { if (uri == null) { throw new IllegalArgumentException("Data Helpers: No uri given for resolving"); } } /** * Assigns data to current context if assign parameter given * * @param options * @param data */ private static void assign(Options options, Object data) { String variableName = options.hash("assign"); if (StringUtils.isNotEmpty(variableName)) { options.context.data(variableName, data); } } private static void logResolveError(Object uri, Exception e) { System.err.printf("Failed resolving data, uri: %s cause: %s", uri, e.getMessage()); //e.printStackTrace(); } }
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.StringField; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BooleanQuery.Builder; import org.apache.lucene.search.ControlledRealTimeReopenThread; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.SearcherManager; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.store.SimpleFSDirectory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Base64; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; /** * Persistent Map implementation based on Lucene */ public class LuceneMap<K extends Serializable, V extends Serializable> implements Map { private static final Logger log = Logger.getLogger(LuceneMap.class.getName()); private static final String VALUE_FIELD = "value"; private static final String KEY_FIELD = "key"; public LuceneMap() { this("lucenemap"); } public LuceneMap(boolean inMemory) { this(null, inMemory); } public LuceneMap(String folderUrl) { this(folderUrl, false); } public LuceneMap(String folderUrl, boolean inMemory) { Analyzer analyzer = new StandardAnalyzer(); IndexWriterConfig writerConfig = new IndexWriterConfig(analyzer); writerConfig.setCommitOnClose(true); writerConfig.setOpenMode(OpenMode.CREATE_OR_APPEND); int numDocs; try { Directory directory; if (!inMemory) { File folder = new File(folderUrl); if (!folder.exists()) { folder.mkdir(); } directory = new SimpleFSDirectory(folder.toPath()); } else { directory = new RAMDirectory(); } writer = new IndexWriter(directory, writerConfig); numDocs = writer.numDocs(); searcherManager = new SearcherManager(writer, true, true, null); log.info("Map loaded, size: " + numDocs); } catch (IOException e) { throw new RuntimeException(e); } ControlledRealTimeReopenThread<IndexSearcher> nrtReopenThread = new ControlledRealTimeReopenThread<>( writer, searcherManager, 1.0, 0.1); nrtReopenThread.setName("NRT Reopen Thread"); nrtReopenThread.setDaemon(true); nrtReopenThread.start(); } private IndexWriter writer; private SearcherManager searcherManager; /** * Read the object from Base64 string. */ private Object fromString(String s) throws IOException, ClassNotFoundException { byte[] data = Base64.getDecoder().decode(s); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data)); Object o = ois.readObject(); ois.close(); return o; } /** * Write the object to a Base64 string. */ private String toString(Serializable o) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); oos.close(); return Base64.getEncoder().encodeToString(baos.toByteArray()); } public Optional<V> lookup(Object key, boolean refresh) { K k = (K) key; try { Optional<V> result = Optional.empty(); Optional<Document> doc = document(this.toString(k), refresh); if (doc.isPresent()) { result = Optional.of((V) fromString(doc.get().get(VALUE_FIELD))); } return result; } catch (ClassNotFoundException | IOException e) { throw new RuntimeException(e); } } private Optional<Document> document(String id, boolean refresh) { Builder builder = new BooleanQuery.Builder(); builder.add(new TermQuery(new Term(KEY_FIELD, id)), Occur.MUST); return loadDoc(builder.build(), refresh); } private Optional<Document> loadDoc(Query q, boolean refresh) { Optional<Document> d = Optional.empty(); try { if (refresh) this.searcherManager.maybeRefresh(); IndexSearcher searcher = this.searcherManager.acquire(); try { TopDocs docs = searcher.search(q, 1); if (docs.scoreDocs.length > 0) { Document document = searcher.doc(docs.scoreDocs[0].doc); if (document != null) { d = Optional.of(document); } } } finally { this.searcherManager.release(searcher); } } catch (IOException e) { throw new RuntimeException(e); } return d; } private void save(K key, V val) { try { Document doc = new Document(); String valueString = this.toString(val); String keyString = this.toString(key); StringField valueField = new StringField(VALUE_FIELD, valueString, Store.YES); StringField keyField = new StringField(KEY_FIELD, keyString, Store.YES); doc.add(keyField); doc.add(valueField); writer.updateDocument(new Term(KEY_FIELD, keyString), doc); } catch (IOException e) { throw new RuntimeException(e); } } @Override public int size() { int indexSize; try { this.searcherManager.maybeRefresh(); IndexSearcher searcher = this.searcherManager.acquire(); try { indexSize = searcher.getIndexReader().numDocs(); } finally { this.searcherManager.release(searcher); } } catch (IOException e) { throw new RuntimeException(e); } return indexSize; } @Override public boolean isEmpty() { return size() <= 0; } @Override public boolean containsKey(Object o) { return lookup(o, true).isPresent(); } @Override public boolean containsValue(Object o) { try { Builder builder = new BooleanQuery.Builder(); V v = (V) o; builder.add(new TermQuery(new Term(VALUE_FIELD, this.toString(v))), Occur.MUST); return loadDoc(builder.build(), true).isPresent(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Object get(Object o) { Optional<V> val = this.lookup(o, true); if (val.isPresent()) { return val.get(); } else { return null; } } @Override public Object put(Object o, Object o2) { Optional<V> val = this.lookup(o, false); K k = (K) o; V v = (V) o2; this.save(k, v); return val.isPresent() ? val.get() : null; } @Override public Object remove(Object o) { Object old = this.get(o); try { K k = (K) o; writer.deleteDocuments(new Term(KEY_FIELD, this.toString(k))); } catch (IOException e) { throw new RuntimeException(e); } return old; } @Override public void putAll(Map map) { map.keySet().forEach(k -> this.put(k, map.get(k))); } @Override public void clear() { try { this.writer.deleteAll(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Set<K> keySet() { return entrySet().stream().map(e -> e.getKey()).collect(Collectors.toSet()); } @Override public Collection<V> values() { return entrySet().stream().map(e -> e.getValue()).collect(Collectors.toList()); } @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> entries = new HashSet<>(); try { this.searcherManager.maybeRefresh(); IndexSearcher searcher = this.searcherManager.acquire(); try { IndexReader reader = searcher.getIndexReader(); for (int i = 0; i < reader.maxDoc(); i++) { Document doc = reader.document(i); V v = (V) this.fromString(doc.get(VALUE_FIELD)); K k = (K) this.fromString(doc.get(KEY_FIELD)); entries.add(new Entry<K, V>() { @Override public K getKey() { return k; } @Override public V getValue() { return v; } @Override public V setValue(V v) { return v; } }); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } finally { this.searcherManager.release(searcher); } } catch (IOException e) { throw new RuntimeException(e); } return entries; } }
package gov.nih.nci.calab.dto.administration; /** * This class represents all properties of a sample that need to be viewed and * saved. * * @author pansu * */ /* CVS $Id: SampleBean.java,v 1.2 2006-03-28 22:59:36 pansu Exp $ */ public class SampleBean { private String sampleId; private String sampleType; private String sampleSOP; private String sampleDescription; private String sampleSource; private String sourceSampleId; private String dateReceived; private String lotId; private String lotDescription; private String solubility; private String numberOfContainers; private String generalComments; private String sampleSubmitter; private String accessionDate; private ContainerBean[] containers; public SampleBean(String sampleId, String sampleType, String sampleSOP, String sampleDescription, String sampleSource, String sourceSampleId, String dateReceived, String solubility, String lotId, String lotDescription, String numberOfContainers, String generalComments, String sampleSubmitter, String accessionDate, ContainerBean[] containers) { super(); // TODO Auto-generated constructor stub this.sampleId = sampleId; this.sampleType = sampleType; this.sampleSOP = sampleSOP; this.sampleDescription = sampleDescription; this.sampleSource = sampleSource; this.sourceSampleId = sourceSampleId; this.dateReceived = dateReceived; this.lotId = lotId; this.lotDescription = lotDescription; this.solubility = solubility; this.numberOfContainers = numberOfContainers; this.generalComments = generalComments; this.sampleSubmitter = sampleSubmitter; this.accessionDate=accessionDate; this.containers = containers; } public String getDateReceived() { return dateReceived; } public String getAccessionDate() { return accessionDate; } public void setAccessionDate(String accessionDate) { this.accessionDate = accessionDate; } public void setDateReceived(String dateReceived) { this.dateReceived = dateReceived; } public String getGeneralComments() { return generalComments; } public void setGeneralComments(String generalComments) { this.generalComments = generalComments; } public String getLotDescription() { return lotDescription; } public void setLotDescription(String lotDescription) { this.lotDescription = lotDescription; } public String getLotId() { return lotId; } public void setLotId(String lotId) { this.lotId = lotId; } public String getNumberOfContainers() { return numberOfContainers; } public void setNumberOfContainers(String numberOfContainers) { this.numberOfContainers = numberOfContainers; } public String getSampleDescription() { return sampleDescription; } public void setSampleDescription(String sampleDescription) { this.sampleDescription = sampleDescription; } public String getSampleId() { return sampleId; } public void setSampleId(String sampleId) { this.sampleId = sampleId; } public String getSampleSOP() { return sampleSOP; } public void setSampleSOP(String sampleSOP) { this.sampleSOP = sampleSOP; } public String getSampleType() { return sampleType; } public void setSampleType(String sampleType) { this.sampleType = sampleType; } public String getSolubility() { return solubility; } public void setSolubility(String solubility) { this.solubility = solubility; } public String getSampleSource() { return sampleSource; } public void setSampleSource(String sampleSource) { this.sampleSource = sampleSource; } public String getSourceSampleId() { return sourceSampleId; } public void setSourceSampleId(String sourceSampleId) { this.sourceSampleId = sourceSampleId; } public String getSampleSubmitter() { return sampleSubmitter; } public void setSampleSubmitter(String sampleSubmitter) { this.sampleSubmitter = sampleSubmitter; } public ContainerBean[] getContainers() { return containers; } public void setContainers(ContainerBean[] containers) { this.containers = containers; } }
package gov.nih.nci.calab.dto.search; import gov.nih.nci.calab.dto.administration.AliquotBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.dto.workflow.FileBean; import gov.nih.nci.calab.dto.workflow.RunBean; /** * This class includes all properties of a workflow to be displayed in the * search workflow result page. * * @author pansu * */ public class WorkflowResultBean { private FileBean file; private AssayBean assay; private AliquotBean aliquot; private RunBean run; public WorkflowResultBean(String filePath, String assayType, String assayName, String assayRunName, String assayRunDate, String aliquotName, String fileSubmissionDate, String fileSubmitter, String fileMaskStatus, String inoutType) { super(); // TODO Auto-generated constructor stub this.file=new FileBean(filePath, fileSubmissionDate, fileSubmitter, fileMaskStatus, inoutType); this.assay=new AssayBean(assayName, assayType); this.run=new RunBean("", assayRunName, assayRunDate); this.aliquot=new AliquotBean(aliquotName); } public AliquotBean getAliquot() { return aliquot; } public void setAliquot(AliquotBean aliquot) { this.aliquot = aliquot; } public AssayBean getAssay() { return assay; } public void setAssay(AssayBean assay) { this.assay = assay; } public FileBean getFile() { return file; } public void setFile(FileBean file) { this.file = file; } public RunBean getRun() { return run; } public void setRun(RunBean run) { this.run = run; } }
package ru.ncedu.tlt.controllers; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Singleton; import javax.ejb.LocalBean; import ru.ncedu.tlt.entity.User; import ru.ncedu.tlt.hash.HashGenerator; import ru.ncedu.tlt.properties.PropertiesCB; /** * * @author Andrew */ @Singleton @LocalBean public class UserController { @EJB HashGenerator hg; Connection connection; public UserController() { } public User createUser(User user) { user.setHash(hg.getHash(user.getPass())); user.setPass(""); System.out.println("getted userhash"); PreparedStatement preparedStatement = null; String insertTableSQL = "INSERT INTO CB_USER" + "(USERMAIL, USERPASSHASH, USERSALT, USERNAME, USERNOTES, USERPIC) VALUES" + "(?,?,?,?,?,?)"; try { connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL); preparedStatement = connection.prepareStatement(insertTableSQL); preparedStatement.setString(1, user.getEmail()); preparedStatement.setString(2, user.getHash()); preparedStatement.setString(3, "user.getSalt"); preparedStatement.setString(4, user.getName()); preparedStatement.setString(5, "user.getNotes"); preparedStatement.setString(6, "user.getPic"); // execute insert SQL stetement preparedStatement.executeUpdate(); System.out.println("retriving new id for user"); // ResultSet rs = preparedStatement.getGeneratedKeys(); // if (rs.next()) { // System.out.println("rs int " + rs.getInt(1)); // user.setId(rs.getInt(1)); System.out.println("Record is inserted into CB_USER table!"); } catch (SQLException e) { System.out.println(e.getMessage()); return null; } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (connection != null) { try { connection.close(); } catch (SQLException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } } return user; } // Add business logic below. (Right-click in editor and choose // "Insert Code > Add Business Method") public User findUser(String userName) throws SQLException { User user = null; connection = DriverManager.getConnection(PropertiesCB.CB_JDBC_URL); PreparedStatement preparedStatement = null; String query = "SELECT * FROM CB_USER WHERE USERNAME = ?"; System.out.println("trying to find user by name " + userName); try { preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, userName); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { user = new User(); user.setId(rs.getInt("USERID")); user.setName(rs.getString("USERNAME")); user.setEmail(rs.getString("USERMAIL")); user.setHash(rs.getString("USERPASSHASH")); user.setNote(rs.getString("USERNOTES")); user.setPicPath(rs.getString("USERPIC")); } } catch (Exception e) { System.out.println("findUser " + e.getMessage()); return null; } finally { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } return user; } public boolean login(User user) { return hg.checkHash(user.getPass(), user.getHash()); } }
package com.jpaquery.core.impl; import java.sql.Timestamp; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import com.jpaquery.core.facade.And; import com.jpaquery.core.facade.Group; import com.jpaquery.core.facade.GroupPath; import com.jpaquery.core.facade.Having; import com.jpaquery.core.facade.HavingPath; import com.jpaquery.core.facade.Join; import com.jpaquery.core.facade.JoinPath; import com.jpaquery.core.facade.JpaQuery; import com.jpaquery.core.facade.JpaQueryEach; import com.jpaquery.core.facade.Or; import com.jpaquery.core.facade.Order; import com.jpaquery.core.facade.OrderPath; import com.jpaquery.core.facade.Select; import com.jpaquery.core.facade.SelectPath; import com.jpaquery.core.facade.SubJpaQuery; import com.jpaquery.core.facade.SubJpaQuery.SubJpaQueryType; import com.jpaquery.core.facade.Where; import com.jpaquery.core.facade.WherePath; import com.jpaquery.core.render.JpaQueryRender; import com.jpaquery.core.vo.EntityInfo; import com.jpaquery.core.vo.FromInfo; import com.jpaquery.core.vo.PathInfo; import com.jpaquery.core.vo.QueryContent; import com.jpaquery.util._Helper; import com.jpaquery.util._MergeMap; /** * Finder * * @author lujijiang * */ public class JpaQueryImpl implements JpaQuery { private static final Logger logger = LoggerFactory.getLogger(JpaQueryImpl.class); /** * each */ private static final int EACH_SIZE = 100; List<JpaQueryImpl> subFinderImpls = new ArrayList<>(); /** * finder */ JpaQueryHandler finderHandler; /** * finder */ Map<Long, FromInfo> parentFromInfos = new _MergeMap<>(); /** * finder */ Map<Long, FromInfo> currentFromInfos = new _MergeMap<>(); /** * finder */ JpaQueryRender finderRender; /** * select */ SelectImpl selectImpl; /** * finderwhere */ WhereImpl whereImpl; /** * order */ OrderImpl orderImpl; /** * group */ GroupImpl groupImpl; /** * having */ HavingImpl havingImpl; /** * join */ JoinImpl joinImpl; /** * finder */ private JpaQueryImpl parentFinder; public List<JpaQueryImpl> getSubFinderImpls() { return subFinderImpls; } public JpaQueryHandler getFinderHandler() { return finderHandler; } public Map<Long, FromInfo> getParentFromInfos() { return parentFromInfos; } public Map<Long, FromInfo> getCurrentFromInfos() { return currentFromInfos; } public JpaQueryRender getFinderRender() { return finderRender; } public SelectImpl getSelectImpl() { return selectImpl; } public WhereImpl getWhereImpl() { return whereImpl; } public OrderImpl getOrderImpl() { return orderImpl; } public GroupImpl getGroupImpl() { return groupImpl; } public HavingImpl getHavingImpl() { return havingImpl; } public JoinImpl getJoinImpl() { return joinImpl; } public JpaQueryImpl(JpaQueryHandler finderHandler, JpaQueryRender finderRender) { this.finderHandler = finderHandler; this.finderRender = finderRender; selectImpl = new SelectImpl(finderHandler, this, new _MergeMap<Long, EntityInfo<?>>()); whereImpl = new WhereImpl(finderHandler, this, Where.WhereType.and, new _MergeMap<Long, EntityInfo<?>>()); orderImpl = new OrderImpl(finderHandler, this); groupImpl = new GroupImpl(finderHandler, this); havingImpl = new HavingImpl(finderHandler, this); joinImpl = new JoinImpl(finderHandler, this); } public JpaQuery subJpaQuery() { JpaQueryImpl subFinderImpl = new JpaQueryImpl(finderHandler, finderRender); subFinderImpl.parentFinder = this; subFinderImpl.getParentFromInfos().putAll(getCurrentFromInfos()); subFinderImpl.getParentFromInfos().putAll(getParentFromInfos()); subFinderImpls.add(subFinderImpl); return subFinderImpl; } public <T> T from(Class<T> type) { T proxy = finderHandler.proxy(null, type); EntityInfo<T> entityInfo = new EntityInfo<T>(finderHandler, type, proxy); FromInfo fromInfo = new FromInfo(entityInfo); getCurrentFromInfos().put(entityInfo.getKey(), fromInfo); return proxy; } public Where where() { return whereImpl; } public <T> WherePath<T> where(T obj) { return where().get(obj); } public Select select() { return selectImpl; } public <T> SelectPath<T> select(T obj) { return select().get(obj); } public Order order() { return orderImpl; } public OrderPath order(Object obj) { return order().get(obj); } public Group group() { return groupImpl; } public GroupPath group(Object obj) { return group().get(obj); } public Having having() { return havingImpl; } public <T> HavingPath<T> having(T obj) { return having().get(obj); } public Join join() { return joinImpl; } public <T> JoinPath<T> join(Collection<T> list) { return join().get(list); } public <T> JoinPath<T> join(T obj) { return join().get(obj); } public <T> Where on(T join) { JoinPathImpl<?> joinPathImpl = joinImpl.getJoinPathMap().get(_Helper.identityHashCode(join)); if (joinPathImpl == null) { throw new IllegalStateException(String.format("%s Finder%sJoin", this, join)); } return joinPathImpl.getWhereImpl(); } /** * QueryContent * * @param countSwich * * @return */ private QueryContent toQueryContent(boolean countSwich) { if (parentFinder == null) { finderHandler.resetParamIndex(); } QueryContent queryContent = new QueryContent(); // select QueryContent selectQueryContent = selectImpl.toQueryContent(); if (selectQueryContent != null) { if (countSwich) { queryContent.append("select count("); queryContent.append(finderRender.toSelectCount(this, selectImpl)); queryContent.append(")"); } else { queryContent.append("select "); queryContent.append(selectQueryContent); } } else { if (countSwich) { queryContent.append("select count(*) "); } } // from QueryContent fromQueryContent = finderRender.toFrom(this); if (fromQueryContent != null) { if (queryContent.length() > 0) { queryContent.append(" "); } queryContent.append("from "); queryContent.append(fromQueryContent); } else { throw new IllegalStateException("Must be exist from statement query"); } // where QueryContent whereQueryContent = whereImpl.toQueryContent(); if (whereQueryContent != null) { queryContent.append(" where "); queryContent.append(whereQueryContent); } // group QueryContent groupQueryContent = groupImpl.toQueryContent(); if (groupQueryContent != null) { queryContent.append(" group by "); queryContent.append(groupQueryContent); } // having QueryContent havingQueryContent = havingImpl.toQueryContent(); if (havingQueryContent != null) { queryContent.append(" having "); queryContent.append(havingQueryContent); } // order if (!countSwich) { QueryContent orderQueryContent = orderImpl.toQueryContent(); if (orderQueryContent != null) { queryContent.append(" order by "); queryContent.append(orderQueryContent); } } return queryContent; } public QueryContent toQueryContent() { return toQueryContent(false); } public QueryContent toCountQueryContent() { return toQueryContent(true); } public SubJpaQuery any() { return new SubJpaQueryImpl(this, SubJpaQueryType.any); } public SubJpaQuery some() { return new SubJpaQueryImpl(this, SubJpaQueryType.some); } public SubJpaQuery all() { return new SubJpaQueryImpl(this, SubJpaQueryType.all); } public String alias(Object proxyInstance) { PathInfo pathInfo = finderHandler.getPathInfo(); if (pathInfo != null) { FromInfo fromInfo = getCurrentFromInfos().get(pathInfo.getRootKey()); if (fromInfo == null) { fromInfo = getParentFromInfos().get(pathInfo.getRootKey()); } if (fromInfo == null) { throw new IllegalArgumentException( String.format("The info path %s root proxy instance is not valid", pathInfo)); } return fromInfo.getEntityInfo().getAlias().concat(".").concat(pathInfo.getPathBuilder().toString()); } if (proxyInstance == null) { throw new IllegalArgumentException(String.format("The proxy instance should't be null")); } if (proxyInstance instanceof JpaQuery) { return ((JpaQuery) proxyInstance).toQueryContent().getQueryString(); } long key = _Helper.identityHashCode(proxyInstance); FromInfo fromInfo = getCurrentFromInfos().get(key); if (fromInfo == null) { fromInfo = getParentFromInfos().get(key); } if (fromInfo != null) { return fromInfo.getEntityInfo().getAlias(); } throw new IllegalStateException(String.format( "Should be call a model getter method or argument is model object in this finder or sub finder object")); } /** * From * * @return */ public Collection<FromInfo> froms() { return getCurrentFromInfos().values(); } /** * * * @param em * @param queryContent * @return */ private Query createQuery(EntityManager em, QueryContent queryContent) { if (logger.isDebugEnabled()) { String caller = _Helper.findCaller(); logger.debug("JPQL({}):{}", caller, queryContent); } Query query = em.createQuery(queryContent.getQueryString()); for (String name : queryContent.getArguments().keySet()) { Object arg = queryContent.getArguments().get(name); if (arg != null && arg instanceof Date) { Timestamp value = new Timestamp(((Date) arg).getTime()); query.setParameter(name, value); continue; } query.setParameter(name, arg); } return query; } private Query createQuery(EntityManager em, JpaQuery finder, boolean cacheable) { QueryContent queryContent = finder.toQueryContent(); Query query = createQuery(em, queryContent); cacheable(query, cacheable); return query; } private Query createQuery(EntityManager em, boolean cacheable) { return createQuery(em, this, cacheable); } /** * * * @param finder * @return */ private Query createCountQuery(EntityManager em) { QueryContent queryContent = toCountQueryContent(); Query query = createQuery(em, queryContent); return query; } @Override public Object one(EntityManager em) { return one(em, false); } @Override public Object one(EntityManager em, boolean cacheable) { Query query = createQuery(em, cacheable); try { return query.getSingleResult(); } catch (NoResultException e) { return null; } } @Override public List<?> list(EntityManager em) { return list(em, false); } @SuppressWarnings("rawtypes") @Override public List<?> list(EntityManager em, boolean cacheable) { final Query query = createQuery(em, cacheable); return new AbstractList() { List<?> list; @Override public Object get(int index) { if (list == null) { list = query.getResultList(); } return list.get(index); } @Override public int size() { if (list == null) { return (int) count(em); } return list.size(); } @Override public Iterator iterator() { if (list == null) { list = query.getResultList(); } return list.iterator(); } }; } private void cacheable(Query query, boolean cacheable) { query.setHint("org.hibernate.cacheable", cacheable); } @Override public List<?> list(EntityManager em, int start, int max) { return list(em, start, max, false); } @Override public List<?> list(EntityManager em, int start, int max, boolean cacheable) { Query query = createQuery(em, cacheable); query.setFirstResult(start); query.setMaxResults(max); return query.getResultList(); } @Override public List<?> top(EntityManager em, int top) { return top(em, top, false); } @Override public List<?> top(EntityManager em, int top, boolean cacheable) { return list(em, 0, top, cacheable); } @Override public Page<?> page(EntityManager em, Pageable pageable) { return page(em, pageable, false); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Page<?> page(EntityManager em, Pageable pageable, boolean cacheable) { JpaQuery finder = this.copy(); Boolean countSwitch = null; Map<String, Object> searchMap = null; Map<String, Object> globalSearchMap = null; // if (pageable instanceof TablePageRequest) { // countSwitch = ((TablePageRequest) pageable).getCountSwitch(); // searchMap = ((TablePageRequest) pageable).getSearchMap(); // globalSearchMap = ((TablePageRequest) pageable).getGlobalSearchMap(); // if (searchMap != null) { // appendSearchMapToFinder(finder, searchMap); // if (globalSearchMap != null) { // appendGlobalSearchMapToFinder(finder, globalSearchMap); long total = countSwitch == null || countSwitch ? ((Number) createCountQuery(em).getSingleResult()).longValue() : -1; List<?> content; if (countSwitch == null) { content = total > pageable.getOffset() ? createQuery(em, appendSortToFinder(finder, pageable.getSort()), cacheable) .setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList() : Collections.emptyList(); } else if (!countSwitch) { content = createQuery(em, appendSortToFinder(finder, pageable.getSort()), cacheable) .setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList(); } else { content = Collections.emptyList(); } return new PageImpl(content, pageable, total); } /** * searchFinder * * @param searchMap */ private void appendSearchMapToFinder(JpaQuery finder, Map<String, Object> searchMap) { JpaQueryImpl finderImpl = (JpaQueryImpl) finder; if (finderImpl.getSelectImpl().getSelectPaths().size() == 1) { Object selectPath = finderImpl.getSelectImpl().getSelectPaths().get(0); if (selectPath != null && selectPath instanceof SelectPathImpl<?>) { SelectPathImpl<?> selectPathImpl = (SelectPathImpl<?>) selectPath; Object arg = selectPathImpl.getArg(); if (arg != null && !(arg instanceof JpaQuery)) { try { String alias = finderImpl.alias(arg); And and = finder.where().and(); for (String name : searchMap.keySet()) { Object value = searchMap.get(name); if (value != null) { if (value instanceof String) { and.append(alias + "." + name + " like ?", value); } else { and.append(alias + "." + name + " = ?", value); } } } return; } catch (IllegalStateException e) { } } } } And and = finder.where().and(); for (String name : searchMap.keySet()) { Object value = searchMap.get(name); if (value != null) { if (value instanceof String) { and.append(name + " like ?", value); } else { and.append(name + " = ?", value); } } } } /** * FinderFinder * * @param finder * @param sort */ private JpaQuery appendSortToFinder(JpaQuery finder, Sort sort) { if (sort == null) { return finder; } JpaQueryImpl finderImpl = (JpaQueryImpl) finder; if (finderImpl.getSelectImpl().getSelectPaths().size() == 1) { Object selectPath = finderImpl.getSelectImpl().getSelectPaths().get(0); if (selectPath != null && selectPath instanceof SelectPathImpl<?>) { SelectPathImpl<?> selectPathImpl = (SelectPathImpl<?>) selectPath; Object arg = selectPathImpl.getArg(); if (arg != null && !(arg instanceof JpaQuery)) { try { String alias = finderImpl.alias(arg); for (Sort.Order order : sort) { finder.order().append(alias.concat(".").concat(order.getProperty()).concat(" ") .concat(order.getDirection().name().toLowerCase())); } return finder; } catch (IllegalStateException e) { } } } } for (Sort.Order order : sort) { finder.order().append(order.getProperty().concat(" ").concat(order.getDirection().name().toLowerCase())); } return finder; } /** * globalSearchFinder * * @param globalSearchMap */ private void appendGlobalSearchMapToFinder(JpaQuery finder, Map<String, Object> globalSearchMap) { JpaQueryImpl finderImpl = (JpaQueryImpl) finder; if (finderImpl.getSelectImpl().getSelectPaths().size() == 1) { Object selectPath = finderImpl.getSelectImpl().getSelectPaths().get(0); if (selectPath != null && selectPath instanceof SelectPathImpl<?>) { SelectPathImpl<?> selectPathImpl = (SelectPathImpl<?>) selectPath; Object arg = selectPathImpl.getArg(); if (arg != null && !(arg instanceof JpaQuery)) { try { String alias = finderImpl.alias(arg); Or or = finder.where().or(); for (String name : globalSearchMap.keySet()) { Object value = globalSearchMap.get(name); if (value != null) { if (value instanceof String) { or.append(alias + "." + name + " like ?", value); } else { or.append(alias + "." + name + " = ?", value); } } } return; } catch (IllegalStateException e) { } } } } Or or = finder.where().or(); for (String name : globalSearchMap.keySet()) { Object value = globalSearchMap.get(name); if (value != null) { if (value instanceof String) { or.append(name + " like ?", value); } else { or.append(name + " = ?", value); } } } } public long count(EntityManager em) { Query query = createCountQuery(em); return ((Number) query.getSingleResult()).longValue(); } public JpaQuery copy() { JpaQueryImpl finder = new JpaQueryImpl(this.finderHandler, this.finderRender); finder.parentFinder = parentFinder; finder.parentFromInfos = parentFromInfos; finder.currentFromInfos = new HashMap<Long, FromInfo>(currentFromInfos); finder.subFinderImpls = new ArrayList<JpaQueryImpl>(subFinderImpls); finder.groupImpl = new GroupImpl(finderHandler, finder); finder.groupImpl.paths = new ArrayList<Object>(groupImpl.paths); finder.havingImpl = new HavingImpl(finderHandler, finder); finder.havingImpl.paths = new ArrayList<Object>(havingImpl.paths); finder.joinImpl = new JoinImpl(finderHandler, finder); finder.joinImpl.joinPathMap = new HashMap<Long, JoinPathImpl<?>>(joinImpl.joinPathMap); finder.orderImpl = new OrderImpl(finderHandler, finder); finder.orderImpl.paths = new ArrayList<Object>(orderImpl.paths); finder.selectImpl = new SelectImpl(finderHandler, finder, selectImpl.entityInfoMap); finder.selectImpl.selectPaths = new ArrayList<Object>(selectImpl.selectPaths); finder.whereImpl = new WhereImpl(finderHandler, finder, whereImpl.type, whereImpl.entityInfoMap); finder.whereImpl.wherePaths = new ArrayList<Object>(whereImpl.wherePaths); return finder; } public String toString() { return "JpaQuery[" + hashCode() + "]"; } @Override public <T> void each(EntityManager em, JpaQueryEach<T> each) { each(em, each, false); } @SuppressWarnings({ "unchecked" }) @Override public <T> void each(EntityManager em, JpaQueryEach<T> each, boolean cacheable) { for (int i = 0;; i += EACH_SIZE) { List<T> list = (List<T>) list(em, i, EACH_SIZE, cacheable); if (list.isEmpty()) { break; } for (T entity : list) { each.handle(entity); } } } }
package de.fernunihagen.dna.jkn.scalephant.storage.sstable.reader; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fernunihagen.dna.jkn.scalephant.ScalephantService; import de.fernunihagen.dna.jkn.scalephant.storage.StorageManagerException; import de.fernunihagen.dna.jkn.scalephant.storage.sstable.SSTableConst; public abstract class AbstractTableReader implements ScalephantService { /** * The number of the table */ protected final int tablebumber; /** * The name of the table */ protected final String name; /** * The filename of the table */ protected File file; /** * The Directoy for the SSTables */ protected final String directory; /** * The memory region */ protected MappedByteBuffer memory; /** * The coresponding fileChanel */ protected FileChannel fileChannel; /** * The Logger */ protected static final Logger logger = LoggerFactory.getLogger(AbstractTableReader.class); public AbstractTableReader(final String directory, final String relation, final int tablenumer) throws StorageManagerException { this.name = relation; this.directory = directory; this.tablebumber = tablenumer; this.file = constructFileToRead(); } /** * Construct the filename to read * * @return */ protected abstract File constructFileToRead(); /** * Get the sequence number of the SSTable * * @return */ public int getTablebumber() { return tablebumber; } /** * Open a stored SSTable and read the magic bytes * * @return a InputStream or null * @throws StorageManagerException */ protected void validateFile() throws StorageManagerException { // Validate file - read the magic from the beginning final byte[] magicBytes = new byte[SSTableConst.MAGIC_BYTES.length]; memory.get(magicBytes, 0, SSTableConst.MAGIC_BYTES.length); if(! Arrays.equals(magicBytes, SSTableConst.MAGIC_BYTES)) { throw new StorageManagerException("File " + file + " does not contain the magic bytes"); } } /** * Reset the position to the first element */ protected void resetPosition() { memory.position(SSTableConst.MAGIC_BYTES.length); } @Override public void init() { try { fileChannel = new RandomAccessFile(file, "r").getChannel(); memory = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); memory.order(SSTableConst.SSTABLE_BYTE_ORDER); validateFile(); } catch (Exception e) { if(! Thread.currentThread().isInterrupted()) { logger.error("Error during an IO operation", e); } shutdown(); } } @Override public void shutdown() { memory = null; if(fileChannel != null) { try { fileChannel.close(); fileChannel = null; } catch (IOException e) { if(! Thread.currentThread().isInterrupted()) { logger.error("Error during an IO operation", e); } } } } /** * Is the reader ready? */ protected boolean isReady() { return memory != null; } /** * Get the name * @return the file handle */ public String getName() { return name; } /** * Get the file handle * @return */ public File getFile() { return file; } /** * Get the directory * @return */ public String getDirectory() { return directory; } /** * Delete the file */ protected void delete() { if(file != null) { logger.info("Delete file: " + file); shutdown(); file.delete(); file = null; } } }
package gov.nih.nci.calab.dto.search; import gov.nih.nci.calab.dto.administration.AliquotBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.dto.workflow.FileBean; import gov.nih.nci.calab.dto.workflow.RunBean; /** * This class includes all properties of a workflow to be displayed in the * search workflow result page. * * @author pansu * */ public class WorkflowResultBean { private FileBean file; private AssayBean assay; private AliquotBean aliquot; private RunBean run; public WorkflowResultBean(String filePath, String assayType, String assayName, String assayRunId, String assayRunName, String assayRunDate, String aliquotName, String aliquotStatus, String fileSubmissionDate, String fileSubmitter, String fileMaskStatus, String inoutType) { super(); // TODO Auto-generated constructor stub this.file = new FileBean(filePath, fileSubmissionDate, fileSubmitter, fileMaskStatus, inoutType); this.assay = new AssayBean(assayName, assayType); this.run = new RunBean(assayRunId, assayRunName, assayRunDate); this.aliquot = new AliquotBean(aliquotName, aliquotStatus); } public AliquotBean getAliquot() { return aliquot; } public void setAliquot(AliquotBean aliquot) { this.aliquot = aliquot; } public AssayBean getAssay() { return assay; } public void setAssay(AssayBean assay) { this.assay = assay; } public FileBean getFile() { return file; } public void setFile(FileBean file) { this.file = file; } public RunBean getRun() { return run; } public void setRun(RunBean run) { this.run = run; } }
import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import com.redhat.ceylon.compiler.js.JsCompiler; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder; import com.redhat.ceylon.compiler.typechecker.io.VirtualFile; /** * Entry point for the type checker * Pass the source diretory as parameter. The source directory is relative to * the startup directory. * * @author Gavin King <gavin@hibernate.org> * @author Emmanuel Bernard <emmanuel@hibernate.org> */ public class MainForJs { /** * Files that are not under a proper module structure are placed under a <nomodule> module. */ public static void main(String[] args) throws Exception { String path; if ( args.length==0 ) { System.err.println("Usage Main <directoryName>"); System.exit(-1); return; } else { path = args[0]; } boolean noisy = "true".equals(System.getProperties().getProperty("verbose")); TypeChecker typeChecker; if ("--".equals(path)) { VirtualFile src = new VirtualFile() { @Override public boolean isFolder() { return false; } @Override public String getName() { return "SCRIPT.ceylon"; } @Override public String getPath() { return getName(); } @Override public InputStream getInputStream() { return System.in; } @Override public List<VirtualFile> getChildren() { return new ArrayList<VirtualFile>(0); } @Override public int hashCode() { return getPath().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof VirtualFile) { return ((VirtualFile) obj).getPath().equals(getPath()); } else { return super.equals(obj); } } }; typeChecker = new TypeCheckerBuilder() .verbose(noisy) .addSrcDirectory(src) .getTypeChecker(); } else { typeChecker = new TypeCheckerBuilder() .verbose(noisy) .addSrcDirectory(new File(path)) .getTypeChecker(); } typeChecker.process(); new JsCompiler(typeChecker, true).generate(); //getting the type checker does process all types in the source directory } }
package com.metaframe.cooma; import com.metaframe.cooma.internal.utils.ConcurrentHashSet; import com.metaframe.cooma.internal.utils.Holder; import com.metaframe.cooma.internal.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.reflect.*; import java.net.URL; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; public class ExtensionLoader<T> { private static final Logger logger = LoggerFactory.getLogger(ExtensionLoader.class); private static final String SERVICES_DIRECTORY = "META-INF/services/"; private static final Pattern NAME_SEPARATOR = Pattern.compile("\\s*,+\\s*"); private static final ConcurrentMap<Class<?>, ExtensionLoader<?>> EXTENSION_LOADERS = new ConcurrentHashMap<Class<?>, ExtensionLoader<?>>(); @SuppressWarnings("unchecked") public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) { if (type == null) throw new IllegalArgumentException("Extension type == null"); if(!withExtensionAnnotation(type)) { throw new IllegalArgumentException("type(" + type + ") is not a extension, because WITHOUT @Extension Annotation!"); } ExtensionLoader<T> loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type); if (loader == null) { EXTENSION_LOADERS.putIfAbsent(type, new ExtensionLoader<T>(type)); loader = (ExtensionLoader<T>) EXTENSION_LOADERS.get(type); } return loader; } public T getExtension(String name) { if (name == null || name.length() == 0) throw new IllegalArgumentException("Extension name == null"); Holder<T> holder = extInstances.get(name); if (holder == null) { extInstances.putIfAbsent(name, new Holder<T>()); holder = extInstances.get(name); } T instance = holder.get(); if (instance == null) { synchronized (holder) { // holder instance = holder.get(); if (instance == null) { instance = createExtension(name); holder.set(instance); } } } return instance; } /** * <code>null</code> */ public T getDefaultExtension() { getExtensionClasses(); if(null == defaultExtension || defaultExtension.length() == 0) { return null; } return getExtension(defaultExtension); } public boolean hasExtension(String name) { if (name == null || name.length() == 0) throw new IllegalArgumentException("Extension name == null"); try { return getExtensionClass(name) != null; } catch (Throwable t) { return false; } } /** * <code>null</code> */ public String getDefaultExtensionName() { getExtensionClasses(); return defaultExtension; } public Set<String> getSupportedExtensions() { Map<String, Class<?>> clazzes = getExtensionClasses(); return Collections.unmodifiableSet(new TreeSet<String>(clazzes.keySet())); } public String getExtensionName(T extensionInstance) { return getExtensionName(extensionInstance.getClass()); } public String getExtensionName(Class<?> extensionClass) { // FIXME return extensionNames.get(extensionClass); } /** * Adaptive * ExtensionLoaderAdaptive * * @deprecated Adaptive */ @Deprecated public T getAdaptiveExtension() { T instance = cachedAdaptiveInstance.get(); if (instance == null) { if(createAdaptiveInstanceError == null) { synchronized (cachedAdaptiveInstance) { instance = cachedAdaptiveInstance.get(); if (instance == null) { try { instance = createAdaptiveInstance0(); cachedAdaptiveInstance.set(instance); } catch (Throwable t) { createAdaptiveInstanceError = t; throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + t.getMessage(), t); } } } } else { throw new IllegalStateException("Can not create adaptive extension " + type + ", cause: " + createAdaptiveInstanceError.getMessage(), createAdaptiveInstanceError); } } return instance; } private final Class<T> type; private final String defaultExtension; private final ConcurrentMap<String, Holder<T>> extInstances = new ConcurrentHashMap<String, Holder<T>>(); private ExtensionLoader(Class<T> type) { this.type = type; String defaultExt = null; final Extension annotation = type.getAnnotation(Extension.class); if(annotation != null) { String value = annotation.value(); if(value != null && (value = value.trim()).length() > 0) { String[] names = NAME_SEPARATOR.split(value); if(names.length > 1) { throw new IllegalStateException("more than 1 default extension name on extension " + type.getName() + ": " + Arrays.toString(names)); } if(names.length == 1 && names[0].trim().length() > 0) { defaultExt = names[0].trim(); } } } defaultExtension = defaultExt; } private IllegalStateException findException(String name) { for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) { if (entry.getKey().toLowerCase().contains(name.toLowerCase())) { return entry.getValue(); } } StringBuilder buf = new StringBuilder("No such extension " + type.getName() + " by name " + name + ", possible causes: "); int i = 1; for (Map.Entry<String, IllegalStateException> entry : exceptions.entrySet()) { buf.append("\r\n("); buf.append(i++); buf.append(") "); buf.append(entry.getKey()); buf.append(":\r\n"); buf.append(StringUtils.toString(entry.getValue())); } return new IllegalStateException(buf.toString()); } @SuppressWarnings("unchecked") private T createExtension(String name) { Class<?> clazz = getExtensionClasses().get(name); if (clazz == null) { throw findException(name); } try { T instance = injectExtension((T) clazz.newInstance()); Set<Class<?>> wrapperClasses = this.wrapperClasses; if (wrapperClasses != null && wrapperClasses.size() > 0) { for (Class<?> wrapperClass : wrapperClasses) { instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance)); } } return instance; } catch (Throwable t) { throw new IllegalStateException("Extension instance(name: " + name + ", class: " + type + ") could not be instantiated: " + t.getMessage(), t); } } private T injectExtension(T instance) { try { for (Method method : instance.getClass().getMethods()) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers())) { Class<?> pt = method.getParameterTypes()[0]; if (pt.isInterface() && withExtensionAnnotation(pt) && getExtensionLoader(pt).getSupportedExtensions().size() > 0) { try { Object adaptive = getExtensionLoader(pt).getAdaptiveExtension(); method.invoke(instance, adaptive); } catch (Exception e) { logger.error("fail to inject via method " + method.getName() + " of interface " + type.getName() + ": " + e.getMessage(), e); } } } } } catch (Exception e) { logger.error(e.getMessage(), e); } return instance; } private Class<?> getExtensionClass(String name) { if (type == null) throw new IllegalArgumentException("Extension type == null"); if (name == null) throw new IllegalArgumentException("Extension name == null"); Class<?> clazz = getExtensionClasses().get(name); if (clazz == null) throw new IllegalStateException("No such extension \"" + name + "\" for " + type.getName() + "!"); return clazz; } // get & create Adaptive Instance private final Holder<T> cachedAdaptiveInstance = new Holder<T>(); private volatile Throwable createAdaptiveInstanceError; private final Holder<T> adaptiveInstanceHolder = new Holder<T>(); private final Map<Method, Integer> method2ConfigArgIndex = new HashMap<Method, Integer>(); private final Map<Method, Method> method2ConfigGetter = new HashMap<Method, Method>(); /** * Thread-safe. */ private T createAdaptiveInstance0() { if(null != adaptiveInstanceHolder.get()) { return adaptiveInstanceHolder.get(); } getExtensionClasses(); synchronized (adaptiveInstanceHolder) { checkAndSetAdaptiveInfo0(); Object p = Proxy.newProxyInstance(ExtensionLoader.class.getClassLoader(), new Class[]{type}, new InvocationHandler() { // FIXME toString public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // if(method.getDeclaringClass().equals(Object.class)) { // return if(!method2ConfigArgIndex.containsKey(method)) { throw new UnsupportedOperationException("method " + method.getName() + " of interface " + type.getName() + " is not adaptive method!"); } int confArgIdx = method2ConfigArgIndex.get(method); Object confArg = args[confArgIdx]; Config config; if(method2ConfigGetter.containsKey(method)) { if(confArg == null) { throw new IllegalArgumentException(method.getParameterTypes()[confArgIdx].getName() + " argument == null"); } Method configGetter = method2ConfigGetter.get(method); config = (Config) configGetter.invoke(confArg); if(config == null) { throw new IllegalArgumentException(method.getParameterTypes()[confArgIdx].getName() + " argument " + configGetter.getName() + "() == null"); } } else { if(confArg == null) { throw new IllegalArgumentException("config == null"); } config = (Config) confArg; } String[] value = method.getAnnotation(Adaptive.class).value(); if(value.length == 0) { value = new String[]{StringUtils.toDotSpiteString(type.getSimpleName())}; } String extName = null; for(int i = 0; i < value.length; ++i) { if(!config.contains(value[i])) { if(i == value.length - 1) extName = defaultExtension; continue; } extName = config.get(value[i]); break; } if(extName == null) throw new IllegalStateException("Fail to get extension(" + type.getName() + ") name from config(" + config + ") use keys())"); return method.invoke(ExtensionLoader.this.getExtension(extName), args); } }); T adaptive = type.cast(p); // try { // injectExtension(adaptive); // } catch (Exception e) { // // FIXME adaptiveInstanceHolder.set(adaptive); return adaptiveInstanceHolder.get(); } } private void checkAndSetAdaptiveInfo0() { Method[] methods = type.getMethods(); boolean hasAdaptiveAnnotation = false; for(Method m : methods) { if(m.isAnnotationPresent(Adaptive.class)) { hasAdaptiveAnnotation = true; break; } } // AdaptiveAdaptive if(! hasAdaptiveAnnotation) throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!"); // ConfigConfigConfig for(Method method : methods) { Adaptive annotation = method.getAnnotation(Adaptive.class); // AdaptiveConfig if(annotation == null) continue; // Configs Class<?>[] parameterTypes = method.getParameterTypes(); for(int i = 0; i < parameterTypes.length; ++i) { if(Config.class.isAssignableFrom(parameterTypes[i])) { method2ConfigArgIndex.put(method, i); break; } } if(method2ConfigArgIndex.containsKey(method)) continue; // Configs LBL_PARAMETER_TYPES: for (int i = 0; i < parameterTypes.length; ++i) { Method[] ms = parameterTypes[i].getMethods(); for (Method m : ms) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && Config.class.isAssignableFrom(m.getReturnType())) { method2ConfigArgIndex.put(method, i); method2ConfigGetter.put(method, m); break LBL_PARAMETER_TYPES; } } } if(!method2ConfigArgIndex.containsKey(method)) { throw new IllegalStateException("fail to create adaptive class for interface " + type.getName() + ": not found config parameter or config attribute in parameters of method " + method.getName()); } } } // get & load Extension Class private final Holder<Map<String, Class<?>>> extClassesHolder = new Holder<Map<String,Class<?>>>(); private volatile Class<?> adaptiveClass = null; private Set<Class<?>> wrapperClasses; private final ConcurrentMap<Class<?>, String> extensionNames = new ConcurrentHashMap<Class<?>, String>(); private Map<String, IllegalStateException> exceptions = new ConcurrentHashMap<String, IllegalStateException>(); /** * Thread-safe */ private Map<String, Class<?>> getExtensionClasses() { Map<String, Class<?>> classes = extClassesHolder.get(); if (classes == null) { synchronized (extClassesHolder) { classes = extClassesHolder.get(); if (classes == null) { // double check classes = loadExtensionClasses0(); extClassesHolder.set(classes); } } } return classes; } private Map<String, Class<?>> loadExtensionClasses0() { Map<String, Class<?>> extName2Class = new HashMap<String, Class<?>>(); String fileName = null; try { ClassLoader classLoader = getClassLoader(); fileName = SERVICES_DIRECTORY + type.getName(); Enumeration<java.net.URL> urls; if (classLoader != null) { urls = classLoader.getResources(fileName); } else { urls = ClassLoader.getSystemResources(fileName); } if(urls == null) { // FIXME throw exception to notify no extension found? return extName2Class; } while (urls.hasMoreElements()) { java.net.URL url = urls.nextElement(); readExtension0(extName2Class, classLoader, url); } } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", description file: " + fileName + ").", t); } return extName2Class; } private void readExtension0(Map<String, Class<?>> extName2Class, ClassLoader classLoader, URL url) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line; while ((line = reader.readLine()) != null) { // delete comments final int ci = line.indexOf(' if (ci >= 0) line = line.substring(0, ci); line = line.trim(); if (line.length() == 0) continue; try { String name = null; int i = line.indexOf('='); if (i > 0) { name = line.substring(0, i).trim(); line = line.substring(i + 1).trim(); } Class<?> clazz = Class.forName(line, true, classLoader); if (! type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error when load extension class(interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + "is not subtype of interface."); } if (clazz.isAnnotationPresent(Adaptive.class)) { if(adaptiveClass == null) { adaptiveClass = clazz; } else if (! adaptiveClass.equals(clazz)) { throw new IllegalStateException("More than 1 adaptive class found: " + adaptiveClass.getClass().getName() + ", " + clazz.getClass().getName()); } } else { if(hasCopyConstructor(clazz)) { Set<Class<?>> wrappers = wrapperClasses; if (wrappers == null) { wrapperClasses = new ConcurrentHashSet<Class<?>>(); wrappers = wrapperClasses; } wrappers.add(clazz); } else { clazz.getConstructor(); // Extension if (name == null || name.length() == 0) { name = findAnnotationName(clazz); if(name == null || name.length() == 0) { throw new IllegalStateException( "No such extension name for the class " + clazz.getName() + " in the config " + url); } } String[] nameList = NAME_SEPARATOR.split(name); for (String n : nameList) { if (! extensionNames.containsKey(clazz)) { extensionNames.put(clazz, n); // FIXME } Class<?> c = extName2Class.get(n); if (c == null) { extName2Class.put(n, clazz); } else if (c != clazz) { throw new IllegalStateException("Duplicate extension " + type.getName() + " name " + n + " on " + c.getName() + " and " + clazz.getName()); } } } } } catch (Throwable t) { IllegalStateException e = new IllegalStateException("Failed to load extension class(interface: " + type + ", class line: " + line + ") in " + url + ", cause: " + t.getMessage(), t); exceptions.put(line, e); } } // end of while read lines } catch (Throwable t) { logger.error("Exception when load extension class(interface: " + type + ", class file: " + url + ") in " + url, t); } finally { if(reader != null) { try { reader.close(); } catch (Throwable t) { // ignore } } } } // small helper methods private boolean hasCopyConstructor(Class<?> clazz) { try { clazz.getConstructor(type); return true; } catch (NoSuchMethodException e) { // ignore } return false; } private String findAnnotationName(Class<?> clazz) { Extension extension = clazz.getAnnotation(Extension.class); return extension == null ? null : extension.value().trim(); } private static ClassLoader getClassLoader() { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { return classLoader; } classLoader = ExtensionLoader.class.getClassLoader(); if(classLoader != null) { return classLoader; } return classLoader; } private static <T> boolean withExtensionAnnotation(Class<T> type) { return type.isAnnotationPresent(Extension.class); } @Override public String toString() { return this.getClass().getName() + "<" + type.getName() + ">"; } }
package gov.nih.nci.cananolab.util; import gov.nih.nci.cananolab.domain.common.DerivedDatum; import gov.nih.nci.cananolab.domain.common.LabFile; import gov.nih.nci.cananolab.domain.common.ProtocolFile; import gov.nih.nci.cananolab.domain.common.Source; import gov.nih.nci.cananolab.domain.particle.NanoparticleSample; import gov.nih.nci.cananolab.domain.particle.characterization.Characterization; import gov.nih.nci.cananolab.domain.particle.characterization.physical.SurfaceChemistry; import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.NanoparticleEntity; import gov.nih.nci.cananolab.domain.particle.samplecomposition.chemicalassociation.ChemicalAssociation; import gov.nih.nci.cananolab.domain.particle.samplecomposition.functionalization.FunctionalizingEntity; import gov.nih.nci.cananolab.dto.common.LabFileBean; import gov.nih.nci.cananolab.dto.common.ProtocolFileBean; import gov.nih.nci.cananolab.dto.particle.ParticleBean; import gov.nih.nci.cananolab.dto.particle.characterization.DerivedBioAssayDataBean; import gov.nih.nci.cananolab.dto.particle.characterization.DerivedDatumBean; import gov.nih.nci.cananolab.dto.particle.composition.ComposingElementBean; import gov.nih.nci.cananolab.dto.particle.composition.FunctionBean; import gov.nih.nci.cananolab.dto.particle.composition.TargetBean; import java.util.Comparator; /** * Contains a list of static comparators for use in caNanoLab * * @author pansu * */ /* CVS $Id: CaNanoLabComparators.java,v 1.10 2008-07-03 17:15:36 pansu Exp $ */ public class CaNanoLabComparators { public static class ParticleSourceComparator implements Comparator<Source> { public int compare(Source source1, Source source2) { int diff = new SortableNameComparator().compare(source1 .getOrganizationName(), source2.getOrganizationName()); return diff; } } public static class SortableNameComparator implements Comparator<String> { public int compare(String name1, String name2) { // in case of sample name, container name and aliquot name if (name1.matches("\\D+(-(\\d+)(\\D+)*)+") && name2.matches("\\D+(-(\\d+)(\\D+)*)+")) { String[] toks1 = name1.split("-"); String[] toks2 = name2.split("-"); int num = 0; if (toks1.length >= toks2.length) { num = toks1.length; } else { num = toks2.length; } for (int i = 0; i < num; i++) { String str1 = "0", str2 = "0"; if (i < toks1.length) { str1 = toks1[i]; } if (i < toks2.length) { str2 = toks2[i]; } try { int num1 = 0, num2 = 0; num1 = Integer.parseInt(str1); num2 = Integer.parseInt(str2); if (num1 != num2) { return num1 - num2; } } catch (Exception e) { if (!str1.equals(str2)) { return str1.compareTo(str2); } } } } // in case of run name else if (name1.matches("(\\D+)(\\d+)") && name2.matches("(\\D+)(\\d+)")) { try { String str1 = name1.replaceAll("(\\D+)(\\d+)", "$1"); String str2 = name2.replaceAll("(\\D+)(\\d+)", "$1"); int num1 = Integer.parseInt(name1.replaceAll( "(\\D+)(\\d+)", "$2")); int num2 = Integer.parseInt(name2.replaceAll( "(\\D+)(\\d+)", "$2")); if (str1.equals(str2)) { return num1 - num2; } else { return str1.compareTo(str2); } } catch (Exception e) { return name1.compareTo(name2); } } return name1.compareTo(name2); } } public static class ParticleBeanComparator implements Comparator<ParticleBean> { public int compare(ParticleBean particle1, ParticleBean particle2) { return new SortableNameComparator().compare(particle1 .getDomainParticleSample().getName(), particle2 .getDomainParticleSample().getName()); } } public static class NanoparticleSampleComparator implements Comparator<NanoparticleSample> { public int compare(NanoparticleSample particle1, NanoparticleSample particle2) { return new SortableNameComparator().compare(particle1.getName(), particle2.getName()); } } public static class DataLinkTypeDateComparator implements Comparator<DataLinkBean> { public int compare(DataLinkBean link1, DataLinkBean link2) { if (link1.getDataDisplayType().equals(link2.getDataDisplayType())) { return link1.getCreatedDate().compareTo(link2.getCreatedDate()); } else { return link1.getDataDisplayType().compareTo( link2.getDataDisplayType()); } } } public static class NanoparticleEntityTypeDateComparator implements Comparator<NanoparticleEntity> { public int compare(NanoparticleEntity entity1, NanoparticleEntity entity2) { if (entity1.getClass().getCanonicalName().equals( entity2.getClass().getCanonicalName())) { return entity1.getCreatedDate().compareTo( entity2.getCreatedDate()); } else { return entity1.getClass().getCanonicalName().compareTo( entity2.getClass().getCanonicalName()); } } } public static class FunctionalizingEntityTypeDateComparator implements Comparator<FunctionalizingEntity> { public int compare(FunctionalizingEntity entity1, FunctionalizingEntity entity2) { if (entity1.getClass().getCanonicalName().equals( entity2.getClass().getCanonicalName())) { return entity1.getCreatedDate().compareTo( entity2.getCreatedDate()); } else { return entity1.getClass().getCanonicalName().compareTo( entity2.getClass().getCanonicalName()); } } } public static class ChemicalAssociationTypeDateComparator implements Comparator<ChemicalAssociation> { public int compare(ChemicalAssociation assoc1, ChemicalAssociation assoc2) { if (assoc1.getClass().getCanonicalName().equals( assoc2.getClass().getCanonicalName())) { return assoc1.getCreatedDate().compareTo( assoc2.getCreatedDate()); } else { return assoc1.getClass().getCanonicalName().compareTo( assoc2.getClass().getCanonicalName()); } } } public static class LabFileTypeDateComparator implements Comparator<LabFile> { public int compare(LabFile file1, LabFile file2) { if (file1.getType().equals(file2.getType())) { return file1.getCreatedDate().compareTo(file2.getCreatedDate()); } else { return file1.getClass().getCanonicalName().compareTo( file2.getClass().getCanonicalName()); } } } public static class LabFileDateComparator implements Comparator<LabFile> { public int compare(LabFile file1, LabFile file2) { return file1.getCreatedDate().compareTo(file2.getCreatedDate()); } } public static class DerivedBioAssayDataBeanDateComparator implements Comparator<DerivedBioAssayDataBean> { public int compare(DerivedBioAssayDataBean bioassay1, DerivedBioAssayDataBean bioassay2) { return bioassay1.getDomainBioAssayData().getCreatedDate() .compareTo( bioassay2.getDomainBioAssayData().getCreatedDate()); } } public static class LabFileBeanDateComparator implements Comparator<LabFileBean> { public int compare(LabFileBean file1, LabFileBean file2) { return file1.getDomainFile().getCreatedDate().compareTo( file2.getDomainFile().getCreatedDate()); } } public static class DerivedDatumBeanDateComparator implements Comparator<DerivedDatumBean> { public int compare(DerivedDatumBean data1, DerivedDatumBean data2) { return data1.getDomainDerivedDatum().getCreatedDate().compareTo( data2.getDomainDerivedDatum().getCreatedDate()); } } public static class DerivedDatumDateComparator implements Comparator<DerivedDatum> { public int compare(DerivedDatum data1, DerivedDatum data2) { return data1.getCreatedDate().compareTo(data2.getCreatedDate()); } } public static class FunctionBeanDateComparator implements Comparator<FunctionBean> { public int compare(FunctionBean function1, FunctionBean function2) { return function1.getDomainFunction().getCreatedDate().compareTo( function2.getDomainFunction().getCreatedDate()); } } public static class ComposingElementBeanDateComparator implements Comparator<ComposingElementBean> { public int compare(ComposingElementBean element1, ComposingElementBean element2) { return element1.getDomainComposingElement().getCreatedDate() .compareTo( element2.getDomainComposingElement() .getCreatedDate()); } } public static class TargetBeanDateComparator implements Comparator<TargetBean> { public int compare(TargetBean target1, TargetBean target2) { return target1.getDomainTarget().getCreatedDate().compareTo( target2.getDomainTarget().getCreatedDate()); } } public static class CharacterizationDateComparator implements Comparator<Characterization> { public int compare(Characterization chara1, Characterization chara2) { return chara1.getCreatedDate().compareTo(chara2.getCreatedDate()); } } public static class SurfaceChemistryDateComparator implements Comparator<SurfaceChemistry> { public int compare(SurfaceChemistry chem1, SurfaceChemistry chem2) { return chem1.getCreatedDate().compareTo(chem2.getCreatedDate()); } } public static class ProtocolFileBeanNameVersionComparator implements Comparator<ProtocolFileBean> { public int compare(ProtocolFileBean protocolFile1, ProtocolFileBean protocolFile2) { String name1 = ((ProtocolFile) protocolFile1.getDomainFile()) .getProtocol().getName(); String name2 = ((ProtocolFile) protocolFile2.getDomainFile()) .getProtocol().getName(); int nameComp = new SortableNameComparator().compare(name1, name2); if (nameComp == 0) { String version1 = protocolFile1.getDomainFile().getVersion(); String version2 = protocolFile2.getDomainFile().getVersion(); if (version1 == null || version2 == null) { return 0; } return version1.compareTo(version2); } else { return nameComp; } } } }
package com.segment.android.internal; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import com.segment.android.Segment; import com.segment.android.internal.integrations.AbstractIntegrationAdapter; import com.segment.android.internal.integrations.AmplitudeIntegrationAdapter; import com.segment.android.internal.integrations.BugsnagIntegrationAdapter; import com.segment.android.internal.integrations.CountlyIntegrationAdapter; import com.segment.android.internal.integrations.CrittercismIntegrationAdapter; import com.segment.android.internal.integrations.FlurryIntegrationAdapter; import com.segment.android.internal.integrations.GoogleAnalyticsIntegrationAdapter; import com.segment.android.internal.integrations.InvalidConfigurationException; import com.segment.android.internal.integrations.LocalyticsIntegrationAdapter; import com.segment.android.internal.integrations.MixpanelIntegrationAdapter; import com.segment.android.internal.integrations.QuantcastIntegrationAdapter; import com.segment.android.internal.integrations.TapstreamIntegrationAdapter; import com.segment.android.internal.payload.AliasPayload; import com.segment.android.internal.payload.BasePayload; import com.segment.android.internal.payload.GroupPayload; import com.segment.android.internal.payload.IdentifyPayload; import com.segment.android.internal.payload.ScreenPayload; import com.segment.android.internal.payload.TrackPayload; import com.segment.android.json.JsonMap; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayDeque; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import static android.os.Process.THREAD_PRIORITY_BACKGROUND; import static com.segment.android.internal.Utils.getSharedPreferences; import static com.segment.android.internal.Utils.isConnected; /** * Manages bundled integrations. This class will maintain it's own queue for events to account for * the latency between receiving the first event, fetching remote settings and enabling the * integrations. Once we enable all integrations - we'll replay any events in the queue. This * should only affect the first app install, subsequent launches will be use a cached value from * disk. */ public class IntegrationManager { private static final String PROJECT_SETTINGS_CACHE_KEY = "project-settings"; static final int REQUEST_FETCH_SETTINGS = 1; static final int REQUEST_INIT = 2; static final int REQUEST_LIFECYCLE_EVENT = 3; static final int REQUEST_ANALYTICS_EVENT = 4; static final int REQUEST_FLUSH = 5; private static final String INTEGRATION_MANAGER_THREAD_NAME = Utils.THREAD_PREFIX + "IntegrationManager"; // A set of integrations available on the device private final Set<AbstractIntegrationAdapter> bundledIntegrations = new HashSet<AbstractIntegrationAdapter>(); // A map of integrations that were found on the device, so that we disable them for servers private Map<String, Boolean> serverIntegrations = new LinkedHashMap<String, Boolean>(); private Queue<IntegrationOperation> operationQueue = new ArrayDeque<IntegrationOperation>(); final AtomicBoolean initialized = new AtomicBoolean(); public enum ActivityLifecycleEvent { CREATED, STARTED, RESUMED, PAUSED, STOPPED, SAVE_INSTANCE, DESTROYED } static class ActivityLifecyclePayload { final ActivityLifecycleEvent type; final WeakReference<Activity> activityWeakReference; final Bundle bundle; ActivityLifecyclePayload(ActivityLifecycleEvent type, Activity activity, Bundle bundle) { this.type = type; this.activityWeakReference = new WeakReference<Activity>(activity); this.bundle = bundle; } } public static IntegrationManager create(Context context, SegmentHTTPApi segmentHTTPApi, Stats stats) { StringCache projectSettingsCache = new StringCache(getSharedPreferences(context), PROJECT_SETTINGS_CACHE_KEY); return new IntegrationManager(context, segmentHTTPApi, projectSettingsCache, stats); } final Context context; final SegmentHTTPApi segmentHTTPApi; final HandlerThread integrationManagerThread; final Handler handler; final Stats stats; final StringCache projectSettingsCache; private IntegrationManager(Context context, SegmentHTTPApi segmentHTTPApi, StringCache projectSettingsCache, Stats stats) { this.context = context; this.segmentHTTPApi = segmentHTTPApi; this.stats = stats; integrationManagerThread = new HandlerThread(INTEGRATION_MANAGER_THREAD_NAME, THREAD_PRIORITY_BACKGROUND); integrationManagerThread.start(); handler = new IntegrationManagerHandler(integrationManagerThread.getLooper(), this); loadIntegrations(); this.projectSettingsCache = projectSettingsCache; ProjectSettings projectSettings = ProjectSettings.load(projectSettingsCache); if (projectSettings == null) { dispatchFetch(); } else { dispatchInit(projectSettings); if (projectSettings.timestamp() + 10800000L < System.currentTimeMillis()) { Logger.v("Stale settings"); dispatchFetch(); } } } void loadIntegrations() { initialized.set(false); // Look up all the integrations available on the device. This is done early so that we can // disable sending to these integrations from the server and properly fill the payloads. addToBundledIntegrations(new AmplitudeIntegrationAdapter()); addToBundledIntegrations(new BugsnagIntegrationAdapter()); addToBundledIntegrations(new CountlyIntegrationAdapter()); addToBundledIntegrations(new CrittercismIntegrationAdapter()); addToBundledIntegrations(new FlurryIntegrationAdapter()); addToBundledIntegrations(new GoogleAnalyticsIntegrationAdapter()); addToBundledIntegrations(new LocalyticsIntegrationAdapter()); addToBundledIntegrations(new MixpanelIntegrationAdapter()); addToBundledIntegrations(new QuantcastIntegrationAdapter()); addToBundledIntegrations(new TapstreamIntegrationAdapter()); } void addToBundledIntegrations(AbstractIntegrationAdapter abstractIntegrationAdapter) { try { Class.forName(abstractIntegrationAdapter.className()); bundledIntegrations.add(abstractIntegrationAdapter); serverIntegrations.put(abstractIntegrationAdapter.key(), false); Logger.v("Loaded integration %s", abstractIntegrationAdapter.key()); } catch (ClassNotFoundException e) { Logger.v("Integration %s not bundled", abstractIntegrationAdapter.key()); } } void dispatchFetch() { Logger.v("Fetching integration settings from server"); handler.sendMessage(handler.obtainMessage(REQUEST_FETCH_SETTINGS)); } void performFetch() { try { if (isConnected(context)) { dispatchInit(segmentHTTPApi.fetchSettings()); } } catch (IOException e) { Logger.e(e, "Failed to fetch settings. Retrying."); dispatchFetch(); } } void dispatchInit(ProjectSettings projectSettings) { handler.sendMessage(handler.obtainMessage(REQUEST_INIT, projectSettings)); } void performInit(ProjectSettings projectSettings) { projectSettingsCache.set(projectSettings.toString()); if (initialized.get()) { Logger.d("Integrations already initialized. Skipping."); return; } Logger.v("Initializing integrations with settings %s", projectSettings); Iterator<AbstractIntegrationAdapter> iterator = bundledIntegrations.iterator(); while (iterator.hasNext()) { AbstractIntegrationAdapter integration = iterator.next(); if (projectSettings.containsKey(integration.key())) { JsonMap settings = new JsonMap(projectSettings.getJsonMap(integration.key())); try { integration.initialize(context, settings); Logger.v("Initialized integration %s", integration.key()); } catch (InvalidConfigurationException e) { iterator.remove(); Logger.e(e, "could not initialize integration " + integration.key()); } } else { iterator.remove(); Logger.v("%s integration not enabled in project settings.", integration.key()); } } initialized.set(true); replay(); } // Activity Lifecycle Events public void dispatchLifecycleEvent(ActivityLifecycleEvent event, Activity activity, Bundle bundle) { handler.sendMessage(handler.obtainMessage(REQUEST_LIFECYCLE_EVENT, new ActivityLifecyclePayload(event, activity, bundle))); } void performEnqueue(final ActivityLifecyclePayload payload) { switch (payload.type) { case CREATED: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivityCreated(payload.activityWeakReference.get(), payload.bundle); } }); } break; case STARTED: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivityStarted(payload.activityWeakReference.get()); } }); } break; case RESUMED: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivityResumed(payload.activityWeakReference.get()); } }); } break; case PAUSED: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivityPaused(payload.activityWeakReference.get()); } }); } break; case STOPPED: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivityStopped(payload.activityWeakReference.get()); } }); } break; case SAVE_INSTANCE: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivitySaveInstanceState(payload.activityWeakReference.get(), payload.bundle); } }); } break; case DESTROYED: if (payload.activityWeakReference.get() != null) { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.onActivityDestroyed(payload.activityWeakReference.get()); } }); } break; default: throw new IllegalArgumentException("Unknown payload type!" + payload.type); } } public void dispatchAnalyticsEvent(BasePayload payload) { handler.sendMessage(handler.obtainMessage(REQUEST_ANALYTICS_EVENT, payload)); } void performEnqueue(final BasePayload payload) { switch (payload.type()) { case alias: enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { if (isBundledIntegrationEnabledForPayload(payload, integration)) { integration.alias((AliasPayload) payload); } } }); break; case group: enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { if (isBundledIntegrationEnabledForPayload(payload, integration)) { integration.group((GroupPayload) payload); } } }); break; case identify: enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { if (isBundledIntegrationEnabledForPayload(payload, integration)) { integration.identify((IdentifyPayload) payload); } } }); break; case page: case screen: enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { if (isBundledIntegrationEnabledForPayload(payload, integration)) { integration.screen((ScreenPayload) payload); } } }); break; case track: enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { if (isBundledIntegrationEnabledForPayload(payload, integration)) { integration.track((TrackPayload) payload); } } }); break; default: throw new IllegalArgumentException("Unknown payload type!" + payload.type()); } } public void dispatchFlush() { handler.sendMessage(handler.obtainMessage(REQUEST_FLUSH)); } void performFlush() { enqueue(new IntegrationOperation() { @Override public void run(AbstractIntegrationAdapter integration) { integration.flush(); } }); } private interface IntegrationOperation { // todo: enumerate operations to avoid inn void run(AbstractIntegrationAdapter integration); } void enqueue(IntegrationOperation operation) { if (!initialized.get()) { Logger.v("Integrations not yet initialized! Queuing operation."); operationQueue.add(operation); } else { run(operation); } } private void run(IntegrationOperation operation) { for (AbstractIntegrationAdapter integration : bundledIntegrations) { long startTime = System.currentTimeMillis(); operation.run(integration); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; Logger.v("Integration %s took %s ms to run operation", integration.key(), duration); stats.dispatchIntegrationOperation(duration); } } void replay() { Logger.v("Replaying %s events.", operationQueue.size()); stats.dispatchReplay(); while (operationQueue.size() > 0) { IntegrationOperation operation = operationQueue.peek(); run(operation); operationQueue.remove(); } } private boolean isBundledIntegrationEnabledForPayload(BasePayload payload, AbstractIntegrationAdapter integration) { Boolean enabled = true; // look in the payload.context.integrations to see which Bundled integrations should be // disabled. payload.integrations is reserved for the server, where all bundled integrations // have been set to false JsonMap integrations = payload.context().getIntegrations(); if (!JsonMap.isNullOrEmpty(integrations)) { String key = integration.key(); if (integrations.containsKey(key)) { enabled = integrations.getBoolean(key); } else if (integrations.containsKey("All")) { enabled = integrations.getBoolean("All"); } else if (integrations.containsKey("all")) { enabled = integrations.getBoolean("all"); } } return enabled; } public Map<String, Boolean> bundledIntegrations() { return serverIntegrations; } private static class IntegrationManagerHandler extends Handler { private final IntegrationManager integrationManager; public IntegrationManagerHandler(Looper looper, IntegrationManager integrationManager) { super(looper); this.integrationManager = integrationManager; } @Override public void handleMessage(final Message msg) { switch (msg.what) { case REQUEST_FETCH_SETTINGS: integrationManager.performFetch(); break; case REQUEST_INIT: ProjectSettings settings = (ProjectSettings) msg.obj; integrationManager.performInit(settings); break; case REQUEST_LIFECYCLE_EVENT: ActivityLifecyclePayload activityLifecyclePayload = (ActivityLifecyclePayload) msg.obj; integrationManager.performEnqueue(activityLifecyclePayload); break; case REQUEST_ANALYTICS_EVENT: BasePayload basePayload = (BasePayload) msg.obj; integrationManager.performEnqueue(basePayload); break; case REQUEST_FLUSH: integrationManager.performFlush(); break; default: Segment.HANDLER.post(new Runnable() { @Override public void run() { throw new AssertionError("Unhandled dispatcher message." + msg.what); } }); } } } }
package com.muzima.view.login; import android.content.*; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockActivity; import com.actionbarsherlock.internal.nineoldandroids.animation.ValueAnimator; import com.muzima.MuzimaApplication; import com.muzima.R; import com.muzima.domain.Credentials; import com.muzima.service.MuzimaSyncService; import com.muzima.utils.NetworkUtils; import com.muzima.utils.StringUtils; import com.muzima.view.MainActivity; import com.muzima.view.cohort.CohortPrefixWizardActivity; import static com.muzima.utils.Constants.DataSyncServiceConstants.SyncStatusConstants.AUTHENTICATION_SUCCESS; public class LoginActivity extends SherlockActivity { private static final String TAG = "LoginActivity"; public static final String isFirstLaunch = "isFirstLaunch"; private EditText serverUrlText; private EditText usernameText; private EditText passwordText; private Button loginButton; private BackgroundAuthenticationTask backgroundAuthenticationTask; private TextView noConnectivityText; private TextView authenticatingText; private ValueAnimator flipFromNoConnToLoginAnimator; private ValueAnimator flipFromLoginToNoConnAnimator; private ValueAnimator flipFromLoginToAuthAnimator; private ValueAnimator flipFromAuthToLoginAnimator; private ValueAnimator flipFromAuthToNoConnAnimator; private boolean honeycombOrGreater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { honeycombOrGreater = true; } initViews(); setupListeners(); initAnimators(); boolean isFirstLaunch = getIntent().getBooleanExtra(LoginActivity.isFirstLaunch, true); if (!isFirstLaunch) { removeServerUrlAsInput(); useSavedServerUrl(); } passwordText.setTypeface(Typeface.DEFAULT); //Hack to get it to use default font space. } private void removeServerUrlAsInput() { serverUrlText.setVisibility(View.GONE); findViewById(R.id.server_url_divider).setVisibility(View.GONE); } private void useSavedServerUrl() { Credentials credentials; credentials = new Credentials(this); serverUrlText.setText(credentials.getServerUrl()); } @Override protected void onResume() { super.onResume(); setupStatusView(); IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(connectivityChangeReceiver, intentFilter); } private void setupStatusView() { if (!NetworkUtils.isConnectedToNetwork(this)) { if (backgroundAuthenticationTask != null) { backgroundAuthenticationTask.cancel(true); } noConnectivityText.setVisibility(View.VISIBLE); loginButton.setVisibility(View.GONE); authenticatingText.setVisibility(View.GONE); } else if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { noConnectivityText.setVisibility(View.GONE); loginButton.setVisibility(View.GONE); authenticatingText.setVisibility(View.VISIBLE); } else { noConnectivityText.setVisibility(View.GONE); loginButton.setVisibility(View.VISIBLE); authenticatingText.setVisibility(View.GONE); } } @Override protected void onPause() { super.onPause(); unregisterReceiver(connectivityChangeReceiver); } @Override protected void onDestroy() { super.onDestroy(); if (backgroundAuthenticationTask != null) { backgroundAuthenticationTask.cancel(true); } } private void setupListeners() { loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validInput()) { if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { Toast.makeText(getApplicationContext(), "Authentication in progress...", Toast.LENGTH_SHORT).show(); return; } backgroundAuthenticationTask = new BackgroundAuthenticationTask(); backgroundAuthenticationTask.execute( new Credentials(serverUrlText.getText().toString(), usernameText.getText().toString(), passwordText.getText().toString() )); } else { int errorColor = getResources().getColor(R.color.error_text_color); if (StringUtils.isEmpty(serverUrlText.getText().toString())) { serverUrlText.setHint("Please Enter Server URL"); serverUrlText.setHintTextColor(errorColor); } if (StringUtils.isEmpty(usernameText.getText().toString())) { usernameText.setHint("Please Enter Username"); usernameText.setHintTextColor(errorColor); } if (StringUtils.isEmpty(passwordText.getText().toString())) { passwordText.setHint("Please Enter Password"); passwordText.setHintTextColor(errorColor); } } } }); } private boolean validInput() { if (StringUtils.isEmpty(serverUrlText.getText().toString()) || StringUtils.isEmpty(usernameText.getText().toString()) || StringUtils.isEmpty(passwordText.getText().toString())) { return false; } return true; } private void initViews() { serverUrlText = (EditText) findViewById(R.id.serverUrl); usernameText = (EditText) findViewById(R.id.username); passwordText = (EditText) findViewById(R.id.password); loginButton = (Button) findViewById(R.id.login); noConnectivityText = (TextView) findViewById(R.id.noConnectionText); authenticatingText = (TextView) findViewById(R.id.authenticatingText); } private class BackgroundAuthenticationTask extends AsyncTask<Credentials, Void, BackgroundAuthenticationTask.Result> { @Override protected void onPreExecute() { if (loginButton.getVisibility() == View.VISIBLE) { flipFromLoginToAuthAnimator.start(); } } @Override protected Result doInBackground(Credentials... params) { Credentials credentials = params[0]; MuzimaSyncService muzimaSyncService = ((MuzimaApplication) getApplication()).getMuzimaSyncService(); int authenticationStatus = muzimaSyncService.authenticate(credentials.getCredentialsArray()); return new Result(credentials, authenticationStatus); } @Override protected void onPostExecute(Result result) { if (result.status == AUTHENTICATION_SUCCESS) { saveCredentials(result.credentials); startNextActivity(); } else { Toast.makeText(getApplicationContext(), "Authentication failed", Toast.LENGTH_SHORT).show(); if (authenticatingText.getVisibility() == View.VISIBLE || flipFromLoginToAuthAnimator.isRunning()) { flipFromLoginToAuthAnimator.cancel(); flipFromAuthToLoginAnimator.start(); } } } private void startNextActivity() { Intent intent; if (isWizardFinished()) { intent = new Intent(getApplicationContext(), MainActivity.class); } else { intent = new Intent(getApplicationContext(), CohortPrefixWizardActivity.class); } startActivity(intent); finish(); } private boolean isWizardFinished() { // return false; SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this); String wizardFinishedKey = getResources().getString(R.string.preference_wizard_finished); return settings.getBoolean(wizardFinishedKey, false); } private void saveCredentials(Credentials credentials) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String usernameKey = getResources().getString(R.string.preference_username); String passwordKey = getResources().getString(R.string.preference_password); String serverKey = getResources().getString(R.string.preference_server); settings.edit() .putString(usernameKey, credentials.getUserName()) .putString(passwordKey, credentials.getPassword()) .putString(serverKey, credentials.getServerUrl()) .commit(); } protected class Result { Credentials credentials; int status; private Result(Credentials credentials, int status) { this.credentials = credentials; this.status = status; } } } private BroadcastReceiver connectivityChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean connectedToNetwork = NetworkUtils.isConnectedToNetwork(context); Log.d(TAG, "onReceive(), connectedToNetwork : " + connectedToNetwork); if (connectedToNetwork) { onConnected(); } else { onDisconnected(); } } }; private void onConnected() { if (noConnectivityText.getVisibility() == View.VISIBLE) { flipFromNoConnToLoginAnimator.start(); } } private void onDisconnected() { if (loginButton.getVisibility() == View.VISIBLE) { flipFromLoginToNoConnAnimator.start(); } else if (authenticatingText.getVisibility() == View.VISIBLE) { flipFromAuthToNoConnAnimator.start(); } if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { backgroundAuthenticationTask.cancel(true); } } private void initAnimators() { flipFromLoginToNoConnAnimator = ValueAnimator.ofFloat(0, 1); flipFromNoConnToLoginAnimator = ValueAnimator.ofFloat(0, 1); flipFromLoginToAuthAnimator = ValueAnimator.ofFloat(0, 1); flipFromAuthToLoginAnimator = ValueAnimator.ofFloat(0, 1); flipFromAuthToNoConnAnimator = ValueAnimator.ofFloat(0, 1); initFlipAnimation(flipFromLoginToNoConnAnimator, loginButton, noConnectivityText); initFlipAnimation(flipFromNoConnToLoginAnimator, noConnectivityText, loginButton); initFlipAnimation(flipFromLoginToAuthAnimator, loginButton, authenticatingText); initFlipAnimation(flipFromAuthToLoginAnimator, authenticatingText, loginButton); initFlipAnimation(flipFromAuthToNoConnAnimator, authenticatingText, noConnectivityText); } public void initFlipAnimation(ValueAnimator valueAnimator, final View from, final View to) { valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); valueAnimator.setDuration(300); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float animatedFraction = animation.getAnimatedFraction(); if (from.getVisibility() == View.VISIBLE) { if (animatedFraction > 0.5) { from.setVisibility(View.INVISIBLE); to.setVisibility(View.VISIBLE); } } else if (to.getVisibility() == View.VISIBLE) { if(honeycombOrGreater){ to.setRotationX(-180 * (1 - animatedFraction)); } } if (from.getVisibility() == View.VISIBLE) { if(honeycombOrGreater){ from.setRotationX(180 * animatedFraction); } } } }); } }
package org.cyclops.integrateddynamics.core.network.diagnostics; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import lombok.Data; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import org.cyclops.cyclopscore.helper.L10NHelpers; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.network.packet.NetworkDiagnosticsSubscribePacket; import java.util.List; /** * Network diagnostics gui. * @author rubensworks */ public class GuiNetworkDiagnostics extends Application { private static GuiNetworkDiagnostics gui = null; private static Stage primaryStage = null; private static TableView<ObservablePartData> table = null; private static Multimap<Integer, ObservablePartData> networkData = ArrayListMultimap.create(); private ObservableList<ObservablePartData> partData = FXCollections.observableArrayList(networkData.values()); public static void setNetworkData(int id, RawNetworkData rawNetworkData) { synchronized (networkData) { networkData.removeAll(id); if (rawNetworkData != null) { List<ObservablePartData> parts = Lists.newArrayList(); for (RawPartData rawPartData : rawNetworkData.getParts()) { parts.add(new ObservablePartData( rawNetworkData.getId(), rawNetworkData.getCables(), rawPartData.getDimension(), rawPartData.getPos(), rawPartData.getSide(), rawPartData.getName(), rawPartData.getLastTickDuration())); } networkData.putAll(id, parts); } } if (gui != null) { gui.updateTable(); } } public static void clearNetworkData() { networkData.clear(); } public void start() { gui = this; Platform.setImplicitExit(false); if (primaryStage != null) { Platform.runLater(() -> { try { start(primaryStage); } catch (Exception e) { e.printStackTrace(); } }); } else { launch(); } } protected void updateTable() { synchronized (networkData) { if (table == null) { table = new TableView<>(); TableColumn<ObservablePartData, Integer> networkCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.network")); networkCol.prefWidthProperty().bind(table.widthProperty().divide(6)); networkCol.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getNetworkId())); TableColumn<ObservablePartData, Integer> cablesCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.cables")); cablesCol.prefWidthProperty().bind(table.widthProperty().divide(12)); cablesCol.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getNetworkCables())); TableColumn<ObservablePartData, String> partCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.part")); partCol.prefWidthProperty().bind(table.widthProperty().divide(6)); partCol.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getName())); TableColumn<ObservablePartData, Long> durationCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.ticktime")); durationCol.prefWidthProperty().bind(table.widthProperty().divide(6)); durationCol.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getLastTickDuration())); TableColumn<ObservablePartData, Integer> dimCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.dimension")); dimCol.prefWidthProperty().bind(table.widthProperty().divide(12)); dimCol.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getDimension())); TableColumn<ObservablePartData, String> posCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.position")); posCol.prefWidthProperty().bind(table.widthProperty().divide(6)); posCol.setCellValueFactory(p -> { BlockPos pos = p.getValue().getPos(); return new ReadOnlyObjectWrapper<>(String.format("%s / %s / %s", pos.getX(), pos.getY(), pos.getZ())); }); TableColumn<ObservablePartData, String> sideCol = new TableColumn<>(L10NHelpers.localize("gui.integrateddynamics.diagnostics.table.side")); sideCol.prefWidthProperty().bind(table.widthProperty().divide(6)); sideCol.setCellValueFactory(p -> new ReadOnlyObjectWrapper<>(p.getValue().getSide().name())); table.getColumns().addAll(networkCol, cablesCol, partCol, durationCol, dimCol, posCol, sideCol); table.setItems(partData); } partData.setAll(networkData.values()); table.sort(); } } @Override public void start(Stage primaryStage) throws Exception { GuiNetworkDiagnostics.primaryStage = primaryStage; primaryStage.setTitle(L10NHelpers.localize("gui.integrateddynamics.diagnostics.title")); BorderPane root = new BorderPane(); root.setPadding(new Insets(10, 20, 10, 20)); updateTable(); root.setCenter(table); table.autosize(); primaryStage.setScene(new Scene(root, 750, 500)); primaryStage.setOnCloseRequest(we -> IntegratedDynamics._instance.getPacketHandler() .sendToServer(NetworkDiagnosticsSubscribePacket.unsubscribe())); primaryStage.show(); } @Data public static class ObservablePartData { private final int networkId; private final int networkCables; private final int dimension; private final BlockPos pos; private final EnumFacing side; private final String name; private final long lastTickDuration; } }
package gov.nih.nci.ncicb.cadsr.loader.parser; import gov.nih.nci.ncicb.cadsr.loader.event.*; import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults; import org.apache.log4j.Logger; import org.omg.uml.foundation.core.*; import org.omg.uml.foundation.datatypes.MultiplicityRange; import org.omg.uml.foundation.extensionmechanisms.*; import org.omg.uml.modelmanagement.Model; import org.omg.uml.modelmanagement.UmlPackage; import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor; import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil; import gov.nih.nci.ncicb.cadsr.loader.validator.*; import gov.nih.nci.codegen.core.util.UML13Utils; import gov.nih.nci.codegen.core.access.UML13ModelAccess; import gov.nih.nci.codegen.framework.ModelAccess; import java.io.*; import java.util.*; /** * Implemetation of <code>Parser</code> for XMI files. Navigates the XMI document and sends UML Object events. * * @author <a href="mailto:ludetc@mail.nih.gov">Christophe Ludet</a> */ public class XMIParser implements Parser { private static final String EA_CONTAINMENT = "containment"; private static final String EA_UNSPECIFIED = "Unspecified"; private UMLHandler listener; private String packageName = ""; private String className = ""; private List associations = new ArrayList(); private Logger logger = Logger.getLogger(XMIParser.class.getName()); private List generalizationEvents = new ArrayList(); private List associationEvents = new ArrayList(); private ProgressListener progressListener = null; private final static String VD_STEREOTYPE = "CADSR Value Domain"; public static final String TV_PROP_ID = "CADSR_PROP_ID"; public static final String TV_PROP_VERSION = "CADSR_PROP_VERSION"; public static final String TV_DE_ID = "CADSR_DE_ID"; public static final String TV_DE_VERSION = "CADSR_DE_VERSION"; public static final String TV_VALUE_DOMAIN = "Value Domain"; public static final String TV_VD_ID = "CADSR_VD_ID"; public static final String TV_VD_VERSION = "CADSR_VD_VERSION"; public static final String TV_OC_ID = "CADSR_OC_ID"; public static final String TV_OC_VERSION = "CADSR_OC_VERSION"; public static final String TV_VD_DEFINITION = "CADSR_ValueDomainDefinition"; public static final String TV_VD_DATATYPE = "CADSR_ValueDomainDatatype"; public static final String TV_VD_TYPE = "CADSR_ValueDomainType"; public static final String TV_CD_ID = "CADSR_ConceptualDomainPublicID"; public static final String TV_CD_VERSION = "CADSR_ConceptDomainVersion"; /** * Tagged Value name for Concept Code */ public static final String TV_CONCEPT_CODE = "ConceptCode"; /** * Tagged Value name for Concept Preferred Name */ public static final String TV_CONCEPT_PREFERRED_NAME = "ConceptPreferredName"; /** * Tagged Value name for Concept Definition */ public static final String TV_CONCEPT_DEFINITION = "ConceptDefinition"; /** * Tagged Value name for Concept Definition Source */ public static final String TV_CONCEPT_DEFINITION_SOURCE = "ConceptDefinitionSource"; /** * Qualifier Tagged Value prepender. */ public static final String TV_QUALIFIER = "Qualifier"; /** * Qualifier Tagged Value prepender. */ public static final String TV_TYPE_CLASS = "ObjectClass"; /** * Qualifier Tagged Value prepender. */ public static final String TV_TYPE_PROPERTY = "Property"; /** * Tagged Value name for Documentation */ public static final String TV_DOCUMENTATION = "documentation"; public static final String TV_DESCRIPTION = "description"; public static final String TV_HUMAN_REVIEWED = "HUMAN_REVIEWED"; private String[] bannedClassNames = null; { bannedClassNames = PropertyAccessor.getProperty("banned.classNames").split(","); } public void setEventHandler(LoaderHandler handler) { this.listener = (UMLHandler) handler; } public void parse(String filename) throws ParserException { try { ProgressEvent evt = new ProgressEvent(); evt.setMessage("Parsing ..."); fireProgressEvent(evt); ModelAccess access = new UML13ModelAccess(); String s = filename.replaceAll("\\ ", "%20"); // Some file systems use absolute URIs that do // not start with '/'. if(!s.startsWith("/")) s = "/" + s; String uriStr = new java.net.URI("file://" + s).toString(); access.readModel(uriStr, "EA Model"); uml.UmlPackage umlExtent = (uml.UmlPackage) access.getOutermostExtent(); Model model = UML13Utils.getModel(umlExtent, "EA Model"); Iterator it = model.getOwnedElement().iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof UmlPackage) { doPackage((UmlPackage) o); } else if (o instanceof DataType) { doDataType((DataType) o); } else if (o instanceof UmlAssociation) { doAssociation((UmlAssociation) o); } else if (o instanceof UmlClass) { doClass((UmlClass) o); } else { logger.debug("Root Element: " + o.getClass()); } } fireLastEvents(); } catch (Exception e) { // logger.fatal("Could not parse: " + filename); // logger.fatal(e, e); throw new ParserException(e); } // end of try-catch } private void doPackage(UmlPackage pack) { UMLDefaults defaults = UMLDefaults.getInstance(); if (packageName.length() == 0) { // if(pack.getName().indexOf(" ") == -1) packageName = pack.getName(); } else { // if(pack.getName().indexOf(" ") == -1) packageName += ("." + pack.getName()); } if(isInPackageFilter(packageName)) { listener.newPackage(new NewPackageEvent(packageName)); } else { logger.info(PropertyAccessor.getProperty("skip.package", packageName)); } Iterator it = pack.getOwnedElement().iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof UmlPackage) { String oldPackage = packageName; doPackage((UmlPackage) o); packageName = oldPackage; } else if (o instanceof UmlClass) { doClass((UmlClass) o); } else if (o instanceof Stereotype) { doStereotype((Stereotype) o); } else if (o instanceof Component) { doComponent((Component) o); } else if (o instanceof UmlAssociation) { doAssociation((UmlAssociation) o); } else if (o instanceof Interface) { doInterface((Interface) o); } else { logger.debug("Package Child: " + o.getClass()); } } packageName = ""; } private void doClass(UmlClass clazz) { UMLDefaults defaults = UMLDefaults.getInstance(); String pName = getPackageName(clazz); className = clazz.getName(); Stereotype st = UML13Utils.getStereotype(clazz); if(st != null) if(st.getName().equals(VD_STEREOTYPE)) { doValueDomain(clazz); return; } if (pName != null) { className = pName + "." + className; } ProgressEvent evt = new ProgressEvent(); evt.setMessage("Parsing " + className); fireProgressEvent(evt); NewClassEvent event = new NewClassEvent(className.trim()); event.setPackageName(pName); setConceptInfo(clazz, event, TV_TYPE_CLASS); logger.debug("CLASS: " + className); logger.debug("CLASS PACKAGE: " + getPackageName(clazz)); if(isClassBanned(className)) { logger.info(PropertyAccessor.getProperty("class.filtered", className)); return; } if(StringUtil.isEmpty(pName)) { logger.info(PropertyAccessor.getProperty("class.no.package", className)); return; } TaggedValue tv = UML13Utils.getTaggedValue(clazz, TV_DOCUMENTATION); if(tv != null) { event.setDescription(tv.getValue()); } tv = UML13Utils.getTaggedValue(clazz, TV_HUMAN_REVIEWED); if(tv != null) { event.setReviewed(tv.getValue().equals("1")?true:false); } // Hold on this for now // tv = UML13Utils.getTaggedValue(clazz, TV_OC_ID); // if(tv != null) { // event.setPersistenceId(tv.getValue()); // tv = UML13Utils.getTaggedValue(clazz, TV_OC_VERSION); // if(tv != null) { // try { // event.setPersistenceVersion(new Float(tv.getValue())); // } catch (NumberFormatException e){ // } // end of try-catch if(isInPackageFilter(pName)) { listener.newClass(event); } else { logger.info(PropertyAccessor.getProperty("class.filtered", className)); return; } for (Iterator it = clazz.getFeature().iterator(); it.hasNext();) { Object o = it.next(); if (o instanceof Attribute) { doAttribute((Attribute) o); } else if (o instanceof Operation) { doOperation((Operation) o); } else { logger.debug("Class child: " + o.getClass()); } } className = ""; for (Iterator it = clazz.getGeneralization().iterator(); it.hasNext();) { Generalization g = (Generalization) it.next(); if (g.getParent() instanceof UmlClass) { UmlClass p = (UmlClass) g.getParent(); NewGeneralizationEvent gEvent = new NewGeneralizationEvent(); gEvent.setParentClassName( getPackageName(p) + "." + p.getName()); gEvent.setChildClassName( getPackageName(clazz) + "." + clazz.getName()); generalizationEvents.add(gEvent); } } } private void doValueDomain(UmlClass clazz) { UMLDefaults defaults = UMLDefaults.getInstance(); className = clazz.getName(); ProgressEvent evt = new ProgressEvent(); evt.setMessage("Parsing " + className); fireProgressEvent(evt); NewValueDomainEvent event = new NewValueDomainEvent(className.trim()); // event.setPackageName("ValueDomains"); setConceptInfo(clazz, event, TV_TYPE_CLASS); logger.debug("Value Domain: " + className); TaggedValue tv = UML13Utils.getTaggedValue(clazz, TV_VD_DEFINITION); if(tv != null) { event.setDescription(tv.getValue()); } tv = UML13Utils.getTaggedValue(clazz, TV_VD_DATATYPE); if(tv != null) { event.setDatatype(tv.getValue()); } tv = UML13Utils.getTaggedValue(clazz, TV_VD_TYPE); if(tv != null) { event.setType(tv.getValue()); } tv = UML13Utils.getTaggedValue(clazz, TV_CD_ID); if(tv != null) { event.setCdId(tv.getValue()); } tv = UML13Utils.getTaggedValue(clazz, TV_CD_VERSION); if(tv != null) { try { event.setCdVersion(new Float(tv.getValue())); } catch (NumberFormatException e){ logger.warn(PropertyAccessor.getProperty("version.numberFormatException", tv.getValue())); } // end of try-catch } tv = UML13Utils.getTaggedValue(clazz, TV_HUMAN_REVIEWED); if(tv != null) { event.setReviewed(tv.getValue().equals("1")?true:false); } for (Object o : clazz.getFeature()) { if (o instanceof Attribute) { doValueMeaning((Attribute) o); } else { logger.debug("Class child: " + o.getClass()); } } listener.newValueDomain(event); className = ""; } private void doInterface(Interface interf) { className = packageName + "." + interf.getName(); // logger.debug("Class: " + className); listener.newInterface(new NewInterfaceEvent(className.trim())); Iterator it = interf.getFeature().iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof Attribute) { doAttribute((Attribute) o); } else if (o instanceof Operation) { doOperation((Operation) o); } else { logger.debug("Class child: " + o.getClass()); } } className = ""; } private void doAttribute(Attribute att) { NewAttributeEvent event = new NewAttributeEvent(att.getName().trim()); event.setClassName(className); if(att.getType() == null || att.getType().getName() == null) { ValidationItems.getInstance() .addItem(new ValidationFatal (PropertyAccessor .getProperty ("validation.type.missing.for" , event.getClassName() + "." + event.getName()), null)); return; } // See if datatype is a simple datatype or a value domain. TaggedValue tv = UML13Utils.getTaggedValue(att, TV_VALUE_DOMAIN); if(tv != null) { // Use Value Domain event.setType(tv.getValue()); } else { // Use datatype event.setType(att.getType().getName()); } tv = UML13Utils.getTaggedValue(att, TV_DESCRIPTION); if(tv != null) { event.setDescription(tv.getValue()); } else { tv = UML13Utils.getTaggedValue(att, TV_DOCUMENTATION); if(tv != null) { event.setDescription(tv.getValue()); } } tv = UML13Utils.getTaggedValue(att, TV_HUMAN_REVIEWED); if(tv != null) { event.setReviewed(tv.getValue().equals("1")?true:false); } // Is this attribute mapped to an existing CDE? tv = UML13Utils.getTaggedValue(att, TV_DE_ID); if(tv != null) { event.setPersistenceId(tv.getValue()); } tv = UML13Utils.getTaggedValue(att, TV_DE_VERSION); if(tv != null) { try { event.setPersistenceVersion(new Float(tv.getValue())); } catch (NumberFormatException e){ } // end of try-catch } setConceptInfo(att, event, TV_TYPE_PROPERTY); listener.newAttribute(event); } private void doValueMeaning(Attribute att) { NewValueMeaningEvent event = new NewValueMeaningEvent(att.getName().trim()); event.setValueDomainName(className); TaggedValue tv = UML13Utils.getTaggedValue(att, TV_HUMAN_REVIEWED); if(tv != null) { event.setReviewed(tv.getValue().equals("1")?true:false); } setConceptInfo(att, event, TV_TYPE_PROPERTY); listener.newValueMeaning(event); } private void doDataType(DataType dt) { listener.newDataType(new NewDataTypeEvent(dt.getName())); } private void doOperation(Operation op) { NewOperationEvent event = new NewOperationEvent(op.getName()); event.setClassName(className); listener.newOperation(event); } private void doStereotype(Stereotype st) { logger.debug("--- Stereotype " + st.getName()); } private void doAssociation(UmlAssociation assoc) { Iterator it = assoc.getConnection().iterator(); NewAssociationEvent event = new NewAssociationEvent(); event.setRoleName(assoc.getName()); String navig = ""; if (it.hasNext()) { Object o = it.next(); if (o instanceof AssociationEnd) { AssociationEnd end = (AssociationEnd) o; // logger.debug("end A is navigable: " + end.isNavigable()); if (end.isNavigable()) { navig += 'A'; } Classifier classif = end.getType(); if(!isInPackageFilter(getPackageName(classif))) { logger.info(PropertyAccessor.getProperty("skip.association", classif.getNamespace().getName())); logger.debug("classif name: " + classif.getName()); return; } Collection range = end.getMultiplicity().getRange(); for (Iterator it2 = range.iterator(); it2.hasNext();) { MultiplicityRange mr = (MultiplicityRange) it2.next(); int low = mr.getLower(); int high = mr.getUpper(); event.setALowCardinality(low); event.setAHighCardinality(high); } event.setAClassName(getPackageName(classif) + "." + classif.getName()); event.setARole(end.getName()); if(event.getAClassName() == null) { logger.debug("AClassName: NULL"); return; } else { logger.debug("AClassName: " + event.getAClassName()); } } } else { logger.debug("Association has one missing END"); return; } if (it.hasNext()) { Object o = it.next(); if (o instanceof AssociationEnd) { AssociationEnd end = (AssociationEnd) o; // logger.debug("end B is navigable: " + end.isNavigable()); if (end.isNavigable()) { navig += 'B'; } Classifier classif = end.getType(); if(!isInPackageFilter(getPackageName(classif))) { logger.info(PropertyAccessor.getProperty("skip.association", classif.getName())); logger.debug("classif name: " + classif.getNamespace().getName()); return; } Collection range = end.getMultiplicity().getRange(); for (Iterator it2 = range.iterator(); it2.hasNext();) { MultiplicityRange mr = (MultiplicityRange) it2.next(); int low = mr.getLower(); int high = mr.getUpper(); event.setBLowCardinality(low); event.setBHighCardinality(high); } event.setBClassName(getPackageName(classif) + "." + classif.getName()); event.setBRole(end.getName()); if(event.getBClassName() == null) return; } } else { logger.debug("Association has one missing END"); return; } // logger.debug("A END -- " + event.getAClassName() + " " + event.getALowCardinality()); // logger.debug("B END -- " + event.getBClassName() + " " + event.getBLowCardinality()); // netbeans seems to read self pointing associations wrong. Such that an end is navigable but has no target role, even though it does in the model. if(event.getAClassName().equals(event.getBClassName())) { if(navig.equals("B") && StringUtil.isEmpty(event.getBRole())) { event.setBRole(event.getARole()); event.setBLowCardinality(event.getALowCardinality()); event.setBHighCardinality(event.getAHighCardinality()); } else if (navig.equals("A") && StringUtil.isEmpty(event.getARole())) { event.setARole(event.getBRole()); event.setALowCardinality(event.getBLowCardinality()); event.setAHighCardinality(event.getBHighCardinality()); } } event.setDirection(navig); logger.debug("Adding association. AClassName: " + event.getAClassName()); associationEvents.add(event); } private void doComponent(Component comp) { logger.debug("--- Component: " + comp.getName()); } private String cardinality(AssociationEnd end) { Collection range = end.getMultiplicity().getRange(); for (Iterator it = range.iterator(); it.hasNext();) { MultiplicityRange mr = (MultiplicityRange) it.next(); int low = mr.getLower(); int high = mr.getUpper(); if (low == high) { return "" + low; } else { String h = (high >= 0) ? ("" + high) : "*"; return low + ".." + h; } } return ""; } private void fireLastEvents() { for (Iterator it = associationEvents.iterator(); it.hasNext();) { listener.newAssociation((NewAssociationEvent) it.next()); } for (Iterator it = generalizationEvents.iterator(); it.hasNext();) { listener.newGeneralization((NewGeneralizationEvent) it.next()); } ProgressEvent evt = new ProgressEvent(); evt.setGoal(100); evt.setStatus(100); evt.setMessage("Done"); fireProgressEvent(evt); } private void setConceptInfo(ModelElement elt, NewConceptualEvent event, String type) { NewConceptEvent concept = new NewConceptEvent(); setConceptInfo(elt, concept, type, "", 0); if(!StringUtil.isEmpty(concept.getConceptCode())) event.addConcept(concept); concept = new NewConceptEvent(); for(int i=1;setConceptInfo(elt, concept, type, TV_QUALIFIER, i); i++) { if(!StringUtil.isEmpty(concept.getConceptCode())) event.addConcept(concept); concept = new NewConceptEvent(); } } private boolean setConceptInfo(ModelElement elt, NewConceptEvent event, String type, String pre, int n) { TaggedValue tv = UML13Utils.getTaggedValue(elt, type + pre + TV_CONCEPT_CODE + ((n>0)?""+n:"")); if (tv != null) { event.setConceptCode(tv.getValue().trim()); } else return false; tv = UML13Utils.getTaggedValue(elt, type + pre + TV_CONCEPT_DEFINITION + ((n>0)?""+n:"")); if (tv != null) { event.setConceptDefinition(tv.getValue().trim()); } tv = UML13Utils.getTaggedValue(elt, type + pre + TV_CONCEPT_DEFINITION_SOURCE + ((n>0)?""+n:"")); if (tv != null) { event.setConceptDefinitionSource(tv.getValue().trim()); } tv = UML13Utils.getTaggedValue(elt, type + pre + TV_CONCEPT_PREFERRED_NAME + ((n>0)?""+n:"")); if (tv != null) { event.setConceptPreferredName(tv.getValue().trim()); } event.setOrder(n); return true; } private boolean isInPackageFilter(String pName) { Map packageFilter = UMLDefaults.getInstance().getPackageFilter(); return (packageFilter.size() == 0) || (packageFilter.containsKey(pName) || (UMLDefaults.getInstance().getDefaultPackageAlias() != null)); } private String getPackageName(ModelElement elt) { StringBuffer pack = new StringBuffer(); String s = null; do { s = null; if (elt.getNamespace() != null) { s = elt.getNamespace().getName(); if(s.indexOf(" ") == -1) { // if(!s.startsWith("EA ")) { if(pack.length() > 0) pack.insert(0, '.'); pack.insert(0, s); } elt = elt.getNamespace(); } } while (s != null); return pack.toString(); } private boolean isClassBanned(String className) { for(int i=0; i<bannedClassNames.length; i++) { if(className.indexOf(bannedClassNames[i]) > -1) return true; } return false; } private void fireProgressEvent(ProgressEvent evt) { if(progressListener != null) progressListener.newProgressEvent(evt); } public void addProgressListener(ProgressListener listener) { progressListener = listener; } }
package com.muzima.view.login; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.internal.nineoldandroids.animation.ValueAnimator; import com.muzima.MuzimaApplication; import com.muzima.R; import com.muzima.domain.Credentials; import com.muzima.service.CredentialsPreferenceService; import com.muzima.service.MuzimaSyncService; import com.muzima.service.WizardFinishPreferenceService; import com.muzima.utils.StringUtils; import com.muzima.view.MainActivity; import com.muzima.view.cohort.CohortWizardActivity; import static com.muzima.utils.Constants.DataSyncServiceConstants.SyncStatusConstants; //This class shouldn't extend BaseActivity. Since it is independent of the application's context public class LoginActivity extends Activity { private static final String TAG = "LoginActivity"; public static final String isFirstLaunch = "isFirstLaunch"; public static final String sessionTimeOut = "SessionTimeOut"; private EditText serverUrlText; private EditText usernameText; private EditText passwordText; private Button loginButton; private TextView versionText ; private BackgroundAuthenticationTask backgroundAuthenticationTask; private TextView authenticatingText; private ValueAnimator flipFromNoConnToLoginAnimator; private ValueAnimator flipFromLoginToNoConnAnimator; private ValueAnimator flipFromLoginToAuthAnimator; private ValueAnimator flipFromAuthToLoginAnimator; private ValueAnimator flipFromAuthToNoConnAnimator; private boolean honeycombOrGreater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MuzimaApplication)getApplication()).cancelTimer(); setContentView(R.layout.activity_login); showSessionTimeOutPopUpIfNeeded(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { honeycombOrGreater = true; } initViews(); setupListeners(); initAnimators(); boolean isFirstLaunch = getIntent().getBooleanExtra(LoginActivity.isFirstLaunch, true); String serverURL = getServerURL(); if (!isFirstLaunch && !StringUtils.isEmpty(serverURL)) { removeServerUrlAsInput(); } useSavedServerUrl(serverURL); //Hack to get it to use default font space. passwordText.setTypeface(Typeface.DEFAULT); versionText.setText(getApplicationVersion()); } private void showSessionTimeOutPopUpIfNeeded() { if (getIntent().getBooleanExtra(LoginActivity.sessionTimeOut, false)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder .setCancelable(true) .setIcon(getResources().getDrawable(R.drawable.ic_warning)) .setTitle(getResources().getString(R.string.session_timed_out_header)) .setMessage(getResources().getString(R.string.session_timed_out_msg)) .setPositiveButton("Ok", null).show(); } } private void removeServerUrlAsInput() { serverUrlText.setVisibility(View.GONE); findViewById(R.id.server_url_divider).setVisibility(View.GONE); } private void useSavedServerUrl(String serverUrl) { if (!StringUtils.isEmpty(serverUrl)) { serverUrlText.setText(serverUrl); } } private String getApplicationVersion() { String versionText = "" ; String versionCode = "" ; try { versionCode = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); versionText = String.format(getResources().getString(R.string.version), versionCode) ; } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Unable to read application version.", e); } return versionText ; } private String getServerURL() { Credentials credentials; credentials = new Credentials(this); return credentials.getServerUrl(); } @Override public void onResume() { super.onResume(); setupStatusView(); } private void setupStatusView() { if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { loginButton.setVisibility(View.GONE); authenticatingText.setVisibility(View.VISIBLE); } else { loginButton.setVisibility(View.VISIBLE); authenticatingText.setVisibility(View.GONE); } } @Override protected void onDestroy() { super.onDestroy(); if (backgroundAuthenticationTask != null) { backgroundAuthenticationTask.cancel(true); } } @Override public void onBackPressed() { moveTaskToBack(true); } private void setupListeners() { loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validInput()) { if (backgroundAuthenticationTask != null && backgroundAuthenticationTask.getStatus() == AsyncTask.Status.RUNNING) { Toast.makeText(getApplicationContext(), "Authentication in progress...", Toast.LENGTH_SHORT).show(); return; } backgroundAuthenticationTask = new BackgroundAuthenticationTask(); backgroundAuthenticationTask.execute( new Credentials(serverUrlText.getText().toString(), usernameText.getText().toString(), passwordText.getText().toString() )); } else { int errorColor = getResources().getColor(R.color.error_text_color); if (StringUtils.isEmpty(serverUrlText.getText().toString())) { serverUrlText.setHint("Please Enter Server URL"); serverUrlText.setHintTextColor(errorColor); } if (StringUtils.isEmpty(usernameText.getText().toString())) { usernameText.setHint("Please Enter Username"); usernameText.setHintTextColor(errorColor); } if (StringUtils.isEmpty(passwordText.getText().toString())) { passwordText.setHint("Please Enter Password"); passwordText.setHintTextColor(errorColor); } } } }); } private boolean validInput() { return !(StringUtils.isEmpty(serverUrlText.getText().toString()) || StringUtils.isEmpty(usernameText.getText().toString()) || StringUtils.isEmpty(passwordText.getText().toString())); } private void initViews() { serverUrlText = (EditText) findViewById(R.id.serverUrl); usernameText = (EditText) findViewById(R.id.username); passwordText = (EditText) findViewById(R.id.password); loginButton = (Button) findViewById(R.id.login); authenticatingText = (TextView) findViewById(R.id.authenticatingText); versionText = (TextView) findViewById(R.id.version) ; } private class BackgroundAuthenticationTask extends AsyncTask<Credentials, Void, BackgroundAuthenticationTask.Result> { @Override protected void onPreExecute() { if (loginButton.getVisibility() == View.VISIBLE) { flipFromLoginToAuthAnimator.start(); } } @Override protected Result doInBackground(Credentials... params) { Credentials credentials = params[0]; MuzimaSyncService muzimaSyncService = ((MuzimaApplication) getApplication()).getMuzimaSyncService(); int authenticationStatus = muzimaSyncService.authenticate(credentials.getCredentialsArray()); return new Result(credentials, authenticationStatus); } @Override protected void onPostExecute(Result result) { if (result.status == SyncStatusConstants.AUTHENTICATION_SUCCESS) { new CredentialsPreferenceService(getApplicationContext()).saveCredentials(result.credentials); ((MuzimaApplication) getApplication()).restartTimer(); startNextActivity(); } else { Toast.makeText(getApplicationContext(), getErrorText(result), Toast.LENGTH_SHORT).show(); if (authenticatingText.getVisibility() == View.VISIBLE || flipFromLoginToAuthAnimator.isRunning()) { flipFromLoginToAuthAnimator.cancel(); flipFromAuthToLoginAnimator.start(); } } } private String getErrorText(Result result) { switch (result.status) { case SyncStatusConstants.MALFORMED_URL_ERROR: return "Invalid Server URL."; case SyncStatusConstants.INVALID_CREDENTIALS_ERROR: return "Invalid Username, Password, Server combination."; case SyncStatusConstants.INVALID_CHARACTER_IN_USERNAME: return "Invalid Character in Username. These are not allowed: " + SyncStatusConstants.INVALID_CHARACTER_FOR_USERNAME ; case SyncStatusConstants.CONNECTION_ERROR: return "Error while connecting your server."; default: return "Authentication failed"; } } private void startNextActivity() { Intent intent; if (new WizardFinishPreferenceService(LoginActivity.this).isWizardFinished()) { intent = new Intent(getApplicationContext(), MainActivity.class); } else { ((MuzimaApplication)getApplication()).clearApplicationData(); intent = new Intent(getApplicationContext(), CohortWizardActivity.class); } startActivity(intent); finish(); } protected class Result { Credentials credentials; int status; private Result(Credentials credentials, int status) { this.credentials = credentials; this.status = status; } } } private void initAnimators() { flipFromLoginToNoConnAnimator = ValueAnimator.ofFloat(0, 1); flipFromNoConnToLoginAnimator = ValueAnimator.ofFloat(0, 1); flipFromLoginToAuthAnimator = ValueAnimator.ofFloat(0, 1); flipFromAuthToLoginAnimator = ValueAnimator.ofFloat(0, 1); flipFromAuthToNoConnAnimator = ValueAnimator.ofFloat(0, 1); initFlipAnimation(flipFromLoginToAuthAnimator, loginButton, authenticatingText); initFlipAnimation(flipFromAuthToLoginAnimator, authenticatingText, loginButton); } public void initFlipAnimation(ValueAnimator valueAnimator, final View from, final View to) { valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); valueAnimator.setDuration(300); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float animatedFraction = animation.getAnimatedFraction(); if (from.getVisibility() == View.VISIBLE) { if (animatedFraction > 0.5) { from.setVisibility(View.INVISIBLE); to.setVisibility(View.VISIBLE); } } else if (to.getVisibility() == View.VISIBLE) { if (honeycombOrGreater) { to.setRotationX(-180 * (1 - animatedFraction)); } } if (from.getVisibility() == View.VISIBLE) { if (honeycombOrGreater) { from.setRotationX(180 * animatedFraction); } } } }); } }
package gov.nih.nci.ncicb.cadsr.loader.parser; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.util.LookupUtil; import org.jdom.*; import org.jdom.input.SAXBuilder; import org.jaxen.JaxenException; import org.jaxen.jdom.JDOMXPath; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import java.io.*; import java.util.*; public class XMIWriter implements ElementWriter { private String output = null; private UserSelections userSelections = UserSelections.getInstance(); private String input = (String)userSelections.getProperty("FILENAME"); private Element modelElement; private HashMap<String, Element> elements = new HashMap(); private ElementsLists cadsrObjects = null; private ReviewTracker reviewTracker = ReviewTracker.getInstance(); public XMIWriter() { try { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(input); modelElement = doc.getRootElement(); } catch (Exception ex) { throw new RuntimeException("Error initializing model", ex); } } public void write(ElementsLists elements) { this.cadsrObjects = elements; readModel(); markHumanReviewed(); writeModel(); } public void setOutput(String url) { this.output = url; } /** * Copy / Paste from caCORE-Toolkit ModelAnnotator * */ private void addTaggedValue (String tagName, String value, String newId, String xmiid, Namespace namespace) throws JaxenException { Element taggedValue = new Element("TaggedValue", namespace); taggedValue.setNamespace(Namespace.getNamespace("UML", "href://org.omg/UML")); taggedValue.setAttribute(new Attribute("xmi.id", newId)); taggedValue.setAttribute(new Attribute("tag", tagName)); taggedValue.setAttribute(new Attribute("modelElement", xmiid)); taggedValue.setAttribute(new Attribute("value", value)); /** * * Copy / Paste from caCORE-Toolkit ModelAnnotator * */ private Element getElement (Element classElement, String exp) throws JaxenException { Element element = null; try { element = (Element) (new JDOMXPath(exp)).selectSingleNode(classElement); } catch (Exception ex) { throw new RuntimeException("Error searching for expression " + exp + " in class " + classElement.getAttributeValue("name"), ex); } return element; } private List<Element> getElements (Element classElement, String elementName) throws JaxenException { List<Element> elementList = null; try { /** * Copy / Paste from caCORE-Toolkit ModelAnnotator * */ private void writeModel() { try { File f = new File(output); Writer writer = new OutputStreamWriter (new FileOutputStream(f), "UTF-8"); XMLOutputter xmlout = new XMLOutputter(); xmlout.setFormat(Format.getPrettyFormat()); writer.write(xmlout.outputString(modelElement)); writer.flush(); writer.close(); } catch (Exception ex) { throw new RuntimeException("Error writing to " + output, ex); } } /** * Copy / Paste from caCORE-Toolkit ModelAnnotator * */ private String getNewId(String xmiid) throws JaxenException { String id = null; try { /** * Copy / Paste from caCORE-Toolkit ModelAnnotator * */ private void readModel(){ try {
package com.nirima.docker.client.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import java.util.List; /** * * @author Konstantin Pelykh (kpelykh@gmail.com) * */ @JsonIgnoreProperties(ignoreUnknown = true) public class Info { @JsonProperty("Debug") private boolean debug; @JsonProperty("Containers") private int containers; @JsonProperty("Driver") private String driver; @JsonProperty("DriverStatus") private List<Object> driverStatuses; @JsonProperty("Images") private int images; @JsonProperty("IPv4Forwarding") private String IPv4Forwarding; @JsonProperty("IndexServerAddress") private String IndexServerAddress; @JsonProperty("KernelVersion") private String kernelVersion; @JsonProperty("LXCVersion") private String lxcVersion; @JsonProperty("MemoryLimit") private boolean memoryLimit; @JsonProperty("NEventsListener") private long nEventListener; @JsonProperty("NFd") private int NFd; @JsonProperty("NGoroutines") private int NGoroutines; @JsonProperty("InitPath") private String initPath; @JsonProperty("InitSha1") private String initSha1; @JsonProperty("SwapLimit") private int swapLimit; @JsonProperty("ExecutionDriver") private String executionDriver; public boolean isDebug() { return debug; } public int getContainers() { return containers; } public String getDriver() { return driver; } public List<Object> getDriverStatuses() { return driverStatuses; } public int getImages() { return images; } public String getIPv4Forwarding() { return IPv4Forwarding; } public String getIndexServerAddress() { return IndexServerAddress; } public String getKernelVersion() { return kernelVersion; } public String getLxcVersion() { return lxcVersion; } public boolean isMemoryLimit() { return memoryLimit; } public long getnEventListener() { return nEventListener; } public int getNFd() { return NFd; } public int getNGoroutines() { return NGoroutines; } public String getExecutionDriver() { return executionDriver; } public int getSwapLimit() { return swapLimit; } public String getInitPath() { return initPath; } public String getInitSha1() { return initSha1; } @Override public String toString() { return Objects.toStringHelper(this) .add("debug", debug) .add("containers", containers) .add("driver", driver) .add("driverStatuses", driverStatuses) .add("images", images) .add("IPv4Forwarding", IPv4Forwarding) .add("IndexServerAddress", IndexServerAddress) .add("kernelVersion", kernelVersion) .add("lxcVersion", lxcVersion) .add("memoryLimit", memoryLimit) .add("nEventListener", nEventListener) .add("NFd", NFd) .add("NGoroutines", NGoroutines) .add("initPath", initPath) .add("initSha1", initSha1) .add("swapLimit", swapLimit) .add("executionDriver", executionDriver) .toString(); } }
package org.sagebionetworks.web.client.widget.table.v2.results; import static org.sagebionetworks.web.client.ServiceEntryPointUtils.fixServiceEntryPoint; import static org.sagebionetworks.web.client.widget.table.v2.TableEntityWidget.DEFAULT_LIMIT; import static org.sagebionetworks.web.client.widget.table.v2.TableEntityWidget.DEFAULT_OFFSET; import java.util.ArrayList; import java.util.List; import org.sagebionetworks.repo.model.ErrorResponseCode; import org.sagebionetworks.repo.model.asynch.AsynchronousResponseBody; import org.sagebionetworks.repo.model.table.FacetColumnRequest; import org.sagebionetworks.repo.model.table.Query; import org.sagebionetworks.repo.model.table.QueryBundleRequest; import org.sagebionetworks.repo.model.table.QueryResult; import org.sagebionetworks.repo.model.table.QueryResultBundle; import org.sagebionetworks.repo.model.table.Row; import org.sagebionetworks.repo.model.table.RowSet; import org.sagebionetworks.repo.model.table.SelectColumn; import org.sagebionetworks.repo.model.table.SortDirection; import org.sagebionetworks.repo.model.table.SortItem; import org.sagebionetworks.web.client.GWTWrapper; import org.sagebionetworks.web.client.PopupUtilsView; import org.sagebionetworks.web.client.PortalGinInjector; import org.sagebionetworks.web.client.SynapseClientAsync; import org.sagebionetworks.web.client.cache.ClientCache; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.asynch.AsynchronousProgressHandler; import org.sagebionetworks.web.client.widget.asynch.AsynchronousProgressWidget; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import org.sagebionetworks.web.client.widget.table.modal.fileview.TableType; import org.sagebionetworks.web.client.widget.table.v2.results.facets.FacetsWidget; import org.sagebionetworks.web.shared.asynch.AsynchType; import org.sagebionetworks.web.shared.exceptions.BadRequestException; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; /** * This widget will execute a table query and show the resulting query results in a paginated view.. * * @author jmhill * */ public class TableQueryResultWidget implements TableQueryResultView.Presenter, IsWidget, PagingAndSortingListener { public static final String SCHEMA_CHANGED_MESSAGE = "The underlying Table/View schema has been changed so this query must be reset."; public static final String FACET_COLUMNS_CHANGED_MESSAGE = "requested facet column names must all be in the set"; public static final int ETAG_CHECK_DELAY_MS = 5000; public static final String VERIFYING_ETAG_MESSAGE = "Verifying that the recent changes have propagated through the system..."; public static final String RUNNING_QUERY_MESSAGE = ""; // while running, just show loading spinner (and cancel) public static final String QUERY_CANCELED = "Query canceled"; /** * Masks for requesting what should be included in the query bundle. */ public static final long BUNDLE_MASK_QUERY_RESULTS = 0x1; public static final long BUNDLE_MASK_QUERY_COUNT = 0x2; public static final long BUNDLE_MASK_QUERY_SELECT_COLUMNS = 0x4; public static final long BUNDLE_MASK_QUERY_MAX_ROWS_PER_PAGE = 0x8; public static final long BUNDLE_MASK_QUERY_COLUMN_MODELS = 0x10; public static final long BUNDLE_MASK_QUERY_FACETS = 0x20; public static final long BUNDLE_MASK_QUERY_SUM_FILE_SIZES = 0x40; public static final long BUNDLE_MASK_QUERY_LAST_UPDATED = 0x80; private static final Long ALL_PARTS_MASK = new Long(255); SynapseClientAsync synapseClient; TableQueryResultView view; PortalGinInjector ginInjector; QueryResultBundle bundle; TablePageWidget pageViewerWidget; QueryResultEditorWidget queryResultEditor; Query startingQuery; boolean isEditable; TableType tableType; QueryResultsListener queryListener; SynapseAlert synapseAlert; CallbackP<FacetColumnRequest> facetChangedHandler; Callback resetFacetsHandler; ClientCache clientCache; GWTWrapper gwt; int currentJobIndex = 0; QueryResultBundle cachedFullQueryResultBundle = null; FacetsWidget facetsWidget; boolean facetsRequireRefresh; PopupUtilsView popupUtils; @Inject public TableQueryResultWidget(TableQueryResultView view, SynapseClientAsync synapseClient, PortalGinInjector ginInjector, SynapseAlert synapseAlert, ClientCache clientCache, GWTWrapper gwt, FacetsWidget facetsWidget, PopupUtilsView popupUtils) { this.synapseClient = synapseClient; fixServiceEntryPoint(synapseClient); this.view = view; this.ginInjector = ginInjector; this.pageViewerWidget = ginInjector.createNewTablePageWidget(); this.synapseAlert = synapseAlert; this.clientCache = clientCache; this.gwt = gwt; this.facetsWidget = facetsWidget; this.popupUtils = popupUtils; view.setFacetsWidget(facetsWidget); this.view.setPageWidget(this.pageViewerWidget); this.view.setPresenter(this); this.view.setSynapseAlertWidget(synapseAlert.asWidget()); resetFacetsHandler = new Callback() { @Override public void invoke() { startingQuery.setSelectedFacets(null); cachedFullQueryResultBundle = null; startingQuery.setOffset(0L); queryChanging(); } }; facetChangedHandler = new CallbackP<FacetColumnRequest>() { @Override public void invoke(FacetColumnRequest request) { List<FacetColumnRequest> selectedFacets = startingQuery.getSelectedFacets(); if (selectedFacets == null) { selectedFacets = new ArrayList<FacetColumnRequest>(); startingQuery.setSelectedFacets(selectedFacets); } for (FacetColumnRequest facetColumnRequest : selectedFacets) { if (facetColumnRequest.getColumnName().equals(request.getColumnName())) { selectedFacets.remove(facetColumnRequest); break; } } selectedFacets.add(request); cachedFullQueryResultBundle = null; startingQuery.setOffset(0L); facetsRequireRefresh = true; queryChanging(); } }; } /** * Configure this widget with a query string. * * @param queryString * @param isEditable Is the user allowed to edit the query results? * @param is table a file view? * @param listener Listener for query start and finish events. */ public void configure(Query query, boolean isEditable, TableType tableType, QueryResultsListener listener) { facetsRequireRefresh = true; this.isEditable = isEditable; this.tableType = tableType; this.startingQuery = query; this.queryListener = listener; cachedFullQueryResultBundle = null; runQuery(); } private void runQuery() { currentJobIndex++; runQuery(currentJobIndex); } private void runQuery(final int jobIndex) { this.view.setErrorVisible(false); fireStartEvent(); pageViewerWidget.setTableVisible(false); this.view.setProgressWidgetVisible(true); String entityId = QueryBundleUtils.getTableId(this.startingQuery); String viewEtag = clientCache.get(entityId + QueryResultEditorWidget.VIEW_RECENTLY_CHANGED_KEY); if (viewEtag == null) { if (facetsRequireRefresh) { // no need to update facets if it's just a page change or sort facetsWidget.configure(startingQuery, facetChangedHandler, resetFacetsHandler); } else { // facet refresh unnecessary for this query execution, but reset to true for next time. facetsRequireRefresh = true; } // run the job QueryBundleRequest qbr = new QueryBundleRequest(); long partMask = BUNDLE_MASK_QUERY_RESULTS | BUNDLE_MASK_QUERY_LAST_UPDATED; // do not ask for query count if (cachedFullQueryResultBundle == null) { partMask = partMask | BUNDLE_MASK_QUERY_COLUMN_MODELS | BUNDLE_MASK_QUERY_SELECT_COLUMNS; } else { // we can release the old query result cachedFullQueryResultBundle.setQueryResult(null); } qbr.setPartMask(partMask); qbr.setQuery(this.startingQuery); qbr.setEntityId(entityId); AsynchronousProgressWidget progressWidget = ginInjector.creatNewAsynchronousProgressWidget(); this.view.setProgressWidget(progressWidget); progressWidget.startAndTrackJob(RUNNING_QUERY_MESSAGE, false, AsynchType.TableQuery, qbr, new AsynchronousProgressHandler() { @Override public void onFailure(Throwable failure) { if (currentJobIndex == jobIndex) { showError(failure); } } @Override public void onComplete(AsynchronousResponseBody response) { if (currentJobIndex == jobIndex) { setQueryResults((QueryResultBundle) response); } } @Override public void onCancel() { if (currentJobIndex == jobIndex) { showError(QUERY_CANCELED); } } }); } else { verifyOldEtagIsNotInView(entityId, viewEtag); } } /** * Look for the given etag in the given file view. If it is still there, wait a few seconds and try * again. If the etag is not in the view, then remove the clientCache key and run the query (since * this indicates that the user change was propagated to the replicated layer) * * @param fileViewEntityId * @param oldEtag */ public void verifyOldEtagIsNotInView(final String fileViewEntityId, String oldEtag) { // check to see if etag exists in view QueryBundleRequest qbr = new QueryBundleRequest(); qbr.setPartMask(ALL_PARTS_MASK); Query query = new Query(); query.setSql("select * from " + fileViewEntityId + " where ROW_ETAG='" + oldEtag + "'"); query.setOffset(DEFAULT_OFFSET); query.setLimit(DEFAULT_LIMIT); qbr.setQuery(query); qbr.setEntityId(fileViewEntityId); AsynchronousProgressWidget progressWidget = ginInjector.creatNewAsynchronousProgressWidget(); this.view.setProgressWidget(progressWidget); progressWidget.startAndTrackJob(VERIFYING_ETAG_MESSAGE, false, AsynchType.TableQuery, qbr, new AsynchronousProgressHandler() { @Override public void onFailure(Throwable failure) { showError(failure); } @Override public void onComplete(AsynchronousResponseBody response) { QueryResultBundle resultBundle = (QueryResultBundle) response; if (resultBundle.getQueryCount() > 0) { // retry after waiting a few seconds gwt.scheduleExecution(new Callback() { @Override public void invoke() { runQuery(); } }, ETAG_CHECK_DELAY_MS); } else { // clear cache value and run the actual query clientCache.remove(fileViewEntityId + QueryResultEditorWidget.VIEW_RECENTLY_CHANGED_KEY); runQuery(); } } @Override public void onCancel() { showError(QUERY_CANCELED); } }); } /** * Called after a successful query. * * @param bundle */ private void setQueryResults(final QueryResultBundle bundle) { if (cachedFullQueryResultBundle != null) { bundle.setColumnModels(cachedFullQueryResultBundle.getColumnModels()); bundle.setFacets(cachedFullQueryResultBundle.getFacets()); bundle.setSelectColumns(cachedFullQueryResultBundle.getSelectColumns()); } else { cachedFullQueryResultBundle = bundle; } setQueryResultsAndSort(bundle, startingQuery.getSort()); } private void setQueryResultsAndSort(QueryResultBundle bundle, List<SortItem> sortItems) { this.bundle = bundle; this.view.setErrorVisible(false); this.view.setProgressWidgetVisible(false); // configure the page widget this.pageViewerWidget.configure(bundle, this.startingQuery, sortItems, false, tableType, null, this, facetChangedHandler); pageViewerWidget.setTableVisible(true); QueryResult result = bundle.getQueryResult(); RowSet rowSet = result.getQueryResults(); List<Row> rows = rowSet.getRows(); if (rows.isEmpty()) { showError("No rows returned."); } fireFinishEvent(true, isQueryResultEditable()); } /** * The results are editable if all of the select columns have ID * * @return */ public boolean isQueryResultEditable() { List<SelectColumn> selectColums = QueryBundleUtils.getSelectFromBundle(this.bundle); if (selectColums == null) { return false; } // Do all columns have IDs? for (SelectColumn col : selectColums) { if (col.getId() == null) { return false; } } // All of the columns have ID so we can edit return true; } /** * Starting a query. */ private void fireStartEvent() { if (this.queryListener != null) { this.queryListener.queryExecutionStarted(); } } /** * Finished a query. */ private void fireFinishEvent(boolean wasSuccessful, boolean resultsEditable) { if (this.queryListener != null) { this.queryListener.queryExecutionFinished(wasSuccessful, resultsEditable); } } /** * Show an error. * * @param caught */ private void showError(Throwable caught) { setupErrorState(); // due to invalid column set? (see PLFM-5491) if (caught instanceof BadRequestException && ErrorResponseCode.INVALID_TABLE_QUERY_FACET_COLUMN_REQUEST.equals(((BadRequestException) caught).getErrorResponseCode())) { popupUtils.showErrorMessage(SCHEMA_CHANGED_MESSAGE); resetFacetsHandler.invoke(); } else { synapseAlert.handleException(caught); } } /** * Show an error message. * * @param message */ private void showError(String message) { setupErrorState(); synapseAlert.showError(message); } private void setupErrorState() { pageViewerWidget.setTableVisible(false); this.view.setProgressWidgetVisible(false); fireFinishEvent(false, false); this.view.setErrorVisible(true); } @Override public Widget asWidget() { return view.asWidget(); } @Override public void onEditRows() { if (this.queryResultEditor == null) { this.queryResultEditor = ginInjector.createNewQueryResultEditorWidget(); view.setEditorWidget(this.queryResultEditor); } this.queryResultEditor.showEditor(bundle, tableType); } @Override public void onPageChange(Long newOffset) { facetsRequireRefresh = false; this.startingQuery.setOffset(newOffset); queryChanging(); } private void queryChanging() { if (this.queryListener != null) { this.queryListener.onStartingNewQuery(this.startingQuery); } view.scrollTableIntoView(); runQuery(); } public Query getStartingQuery() { return this.startingQuery; } @Override public void onToggleSort(String header) { facetsRequireRefresh = false; SortItem targetSortItem = null; List<SortItem> sortItems = startingQuery.getSort(); if (sortItems == null) { sortItems = new ArrayList<>(); startingQuery.setSort(sortItems); } for (SortItem sortItem : sortItems) { if (header.equals(sortItem.getColumn())) { targetSortItem = sortItem; break; } } // transition through UNSORTED (not in sort list) -> DESC -> ASC -> UNSORTED (remove from sort list) if (targetSortItem == null) { // new sort, set to default targetSortItem = new SortItem(); targetSortItem.setColumn(header); targetSortItem.setDirection(SortDirection.DESC); sortItems.add(targetSortItem); } else if (SortDirection.DESC.equals(targetSortItem.getDirection())) { targetSortItem.setDirection(SortDirection.ASC); } else { sortItems.remove(targetSortItem); } // reset offset and run the new query startingQuery.setOffset(0L); queryChanging(); } public void setFacetsVisible(boolean visible) { view.setFacetsVisible(visible); } }
package com.sandwell.JavaSimulation3D; import com.sandwell.JavaSimulation.InputErrorException; /** * Class to implement Audition-style clock calculations. Re-implementing the * class digitalclock. */ public class Clock{ private static final int[] firstDayOfMonth; private static final int[] daysInMonth; private static final int[] secsInMonth; private static final String monthNames[]; private static int startingYear; private static int startingMonth; private static int startingDay; private static final double HOURS_PER_YEAR = 8760.0d; private static final double HOURS_PER_DAY = 24.0d; static { firstDayOfMonth = new int[13]; firstDayOfMonth[0] = 1; firstDayOfMonth[1] = 32; firstDayOfMonth[2] = 60; firstDayOfMonth[3] = 91; firstDayOfMonth[4] = 121; firstDayOfMonth[5] = 152; firstDayOfMonth[6] = 182; firstDayOfMonth[7] = 213; firstDayOfMonth[8] = 244; firstDayOfMonth[9] = 274; firstDayOfMonth[10] = 305; firstDayOfMonth[11] = 335; firstDayOfMonth[12] = 366; daysInMonth = new int[12]; daysInMonth[0] = 31; daysInMonth[1] = 28; daysInMonth[2] = 31; daysInMonth[3] = 30; daysInMonth[4] = 31; daysInMonth[5] = 30; daysInMonth[6] = 31; daysInMonth[7] = 31; daysInMonth[8] = 30; daysInMonth[9] = 31; daysInMonth[10] = 30; daysInMonth[11] = 31; secsInMonth = new int[12]; for (int i = 0; i < daysInMonth.length; i++) secsInMonth[i] = daysInMonth[i] * 24 * 60 * 60; monthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; } public static void setStartDate(int year, int month, int day) { startingYear = year; startingMonth = month; startingDay = day; } public static class ClockTime { public final int year; public final int month; public final int day; public final double hour; public ClockTime(int y, int m, int d, double h) { year = y; month = m; day = d; hour = h; } } public static ClockTime getClockTime(double time) { int lyear = (int)Math.floor( time / 8760.0 ); double remainder = time % 8760.0; int lday = (int)Math.floor( remainder / 24.0 ); lday++; double lhour = remainder % 24.0; // Calculate what month this is int lmonth = getMonthForDay( lday ); lday -= firstDayOfMonth[lmonth - 1]; return new ClockTime(lyear + 1, lmonth, lday + 1, lhour); } public static double calcTimeForYear_Month_Day_Hour( int y, int m, int d, double h ) { double result = (y - 1) * 8760.0; // year result += ((firstDayOfMonth[m - 1] - 1) * 24.0); // months to this point result += (d - 1) * 24.0; // days into this month result += h; // hours into this day return result; } public static int getYearForTime( double time ) { return (int)Math.floor( time / 8760.0 ) + 1; } public static int getHourForTime( double time ) { return (int)Math.floor( time % 24.0 ); } public static int getMinuteForTime( double time ) { double temp = time - Math.floor( time ); return (int)Math.floor( temp * 60.0 ); } public static int getSecondForTime( double time ) { double temp = time - Math.floor( time ); temp = temp * 60.0 ; temp = temp - Math.floor( temp ); return (int)Math.round( temp * 60.0 ); } /** * Return the month 1-12 for the given day of the year 1-365 */ public static int getMonthForDay( int d ) { for (int i = 1; i < firstDayOfMonth.length; i++) { if (d < firstDayOfMonth[i]) { return i; } } return 12; } public static int getMonthForTime(double hours) { // Add 1 to make the first day of year be 1 rather than 0 int day = (int)(((hours % HOURS_PER_YEAR) / HOURS_PER_DAY) + 1.0d); return getMonthForDay(day); } public static int getMonthIndex(double hours) { // Add 1 to make the first day of year be 1 rather than 0 int day = (int)(((hours % HOURS_PER_YEAR) / HOURS_PER_DAY) + 1.0d); for (int i = 1; i < firstDayOfMonth.length; i++) { if (day < firstDayOfMonth[i]) { return i - 1; } } return 11; } public static int getNextMonthForTime(double hours) { int month = getMonthForTime(hours); return (month % 12) + 1; } public static double getDecHour(double time) { return time % 24.0; } public static int getStartingYear() { return startingYear; } public static int getStartingMonth() { return startingMonth; } public static int getStartingDay() { return startingDay; } /** * Return the number of days in the given month 1-12 */ public static int getDaysInMonth( int m ) { return daysInMonth[m - 1]; } /** * Return the number of seconds in the given month index 0-11 */ public static int getSecsInMonthIdx(int idx) { return secsInMonth[idx]; } public static void getStartingDateFromString( String startingDate ) { String[] startingVal = startingDate.split( "-" ); if( startingVal.length < 3 ) { throw new InputErrorException( "Starting date string not formatted correctly" ); } startingYear = Integer.valueOf( startingVal[0] ).intValue(); startingMonth = Integer.valueOf( startingVal[1] ).intValue(); startingDay = Integer.valueOf( startingVal[2] ).intValue(); } /** * Returns a formatted string to reflect the current simulation time. */ public static String getDateStringForTime(double time) { ClockTime cTime = getClockTime(time); int y = cTime.year + startingYear - 1; return String.format("%04d-%s-%02d %02d:%02d", y, monthNames[cTime.month - 1], cTime.day, getHourForTime( time ), getMinuteForTime( time )); } /** * Returns a formatted string to reflect the given year, month, day, and hour */ public static String getDateString( int y, int m, int d, double h) { int hr = getHourForTime( h ); int min = getMinuteForTime( h ); return String.format("%04d-%02d-%02d %02d:%02d", y, m, d, hr, min); } }
package uk.ac.ebi.pride.proteinidentificationindex.search.model; import org.apache.solr.client.solrj.beans.Field; import uk.ac.ebi.pride.archive.dataprovider.identification.IdentificationProvider; import uk.ac.ebi.pride.archive.dataprovider.identification.ModificationProvider; import uk.ac.ebi.pride.indexutils.helpers.ModificationHelper; import java.util.*; /** * @author Jose A. Dianes * @version $Id$ */ public class ProteinIdentification implements IdentificationProvider { @Field(ProteinIdentificationFields.ID) private String id; @Field(ProteinIdentificationFields.ACCESSION) private String accession; @Field(ProteinIdentificationFields.MOD_NAMES) private List<String> modificationNames; @Field(ProteinIdentificationFields.PROJECT_ACCESSION) private String projectAccession; @Field(ProteinIdentificationFields.ASSAY_ACCESSION) private String assayAccession; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAccession() { return accession; } public void setAccession(String accession) { this.accession = accession; } public String getProjectAccession() { return projectAccession; } public void setProjectAccession(String projectAccession) { this.projectAccession = projectAccession; } public String getAssayAccession() { return assayAccession; } public void setAssayAccession(String assayAccession) { this.assayAccession = assayAccession; } public Iterable<String> getModificationNames() { return this.modificationNames; } public void setModificationNames(List<ModificationProvider> modifications) { this.modificationNames = new ArrayList<>(); if (modifications == null && modifications.size()>0) { for (ModificationProvider modification : modifications) { modificationNames.add(modification.getName()); } } } public void addModificationName(ModificationProvider modification) { if (modificationNames == null) { modificationNames = new ArrayList<>(); } if (modification!=null) { modificationNames.add(modification.getName()); } } }
package io.flutter.editor; import static io.flutter.dart.DartPsiUtil.getNamedArgumentExpression; import static io.flutter.dart.DartPsiUtil.getNewExprFromType; import static io.flutter.dart.DartPsiUtil.getValueOfNamedArgument; import static io.flutter.dart.DartPsiUtil.getValueOfPositionalArgument; import static io.flutter.dart.DartPsiUtil.parseLiteralNumber; import static io.flutter.dart.DartPsiUtil.topmostReferenceExpression; import com.intellij.codeInsight.daemon.GutterName; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.codeInsight.daemon.LineMarkerProviderDescriptor; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.markup.GutterIconRenderer; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.AstBufferUtil; import com.jetbrains.lang.dart.DartTokenTypes; import com.jetbrains.lang.dart.psi.DartArguments; import com.jetbrains.lang.dart.psi.DartCallExpression; import com.jetbrains.lang.dart.psi.DartNewExpression; import com.jetbrains.lang.dart.psi.DartReference; import com.jetbrains.lang.dart.util.DartPsiImplUtil; import com.jetbrains.lang.dart.util.DartResolveUtil; import io.flutter.FlutterBundle; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.Icon; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class FlutterIconLineMarkerProvider extends LineMarkerProviderDescriptor { static final private Map<String, String> KnownPaths = new HashMap<>(); static { KnownPaths.put("Icons", "packages/flutter/lib/src/material"); KnownPaths.put("IconData", "packages/flutter/lib/src/widgets"); KnownPaths.put("CupertinoIcons", "packages/flutter/lib/src/cupertino"); } @Nullable("null means disabled") @Override public @GutterName String getName() { return FlutterBundle.message("fluitter.icon.preview.title"); } @Override public LineMarkerInfo<?> getLineMarkerInfo(@NotNull PsiElement element) { if (element.getNode().getElementType() != DartTokenTypes.IDENTIFIER) return null; final String name = element.getText(); if (!(name.equals("Icons") || name.equals("CupertinoIcons") || name.equals("IconData"))) return null; final PsiElement refExpr = topmostReferenceExpression(element); if (refExpr == null) return null; PsiElement parent = refExpr.getParent(); if (parent == null) return null; // Resolve the class reference and check that it is one of the known, cached classes. if (!ApplicationManager.getApplication().isUnitTestMode()) { final PsiElement symbol = "IconData".equals(name) ? refExpr : refExpr.getFirstChild(); if (!(symbol instanceof DartReference)) return null; final PsiElement result = ((DartReference)symbol).resolve(); if (result == null) return null; final List<VirtualFile> library = DartResolveUtil.findLibrary(result.getContainingFile()); boolean found = false; for (VirtualFile file : library) { VirtualFile dir = file.getParent(); if (dir.isInLocalFileSystem()) { final String path = dir.getPath(); if (path.endsWith(KnownPaths.get(name))) { found = true; break; } } } if (!found) return null; } if (parent.getNode().getElementType() == DartTokenTypes.CALL_EXPRESSION) { // Check font family and package final DartArguments arguments = DartPsiImplUtil.getArguments((DartCallExpression)parent); if (arguments == null) return null; final String family = getValueOfNamedArgument(arguments, "fontFamily"); if (family != null) { if (!"MaterialIcons".equals(family)) return null; } final PsiElement fontPackage = getNamedArgumentExpression(arguments, "fontPackage"); if (fontPackage != null) return null; // See previous TODO final String argument = getValueOfPositionalArgument(arguments, 0); if (argument == null) return null; final Icon icon = getIconFromCode(argument); if (icon != null) { return createLineMarker(element, icon); } } else if (parent.getNode().getElementType() == DartTokenTypes.SIMPLE_TYPE) { parent = getNewExprFromType(parent); if (parent == null) return null; final DartArguments arguments = DartPsiImplUtil.getArguments((DartNewExpression)parent); if (arguments == null) return null; final String argument = getValueOfPositionalArgument(arguments, 0); if (argument == null) return null; final Icon icon = getIconFromCode(argument); if (icon != null) { return createLineMarker(element, icon); } } else { final PsiElement idNode = refExpr.getFirstChild(); if (idNode == null) return null; if (name.equals(idNode.getText())) { final PsiElement selectorNode = refExpr.getLastChild(); if (selectorNode == null) return null; final String selector = AstBufferUtil.getTextSkippingWhitespaceComments(selectorNode.getNode()); final Icon icon; if (name.equals("Icons")) { icon = FlutterMaterialIcons.getIconForName(selector); } else { icon = FlutterCupertinoIcons.getIconForName(selector); } if (icon != null) { return createLineMarker(element, icon); } } } return null; } private Icon getIconFromCode(@NotNull String value) { final int code = parseLiteralNumber(value); final String hex = Long.toHexString(code); // We look for the codepoint for material icons, and fall back on those for Cupertino. Icon icon = FlutterMaterialIcons.getIconForHex(hex); if (icon == null) { icon = FlutterCupertinoIcons.getIconForHex(hex); } return icon; } private LineMarkerInfo<PsiElement> createLineMarker(@Nullable PsiElement element, @NotNull Icon icon) { if (element == null) return null; return new LineMarkerInfo<>(element, element.getTextRange(), icon, null, null, GutterIconRenderer.Alignment.LEFT); } }
package io.xchris6041x.devin.commands; import java.util.ArrayList; import java.util.List; import org.bukkit.command.CommandSender; import io.xchris6041x.devin.DevinException; import io.xchris6041x.devin.MessageSender; import io.xchris6041x.devin.Validator; class HelpCommandMethod implements CommandMethod { private String usage; public HelpCommandMethod(CommandHandler root, String name) { this.usage = "/" + root.getName() + " " + name + " [page]"; } @Override public String getUsage() { return usage; } @Override public void invoke(CommandHandler handler, CommandSender sender, String[] rawArgs, MessageSender msgSender) throws DevinException { CommandHandlerContainer root = handler.getParent(); List<String> helpMessages = new ArrayList<String>(); buildHelpMessages(helpMessages, root); int pageLength = 7; int maxPages = (int) Math.ceil(helpMessages.size() / (double) pageLength); int page = 0; if(rawArgs.length > 0) { if(!Validator.isInteger(rawArgs[0], sender, msgSender)) return; page = Integer.parseInt(rawArgs[0]) - 1; } if(page > maxPages - 1) { page = maxPages - 1; } else if(page < 0) { page = 0; } msgSender.info(sender, root.getName().toUpperCase() + " Commands | Page " + (page + 1) + "/" + maxPages); msgSender.send(sender, " msgSender.send(sender, CommandUtils.pagination(helpMessages, pageLength, page)); } private void buildHelpMessages(List<String> helpMessages, CommandHandlerContainer container) { if(container instanceof CommandHandler && ((CommandHandler)container).getMethod() != null) { CommandHandler handler = (CommandHandler) container; helpMessages.add(handler.getMethod().getUsage() + (handler.getDescription().length() > 0 ? " - " + handler.getDescription() : "")); } // Build messages for children. for(CommandHandlerContainer chc : container.getChildren()) { buildHelpMessages(helpMessages, chc); } } }
package org.jboss.jca.sjc; import org.jboss.jca.fungal.api.Kernel; import org.jboss.jca.fungal.impl.KernelConfiguration; import org.jboss.jca.fungal.impl.KernelImpl; import java.io.File; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.reflect.Method; import java.net.URI; /** * The main class for JBoss JCA SJC * @author <a href="mailto:jesper.pedersen@jboss.org">Jesper Pedersen</a> */ public class Main { /** Kernel */ private static Kernel kernel; /** Logging */ private static Object logging; /** * Default constructor */ private Main() { } /** * Boot * @param args The arguments * @param tg The thread group used */ private static void boot(final String[] args, final ThreadGroup tg) { try { KernelConfiguration kernelConfiguration = new KernelConfiguration(); String home = SecurityActions.getSystemProperty("jboss.jca.home"); if (home != null) { kernelConfiguration.home(new File(home).toURI().toURL()); } else { home = new File(".").toURI().toURL().toString(); File root = new File(new URI(home.substring(0, home.lastIndexOf("bin")))); kernelConfiguration.home(root.toURI().toURL()); } if (args != null && args.length > 0) { for (int i = 0; i < args.length; i++) { if ("-b".equals(args[i])) { kernelConfiguration.bindAddress(args[++i]); } } } if (tg != null) kernelConfiguration.threadGroup(tg); kernel = new KernelImpl(kernelConfiguration); kernel.startup(); initLogging(SecurityActions.getThreadContextClassLoader()); } catch (Throwable t) { error(t.getMessage(), t); } } /** * Init logging * @param cl The classloader to load from */ private static void initLogging(ClassLoader cl) { try { Class clz = Class.forName("org.jboss.logmanager.log4j.BridgeRepositorySelector", true, cl); Method mStart = clz.getMethod("start", (Class[])null); Object brs = clz.newInstance(); logging = mStart.invoke(brs, (Object[])null); } catch (Throwable t) { // Nothing we can do } try { Class clz = Class.forName("org.jboss.logging.Logger", true, cl); Method mGetLogger = clz.getMethod("getLogger", String.class); logging = mGetLogger.invoke((Object)null, new Object[] {"org.jboss.jca.sjc.Main"}); } catch (Throwable t) { // Nothing we can do } } /** * Logging: ERROR * @param s The string * @param t The throwable */ private static void error(String s, Throwable t) { if (logging != null) { try { Class clz = logging.getClass(); Method mError = clz.getMethod("error", Object.class, Throwable.class); mError.invoke(logging, new Object[] {s, t}); } catch (Throwable th) { // Nothing we can do } } else { System.out.println(s); t.printStackTrace(System.out); } } /** * Logging: WARN * @param s The string */ private static void warn(String s) { if (logging != null) { try { Class clz = logging.getClass(); Method mWarn = clz.getMethod("warn", Object.class); mWarn.invoke(logging, new Object[] {s}); } catch (Throwable t) { // Nothing we can do } } else { System.out.println(s); } } /** * Logging: INFO * @param s The string */ private static void info(String s) { if (logging != null) { try { Class clz = logging.getClass(); Method mInfo = clz.getMethod("info", Object.class); mInfo.invoke(logging, new Object[] {s}); } catch (Throwable t) { // Nothing we can do } } else { System.out.println(s); } } /** * Logging: Is DEBUG enabled * @return True if debug is enabled; otherwise false */ private static boolean isDebugEnabled() { if (logging != null) { try { Class clz = logging.getClass(); Method mIsDebugEnabled = clz.getMethod("isDebugEnabled", (Class[])null); return ((Boolean)mIsDebugEnabled.invoke(logging, (Object[])null)).booleanValue(); } catch (Throwable t) { // Nothing we can do } } return true; } /** * Logging: DEBUG * @param s The string */ private static void debug(String s) { if (logging != null) { try { Class clz = logging.getClass(); Method mDebug = clz.getMethod("debug", Object.class); mDebug.invoke(logging, new Object[] {s}); } catch (Throwable t) { // Nothing we can do } } else { System.out.println(s); } } /** * Main * @param args The arguments */ public static void main(final String[] args) { long l1 = System.currentTimeMillis(); try { final ThreadGroup threads = new ThreadGroup("jboss-jca"); Main.boot(args, threads); LifeThread lifeThread = new LifeThread(threads); lifeThread.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { if (kernel != null) kernel.shutdown(); } catch (Throwable t) { error(t.getMessage(), t); } info("Shutdown complete"); } }); if (isDebugEnabled()) { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); debug("Heap memory: " + memoryBean.getHeapMemoryUsage().toString()); debug("NonHeap memory: " + memoryBean.getNonHeapMemoryUsage().toString()); } long l2 = System.currentTimeMillis(); info("Server started in " + (l2 - l1) + "ms"); } catch (Exception e) { error("Exception during main()", e); } } /** * A simple thread that keeps the vm alive in the event there are no * other threads started. */ private static class LifeThread extends Thread { private Object lock = new Object(); LifeThread(ThreadGroup tg) { super(tg, "JBossLifeThread"); } public void run() { synchronized (lock) { try { lock.wait(); } catch (InterruptedException ignore) { } } } } }
package li.aop; import li.annotation.Bean; import li.annotation.Inject; @Bean public class LogFilter implements AopFilter { @Inject(" private String msg; public void doFilter(AopChain chain) { System.err.println("log before " + msg); System.err.println(chain.getTarget()); System.err.println(chain.getTarget().getClass()); System.err.println(chain.getTarget().getClass().getSuperclass()); System.err.println(chain.getMethod()); for (Object arg : chain.getArgs()) { System.out.println("Arg: " + arg); } chain.doFilter(); System.err.println(chain.getResult()); System.err.println("log after"); } }
package ca.corefacility.bioinformatics.irida.ria.integration.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; /** * <p> * Page Object to represent the project details page. * </p> * * @author Josh Adam <josh.adam@phac-aspc.gc.ca> */ public class ProjectDetailsPage { private WebDriver driver; public ProjectDetailsPage(WebDriver driver, Long projectId) { this.driver = driver; driver.get("http://localhost:8080/projects/" + projectId); } public String getPageTitle() { WebElement title = driver.findElement(By.tagName("h1")); return title.getText(); } public String getOrganism() { WebElement organism = driver.findElement(By.id("project-organism")); return organism.getText(); } public String getProjectOwner() { WebElement owner = driver.findElement(By.id("project-owner")); return owner.getText(); } public String getCreatedDate() { WebElement date = driver.findElement(By.id("project-created")); return date.getText(); } public String getModifiedDate() { WebElement date = driver.findElement(By.id("project-modified")); return date.getText(); } }
package com.witchworks.common.tile; import com.witchworks.common.crafting.oven.OvenCrafting; import com.witchworks.common.item.ModItems; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.ItemStackHandler; import javax.annotation.Nullable; public class TileOven extends TileEntity implements ITickable { public int workTime; public int totalWorkTime; public boolean isBurning = false; public int burnTime; public int itemBurnTime = 0; public ItemStackHandler inventory = new ItemStackHandler(5) { @Override protected void onContentsChanged(int slot) { TileOven.this.markDirty(); } }; //come back to for input with hopper/other ducts //private static final int[] SLOT_TOP = new int[]{3, 4}; //private static final int[] SLOT_BOTTOM = new int[]{0, 1, 2}; private String customName; public void dropItems() { for (int i = 0; i < 5; ++i) { final ItemStack stack = inventory.getStackInSlot(i); if (!world.isRemote && !stack.isEmpty()) { final EntityItem item = new EntityItem(world, pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D, stack); world.spawnEntity(item); } inventory.setStackInSlot(i, ItemStack.EMPTY); } } @Override public void update() { if (!world.isRemote) { IBlockState state = world.getBlockState(pos); world.notifyBlockUpdate(pos, state, state, 3); } this.totalWorkTime = getWorkTime(); if (!isBurning) { if (!inventory.getStackInSlot(1).isEmpty()) { if (TileEntityFurnace.isItemFuel(inventory.getStackInSlot(1))) { if (canSmelt()) { itemBurnTime = TileEntityFurnace.getItemBurnTime(inventory.getStackInSlot(1)); inventory.getStackInSlot(1).shrink(1); isBurning = true; } } } } else if (isBurning) { burnTime++; if (burnTime >= itemBurnTime) { burnTime = 0; isBurning = false; } if (canSmelt()) { workTime++; if (workTime >= totalWorkTime) { workTime = 0; smelt(); } } else if (workTime > 0) { workTime = 0; } } if (burnTime >= itemBurnTime) { isBurning = false; burnTime = 0; } } //Change to speed up smelting, lower = faster public int getWorkTime() { return 256; } public boolean canSmelt() { if (!inventory.getStackInSlot(0).isEmpty()) { if (OvenCrafting.instance().getSmeltResult(inventory.getStackInSlot(0)) != ItemStack.EMPTY) { if (!inventory.getStackInSlot(2).isEmpty()) { if (inventory.getStackInSlot(2).getItem() == ModItems.glass_jar || inventory.getStackInSlot(2).getItem() == Items.GLASS_BOTTLE) { ItemStack stack = inventory.getStackInSlot(0); if (inventory.getStackInSlot(3).isEmpty() && inventory.getStackInSlot(4).isEmpty()) { return true; } else if (!inventory.getStackInSlot(3).isEmpty() && inventory.getStackInSlot(4).isEmpty()) { ItemStack stackFume = inventory.getStackInSlot(3); if (inventory.getStackInSlot(3).getCount() < 64) { if (stackFume == OvenCrafting.instance().getFumesResult(stack)) { return true; } } } else if (!inventory.getStackInSlot(4).isEmpty() && inventory.getStackInSlot(3).isEmpty()) { if (inventory.getStackInSlot(4).getCount() < 64) { ItemStack stackOutput = inventory.getStackInSlot(4); if (stackOutput == OvenCrafting.instance().getSmeltResult(stack)) { return true; } } } else if (!inventory.getStackInSlot(3).isEmpty() && !inventory.getStackInSlot(4).isEmpty()) { ItemStack stackFume = inventory.getStackInSlot(3); ItemStack stackOutput = inventory.getStackInSlot(4); if (inventory.getStackInSlot(3).getCount() < 64 && inventory.getStackInSlot(4).getCount() < 64) { if (stackFume == OvenCrafting.instance().getFumesResult(stack) && stackOutput == OvenCrafting.instance().getSmeltResult(stack)) { return true; } } } else { return false; } } } else { return false; } } } return false; } public void smelt() { if (canSmelt()) { ItemStack stack = inventory.getStackInSlot(0); ItemStack outputStack = OvenCrafting.instance().getSmeltResult(stack); ItemStack fumesStack = OvenCrafting.instance().getFumesResult(stack); if (inventory.getStackInSlot(3).isEmpty()) { inventory.setStackInSlot(3, fumesStack); } else { if (inventory.getStackInSlot(3).getCount() < 64) { inventory.getStackInSlot(3).grow(1); } } /** * This is where you could add random checks for random chances */ if (inventory.getStackInSlot(4).isEmpty()) { inventory.setStackInSlot(4, outputStack); } else { if (inventory.getStackInSlot(4).getCount() < 64) { inventory.getStackInSlot(4).grow(1); } } inventory.getStackInSlot(0).shrink(1); inventory.getStackInSlot(2).shrink(1); } } public void setCustomName(String name) { this.customName = name; } public String getName() { return this.customName; } public boolean hasCustomName() { return this.customName != null && !this.customName.isEmpty(); } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); if (compound.hasKey("items")) { inventory.deserializeNBT((NBTTagCompound) compound.getTag("items")); } if (compound.hasKey("CustomName", 8)) { this.customName = compound.getString("CustomName"); } this.workTime = compound.getInteger("WorkTime"); this.totalWorkTime = compound.getInteger("totalWorkTime"); this.burnTime = compound.getInteger("BurnTime"); this.itemBurnTime = compound.getInteger("itemBurnTime"); this.isBurning = compound.getBoolean("isBurning"); } @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { super.writeToNBT(compound); compound.setTag("items", inventory.serializeNBT()); if (this.hasCustomName()) { compound.setString("CustomName", this.customName); } compound.setInteger("WorkTime", (short) this.workTime); compound.setInteger("totalWorkTime", (short) this.totalWorkTime); compound.setInteger("BurnTime", (short) this.burnTime); compound.setInteger("itemBurnTime", (short) this.itemBurnTime); compound.setBoolean("isBurning", this.isBurning); return compound; } @Override public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY ? true : super.hasCapability(capability, facing); } @Nullable @Override public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return (T) inventory; } return super.getCapability(capability, facing); } }
package com.cross.amsecure; import java.util.HashMap; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /* @author to Ibrahim Hanna @2016 ibrahim.seniore@gmail.com */ public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "AmSecure.db"; public static final String SITES_TABLE_NAME = "Sites"; public static final String SITES_COLUMN_ID = "ID"; public static final String SITES_COLUMN_NAME = "Name"; public static final String SITES_COLUMN_PASSWORD = "Password"; public static final int DATABASE_VERSION=1; private HashMap sitesMap; DBHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "CREATE TABLE " +SITES_TABLE_NAME+ " (ID integer primary key, Name text,Password text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS Sites"); onCreate(db); } public boolean inserSite(String name){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put("Name", name); contentValues.put("Password", "sadasdfhjkkl"); db.insert(SITES_TABLE_NAME, null, contentValues); return true; } public boolean insertSite(String name, String passworsd){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put("Name", name); contentValues.put("Password",passworsd); db.insert(SITES_TABLE_NAME, null, contentValues); return true; } public Cursor getSites(){ SQLiteDatabase db=this.getReadableDatabase(); Cursor cursor=db.query(SITES_TABLE_NAME, new String[]{"Name"}, null, null, null, null, null); return cursor; } public Cursor getSiteRow(String name){ SQLiteDatabase db=this.getReadableDatabase(); Cursor cursor=db.rawQuery("select * from Sites where Name="+name, null); return cursor; } }
package de.hftstuttgart.projectindoorweb.web.controllertests; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import de.hftstuttgart.projectindoorweb.Application; import de.hftstuttgart.projectindoorweb.persistence.repositories.BuildingRepository; import de.hftstuttgart.projectindoorweb.persistence.repositories.ProjectRepository; import de.hftstuttgart.projectindoorweb.web.configuration.TestWebConfiguration; import de.hftstuttgart.projectindoorweb.web.helpers.TestHelper; import de.hftstuttgart.projectindoorweb.web.internal.ResponseWrapper; import de.hftstuttgart.projectindoorweb.web.internal.requests.positioning.BatchPositionResult; import de.hftstuttgart.projectindoorweb.web.internal.requests.positioning.GenerateBatchPositionResults; import de.hftstuttgart.projectindoorweb.web.internal.requests.positioning.GetEvaluationFilesForBuilding; import de.hftstuttgart.projectindoorweb.web.internal.requests.positioning.GetRadioMapFilesForBuilding; import de.hftstuttgart.projectindoorweb.web.internal.requests.project.AddNewProject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) @ContextConfiguration(classes = TestWebConfiguration.class) @WebAppConfiguration public class EverythingControllerTest { private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); private MockMvc mockMvc; private ObjectMapper objectMapper; private MockMultipartFile radioMapFileR01A5; private MockMultipartFile radioMapFileR01S4Mini; private MockMultipartFile radioMapFileR01S4; private MockMultipartFile radioMapFileR02A5; private MockMultipartFile radioMapFileR02S4Mini; private MockMultipartFile radioMapFileR02S4; private MockMultipartFile radioMapFileR03S4Mini; private MockMultipartFile radioMapFileR03S4; private MockMultipartFile radioMapFileR04A5; private MockMultipartFile radioMapFileR04S4Mini; private MockMultipartFile radioMapFileR04S4; private MockMultipartFile emptyRadioMapFileHfT; private MockMultipartFile transformedPointsFile; private MockMultipartFile evaluationFile; private long[] emptyRadioMapIdArray = new long[2]; private final static String ALGORITHM_TYPE = "WIFI"; private final static String DUMMY = "Dummy"; @Autowired private WebApplicationContext webApplicationContext; @Autowired private BuildingRepository buildingRepository; @Autowired private ProjectRepository projectRepository; @Before public void setUp() throws Exception { this.objectMapper = new ObjectMapper(); this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); this.projectRepository.deleteAll(); this.buildingRepository.deleteAll(); radioMapFileR01A5 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R01-2017_A5.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R01-2017_A5.txt"))); radioMapFileR01S4Mini = new MockMultipartFile("radioMapFiles", "logfile_CAR_R01-2017_S4Mini.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R01-2017_S4MINI.txt"))); radioMapFileR01S4 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R01-2017_S4.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R01-2017_S4.txt"))); radioMapFileR02A5 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R02-2017_A5.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R02-2017_A5.txt"))); radioMapFileR02S4Mini = new MockMultipartFile("radioMapFiles", "logfile_CAR_R02-2017_S4Mini.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R02-2017_S4MINI.txt"))); radioMapFileR02S4 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R02-2017_S4.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R02-2017_S4.txt"))); radioMapFileR03S4Mini = new MockMultipartFile("radioMapFiles", "logfile_CAR_R03-2017_S4Mini.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R03-2017_S4MINI.txt"))); radioMapFileR03S4 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R03-2017_S4.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R03-2017_S4.txt"))); radioMapFileR04A5 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R04-2017_A5.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R04-2017_A5.txt"))); radioMapFileR04S4Mini = new MockMultipartFile("radioMapFiles", "logfile_CAR_R04-2017_S4Mini.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R04-2017_S4MINI.txt"))); radioMapFileR04S4 = new MockMultipartFile("radioMapFiles", "logfile_CAR_R04-2017_S4.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_CAR_R04-2017_S4.txt"))); emptyRadioMapFileHfT = new MockMultipartFile("radioMapFiles", "logfile_2017_11_25_10_23_07_Survey1.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/radiomapfiles/logfile_2017_11_25_10_23_07_Survey1.txt"))); transformedPointsFile = new MockMultipartFile("transformedPointsFiles", "Survey1.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/transformedpointsfiles/Survey1.txt"))); evaluationFile = new MockMultipartFile("evalFiles", "logfile_CAR_R01-2017_A5.txt", "text/plain", Files.readAllBytes(Paths.get("./src/test/resources/evaluationfiles/logfile_CAR_R01-2017_A5.txt"))); } @Test public void testProcessSingleRadioMapFile() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(radioMapFileR01A5) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occuured."); } } @Test public void testProcessMultipleRadioMapFiles() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(radioMapFileR01A5) .file(radioMapFileR01S4Mini) .file(radioMapFileR01S4) .file(radioMapFileR02A5) .file(radioMapFileR02S4Mini) .file(radioMapFileR02S4) .file(radioMapFileR03S4Mini) .file(radioMapFileR03S4) .file(radioMapFileR04A5) .file(radioMapFileR04S4Mini) .file(radioMapFileR04S4) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } } @Test public void testProcessEmptyRadioMapFile() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(emptyRadioMapFileHfT) .file(transformedPointsFile) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } } @Test public void testProcessEvaluationFile() { try { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processEvalFiles") .file(evaluationFile) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } } @Test public void testGenerateBatchPositionResultsWoProject() { try { long buildingId = prepareBuildingForBatchPositionResultCalculations(); long radioMapFileId = prepareRadioMapForBatchPositionResultCalculations(buildingId); long evalFileId = prepareEvalFileForBatchPositionResultCalculations(buildingId); GenerateBatchPositionResults defaultGenerateBatchPositionResults = TestHelper.createDefaultBatchPositionRequestObject(); defaultGenerateBatchPositionResults.setBuildingIdentifier(buildingId); defaultGenerateBatchPositionResults.setEvalFileIdentifier(evalFileId); defaultGenerateBatchPositionResults.setRadioMapFileIdentifiers(new long[]{radioMapFileId}); ResultActions generateBatchPositionsResultActions = mockMvc.perform(post("/position/generateBatchPositionResults") .content(TestHelper.jsonify(defaultGenerateBatchPositionResults)) .contentType(this.contentType)); generateBatchPositionsResultActions.andExpect(status().isOk()); String batchPositionResult = generateBatchPositionsResultActions.andReturn().getResponse().getContentAsString(); List<BatchPositionResult> batchPositionResults = (List<BatchPositionResult>) this.objectMapper.readValue(batchPositionResult, new TypeReference<List<BatchPositionResult>>() { }); assertTrue("The backend returned an unexpected number of results.", batchPositionResults.size() == 396); } catch (Exception e) { e.printStackTrace(); fail("An unexpected Exception of type " + e.getClass().getSimpleName() + " has occurred."); } } @Test public void testGenerateBatchPositionResultsWithProject() throws Exception { long buildingId = prepareBuildingForBatchPositionResultCalculations(); long radioMapFileId = prepareRadioMapForBatchPositionResultCalculations(buildingId); long evalFileId = prepareEvalFileForBatchPositionResultCalculations(buildingId); long projectId = prepareProjectForBatchPositionResultCalculations(buildingId); GenerateBatchPositionResults positionRequestObject = TestHelper.createPositionRequestObjectWithProjectId(projectId); positionRequestObject.setBuildingIdentifier(buildingId); positionRequestObject.setEvalFileIdentifier(evalFileId); positionRequestObject.setRadioMapFileIdentifiers(new long[]{radioMapFileId}); ResultActions generateBatchPositionsResultActions = mockMvc.perform(post("/position/generateBatchPositionResults") .content(TestHelper.jsonify(positionRequestObject)) .contentType(this.contentType)); generateBatchPositionsResultActions.andExpect(status().isOk()); String batchPositionResult = generateBatchPositionsResultActions.andReturn().getResponse().getContentAsString(); List<BatchPositionResult> batchPositionResults = (List<BatchPositionResult>) this.objectMapper.readValue(batchPositionResult, new TypeReference<List<BatchPositionResult>>() { }); assertTrue("The backend returned an unexpected number of results.", batchPositionResults.size() == 396); } @Test public void testGenerateBatchPositionResultsWoProjectWoParameterSet() throws Exception { long buildingId = prepareBuildingForBatchPositionResultCalculations(); long radioMapFileId = prepareRadioMapForBatchPositionResultCalculations(buildingId); long evalFileId = prepareEvalFileForBatchPositionResultCalculations(buildingId); ResultActions getRadioMapResultActions = mockMvc.perform(get("/position/getRadioMapsForBuildingId?" + "buildingIdentifier=" + buildingId)); getRadioMapResultActions.andExpect(status().isOk()); GenerateBatchPositionResults positionRequestObject = TestHelper.createPositionRequestObjectWithProjectId(1l); positionRequestObject.setBuildingIdentifier(buildingId); positionRequestObject.setEvalFileIdentifier(evalFileId); positionRequestObject.setRadioMapFileIdentifiers(new long[]{radioMapFileId}); ResultActions generateBatchPositionsResultActions = mockMvc.perform(post("/position/generateBatchPositionResults") .content(TestHelper.jsonify(positionRequestObject)) .contentType(this.contentType)); generateBatchPositionsResultActions.andExpect(status().isOk()); String batchPositionResult = generateBatchPositionsResultActions.andReturn().getResponse().getContentAsString(); List<BatchPositionResult> batchPositionResults = (List<BatchPositionResult>) this.objectMapper.readValue(batchPositionResult, new TypeReference<List<BatchPositionResult>>() { }); assertTrue("The backend returned an unexpected number of results.", batchPositionResults.size() == 396); } private long prepareBuildingForBatchPositionResultCalculations() throws Exception { long buildingId = TestHelper.addNewBuildingAndRetrieveId(this.mockMvc, this.contentType); assertTrue("Failed to add new building.", buildingId > 0); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processRadioMapFiles") .file(radioMapFileR01A5) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/position/processEvalFiles") .file(evaluationFile) .param("buildingIdentifier", String.valueOf(buildingId))) .andExpect(status().isOk()); return buildingId; } private long prepareRadioMapForBatchPositionResultCalculations(long buildingId) throws Exception { ResultActions getRadioMapResultActions = mockMvc.perform(get("/position/getRadioMapsForBuildingId?" + "buildingIdentifier=" + buildingId)); getRadioMapResultActions.andExpect(status().isOk()); String getRadioMapResult = getRadioMapResultActions.andReturn().getResponse().getContentAsString(); List<GetRadioMapFilesForBuilding> getRadioMapFilesForBuilding = (List<GetRadioMapFilesForBuilding>) this.objectMapper.readValue(getRadioMapResult, new TypeReference<List<GetRadioMapFilesForBuilding>>() { }); assertTrue("The returned list of type " + GetRadioMapFilesForBuilding.class.getSimpleName() + " had an unexpected size.", getRadioMapFilesForBuilding.size() == 1); return getRadioMapFilesForBuilding.get(0).getId(); } private long prepareEvalFileForBatchPositionResultCalculations(long buildingId) throws Exception { ResultActions getEvalFileResultActions = mockMvc.perform(get("/position/getEvalFilesForBuildingId?" + "buildingIdentifier=" + buildingId)); getEvalFileResultActions.andExpect(status().isOk()); String getEvalFileResult = getEvalFileResultActions.andReturn().getResponse().getContentAsString(); List<GetEvaluationFilesForBuilding> getEvaluationFilesForBuilding = (List<GetEvaluationFilesForBuilding>) this.objectMapper.readValue(getEvalFileResult, new TypeReference<List<GetEvaluationFilesForBuilding>>() { }); assertTrue("The returned list of type " + GetEvaluationFilesForBuilding.class.getSimpleName() + " had an unexpected size.", getEvaluationFilesForBuilding.size() == 1); return getEvaluationFilesForBuilding.get(0).getId(); } private long prepareProjectForBatchPositionResultCalculations(long buildingId) throws Exception { AddNewProject addNewProjectElement = new AddNewProject(TestHelper.getSimpleProjectParameterSet(), DUMMY, ALGORITHM_TYPE, buildingId, 0l, emptyRadioMapIdArray); ResultActions saveNewProjectAction = mockMvc.perform(post("/project/saveNewProject") .content(TestHelper.jsonify(addNewProjectElement)) .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); String saveNewProjectResult = saveNewProjectAction.andReturn().getResponse().getContentAsString(); ResponseWrapper responseWrapper = this.objectMapper.readValue(saveNewProjectResult, new TypeReference<ResponseWrapper>() { }); return responseWrapper.getId(); } //To be continued ;) }
package org.jasig.portal.tools; import org.jasig.portal.UtilitiesBean; import org.jasig.portal.RdbmServices; import org.jasig.portal.utils.DTDResolver; import java.io.File; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.sql.Connection; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.Types; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Text; import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import org.xml.sax.AttributeList; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.DocumentHandler; import org.apache.xalan.xslt.XSLTProcessorFactory; import org.apache.xalan.xslt.XSLTProcessor; import org.apache.xalan.xslt.XSLTInputSource; import org.apache.xalan.xslt.XSLTResultTarget; import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.dom.DocumentImpl; /** * <p>A tool to set up a uPortal database. This tool was created so that uPortal * developers would only have to maintain a single set of xml documents to define * the uPortal database schema and data. Previously it was necessary to maintain * different scripts for each database we wanted to support.</p> * * <p>DbLoader reads the generic types that are specified in tables.xml and * tries to map them to local types by querying the database metadata via methods * implemented by the JDBC driver. Fallback mappings can be supplied in * dbloader.xml for cases where the JDBC driver is not able to determine the * appropriate mapping. Such cases will be reported to standard out.</p> * * <p>An xsl transformation is used to produce the DROP TABLE and CREATE TABLE * SQL statements. These statements can be altered by modifying tables.xsl</p> * * <p>Generic data types (as defined in java.sql.Types) which may be specified * in tables.xml include: * <code>BIT, TINYINT, SMALLINT, INTEGER, BIGINT, FLOAT, REAL, DOUBLE, * NUMERIC, DECIMAL, CHAR, VARCHAR, LONGVARCHAR, DATE, TIME, TIMESTAMP, * BINARY, VARBINARY, LONGVARBINARY, NULL, OTHER, JAVA_OBJECT, DISTINCT, * STRUCT, ARRAY, BLOB, CLOB, REF</code> * * <p><strong>WARNING: YOU MAY WANT TO MAKE A BACKUP OF YOUR DATABASE BEFORE RUNNING DbLoader</strong></p> * * <p>DbLoader will perform the following steps: * <ol> * <li>Read configurable properties from <portal.home>/properties/dbloader.xml</li> * <li>Get database connection from RdbmServices * (reads JDBC database settings from <portal.home>/properties/rdbm.properties).</li> * <li>Read tables.xml and issue corresponding DROP TABLE and CREATE TABLE SQL statements.</li> * <li>Read data.xml and issue corresponding INSERT SQL statements.</li> * </ol></p> * * <p>You will need to set the system property "portal.home" For example, * java -Dportal.home=/usr/local/uPortal</p> * * @author Ken Weiner, kweiner@interactivebusiness.com * @version $Revision$ * @see java.sql.Types * @since uPortal 2.0 */ public class DbLoader { private static String portalBaseDir; private static String propertiesUri; private static Connection con; private static Statement stmt; private static PreparedStatement pstmt; private static RdbmServices rdbmService; private static Document tablesDoc; private static Document tablesDocGeneric; private static boolean createScript; private static boolean dropTables; private static boolean createTables; private static boolean populateTables; private static PrintWriter scriptOut; public static void main(String[] args) { try { setPortalBaseDir(); propertiesUri = UtilitiesBean.fixURI("properties" + File.separator + "dbloader.xml"); con = rdbmService.getConnection (); if (con != null) { long startTime = System.currentTimeMillis(); // Read in the properties XMLReader parser = getXMLReader(); printInfo(); readProperties(parser); // Read drop/create/populate table settings dropTables = Boolean.valueOf(PropertiesHandler.properties.getDropTables()).booleanValue(); createTables = Boolean.valueOf(PropertiesHandler.properties.getCreateTables()).booleanValue(); populateTables = Boolean.valueOf(PropertiesHandler.properties.getPopulateTables()).booleanValue(); // Set up script createScript = Boolean.valueOf(PropertiesHandler.properties.getCreateScript()).booleanValue(); if (createScript) initScript(); try { String tablesURI = UtilitiesBean.fixURI(PropertiesHandler.properties.getTablesUri()); // Read tables.xml DOMParser domParser = new DOMParser(); // Eventually, write and validate against a DTD //domParser.setEntityResolver(new DTDResolver("tables.dtd")); domParser.parse(tablesURI); tablesDoc = domParser.getDocument(); } catch(Exception e) { System.out.println("Could not open " + UtilitiesBean.fixURI(PropertiesHandler.properties.getTablesUri())); e.printStackTrace(); return; } // Hold on to tables xml with generic types tablesDocGeneric = (Document)tablesDoc.cloneNode(true); // Replace all generic data types with local data types replaceDataTypes(tablesDoc); String tablesXslUri = UtilitiesBean.fixURI(PropertiesHandler.properties.getTablesXslUri()); // tables.xml + tables.xsl --> DROP TABLE and CREATE TABLE sql statements XSLTProcessor processor = XSLTProcessorFactory.getProcessor (new org.apache.xalan.xpath.xdom.XercesLiaison ()); XSLTInputSource tablesInputSource = new XSLTInputSource(tablesDoc); XSLTInputSource tablesXslInputSource = new XSLTInputSource(tablesXslUri); XSLTResultTarget tablesTarget = new XSLTResultTarget(new TableHandler()); processor.process (tablesInputSource, tablesXslInputSource, tablesTarget); // data.xml --> INSERT sql statements readData(parser); System.out.println("Done!"); long endTime = System.currentTimeMillis(); System.out.println("Elapsed time: " + ((endTime - startTime) / 1000f) + " seconds"); exit(); } else System.out.println("DbLoader couldn't obtain a database connection. See '" + portalBaseDir + "logs" + File.separator + "portal.log' for details."); } catch (Exception e) { e.printStackTrace(); } finally { exit(); } } private static void setPortalBaseDir() { String portalBaseDirParam = System.getProperty("portal.home"); if (portalBaseDirParam != null) { portalBaseDir = portalBaseDirParam; if (!portalBaseDir.endsWith(File.separator)) portalBaseDir += File.separator; UtilitiesBean.setPortalBaseDir(portalBaseDir); } else { System.out.println("Please set the system parameter portal.home. For example: java -Dportal.home=/usr/local/portal"); exit(); } } private static XMLReader getXMLReader() { // This method of getting a parser won't compile until we start using Xerces 1.2.2 and higher // SAXParserFactory spf = SAXParserFactory.newInstance(); // SAXParser saxParser = spf.newSAXParser(); // XMLReader xr = saxParser.getXMLReader(); // For now, we'll use the hard-coded instantiaiton of a Xerces SAX Parser XMLReader xr = new org.apache.xerces.parsers.SAXParser(); return xr; } private static void printInfo () throws SQLException { DatabaseMetaData dbMetaData = con.getMetaData(); String dbName = dbMetaData.getDatabaseProductName(); String dbVersion = dbMetaData.getDatabaseProductVersion(); String driverName = dbMetaData.getDriverName(); String driverVersion = dbMetaData.getDriverVersion(); System.out.println("Starting DbLoader..."); System.out.println("Database: '" + dbName + "', version: '" + dbVersion + "'"); System.out.println("Driver: '" + driverName + "', version: '" + driverVersion + "'"); } private static void readData (XMLReader parser) throws SAXException, IOException { DataHandler dataHandler = new DataHandler(); parser.setContentHandler(dataHandler); parser.setErrorHandler(dataHandler); parser.parse(UtilitiesBean.fixURI(PropertiesHandler.properties.getDataUri())); } private static void initScript() throws java.io.IOException { String scriptFileName = UtilitiesBean.getPortalBaseDir() + "properties" + File.separator + PropertiesHandler.properties.getScriptFileName().replace('/', File.separatorChar); File scriptFile = new File(scriptFileName); if (scriptFile.exists()) scriptFile.delete(); scriptFile.createNewFile(); scriptOut = new PrintWriter (new BufferedWriter (new FileWriter (scriptFileName, true))); } private static void replaceDataTypes (Document tablesDoc) { Element tables = tablesDoc.getDocumentElement(); NodeList types = tables.getElementsByTagName("type"); for (int i = 0; i < types.getLength(); i++) { Node type = (Node)types.item(i); NodeList typeChildren = type.getChildNodes(); for (int j = 0; j < typeChildren.getLength(); j++) { Node text = (Node)typeChildren.item(j); String genericType = text.getNodeValue(); // Replace generic type with mapped local type text.setNodeValue(getLocalDataTypeName(genericType)); } } } private static int getJavaSqlDataTypeOfColumn(Document tablesDocGeneric, String tableName, String columnName) { int dataType = 0; // Find the right table element Element table = getTableWithName(tablesDocGeneric, tableName); // Find the columns element within Element columns = getFirstChildWithName(table, "columns"); // Search for the first column who's name is columnName for (Node ch = columns.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Element && ch.getNodeName().equals("column")) { Element name = getFirstChildWithName((Element)ch, "name"); if (getNodeValue(name).equals(columnName)) { // Get the corresponding type and return it's type code Element value = getFirstChildWithName((Element)ch, "type"); dataType = getJavaSqlType(getNodeValue(value)); } } } return dataType; } private static Element getFirstChildWithName (Element parent, String name) { Element child = null; for (Node ch = parent.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Element && ch.getNodeName().equals(name)) { child = (Element)ch; break; } } return child; } private static Element getTableWithName (Document tablesDoc, String tableName) { Element tableElement = null; NodeList tables = tablesDoc.getElementsByTagName("table"); for (int i = 0; i < tables.getLength(); i++) { Node table = (Node)tables.item(i); for (Node tableChild = table.getFirstChild(); tableChild != null; tableChild = tableChild.getNextSibling()) { if (tableChild instanceof Element && tableChild.getNodeName() != null && tableChild.getNodeName().equals("name")) { if (tableName.equals(getNodeValue(tableChild))) { tableElement = (Element)table; break; } } } } return tableElement; } private static String getNodeValue (Node node) { String nodeVal = null; for (Node ch = node.getFirstChild(); ch != null; ch = ch.getNextSibling()) { if (ch instanceof Text) nodeVal = ch.getNodeValue(); } return nodeVal; } private static String getLocalDataTypeName (String genericDataTypeName) { // Find the type code for this generic type name int dataTypeCode = getJavaSqlType(genericDataTypeName); // Find the first local type name matching the type code String localDataTypeName = null; try { DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = dbmd.getTypeInfo(); try { while (rs.next()) { int localDataTypeCode = rs.getInt("DATA_TYPE"); if (dataTypeCode == localDataTypeCode) { try { localDataTypeName = rs.getString("TYPE_NAME"); } catch (SQLException sqle) { } break; } } } finally { rs.close(); } // If a local data type wasn't found, look in properties file // for a mapped data type name if (localDataTypeName == null) { DatabaseMetaData dbMetaData = con.getMetaData(); String dbName = dbMetaData.getDatabaseProductName(); String dbVersion = dbMetaData.getDatabaseProductVersion(); String driverName = dbMetaData.getDriverName(); String driverVersion = dbMetaData.getDriverVersion(); localDataTypeName = PropertiesHandler.properties.getMappedDataTypeName(dbName, dbVersion, driverName, driverVersion, genericDataTypeName); if (localDataTypeName == null) { System.out.println("Your database driver, '"+ driverName + "', version '" + driverVersion + "', was unable to find a local type name that matches the generic type name, '" + genericDataTypeName + "'."); System.out.println("Please add a mapped type for database '" + dbName + "', version '" + dbVersion + "' inside '" + propertiesUri + "' and run this program again."); System.out.println("Exiting..."); exit(); } } } catch (Exception e) { e.printStackTrace(); exit(); } return localDataTypeName; } private static int getJavaSqlType (String genericDataTypeName) { // Find the type code for this generic type name int dataTypeCode = 0; if (genericDataTypeName.equalsIgnoreCase("BIT")) dataTypeCode = Types.BIT; else if (genericDataTypeName.equalsIgnoreCase("TINYINT")) dataTypeCode = Types.TINYINT; else if (genericDataTypeName.equalsIgnoreCase("SMALLINT")) dataTypeCode = Types.SMALLINT; else if (genericDataTypeName.equalsIgnoreCase("INTEGER")) dataTypeCode = Types.INTEGER; else if (genericDataTypeName.equalsIgnoreCase("BIGINT")) dataTypeCode = Types.BIGINT; else if (genericDataTypeName.equalsIgnoreCase("FLOAT")) dataTypeCode = Types.FLOAT; else if (genericDataTypeName.equalsIgnoreCase("REAL")) dataTypeCode = Types.REAL; else if (genericDataTypeName.equalsIgnoreCase("DOUBLE")) dataTypeCode = Types.DOUBLE; else if (genericDataTypeName.equalsIgnoreCase("NUMERIC")) dataTypeCode = Types.NUMERIC; else if (genericDataTypeName.equalsIgnoreCase("DECIMAL")) dataTypeCode = Types.DECIMAL; else if (genericDataTypeName.equalsIgnoreCase("CHAR")) dataTypeCode = Types.CHAR; else if (genericDataTypeName.equalsIgnoreCase("VARCHAR")) dataTypeCode = Types.VARCHAR; else if (genericDataTypeName.equalsIgnoreCase("LONGVARCHAR")) dataTypeCode = Types.LONGVARCHAR; else if (genericDataTypeName.equalsIgnoreCase("DATE")) dataTypeCode = Types.DATE; else if (genericDataTypeName.equalsIgnoreCase("TIME")) dataTypeCode = Types.TIME; else if (genericDataTypeName.equalsIgnoreCase("TIMESTAMP")) dataTypeCode = Types.TIMESTAMP; else if (genericDataTypeName.equalsIgnoreCase("BINARY")) dataTypeCode = Types.BINARY; else if (genericDataTypeName.equalsIgnoreCase("VARBINARY")) dataTypeCode = Types.VARBINARY; else if (genericDataTypeName.equalsIgnoreCase("LONGVARBINARY")) dataTypeCode = Types.LONGVARBINARY; else if (genericDataTypeName.equalsIgnoreCase("NULL")) dataTypeCode = Types.NULL; else if (genericDataTypeName.equalsIgnoreCase("OTHER")) dataTypeCode = Types.OTHER; // 1111 else if (genericDataTypeName.equalsIgnoreCase("JAVA_OBJECT")) dataTypeCode = Types.JAVA_OBJECT; // 2000 else if (genericDataTypeName.equalsIgnoreCase("DISTINCT")) dataTypeCode = Types.DISTINCT; // 2001 else if (genericDataTypeName.equalsIgnoreCase("STRUCT")) dataTypeCode = Types.STRUCT; // 2002 else if (genericDataTypeName.equalsIgnoreCase("ARRAY")) dataTypeCode = Types.ARRAY; // 2003 else if (genericDataTypeName.equalsIgnoreCase("BLOB")) dataTypeCode = Types.BLOB; // 2004 else if (genericDataTypeName.equalsIgnoreCase("CLOB")) dataTypeCode = Types.CLOB; // 2005 else if (genericDataTypeName.equalsIgnoreCase("REF")) dataTypeCode = Types.REF; // 2006 return dataTypeCode; } private static void dropTable (String dropTableStatement) { System.out.print("..."); if (createScript) scriptOut.println(dropTableStatement + PropertiesHandler.properties.getStatementTerminator()); try { stmt = con.createStatement(); try { stmt.executeUpdate(dropTableStatement); } catch (SQLException sqle) {/*Table didn't exist*/} } catch (Exception e) { e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } private static void createTable (String createTableStatement) { System.out.print("..."); if (createScript) scriptOut.println(createTableStatement + PropertiesHandler.properties.getStatementTerminator()); try { stmt = con.createStatement(); stmt.executeUpdate(createTableStatement); } catch (Exception e) { System.out.println(createTableStatement); e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } private static void readProperties (XMLReader parser) throws SAXException, IOException { PropertiesHandler propertiesHandler = new PropertiesHandler(); parser.setContentHandler(propertiesHandler); parser.setErrorHandler(propertiesHandler); parser.parse(propertiesUri); } static class PropertiesHandler extends DefaultHandler { private static StringBuffer charBuff = null; static Properties properties; static DbTypeMapping dbTypeMapping; static Type type; public void startDocument () { System.out.print("Parsing " + propertiesUri + "..."); } public void endDocument () { System.out.println(""); } public void startElement (String uri, String name, String qName, Attributes atts) { charBuff = new StringBuffer(); if (name.equals("properties")) properties = new Properties(); else if (name.equals("db-type-mapping")) dbTypeMapping = new DbTypeMapping(); else if (name.equals("type")) type = new Type(); } public void endElement (String uri, String name, String qName) { if (name.equals("drop-tables")) // drop tables ("true" or "false") properties.setDropTables(charBuff.toString()); else if (name.equals("create-tables")) // create tables ("true" or "false") properties.setCreateTables(charBuff.toString()); else if (name.equals("populate-tables")) // populate tables ("true" or "false") properties.setPopulateTables(charBuff.toString()); else if (name.equals("tables-uri")) // tables URI properties.setTablesUri(charBuff.toString()); else if (name.equals("tables-xsl-uri")) // tables xsl URI properties.setTablesXslUri(charBuff.toString()); else if (name.equals("data-uri")) // data xml URI properties.setDataUri(charBuff.toString()); else if (name.equals("create-script")) // create script ("true" or "false") properties.setCreateScript(charBuff.toString()); else if (name.equals("script-file-name")) // script file name properties.setScriptFileName(charBuff.toString()); else if (name.equals("statement-terminator")) // statement terminator properties.setStatementTerminator(charBuff.toString()); else if (name.equals("db-type-mapping")) properties.addDbTypeMapping(dbTypeMapping); else if (name.equals("db-name")) // database name dbTypeMapping.setDbName(charBuff.toString()); else if (name.equals("db-version")) // database version dbTypeMapping.setDbVersion(charBuff.toString()); else if (name.equals("driver-name")) // driver name dbTypeMapping.setDriverName(charBuff.toString()); else if (name.equals("driver-version")) // driver version dbTypeMapping.setDriverVersion(charBuff.toString()); else if (name.equals("type")) dbTypeMapping.addType(type); else if (name.equals("generic")) // generic type type.setGeneric(charBuff.toString()); else if (name.equals("local")) // local type type.setLocal(charBuff.toString()); } public void characters (char ch[], int start, int length) { charBuff.append(ch, start, length); } class Properties { private String dropTables; private String createTables; private String populateTables; private String tablesUri; private String tablesXslUri; private String dataUri; private String dataXslUri; private String createScript; private String scriptFileName; private String statementTerminator; private ArrayList dbTypeMappings = new ArrayList(); public String getDropTables() { return dropTables; } public String getCreateTables() { return createTables; } public String getPopulateTables() { return populateTables; } public String getTablesUri() { return tablesUri; } public String getTablesXslUri() { return tablesXslUri; } public String getDataUri() { return dataUri; } public String getDataXslUri() { return dataXslUri; } public String getCreateScript() { return createScript; } public String getScriptFileName() { return scriptFileName; } public String getStatementTerminator() { return statementTerminator; } public ArrayList getDbTypeMappings() { return dbTypeMappings; } public void setDropTables(String dropTables) { this.dropTables = dropTables; } public void setCreateTables(String createTables) { this.createTables = createTables; } public void setPopulateTables(String populateTables) { this.populateTables = populateTables; } public void setTablesUri(String tablesUri) { this.tablesUri = tablesUri; } public void setTablesXslUri(String tablesXslUri) { this.tablesXslUri = tablesXslUri; } public void setDataUri(String dataUri) { this.dataUri = dataUri; } public void setDataXslUri(String dataXslUri) { this.dataXslUri = dataXslUri; } public void setCreateScript(String createScript) { this.createScript = createScript; } public void setScriptFileName(String scriptFileName) { this.scriptFileName = scriptFileName; } public void setStatementTerminator(String statementTerminator) { this.statementTerminator = statementTerminator; } public void addDbTypeMapping(DbTypeMapping dbTypeMapping) { dbTypeMappings.add(dbTypeMapping); } public String getMappedDataTypeName(String dbName, String dbVersion, String driverName, String driverVersion, String genericDataTypeName) { String mappedDataTypeName = null; Iterator iterator = dbTypeMappings.iterator(); while (iterator.hasNext()) { DbTypeMapping dbTypeMapping = (DbTypeMapping)iterator.next(); String dbNameProp = dbTypeMapping.getDbName(); String dbVersionProp = dbTypeMapping.getDbVersion(); String driverNameProp = dbTypeMapping.getDriverName(); String driverVersionProp = dbTypeMapping.getDriverVersion(); if (dbNameProp.equalsIgnoreCase(dbName) && dbVersionProp.equalsIgnoreCase(dbVersion) && driverNameProp.equalsIgnoreCase(driverName) && driverVersionProp.equalsIgnoreCase(driverVersion)) { // Found a matching database/driver combination mappedDataTypeName = dbTypeMapping.getMappedDataTypeName(genericDataTypeName); } } return mappedDataTypeName; } } class DbTypeMapping { String dbName; String dbVersion; String driverName; String driverVersion; ArrayList types = new ArrayList(); public String getDbName() { return dbName; } public String getDbVersion() { return dbVersion; } public String getDriverName() { return driverName; } public String getDriverVersion() { return driverVersion; } public ArrayList getTypes() { return types; } public void setDbName(String dbName) { this.dbName = dbName; } public void setDbVersion(String dbVersion) { this.dbVersion = dbVersion; } public void setDriverName(String driverName) { this.driverName = driverName; } public void setDriverVersion(String driverVersion) { this.driverVersion = driverVersion; } public void addType(Type type) { types.add(type); } public String getMappedDataTypeName(String genericDataTypeName) { String mappedDataTypeName = null; Iterator iterator = types.iterator(); while (iterator.hasNext()) { Type type = (Type)iterator.next(); if (type.getGeneric().equalsIgnoreCase(genericDataTypeName)) mappedDataTypeName = type.getLocal(); } return mappedDataTypeName; } } class Type { String genericType; // "generic" is a Java reserved word String local; public String getGeneric() { return genericType; } public String getLocal() { return local; } public void setGeneric(String genericType) { this.genericType = genericType; } public void setLocal(String local) { this.local = local; } } } static class TableHandler implements DocumentHandler { private static final int UNSET = -1; private static final int DROP = 0; private static final int CREATE = 1; private static int mode = UNSET; private static StringBuffer stmtBuffer; public void startDocument () { } public void endDocument () { System.out.println(); } public void startElement (String name, AttributeList atts) { if (name.equals("statement")) { stmtBuffer = new StringBuffer(1024); String statementType = atts.getValue("type"); if (mode == UNSET || mode == CREATE && statementType != null && statementType.equals("drop")) { mode = DROP; System.out.print("Dropping tables..."); if (!dropTables) System.out.print("disabled."); } else if (mode == UNSET || mode == DROP && statementType != null && statementType.equals("create")) { mode = CREATE; System.out.print("\nCreating tables..."); if (!createTables) System.out.print("disabled."); } } } public void endElement (String name) { if (name.equals("statement")) { String statement = stmtBuffer.toString(); switch (mode) { case DROP: if (dropTables) dropTable(statement); break; case CREATE: if (createTables) createTable(statement); break; default: break; } } } public void characters (char ch[], int start, int length) { stmtBuffer.append(ch, start, length); } public void setDocumentLocator (Locator locator) { } public void processingInstruction (String target, String data) { } public void ignorableWhitespace (char[] ch, int start, int length) { } } static class DataHandler extends DefaultHandler { private static boolean insideData = false; private static boolean insideTable = false; private static boolean insideName = false; private static boolean insideRow = false; private static boolean insideColumn = false; private static boolean insideValue = false; static Table table; static Row row; static Column column; public void startDocument () { System.out.print("Populating tables..."); if (!populateTables) System.out.print("disabled."); } public void endDocument () { System.out.println(""); } public void startElement (String uri, String name, String qName, Attributes atts) { if (name.equals("data")) insideData = true; else if (name.equals("table")) { insideTable = true; table = new Table(); } else if (name.equals("name")) insideName = true; else if (name.equals("row")) { insideRow = true; row = new Row(); } else if (name.equals("column")) { insideColumn = true; column = new Column(); } else if (name.equals("value")) insideValue = true; } public void endElement (String uri, String name, String qName) { if (name.equals("data")) insideData = false; else if (name.equals("table")) insideTable = false; else if (name.equals("name")) insideName = false; else if (name.equals("row")) { insideRow = false; if (populateTables) insertRow(table, row); } else if (name.equals("column")) { insideColumn = false; row.addColumn(column); } else if (name.equals("value")) insideValue = false; } public void characters (char ch[], int start, int length) { // Implicitly inside <data> and <table> if (insideName && !insideColumn) // table name table.setName(new String(ch, start, length)); else if (insideColumn && insideName) // column name column.setName(new String(ch, start, length)); else if (insideColumn && insideValue) // column value column.setValue(new String(ch, start, length)); } private String prepareInsertStatement (String tableName, Row row, boolean preparedStatement) { StringBuffer sb = new StringBuffer("INSERT INTO "); sb.append(table.getName()).append(" ("); ArrayList columns = row.getColumns(); Iterator iterator = columns.iterator(); while (iterator.hasNext()) { Column column = (Column)iterator.next(); sb.append(column.getName()).append(", "); } // Delete comma and space after last column name (kind of sloppy, but it works) sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append(") VALUES ("); iterator = columns.iterator(); while (iterator.hasNext()) { Column column = (Column)iterator.next(); if (preparedStatement) sb.append("?"); else { sb.append("'"); String value = column.getValue(); sb.append(value != null ? value.trim() : ""); sb.append("'"); } sb.append(", "); } // Delete comma and space after last value (kind of sloppy, but it works) sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1); sb.append(")"); return sb.toString(); } private void insertRow (Table table, Row row) { System.out.print("..."); if (createScript) scriptOut.println(prepareInsertStatement(table.getName(), row, false) + PropertiesHandler.properties.getStatementTerminator()); boolean supportsPreparedStatements = supportsPreparedStatements(); if (supportsPreparedStatements) { String preparedStatement = ""; try { preparedStatement = prepareInsertStatement(table.getName(), row, true); //System.out.println(preparedStatement); pstmt = con.prepareStatement(preparedStatement); pstmt.clearParameters (); // Loop through parameters and set them, checking for any that excede 4k ArrayList columns = row.getColumns(); Iterator iterator = columns.iterator(); for (int i = 1; iterator.hasNext(); i++) { Column column = (Column)iterator.next(); String value = column.getValue(); if (value != null && !value.equals("NULL")) { value = value.trim(); // portal can't read xml properly without this, don't know why yet int valueLength = value.length(); // Get a java sql data type for column name int javaSqlDataType = getJavaSqlDataTypeOfColumn(tablesDocGeneric, table.getName(), column.getName()); if (valueLength <= 4000) { try { // Needed for Sybase and maybe others pstmt.setObject(i, value, javaSqlDataType); } catch (Exception e) { // Needed for Oracle and maybe others pstmt.setObject(i, value); } } else { try { try { // Needed for Sybase and maybe others pstmt.setObject(i, value, javaSqlDataType); } catch (Exception e) { // Needed for Oracle and maybe others pstmt.setObject(i, value); } } catch (SQLException sqle) { // For Oracle and maybe others pstmt.setCharacterStream(i, new StringReader(value), valueLength); } } } else pstmt.setString(i, ""); } pstmt.executeUpdate(); } catch (SQLException sqle) { System.err.println(); System.err.println(preparedStatement); sqle.printStackTrace(); } catch (Exception e) { System.err.println(); e.printStackTrace(); } finally { try { pstmt.close(); } catch (Exception e) { } } } else { // If prepared statements aren't supported, try a normal insert statement String insertStatement = prepareInsertStatement(table.getName(), row, false); //System.out.println(insertStatement); try { stmt = con.createStatement(); stmt.executeUpdate(insertStatement); } catch (Exception e) { System.err.println(); System.err.println(insertStatement); e.printStackTrace(); } finally { try { stmt.close(); } catch (Exception e) { } } } } private static boolean supportsPreparedStatements() { boolean supportsPreparedStatements = true; try { // Issue a prepared statement to see if database/driver accepts them. // The assumption is that if a SQLException is thrown, it doesn't support them. // I don't know of any other way to check if the database/driver accepts // prepared statements. If you do, please change this method! pstmt = con.prepareStatement("SELECT * FROM UP_USERS WHERE USER_NAME=?"); pstmt.clearParameters (); pstmt.setString(1, "DUMMY_VALUE"); pstmt.execute(); } catch (SQLException sqle) { supportsPreparedStatements = false; sqle.printStackTrace(); exit(); } finally { try { pstmt.close(); } catch (Exception e) { } } return supportsPreparedStatements; } class Table { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Row { ArrayList columns = new ArrayList(); public ArrayList getColumns() { return columns; } public void addColumn(Column column) { columns.add(column); } } class Column { private String name; private String value; public String getName() { return name; } public String getValue() { return value; } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } } } private static void exit() { rdbmService.releaseConnection(con); if (scriptOut != null) scriptOut.close(); System.exit(0); } }
package coordinates; import db.DatabaseManager; import java.util.ArrayList; @SuppressWarnings("unused") public class CoordinateDetermination { /** * List with starting points of each link. * The segment Id's correspond to those in the "toIDs" list (in order). */ private ArrayList<Integer> fromIDs; /** * List with ending points of each link. * The segment Id's correspond to those in the "fromIDs" list (in order). */ private ArrayList<Integer> toIDs; private int[] noOfGpS; /** * List with coordinates of each segment. */ private Coordinate[] coordinates; /** * List with amount of genomes that travel throgh a certain link. */ private int[] cweights; /** * Database Object required to extract required data about segments and links. */ private DatabaseManager dbm; /** * Constructor. Gets required data from database. * @param dbm */ public CoordinateDetermination(DatabaseManager dbm) { this.dbm = dbm; getData(); } /** * Calculates coordinates involving all segments to determine a path to be used by ribbons. * * @return coordinates * Array of coordinates of segments. */ public Coordinate[] calcCoords() { getData(); int noOfSegments = toIDs.get(toIDs.size() - 1); /*** * TODO: Substitute "4" for number of genomes */ coordinates = new Coordinate[noOfSegments]; cweights = new int[noOfSegments]; coordinates[0] = new Coordinate(0,10); cweights[0] = 10; System.out.println(noOfSegments); for (int i = 1; i <= noOfSegments; i++) { System.out.println(i); int alreadyDrawn = 0; int leftToDraw = countGenomesInSeg(i); Coordinate coords = coordinates[i - 1]; ArrayList<Integer> outgoingedges = getToIDs(i); for (int j = 0; j < outgoingedges.size(); j++) { leftToDraw = leftToDraw - countGenomesInLink(i, outgoingedges.get(j)); int xc = coords.getX() + 1; int yc = coords.getY() - leftToDraw + alreadyDrawn; storeCoord(new Coordinate(xc,yc), outgoingedges.get(j), countGenomesInLink(i, outgoingedges.get(j))); alreadyDrawn += countGenomesInLink(i, outgoingedges.get(j)); } } for (int i = 1; i <= 9; i++) { System.out.println("SegID: " + i); System.out.println("X: " + coordinates[i - 1].getX()); System.out.println("Y: " + coordinates[i - 1].getY()); } return coordinates; } /** * Stores a specific coordinate in the global coordinates list. * * @param coord * @param segId * @param weight */ public void storeCoord(Coordinate coord, int segId, int weight) { if (coordinates[segId - 1] == null) { coordinates[segId - 1] = coord; cweights[segId - 1] = weight; } else { Coordinate oldCoord = coordinates[segId - 1]; int newX = Math.max(coord.getX(), oldCoord.getX()); int newY = (coord.getY() * weight + oldCoord.getY() * cweights[segId - 1]) / (weight + cweights[segId - 1]); coordinates[segId - 1] = new Coordinate(newX, newY); cweights[segId - 1] += weight; } } private ArrayList<Integer> getTo(int fromId) { return dbm.getDBReader().getToIDs(fromId); } private void getData() { fromIDs = dbm.getDBReader().getAllFromID(); toIDs = dbm.getDBReader().getAllToID(); } public int countGenomesInLink(int start, int end) { return dbm.getDBReader().countGenomesInLink(start, end); } public int countGenomesInSeg(int segmentId) { return dbm.getDBReader().countGenomesInSeg(segmentId); } public ArrayList<Integer> getToIDs(int fromId) { return dbm.getDBReader().getToIDs(fromId); } }
package io.github.pascalgrimaud.qualitoast.web.rest; import io.github.pascalgrimaud.qualitoast.QualiToastApp; import io.github.pascalgrimaud.qualitoast.service.ElasticsearchIndexService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Test class for ElasticsearchIndexResource REST controller. * * @see ElasticsearchIndexResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = QualiToastApp.class) public class ElasticsearchIndexResourceIntTest { @Autowired private ElasticsearchIndexService elasticsearchIndexService; private MockMvc restElasticsearchMockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); ElasticsearchIndexResource elasticResource = new ElasticsearchIndexResource(elasticsearchIndexService); this.restElasticsearchMockMvc = MockMvcBuilders.standaloneSetup(elasticResource) .build(); } @Test public void launchReindex() throws Exception { restElasticsearchMockMvc.perform(post("/api/elasticsearch/index")) .andExpect(status().isAccepted()); // As the ElasticsearchIndexService.reindexAll method is async // this test need to be achieved before going on other tests. // Otherwise, there can be some random failures like this: // SearchPhaseExecutionException: all shards failed Thread.sleep(5000); } }
package org.carlspring.strongbox.data.domain; import java.util.Date; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.orientechnologies.orient.core.exception.OValidationException; import com.orientechnologies.orient.core.hook.ORecordHookAbstract; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.impl.ODocument; /** * @author Sergey Bespalov * */ public class GenericEntityHook extends ORecordHookAbstract { private static final Logger logger = LoggerFactory.getLogger(GenericEntityHook.class); @Override public DISTRIBUTED_EXECUTION_MODE getDistributedExecutionMode() { return DISTRIBUTED_EXECUTION_MODE.SOURCE_NODE; } @Override public RESULT onRecordBeforeCreate(ORecord iRecord) { RESULT result = RESULT.RECORD_NOT_CHANGED; if (!(iRecord instanceof ODocument)) { return result; } ODocument doc = (ODocument) iRecord; if ("ArtifactEntry".equals(doc.getClassName())) { validateArtifactEntryCreatedProperty(doc); } for (OClass oClass : doc.getSchemaClass().getAllSuperClasses()) { if ("GenericEntity".equals(oClass.getName())) { String uuid = doc.field("uuid"); if (uuid == null || uuid.trim().isEmpty()) { throw new OValidationException( String.format("Failed to persist document [%s]. UUID can't be empty or null.", doc.getSchemaClass())); } } else if ("ArtifactEntry".equals(oClass.getName())) { ODocument artifactCoordinates = doc.field("artifactCoordinates"); String artifactCoordinatesPath = artifactCoordinates == null ? "" : artifactCoordinates.field("path"); String artifactEntryPath = doc.field("artifactPath"); artifactEntryPath = artifactEntryPath == null ? "" : artifactEntryPath.trim(); if (artifactCoordinatesPath.trim().isEmpty() && artifactEntryPath.trim().isEmpty()) { throw new OValidationException( String.format("Failed to persist document [%s]. 'artifactPath' can't be empty or null.", doc.getSchemaClass())); } else if (artifactCoordinates != null && !artifactEntryPath.equals(artifactCoordinatesPath)) { throw new OValidationException( String.format("Failed to persist document [%s]. Paths [%s] and [%s] dont match.", doc.getSchemaClass(), artifactEntryPath, artifactCoordinatesPath)); } validateArtifactEntryCreatedProperty(doc); } } return result; } private void validateArtifactEntryCreatedProperty(ODocument doc) { Date created = doc.field("created"); if (created == null) { throw new OValidationException( String.format("Failed to persist document [%s]. 'created' can't be null.", doc.getSchemaClass())); } } }
package de.cronn.jira.sync.domain; public enum JiraField { SUMMARY("summary"), STATUS("status"), ISSUETYPE("issuetype"), DESCRIPTION("description"), PRIORITY("priority"), PROJECT("project"), RESOLUTION("resolution"), LABELS("labels"), VERSIONS("versions"), FIX_VERSIONS("fixVersions"), ASSIGNEE("assignee"); private final String name; JiraField(String name) { this.name = name; } public String getName() { return name; } }
package de.db0x.eslog; import java.io.IOException; import java.net.URL; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import com.internetitem.logback.elasticsearch.AbstractElasticsearchAppender; import com.internetitem.logback.elasticsearch.ClassicElasticsearchPublisher; import com.internetitem.logback.elasticsearch.config.ElasticsearchProperties; import com.internetitem.logback.elasticsearch.config.Property; import com.internetitem.logback.elasticsearch.config.Settings; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; @Component public class ElasticsearchAppender extends AbstractElasticsearchAppender<ILoggingEvent> { private final static Logger LOG = LoggerFactory.getLogger(ElasticsearchAppender.class); @Autowired Environment env; @Value(value="${server.port}") private String serverPort; @Value(value="${spring.application.name}") private String appName; @Value(value="${spring.application.log.enable-es-log}") private Boolean enabled; @Value(value="${spring.application.log.type}") private String type; @Value(value="${spring.application.log.index-name}") private String indexName; @Value(value="${spring.application.log.es-log-url}") private String url; @Autowired private LogProperties properties; @PostConstruct private void init() { try { if ( enabled != null && enabled.booleanValue() == false ) { LOG.info("ElasticsearchAppender is disabled"); return; } MDC.put("host",Utils.getHost()); if ( serverPort != null ) { MDC.put("port",serverPort); } else { MDC.put("port","-UNKNOWN-"); } if ( appName != null ) { MDC.put("spring.application.name", appName); } else { MDC.put("spring.application.name", "-UNKNOWN-"); } ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); Settings settings = new Settings(); if ( indexName == null || indexName.length() == 0 ) indexName = "log-%date{yyyy-MM-dd}"; settings.setIndex(indexName); settings.setLoggerName("es-logger"); if ( url == null || url.length() == 0 ) url = "http://localhost:9200/_bulk"; settings.setUrl(new URL(url)); if ( type == null || type.length() == 0 ) type = "eslog"; settings.setType(type); ElasticsearchAppender ea = new ElasticsearchAppender(settings); ElasticsearchProperties ep = new ElasticsearchProperties(); addParameter(ep, "logger", properties.getParameters().get("logger"), "%logger"); addParameter(ep, "thread", properties.getParameters().get("thread"), "%thread"); addParameter(ep, "severity", properties.getParameters().get("severity"), "%level"); addParameter(ep, "stacktrace", properties.getParameters().get("stacktrace"), "%ex"); if ( properties.getParameters() != null ) { for ( String key : properties.getParameters().keySet() ) { LOG.info(" -> " + key.toString() + " - " + properties.getParameters().get(key)); if ( !"logger.thread.severity.stacktrace".contains(key) ) { addParameter(ep, key, properties.getParameters().get(key), properties.getParameters().get(key)); } } } ea.setProperties(ep); ea.setContext(lc); ea.start(); root.addAppender(ea); ch.qos.logback.classic.Logger eslog = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("es-logger"); eslog.setAdditive(false); LOG.info("ElasticsearchAppender added ["+url+"]"); } catch (Exception e) { LOG.error(e.getMessage()); } } private void addParameter(ElasticsearchProperties ep, String parameter, String value, String defaultValue) { Property property = new Property(); property.setName(parameter); if ( value == null ) value = defaultValue; property.setValue(value); ep.addProperty(property); } public ElasticsearchAppender() { } public ElasticsearchAppender(Settings settings) { super(settings); } @Override protected void appendInternal(ILoggingEvent eventObject) { String targetLogger = eventObject.getLoggerName(); String loggerName = settings.getLoggerName(); if (loggerName != null && loggerName.equals(targetLogger)) { return; } String errorLoggerName = settings.getErrorLoggerName(); if (errorLoggerName != null && errorLoggerName.equals(targetLogger)) { return; } eventObject.prepareForDeferredProcessing(); if (settings.isIncludeCallerData()) { eventObject.getCallerData(); } publishEvent(eventObject); } protected ClassicElasticsearchPublisher buildElasticsearchPublisher() throws IOException { return new ClassicElasticsearchPublisher(getContext(), errorReporter, settings, elasticsearchProperties); } }
package de.kopis.timeclicker.pages; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.time.Duration; import com.google.appengine.api.users.User; import de.kopis.timeclicker.exceptions.NotAuthenticatedException; import de.kopis.timeclicker.model.TimeEntry; import de.kopis.timeclicker.model.TimeSum; import de.kopis.timeclicker.panels.ActiveEntryPanel; import de.kopis.timeclicker.utils.DurationUtils; import de.kopis.timeclicker.utils.WorkdayCalculator; public class HomePage extends TemplatePage { private static final long serialVersionUID = 1L; /** * Update interval for sums. */ public static final Duration UPDATE_INTERVAL = Duration.seconds(30); //TODO GAppEngine does not have a user locale // maybe return all times as timestamps in UNIX format and convert in frontend? private final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", getLocale()); private ActiveEntryPanel activeEntry; private Link stop; private Link start; public HomePage(final PageParameters parameters) { super("Statistics", parameters); } @Override public void onInitialize() { super.onInitialize(); add(activeEntry = new ActiveEntryPanel("activePanel", new LoadableDetachableModel<String>() { @Override protected String load() { String activeEntry = null; final User user = getCurrentUser(); if (user == null) { return null; } try { final TimeEntry latest = getApi().latest(user); if (latest != null) { final Date start = latest.getStart(); activeEntry = DATE_FORMAT.format(start); } else { activeEntry = null; } } catch (NotAuthenticatedException e) { LOGGER.severe("Can not load active entry: " + e.getMessage()); } return activeEntry; } })); add(start = new Link("start") { @Override public boolean isVisible() { return !activeEntry.isVisible(); } @Override public void onClick() { // start a new entry if (getCurrentUser() == null) { error("You are not logged in."); } else { try { final TimeEntry entry = getApi().start(getCurrentUser()); success("Entry " + entry.getKey() + " started."); } catch (NotAuthenticatedException e) { LOGGER.severe("Can not start entry: " + e.getMessage()); error(e.getMessage()); } } setResponsePage(findPage()); } }); add(stop = new Link("stop") { @Override public boolean isVisible() { return activeEntry.isVisible(); } @Override public void onClick() { // stop latest entry if (getCurrentUser() == null) { error("You are not logged in."); } else { try { getApi().stopLatest(getCurrentUser()); // TODO how to invalidate activeEntry model? activeEntry.modelChanged(); success("Latest entry stopped."); } catch (NotAuthenticatedException e) { LOGGER.severe("Can not stop entry: " + e.getMessage()); error(e.getMessage()); } } setResponsePage(findPage()); } }); final IModel<TimeSum> overallSum = new LoadableDetachableModel<TimeSum>() { private TimeSum sum; @Override protected TimeSum load() { try { sum = getApi().getOverallSum(getCurrentUser()); } catch (NotAuthenticatedException e) { LOGGER.severe("Can not load overall sum: " + e.getMessage()); } return sum; } }; final IModel<TimeSum> monthlySum = new LoadableDetachableModel<TimeSum>() { private TimeSum sum; @Override protected TimeSum load() { try { sum = getApi().getMonthlySum(getCurrentUser()); } catch (NotAuthenticatedException e) { LOGGER.severe("Can not load monthly sum: " + e.getMessage()); } return sum; } }; final IModel<TimeSum> weeklySum = new LoadableDetachableModel<TimeSum>() { private TimeSum sum; @Override protected TimeSum load() { try { sum = getApi().getWeeklySum(getCurrentUser()); } catch (NotAuthenticatedException e) { LOGGER.severe("Can not load weekly sum: " + e.getMessage()); } return sum; } }; final IModel<TimeSum> dailySum = new LoadableDetachableModel<TimeSum>() { private TimeSum sum; @Override protected TimeSum load() { try { sum = getApi().getDailySum(getCurrentUser()); } catch (NotAuthenticatedException e) { LOGGER.severe("Can not load daily sum: " + e.getMessage()); } return sum; } }; final IModel<Integer> workdaysModel = new LoadableDetachableModel<Integer>() { @Override protected Integer load() { final Calendar cal = Calendar.getInstance(); // end today midnight cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); final Date endDate = cal.getTime(); // start first of month cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); final Date startDate = cal.getTime(); final int workdays = WorkdayCalculator.getWorkingDays(startDate, endDate); return workdays; } }; final IModel<Long> averagePerWorkdayPerMonth = new LoadableDetachableModel<Long>() { @Override protected Long load() { Long averagePerDay = Long.valueOf(0L); final TimeSum overallTimeSum = monthlySum.getObject(); final long workdays = (long) workdaysModel.getObject(); if (overallTimeSum != null) { averagePerDay = overallTimeSum.getDuration() / workdays; } // return in milliseconds return averagePerDay; } }; final IModel<String> readableAveragePerDay = new LoadableDetachableModel<String>() { @Override protected String load() { final Long averagePerDay = averagePerWorkdayPerMonth.getObject(); final String readableDuration = DurationUtils.getReadableDuration(averagePerDay); return readableDuration; } }; final Label averagePerDayLabel = new Label("averagePerDay", new StringResourceModel("average.sum", null, new Object[]{ readableAveragePerDay.getObject(), workdaysModel.getObject().intValue() })); averagePerDayLabel.add(new AjaxSelfUpdatingTimerBehavior(UPDATE_INTERVAL)); add(averagePerDayLabel); final Label perDayLabel = new Label("dailySum", new StringResourceModel("daily.sum", dailySum)); perDayLabel.add(new AjaxSelfUpdatingTimerBehavior(UPDATE_INTERVAL)); add(perDayLabel); final Label perWeekLabel = new Label("weeklySum", new StringResourceModel("weekly.sum", weeklySum)); perWeekLabel.add(new AjaxSelfUpdatingTimerBehavior(UPDATE_INTERVAL)); add(perWeekLabel); final Label perMonthLabel = new Label("monthlySum", new StringResourceModel("monthly.sum", monthlySum)); perMonthLabel.add(new AjaxSelfUpdatingTimerBehavior(UPDATE_INTERVAL)); add(perMonthLabel); final Label sumLabel = new Label("sum", new StringResourceModel("overall.sum", overallSum)); sumLabel.add(new AjaxSelfUpdatingTimerBehavior(UPDATE_INTERVAL)); add(sumLabel); } }
package dk.aau.cs.qweb.airbase.types; public class Object { private String object = ""; private String type = ""; public Object(String string) { object = string; } public Object(String object, String type) { this.object = object; this.type = type; } public Object(int i, String integerType) { object = String.valueOf(i); this.type = integerType; } public String getliteral() { return object; } public void setObject(String object) { this.object = object; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isEmpty() { return this.object.isEmpty(); } public boolean hasType() { if (!type.isEmpty()) { return true; } return false; } @Override public String toString() { return object+type; } }
package ch.srsx.swat.datapower.tools.ant.taskdefs; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Vector; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.apache.tools.ant.util.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * This ANT task generates a DataPower configuration specific files element. * * @author <a href="mailto:pshah@schlagundrahm.ch">Pierce Shah</a> * */ public class CreateFilesConfig extends Task { private File file; private Vector<FileSet> filesets; private FileUtils fileUtils; private String env; private String domain; private String comment; private String location = "local"; private boolean useBaseDir = true; private boolean createDpConfig = false; private String dpBaseDir; private String targetdir; private String targetfile; private final String dpFileSeparator = "/"; private final String systemFileSeparator = System.getProperty("file.separator"); private final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); private final SimpleDateFormat tf = new SimpleDateFormat("HH:mm:ss"); public CreateFilesConfig() { fileUtils = FileUtils.getFileUtils(); file = null; filesets = new Vector<FileSet>(); } public void setFile(File file) { this.file = file; } public void addFileset(FileSet set) { filesets.addElement(set); } public void setEnv(String env) { this.env = env; } public void setTargetdir(String targetdir) { this.targetdir = targetdir; } public void setTargetfile(String targetfile) { this.targetfile = targetfile; } public void setLocation(String location) { this.location = location; } public void setUseBaseDir(boolean useBaseDir) { this.useBaseDir = useBaseDir; } public void setDpBaseDir(String dpBaseDir) { this.dpBaseDir = dpBaseDir; } public void setCreateDpConfig(boolean createDpConfig) { this.createDpConfig = createDpConfig; } public void setDomain(String domain) { this.domain = domain; } public void setComment(String comment) { this.comment = comment; } public void execute() throws BuildException { if ((file != null) && (filesets.size() > 0)) { throw new BuildException( "You cannot supply the 'file' attribute and filesets at the same time."); } if ((file != null) && file.exists()) { log(file + " ==> " + file.getAbsolutePath()); } else if (file != null) { log("The following file is missing: '" + file.getAbsolutePath() + "'", 0); } int sz = filesets.size(); Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // initialize files element Element filesNode = doc.createElement("files"); if (createDpConfig) { // create datapower-configuration element Element dpNode = doc.createElement("datapower-configuration"); dpNode.setAttribute("version", "3"); // create export-details element Element detailsNode = doc.createElement("export-details"); Element descNode = doc.createElement("description"); descNode.setTextContent("SWAT generated configuration"); detailsNode.appendChild(descNode); Element userNode = doc.createElement("user"); userNode.setTextContent(System.getProperty("user.name")); detailsNode.appendChild(userNode); Element domainNode = doc.createElement("domain"); domainNode.setTextContent(domain); detailsNode.appendChild(domainNode); Element commentNode = doc.createElement("comment"); commentNode.setTextContent(comment); detailsNode.appendChild(commentNode); Calendar cal = Calendar.getInstance(); Element dateNode = doc.createElement("current-date"); dateNode.setTextContent(df.format(cal.getTime())); detailsNode.appendChild(dateNode); Element timeNode = doc.createElement("current-time"); timeNode.setTextContent(tf.format(cal.getTime())); detailsNode.appendChild(timeNode); dpNode.appendChild(detailsNode); // create configuration element Element configNode = doc.createElement("configuration"); configNode.setAttribute("domain", domain); dpNode.appendChild(configNode); // append empty files node dpNode.appendChild(filesNode); // append root node to the document doc.appendChild(dpNode); } else { doc.appendChild(filesNode); } for (int i = 0; i < sz; i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); log("number of files: " + files.length); for (int j = 0; j < files.length; j++) { log("file[" + j + "] = " + files[j]); File f = new File(fs.getDir(getProject()), files[j]); String dpFileSrc = files[j].replace( systemFileSeparator, dpFileSeparator); String dpFileName = dpFileSrc; if (useBaseDir) { int pos = dpFileName.indexOf(dpFileSeparator); dpBaseDir = dpFileName.substring(0, pos); dpFileName = dpFileName.substring(pos + 1); } else { dpBaseDir = location; } if (f.exists()) { try { log("File: " + f); Element child = doc.createElement("file"); filesNode.appendChild(child); child.setAttribute("name", dpBaseDir + ":///" + dpFileName); child.setAttribute("src", dpFileSrc); child.setAttribute("location", location); child.setAttribute("hash", calculateFileHash(f)); } catch (Exception e) { log("An error occurred processing file: '" + f.getAbsolutePath() + "': " + e.toString(), 0); } } else { log("The following file is missing: '" + f.getAbsolutePath() + "'", 0); } } } /* * OutputFormat format = new OutputFormat(document); * format.setLineWidth(65); format.setIndenting(true); * format.setIndent(2); */ try { Transformer serializer = TransformerFactory.newInstance() .newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4"); File f = new File(targetdir + systemFileSeparator + targetfile); log("file: " + f); URI uri = f.toURI(); log("URI: " + uri); StreamResult sr = new StreamResult(new File(uri)); serializer.transform(new DOMSource(doc), sr); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } } private String calculateFileHash(File file) throws IOException { InputStream is = new FileInputStream(file); byte[] hash = null; try { hash = DigestUtils.sha(is); } finally { if (is != null) { is.close(); } } if (hash == null) { throw new BuildException("Could not calcualte SHA-1 hash for file: " + file); } return Base64.encodeBase64String(hash).trim(); } }
package dmillerw.asm.core; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import dmillerw.asm.annotation.MConstructor; import dmillerw.asm.annotation.MField; import dmillerw.asm.annotation.MImplement; import dmillerw.asm.annotation.MOverride; import dmillerw.asm.template.Template; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Map; import java.util.Set; import static org.objectweb.asm.Opcodes.*; public class SubclassGenerator<T> { public static <T> Class<T> generateSubclass(Class<?> superClass, Class<? extends Template<T>> templateClass) { SubclassGenerator<T> subclassGenerator = new SubclassGenerator<T>(superClass, templateClass); return subclassGenerator.generateSubclass(); } private static final ASMClassLoader LOADER = new ASMClassLoader(); private static class ASMClassLoader extends ClassLoader { private ASMClassLoader() { super(ASMClassLoader.class.getClassLoader()); } public Class<?> define(String name, byte[] data) { return defineClass(name, data, 0, data.length); } } private static final boolean DEBUG = true; private static void debug(String msg) { if (DEBUG) System.out.println("DEBUG: " + msg); } // Class instances final Class<?> superClass; final Class<? extends Template<?>> templateClass; // Super class node. Used for protecting the original methods when overridden final ClassNode superNode; // Template class node. Used for copying methods final ClassNode templateNode; // Internal class names final String superType; String subName; String subType; final String templateType; // Mappings of all valid constructors found in the super class final Set<MethodMapping> superConstructors = Sets.newHashSet(); // Mappings of all valid constructors found in the template final Set<MethodMapping> templateConstructors = Sets.newHashSet(); // All collected method nodes. Can be for constructors, overrides, or implementations final Map<MethodMapping, MethodNode> methodNodes = Maps.newHashMap(); // All methods that the template will override final Set<MethodMapping> overrideMethods = Sets.newHashSet(); // All methods that will be implemented in the sub-class from the template final Set<MethodMapping> implementMethods = Sets.newHashSet(); // Mappings of all fields found in the template final Set<FieldMapping> implementFields = Sets.newHashSet(); // All collected field nodes. Used for copying mainly final Map<FieldMapping, FieldNode> fieldNodes = Maps.newHashMap(); public SubclassGenerator(Class<?> superClass, Class<? extends Template<T>> templateClass) { this.superClass = superClass; this.templateClass = templateClass; this.superNode = ASMUtils.getClassNode(superClass); this.templateNode = ASMUtils.getClassNode(templateClass); this.superType = Type.getInternalName(superClass); this.subName = superClass.getName() + "_GENERATED_" + templateClass.hashCode(); this.subType = subName.replace(".", "/"); this.templateType = Type.getInternalName(templateClass); gatherSuperclassConstructors(); gatherTemplateFields(); gatherTemplateMethods(); } public SubclassGenerator<T> setClassName(String name) { this.subName = name; this.subType = subName.replace(".", "/"); return this; } /** * Gather all constructors directly declared in the super class */ private void gatherSuperclassConstructors() { for (Constructor constructor : superClass.getDeclaredConstructors()) { MethodMapping methodMapping = new MethodMapping(constructor); superConstructors.add(methodMapping); debug("Found super-class constructor: " + methodMapping.toString()); } } /** * Gather all annotated fields directly declared in the template class */ private void gatherTemplateFields() { for (Field field : templateClass.getDeclaredFields()) { if (Modifier.isAbstract(field.getModifiers())) continue; MField mField = field.getAnnotation(MField.class); if (mField != null) { FieldMapping fieldMapping = new FieldMapping(field); debug("Found annotated field in template: " + fieldMapping.toString()); implementFields.add(fieldMapping); for (FieldNode fieldNode : templateNode.fields) { if (fieldNode.name.equals(fieldMapping.name) && fieldNode.desc.equals(fieldMapping.signature)) { fieldNodes.put(fieldMapping, fieldNode); } } } } } /** * Gather all annotated methods directly declared in the template class, and sanity checking */ private void gatherTemplateMethods() { for (Method method : templateClass.getDeclaredMethods()) { MConstructor mConstructor = method.getAnnotation(MConstructor.class); MOverride mOverride = method.getAnnotation(MOverride.class); MImplement mImplement = method.getAnnotation(MImplement.class); if (mConstructor != null) { MethodMapping methodMapping = new MethodMapping(method); methodMapping.signature = methodMapping.signature.substring(0, methodMapping.signature.length() - 1); for (MethodNode methodNode : templateNode.methods) { if (methodNode.name.equals(methodMapping.name) && methodNode.desc.equals(methodMapping.signature + "V")) { methodNodes.put(methodMapping, methodNode); } } debug("Found template constructor: " + methodMapping.toString()); templateConstructors.add(methodMapping); } if (mOverride != null) { MethodMapping methodMapping = new MethodMapping(method); debug("Overridding method: " + methodMapping); // We're overriding a method. Make sure the superclass actually has it try { superClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { throw new RuntimeException("Cannot override " + method.getName() + " from " + superType + " as it doesn't exist"); } overrideMethods.add(methodMapping); for (MethodNode methodNode : templateNode.methods) { if (methodNode.name.equals(methodMapping.name) && methodNode.desc.equals(methodMapping.signature)) { methodNodes.put(methodMapping, methodNode); } } // Also grab the method node from the super class and store MethodMapping defMethodMapping = new MethodMapping("default_" + methodMapping.name, methodMapping.signature); for (MethodNode methodNode : superNode.methods) { if (methodNode.name.equals(methodMapping.name) && methodNode.desc.equals(methodMapping.signature)) { methodNodes.put(defMethodMapping, methodNode); } } } if (mImplement != null) { MethodMapping methodMapping = new MethodMapping(method); implementMethods.add(methodMapping); for (MethodNode methodNode : templateNode.methods) { if (methodNode.name.equals(methodMapping.name) && methodNode.desc.equals(methodMapping.signature)) { methodNodes.put(methodMapping, methodNode); } } } } } public Class<T> generateSubclass() { // All interfaces that the template class implements Class<?>[] interfaces = templateClass.getInterfaces(); // The fully qualified type strings for those interfaces String[] interfaceStrs = new String[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { interfaceStrs[i] = interfaces[i].getName().replace(".", "/"); } ClassWriter classWriter = new ClassWriter(0); // Write class header classWriter.visit( V1_6, ACC_PUBLIC | ACC_SUPER, subType, null, superType, interfaceStrs ); classWriter.visitSource(".dynamic", null); addFields(classWriter); addConstructors(classWriter); overrideMethods(classWriter); implementMethods(classWriter); classWriter.visitEnd(); Class<?> clazz = LOADER.define(subName, classWriter.toByteArray()); return (Class<T>) clazz; } private void addFields(ClassWriter classWriter) { for (FieldNode fieldNode : fieldNodes.values()) { classWriter.visitField(fieldNode.access, fieldNode.name, fieldNode.desc, null, null); } } private void addConstructors(ClassWriter classWriter) { for (MethodMapping methodMapping : superConstructors) { MethodVisitor methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", methodMapping.signature + "V", null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(ALOAD, 0); for (int i = 0; i < methodMapping.params.length; i++) { methodVisitor.visitVarInsn(ASMUtils.getLoadCode(methodMapping.params[i]), i + 1); } methodVisitor.visitMethodInsn(INVOKESPECIAL, superType, "<init>", methodMapping.signature + "V", false); int maxStack = methodMapping.params.length + 1; int maxLocals = methodMapping.params.length + 2; // If the template has the same constructor // We loop because the constructors found in template are proper methods, and have names for (MethodMapping methodMapping1 : templateConstructors) { if (methodMapping1.signature.equals(methodMapping.signature)) { debug("Found matching super constructor in template: " + methodMapping1); MethodNode methodNode = methodNodes.get(methodMapping1); InsnList insnList = interpretAndCopyNodes(methodNode); insnList.accept(methodVisitor); maxStack += methodNode.maxStack; maxLocals += methodNode.maxLocals; break; } } methodVisitor.visitInsn(RETURN); methodVisitor.visitMaxs(maxStack, maxLocals); methodVisitor.visitEnd(); } } private void overrideMethods(ClassWriter classWriter) { for (MethodMapping methodMapping : overrideMethods) { MethodNode methodNode = methodNodes.get(methodMapping); MethodMapping defMethodMapping = new MethodMapping("default_" + methodMapping.name, methodMapping.signature); MethodNode defNode = methodNodes.get(defMethodMapping); MethodVisitor methodVisitor; InsnList insnList; // Generate a new method that contains the super-class method instructions methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "default_" + defNode.name, defNode.desc, null, null); methodVisitor.visitCode(); insnList = new InsnList(); Iterator<AbstractInsnNode> iterator = defNode.instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); if (insnNode instanceof LabelNode || insnNode instanceof LineNumberNode) continue; insnList.add(insnNode); } insnList.accept(methodVisitor); methodVisitor.visitMaxs(defNode.maxStack, defNode.maxLocals); methodVisitor.visitEnd(); // Then generate the override method methodVisitor = classWriter.visitMethod(ACC_PUBLIC, methodMapping.name, methodMapping.signature, null, null); methodVisitor.visitCode(); insnList = interpretAndCopyNodes(methodNode); insnList.accept(methodVisitor); methodVisitor.visitMaxs(methodMapping.params.length + 1 + methodNode.maxStack, methodMapping.params.length + 1 + methodNode.maxLocals); methodVisitor.visitEnd(); } } private void implementMethods(ClassWriter classWriter) { for (MethodMapping methodMapping : implementMethods) { MethodNode methodNode = methodNodes.get(methodMapping); String desc = methodNode.desc; MethodVisitor methodVisitor; InsnList insnList; methodVisitor = classWriter.visitMethod(methodNode.access, methodMapping.name, desc, null, null); methodVisitor.visitCode(); insnList = interpretAndCopyNodes(methodNode); insnList.accept(methodVisitor); methodVisitor.visitMaxs(methodNode.maxStack, methodNode.maxLocals); methodVisitor.visitEnd(); } } /** * Reads all instructions from a method node, and copies them into a new InsnList * <p/> * If the node needs to be modified at all (redirects, super calls) that's done as well */ private InsnList interpretAndCopyNodes(MethodNode methodNode) { NodeCopier nodeCopier = new NodeCopier(methodNode.instructions); InsnList insnList = new InsnList(); int skip = 0; int index = 0; Iterator<AbstractInsnNode> iterator = methodNode.instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); if (skip > 0) { debug("Skipping {" + ASMUtils.nodeToString(insnNode) + "} " + skip + " left."); skip index++; continue; } if (insnNode instanceof MethodInsnNode) { AbstractInsnNode newNode = redirectLocalMethod((MethodInsnNode) insnNode); if (newNode != null) { nodeCopier.copyTo(newNode, insnList); } else { nodeCopier.copyTo(insnNode, insnList); } } else if (insnNode instanceof FieldInsnNode) { AbstractInsnNode newNode = redirectSuperCall(methodNode, (FieldInsnNode) insnNode, index); if (newNode != null) { debug("Redirected super call!"); debug(" * OLD: " + ASMUtils.nodeToString(insnNode)); debug(" * NEW: " + ASMUtils.nodeToString(newNode)); skip = 2; // Skipping the GETFIELD and the CHECKCAST nodeCopier.copyTo(newNode, insnList); } else { newNode = redirectLocalField((FieldInsnNode) insnNode); if (newNode != null) { nodeCopier.copyTo(newNode, insnList); } else { nodeCopier.copyTo(insnNode, insnList); } } } else { nodeCopier.copyTo(insnNode, insnList); } index++; } return insnList; } /** * Take a FieldInsnNode and determines whether or not it should be treated as a super call * If so, it looks and sees whether it's a field or method call, and delegates accordingly * <p/> * If it's a method call, we check to see if there's a default_ method, and if so, we redirect * the call to the that default method, removing the in-between bytecode (GETFIELD and CHECKCAST) * <p/> * If it's a field call, we simply chop out the GETFIELD call to the super field, and redirect directly * to the field in the subclass * * @return Whatever node has been generated to properly redirect */ private AbstractInsnNode redirectSuperCall(MethodNode methodNode, FieldInsnNode fieldNode, int index) { if (fieldNode.name.equals("_super") && fieldNode.getOpcode() == GETFIELD) { AbstractInsnNode nextNode = methodNode.instructions.get(index + 1); // We're for certain handling usage of the _super field if (nextNode.getOpcode() == CHECKCAST) { nextNode = methodNode.instructions.get(index + 2); if (nextNode instanceof MethodInsnNode) { MethodInsnNode nextMethodNode = (MethodInsnNode) nextNode; MethodMapping oldMethodMapping = new MethodMapping(nextMethodNode.name, nextMethodNode.desc); // If there's a super call to a method that's been overridden, pass it through // to the generated default method if (overrideMethods.contains(oldMethodMapping)) { debug("Found super call to overridden method!"); // Fun fact. This somehow handles super super super methods and I don't even know how return new MethodInsnNode(INVOKESPECIAL, subType, "default_" + nextMethodNode.name, nextMethodNode.desc, false); } else { return new MethodInsnNode(INVOKESPECIAL, superType, nextMethodNode.name, nextMethodNode.desc, false); } } else if (nextNode instanceof FieldInsnNode) { FieldInsnNode nextFieldNode = (FieldInsnNode) nextNode; return ASMUtils.redirect(nextFieldNode, subType); } else { return null; // Shouldn't happen } } else { return null; // Also shouldn't happen } } else { return null; } } /** * Takes a FieldInsnNode and re-directs it to the defined super class IF and ONLY IF it currently points * to the template as its owner */ private AbstractInsnNode redirectLocalField(FieldInsnNode fieldNode) { if (fieldNode.owner.equals(templateType)) { return ASMUtils.redirect(fieldNode, subType); } else { return null; } } /** * Takes a MethodInsnNode and re-directs it to the defined super class IF and ONLY IF it currently points * to the template as its owner */ private AbstractInsnNode redirectLocalMethod(MethodInsnNode methodInsnNode) { if (methodInsnNode.owner.equals(templateType)) { return ASMUtils.redirect(methodInsnNode, subType); } else { return null; } } }
package edu.uib.info310.search; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import edu.uib.info310.transformation.XslTransformer; @Component public class LastFMSearch { private static final String similarArtistRequest = "http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist="; private static final String artistEvents = "http://ws.audioscrobbler.com/2.0/?method=artist.getevents&artist="; private static final String apiKey = "&api_key=a7123248beb0bbcb90a2e3a9ced3bee9"; private static final Logger LOGGER = LoggerFactory.getLogger(LastFMSearch.class); public InputStream getArtistEvents (String artist) throws Exception { URL lastFMRequest = new URL(artistEvents+artist+apiKey); URLConnection lastFMConnection = lastFMRequest.openConnection(); return lastFMConnection.getInputStream(); } public InputStream getSimilarArtist(String artist) throws Exception { URL lastFMRequest = new URL(similarArtistRequest+artist+apiKey); URLConnection lastFMConnection = lastFMRequest.openConnection(); return lastFMConnection.getInputStream(); } public static void main(String[] args) throws Exception { File xsl = new File("src/main/resources/XSL/SimilarArtistLastFM.xsl"); LastFMSearch search = new LastFMSearch(); XslTransformer transform = new XslTransformer(); transform.setXml(search.getSimilarArtist("Metallica")); transform.setXsl(xsl); File file = new File("log/rdf-artist.xml"); FileOutputStream fileOutputStream = new FileOutputStream(file); transform.transform().writeTo(fileOutputStream); // System.out.println(transform.transform()); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.admin.server; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import com.samskivert.io.ByteArrayOutInputStream; import com.samskivert.util.StringUtil; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; import com.threerings.presents.dobj.AccessController; import com.threerings.presents.dobj.AttributeChangeListener; import com.threerings.presents.dobj.AttributeChangedEvent; import com.threerings.presents.dobj.DObject; import com.threerings.presents.dobj.DSet; import com.threerings.presents.dobj.ElementUpdateListener; import com.threerings.presents.dobj.ElementUpdatedEvent; import com.threerings.presents.dobj.EntryAddedEvent; import com.threerings.presents.dobj.EntryRemovedEvent; import com.threerings.presents.dobj.EntryUpdatedEvent; import com.threerings.presents.dobj.ObjectAccessException; import com.threerings.presents.dobj.SetListener; import static com.threerings.admin.Log.log; /** * Provides a registry of configuration distributed objects. Using distributed object to store * runtime configuration data can be exceptionally useful in that clients (with admin privileges) * can view and update the running server's configuration parameters on the fly. * * <p> Users of the service are responsible for creating their own configuration objects which are * then registered via this class. The config object registry then performs a few functions: * * <ul> * <li> It populates the config object with values from the persistent configuration information. * <li> It mirrors object updates out to the persistent configuration repository. * <li> It makes the set of registered objects available for inspection and modification via the * admin client interface. * </ul> * * <p> Users of this service will want to use {@link AccessController}s on their configuration * distributed objects to prevent non-administrators from subscribing to or modifying the objects. */ public abstract class ConfigRegistry { /** * Creates a ConfigRegistry that isn't transitioning. */ public ConfigRegistry () { this(false); } /** * Creates a ConfigRegistry. * * @param transitioning if true, serialized Streamable instances stored in the registry will * be written back out immediately to allow them to be transitioned to new class names. */ public ConfigRegistry (boolean transitioning) { _transitioning = transitioning; } /** * Registers the supplied configuration object with the system. * * @param key a string that identifies this object. These are generally hierarchical in nature * (of the form <code>system.subsystem</code>), for example: <code>yohoho.crew</code>. * @param path The the path in the persistent configuration repository. This may mean * something to the underlying persistent store, for example in the preferences backed * implementation it defines the path to the preferences node in the package hierarchy. * @param object the object to be registered. */ public void registerObject (String key, String path, DObject object) { ObjectRecord record = createObjectRecord(path, object); record.init(); _configs.put(key, record); } /** * Returns the config object mapped to the specified key, or null if none exists for that key. */ public DObject getObject (String key) { ObjectRecord record = _configs.get(key); return (record == null) ? null : record.object; } /** * Returns an array containing the keys of all registered configuration objects. */ public String[] getKeys () { return _configs.keySet().toArray(new String[_configs.size()]); } /** * Creates an object record derivation that will handle the management of the specified object. */ protected abstract ObjectRecord createObjectRecord (String path, DObject object); /** * Create an ObjectInputStream to read serialized config entries. */ protected ObjectInputStream createObjectInputStream (InputStream bin) { return new ObjectInputStream(bin); } /** * Create an ObjectOutputStream to write serialized config entries. */ protected ObjectOutputStream createObjectOutputStream (OutputStream bin) { return new ObjectOutputStream(bin); } /** * Contains all necessary info for a configuration object registration. */ protected abstract class ObjectRecord implements AttributeChangeListener, SetListener<DSet.Entry>, ElementUpdateListener { public DObject object; public ObjectRecord (DObject obj) { object = obj; } public void init () { // read in the initial configuration settings from the persistent config repository Class<?> cclass = object.getClass(); try { Field[] fields = cclass.getFields(); for (Field field : fields) { int mods = field.getModifiers(); if ((mods & Modifier.STATIC) != 0 || (mods & Modifier.PUBLIC) == 0 || (mods & Modifier.TRANSIENT) != 0) { continue; } initField(field); } // listen for attribute updates object.addListener(this); } catch (SecurityException se) { log.warning("Unable to reflect on " + cclass.getName() + ": " + se + ". " + "Refusing to monitor object."); } } // from SetListener public void entryAdded (EntryAddedEvent<DSet.Entry> event) { serializeAttribute(event.getName()); } // from SetListener public void entryUpdated (EntryUpdatedEvent<DSet.Entry> event) { serializeAttribute(event.getName()); } // from SetListener public void entryRemoved (EntryRemovedEvent<DSet.Entry> event) { serializeAttribute(event.getName()); } // from ElementUpdateListener public void elementUpdated (ElementUpdatedEvent event) { Object value; try { value = object.getAttribute(event.getName()); } catch (ObjectAccessException oae) { log.warning("Exception getting field [name=" + event.getName() + ", exception=" + oae + "]."); return; } updateValue(event.getName(), value); } // from AttributeChangeListener public void attributeChanged (AttributeChangedEvent event) { // mirror this configuration update to the persistent config Object value = event.getValue(); if (value instanceof DSet) { serializeAttribute(event.getName()); } else { updateValue(event.getName(), value); } } protected void updateValue (String name, Object value) { String key = nameToKey(name); if (value instanceof Boolean) { setValue(key, ((Boolean)value).booleanValue()); } else if (value instanceof Short) { setValue(key, ((Short)value).shortValue()); } else if (value instanceof Integer) { setValue(key, ((Integer)value).intValue()); } else if (value instanceof Long) { setValue(key, ((Long)value).longValue()); } else if (value instanceof Float) { setValue(key, ((Float)value).floatValue()); } else if (value instanceof String) { setValue(key, (String)value); } else if (value instanceof float[]) { setValue(key, (float[])value); } else if (value instanceof int[]) { setValue(key, (int[])value); } else if (value instanceof String[]) { setValue(key, (String[])value); } else if (value instanceof long[]) { setValue(key, (long[])value); } else { log.info("Unable to flush config obj change [cobj=" + object.getClass().getName() + ", key=" + key + ", type=" + value.getClass().getName() + ", value=" + value + "]."); } } /** * Initializes a single field of a config distributed object from its corresponding value * in the associated config repository. */ protected void initField (Field field) { String key = nameToKey(field.getName()); Class<?> type = field.getType(); try { if (type.equals(Boolean.TYPE)) { boolean defval = field.getBoolean(object); field.setBoolean(object, getValue(key, defval)); } else if (type.equals(Short.TYPE)) { short defval = field.getShort(object); field.setShort(object, getValue(key, defval)); } else if (type.equals(Integer.TYPE)) { int defval = field.getInt(object); field.setInt(object, getValue(key, defval)); } else if (type.equals(Long.TYPE)) { long defval = field.getLong(object); field.setLong(object, getValue(key, defval)); } else if (type.equals(Float.TYPE)) { float defval = field.getFloat(object); field.setFloat(object, getValue(key, defval)); } else if (type.equals(String.class)) { String defval = (String)field.get(object); field.set(object, getValue(key, defval)); } else if (type.equals(int[].class)) { int[] defval = (int[])field.get(object); field.set(object, getValue(key, defval)); } else if (type.equals(float[].class)) { float[] defval = (float[])field.get(object); field.set(object, getValue(key, defval)); } else if (type.equals(String[].class)) { String[] defval = (String[])field.get(object); field.set(object, getValue(key, defval)); } else if (type.equals(long[].class)) { long[] defval = (long[])field.get(object); field.set(object, getValue(key, defval)); } else if (Streamable.class.isAssignableFrom(type)) { // don't freak out if the conf is blank. String value = getValue(key, ""); if (StringUtil.isBlank(value)) { return; } try { ByteArrayInputStream bin = new ByteArrayInputStream(StringUtil.unhexlate(value)); ObjectInputStream oin = createObjectInputStream(bin); Object deserializedValue = oin.readObject(); field.set(object, deserializedValue); if (_transitioning) { // Use serialize rather than serializeAttribute so we don't get // ObjectAccessExceptions serialize(key, nameToKey(key), deserializedValue); } } catch (Exception e) { log.warning("Failure decoding config value [type=" + type + ", field=" + field + ", exception=" + e + "]."); } } else { log.warning("Can't init field of unknown type " + "[cobj=" + object.getClass().getName() + ", key=" + key + ", type=" + type.getName() + "]."); } } catch (IllegalAccessException iae) { log.warning("Can't set field [cobj=" + object.getClass().getName() + ", key=" + key + ", error=" + iae + "]."); } } /** * Get the specified attribute from the configuration object, and serialize it. */ protected void serializeAttribute (String attributeName) { String key = nameToKey(attributeName); Object value; try { value = object.getAttribute(attributeName); } catch (ObjectAccessException oae) { log.warning("Exception getting field [name=" + attributeName + ", error=" + oae + "]."); return; } if (value instanceof Streamable) { serialize(attributeName, key, value); } else { log.info("Unable to flush config obj change [cobj=" + object.getClass().getName() + ", key=" + key + ", type=" + value.getClass().getName() + ", value=" + value + "]."); } } /** * Save the specified object as serialized data associated with the specified key. */ protected void serialize (String name, String key, Object value) { ByteArrayOutInputStream out = new ByteArrayOutInputStream(); ObjectOutputStream oout = createObjectOutputStream(out); try { oout.writeObject(value); oout.flush(); setValue(key, StringUtil.hexlate(out.toByteArray())); } catch (IOException ioe) { log.info("Error serializing value " + value); } } /** * Converts a config object field name (someConfigMember) to a configuration key * (some_config_member). */ protected String nameToKey (String attributeName) { return StringUtil.unStudlyName(attributeName).toLowerCase(); } protected abstract boolean getValue (String field, boolean defval); protected abstract short getValue (String field, short defval); protected abstract int getValue (String field, int defval); protected abstract long getValue (String field, long defval); protected abstract float getValue (String field, float defval); protected abstract String getValue (String field, String defval); protected abstract int[] getValue (String field, int[] defval); protected abstract float[] getValue (String field, float[] defval); protected abstract long[] getValue (String field, long[] defval); protected abstract String[] getValue (String field, String[] defval); protected abstract void setValue (String field, boolean value); protected abstract void setValue (String field, short value); protected abstract void setValue (String field, int value); protected abstract void setValue (String field, long value); protected abstract void setValue (String field, float value); protected abstract void setValue (String field, String value); protected abstract void setValue (String field, int[] value); protected abstract void setValue (String field, float[] value); protected abstract void setValue (String field, long[] value); protected abstract void setValue (String field, String[] value); } /** A mapping from identifying key to config object. */ protected HashMap<String, ObjectRecord> _configs = new HashMap<String, ObjectRecord>(); /** If we need to transition serialized Streamables to a new class format in init.. */ protected boolean _transitioning; }
package com.tinkerpop.gremlin.tinkergraph.structure; import com.tinkerpop.gremlin.process.Traversal; import com.tinkerpop.gremlin.process.graph.step.map.FlatMapStep; import com.tinkerpop.gremlin.process.graph.step.map.MapStep; import com.tinkerpop.gremlin.process.graph.step.sideEffect.StartStep; import com.tinkerpop.gremlin.process.util.DefaultTraversal; import com.tinkerpop.gremlin.structure.Element; import com.tinkerpop.gremlin.structure.Graph; import com.tinkerpop.gremlin.structure.Vertex; public class TinkerFactory { public static TinkerGraph createClassic() { final TinkerGraph g = TinkerGraph.open(); generateClassic(g); return g; } public static void generateClassic(final TinkerGraph g) { final Vertex marko = g.addVertex(Element.ID, 1, "name", "marko", "age", 29); final Vertex vadas = g.addVertex(Element.ID, 2, "name", "vadas", "age", 27); final Vertex lop = g.addVertex(Element.ID, 3, "name", "lop", "lang", "java"); final Vertex josh = g.addVertex(Element.ID, 4, "name", "josh", "age", 32); final Vertex ripple = g.addVertex(Element.ID, 5, "name", "ripple", "lang", "java"); final Vertex peter = g.addVertex(Element.ID, 6, "name", "peter", "age", 35); marko.addEdge("knows", vadas, Element.ID, 7, "weight", 0.5f); marko.addEdge("knows", josh, Element.ID, 8, "weight", 1.0f); marko.addEdge("created", lop, Element.ID, 9, "weight", 0.4f); josh.addEdge("created", ripple, Element.ID, 10, "weight", 1.0f); josh.addEdge("created", lop, Element.ID, 11, "weight", 0.4f); peter.addEdge("created", lop, Element.ID, 12, "weight", 0.2f); } public static TinkerGraph createModern() { final TinkerGraph g = TinkerGraph.open(); generateModern(g); return g; } public static void generateModern(final TinkerGraph g) { final Vertex marko = g.addVertex(Element.ID, 1, Element.LABEL, "person", "name", "marko", "age", 29); final Vertex vadas = g.addVertex(Element.ID, 2, Element.LABEL, "person", "name", "vadas", "age", 27); final Vertex lop = g.addVertex(Element.ID, 3, Element.LABEL, "software", "name", "lop", "lang", "java"); final Vertex josh = g.addVertex(Element.ID, 4, Element.LABEL, "person", "name", "josh", "age", 32); final Vertex ripple = g.addVertex(Element.ID, 5, Element.LABEL, "software", "name", "ripple", "lang", "java"); final Vertex peter = g.addVertex(Element.ID, 6, Element.LABEL, "person", "name", "peter", "age", 35); marko.addEdge("knows", vadas, Element.ID, 7, "weight", 0.5d); marko.addEdge("knows", josh, Element.ID, 8, "weight", 1.0d); marko.addEdge("created", lop, Element.ID, 9, "weight", 0.4d); josh.addEdge("created", ripple, Element.ID, 10, "weight", 1.0d); josh.addEdge("created", lop, Element.ID, 11, "weight", 0.4d); peter.addEdge("created", lop, Element.ID, 12, "weight", 0.2d); } public static TinkerGraph createTheCrew() { final TinkerGraph g = TinkerGraph.open(); generateTheCrew(g); return g; } public static void generateTheCrew(final TinkerGraph g) { final Vertex marko = g.addVertex(Element.ID, 1, Element.LABEL, "person", "name", "marko", Graph.Key.hide("visible"), true); final Vertex stephen = g.addVertex(Element.ID, 7, Element.LABEL, "person", "name", "stephen", Graph.Key.hide("visible"), true); final Vertex matthias = g.addVertex(Element.ID, 8, Element.LABEL, "person", "name", "matthias", Graph.Key.hide("visible"), true); final Vertex daniel = g.addVertex(Element.ID, 9, Element.LABEL, "person", "name", "daniel", Graph.Key.hide("visible"), false); final Vertex gremlin = g.addVertex(Element.ID, 10, Element.LABEL, "software", "name", "gremlin", Graph.Key.hide("visible"), true); final Vertex titan = g.addVertex(Element.ID, 11, Element.LABEL, "software", "name", "titan", Graph.Key.hide("visible"), false); marko.property("location", "san diego", "startTime", 1997, "endTime", 2001); marko.property("location", "santa cruz", "startTime", 2001, "endTime", 2004); marko.property("location", "brussels", "startTime", 2004, "endTime", 2005); marko.property("location", "santa fe", "startTime", 2005); stephen.property("location", "centreville", "startTime", 1990, "endTime", 2000); stephen.property("location", "dulles", "startTime", 2000, "endTime", 2006); stephen.property("location", "purcellville", "startTime", 2006); matthias.property("location", "bremen", "startTime", 2004, "endTime", 2007); matthias.property("location", "baltimore", "startTime", 2007, "endTime", 2011); matthias.property("location", "oakland", "startTime", 2011, "endTime", 2014); matthias.property("location", "seattle", "startTime", 2014); daniel.property("location", "spremberg", "startTime", 1982, "endTime", 2005); daniel.property("location", "kaiserslautern", "startTime", 2005, "endTime", 2009); daniel.property("location", "aachen", "startTime", 2009); marko.addEdge("created", gremlin, "date", 2009); marko.addEdge("created", titan, "date", 2012); marko.addEdge("uses", gremlin, "skill", 4); marko.addEdge("uses", titan, "skill", 2); stephen.addEdge("created", gremlin, "date", 2011); stephen.addEdge("created", titan, "date", 2012); stephen.addEdge("uses", gremlin, "skill", 4); stephen.addEdge("uses", titan, "skill", 3); matthias.addEdge("created", gremlin, "date", 2012); matthias.addEdge("created", titan, "date", 2011); matthias.addEdge("uses", gremlin, "skill", 3); matthias.addEdge("uses", titan, "skill", 5); daniel.addEdge("uses", gremlin, "skill", 5); daniel.addEdge("uses", titan, "skill", 4); titan.addEdge("dependsOn", gremlin, Graph.Key.hide("visible"), false); g.variables().set("creator", "marko"); g.variables().set("lastModified", 2014); g.variables().set("comment", "this graph was created to provide examples and test coverage for tinkerpop3 api advances"); } public interface SocialTraversal<S, E> extends Traversal<S, E> { public default SocialTraversal<S, Vertex> people() { return (SocialTraversal) this.addStep(new StartStep<>(this, this.sideEffects().getGraph().V().has("age"))); } public default SocialTraversal<S, Vertex> people(String name) { return (SocialTraversal) this.addStep(new StartStep<>(this, this.sideEffects().getGraph().V().has("name", name))); } public default SocialTraversal<S, Vertex> knows() { final FlatMapStep<Vertex, Vertex> flatMapStep = new FlatMapStep<>(this); flatMapStep.setFunction(v -> v.get().out("knows")); return (SocialTraversal) this.addStep(flatMapStep); } public default SocialTraversal<S, Vertex> created() { final FlatMapStep<Vertex, Vertex> flatMapStep = new FlatMapStep<>(this); flatMapStep.setFunction(v -> v.get().out("created")); return (SocialTraversal) this.addStep(flatMapStep); } public default SocialTraversal<S, String> name() { MapStep<Vertex, String> mapStep = new MapStep<>(this); mapStep.setFunction(v -> v.get().<String>value("name")); return (SocialTraversal) this.addStep(mapStep); } public static <S> SocialTraversal<S, S> of(final Graph graph) { final SocialTraversal traversal = new DefaultSocialTraversal(); traversal.sideEffects().setGraph(graph); return traversal; } public class DefaultSocialTraversal extends DefaultTraversal implements SocialTraversal { } } }
package edu.uib.info310.search; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Model; import edu.uib.info310.model.Artist; import edu.uib.info310.model.Event; import edu.uib.info310.model.Record; import edu.uib.info310.model.Track; import edu.uib.info310.model.imp.ArtistImpl; import edu.uib.info310.model.imp.EventImpl; import edu.uib.info310.model.imp.RecordImp; import edu.uib.info310.search.builder.OntologyBuilder; @Component public class SearcherImpl implements Searcher { private static final Logger LOGGER = LoggerFactory.getLogger(SearcherImpl.class); private OntologyBuilder builder = new OntologyBuilder(); private Model model; private ArtistImpl artist; public Artist searchArtist(String search_string) throws ArtistNotFoundException { this.artist = new ArtistImpl(); this.model = builder.createArtistOntology(search_string); LOGGER.debug("Size of infered model: " + model.size()); setArtistIdAndName(); setSimilarArtist(); setArtistEvents(); setArtistDiscography(); setArtistInfo(); return this.artist; } private void setArtistIdAndName() { String getIdStr = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns QueryExecution execution = QueryExecutionFactory.create(getIdStr, model); ResultSet similarResults = execution.execSelect(); if(similarResults.hasNext()){ QuerySolution solution = similarResults.next(); this.artist.setId(solution.get("id").toString()); this.artist.setName(solution.get("name").toString()); } LOGGER.debug("Artist id set to " + this.artist.getId()); } private void setArtistDiscography() { List<Record> discog = new LinkedList<Record>(); Map<String,Record> uniqueRecord = new HashMap<String, Record>(); String getDiscographyStr = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "PREFIX mo: <http://purl.org/ontology/mo/> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema "PREFIX dc: <http://purl.org/dc/terms/> " + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns "SELECT DISTINCT " + " ?artistId ?albumId ?release ?title ?image ?year ?labelId ?labelName ?track ?artist "+ " WHERE { <" + // "?artistId foaf:name \"" + artist.getName() + "\". "+ this.artist.getId()+ "> foaf:made ?albumId."+ "?albumId dc:title ?title." + "OPTIONAL {?albumId mo:publisher ?labelId. } "+ "OPTIONAL {?albumId dc:issued ?year. }" + "OPTIONAL {?albumId foaf:depiction ?image. }" + "}"; LOGGER.debug("Search for albums for artist with name: " + this.artist.getName() + ", with query:" + getDiscographyStr); QueryExecution execution = QueryExecutionFactory.create(getDiscographyStr, model); ResultSet albums = execution.execSelect(); LOGGER.debug("Found records? " + albums.hasNext()); while(albums.hasNext()){ RecordImp recordResult = new RecordImp(); QuerySolution queryAlbum = albums.next(); recordResult.setId(queryAlbum.get("albumId").toString()); recordResult.setName(queryAlbum.get("title").toString()); if(queryAlbum.get("image") != null) { recordResult.setImage(queryAlbum.get("image").toString()); } if(queryAlbum.get("year") != null) { recordResult.setYear(queryAlbum.get("year").toString()); } if(recordResult.getImage() != null){ uniqueRecord.put(recordResult.getName(), recordResult); } } for(Record record : uniqueRecord.values()){ discog.add(record); } this.artist.setDiscography(discog); LOGGER.debug("Found "+ artist.getDiscography().size() +" artist records"); } private void setSimilarArtist() { List<Artist> similar = new LinkedList<Artist>(); String similarStr = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns "PREFIX mo:<http://purl.org/ontology/mo/> " + "PREFIX foaf:<http://xmlns.com/foaf/0.1/> " + "SELECT ?name ?id ?image " + " WHERE { <" + this.artist.getId() + "> mo:similar-to ?id . " + "?id foaf:name ?name; " + " mo:image ?image } "; QueryExecution execution = QueryExecutionFactory.create(similarStr, model); ResultSet similarResults = execution.execSelect(); while(similarResults.hasNext()){ ArtistImpl similarArtist = new ArtistImpl(); QuerySolution queryArtist = similarResults.next(); similarArtist.setName(queryArtist.get("name").toString()); similarArtist.setId(queryArtist.get("id").toString()); similarArtist.setImage(queryArtist.get("image").toString()); similar.add(similarArtist); } artist.setSimilar(similar); LOGGER.debug("Found " + this.artist.getSimilar().size() +" similar artists"); } private void setArtistEvents(){ List<Event> events = new LinkedList<Event>(); String getArtistEventsStr = " PREFIX foaf:<http://xmlns.com/foaf/0.1/> PREFIX event: <http://purl.org/NET/c4dm/event.owl "SELECT ?venueId ?venueName ?date ?lng ?lat ?location " + " WHERE {?preformance foaf:hasAgent <" + this.artist.getId() + ">; event:place ?venueId; event:time ?date. ?venueId v:organisation-name ?venueName; geo:lat ?lat; geo:long ?lng; v:locality ?location}"; QueryExecution execution = QueryExecutionFactory.create(getArtistEventsStr, model); ResultSet eventResults = execution.execSelect(); while(eventResults.hasNext()){ EventImpl event = new EventImpl(); QuerySolution queryEvent = eventResults.next(); event.setId(queryEvent.get("venueId").toString()); event.setVenue(queryEvent.get("venueName").toString()); event.setLat(queryEvent.get("lat").toString()); event.setLng(queryEvent.get("lng").toString()); event.setDate(queryEvent.get("date").toString()); event.setLocation(queryEvent.get("location").toString()); events.add(event); } this.artist.setEvents(events); LOGGER.debug("Found "+ artist.getEvents().size() +" artist events"); } private void setArtistInfo() { String id = " <" + artist.getId() + "> "; String getArtistInfoStr = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "PREFIX mo: <http://purl.org/ontology/mo/> " + "PREFIX dbpedia: <http://dbpedia.org/property/> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema "PREFIX owl: <http://www.w3.org/2002/07/owl "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema "PREFIX dbont: <http://dbpedia.org/ontology/> " + "SELECT DISTINCT * WHERE {" + // id + "foaf:name ?name" + "OPTIONAL { ?artist1 foaf:name ?name; mo:image ?image}" + "OPTIONAL { ?bbcartist foaf:name ?name; mo:fanpage ?fanpage.} " + "OPTIONAL { ?bbcartist mo:imdb ?imdb. } " + "OPTIONAL { ?bbcartist mo:myspace ?myspace. } " + "OPTIONAL { ?bbcartist foaf:homepage ?homepage. } " + "OPTIONAL { ?bbcartist rdfs:comment ?shortDesc. Filter (lang(?shortDesc) = '').} " + "OPTIONAL { ?dbartist dbpedia:shortDescription ?shortDescEn .} " + "OPTIONAL { ?dbartist dbpedia:abstract ?bio. Filter (lang(?bio) = 'en').} " + "OPTIONAL { ?dbartist dbont:abstract ?bio. Filter (lang(?bio) = 'en').} " + "OPTIONAL { ?dbartist dbont:birthname ?birthname} " + "OPTIONAL { ?dbartist dbont:hometown ?origin. } " + "OPTIONAL { ?dbartist dbpedia:origin ?origin. } " + "OPTIONAL { ?dbartist dbpedia:yearsActive ?yearsactive. } " + "OPTIONAL { ?dbartist dbpedia:dateOfBirth ?birthdate. } " + // "OPTIONAL { ?artist15 foaf:name ?name; foaf:page ?wikipedia. } " + "OPTIONAL { ?bbcartist foaf:name ?name; foaf:page ?bbcpage. }}"; QueryExecution ex = QueryExecutionFactory.create(getArtistInfoStr, model); ResultSet results = ex.execSelect(); HashMap<String,String> metaMap = new HashMap<String,String>(); List<String> fanpages = new LinkedList<String>(); while(results.hasNext()) { // TODO: optimize (e.g storing in variables instead of performing query.get several times?) QuerySolution query = results.next(); if(query.get("image") != null){ artist.setImage(query.get("image").toString()); } if(query.get("fanpage") != null){ String fanpage = "<a href=\"" + query.get("fanpage").toString() + "\">" + query.get("fanpage").toString() + "</a>"; if(!fanpages.contains(fanpage)) { fanpages.add(fanpage); } } if(query.get("bio") != null) { artist.setBio(query.get("bio").toString()); } if(query.get("wikipedia") != null) { metaMap.put("Wikipedia", ("<a href=\"" + query.get("wikipedia").toString() + "\">" + query.get("wikipedia").toString() + "</a>")); } if(query.get("bbcpage") != null) { metaMap.put("BBC Music", ("<a href=\"" + query.get("bbcpage").toString() + "\">" + query.get("bbcpage").toString() + "</a>")); } if(query.get("birthdate") != null) { metaMap.put("Born", (query.get("birthdate").toString())); } if(query.get("homepage") != null) { metaMap.put("Homepage", ("<a href=\"" + query.get("homepage").toString() + "\">" + query.get("homepage").toString() + "</a>")); } if(query.get("imdb") != null) { metaMap.put("IMDB", ("<a href=\"" + query.get("imdb").toString() + "\">" + query.get("imdb").toString() + "</a>")); } if(query.get("myspace") != null) { metaMap.put("MySpace", ("<a href=\"" + query.get("myspace").toString() + "\">" + query.get("myspace").toString() + "</a>")); } if(query.get("shortDesc") != null) { artist.setShortDescription(query.get("shortDesc").toString()); }else{ if(query.get("shortDescEn") != null){ artist.setShortDescription(query.get("shortDescEn").toString()); } } if(query.get("birthname") != null) { metaMap.put("Name", (query.get("birthname").toString())); } if(query.get("origin") != null) { metaMap.put("From", (query.get("origin").toString())); } if(query.get("yearsactive") != null) { metaMap.put("Active", (query.get("yearsactive").toString())); } } if(!fanpages.isEmpty()) { metaMap.put("Fanpages", fanpages.toString()); } artist.setMeta(metaMap); LOGGER.debug("Found " + artist.getMeta().size() + " fun facts."); } public Event searchEvent(String search_string) { // TODO Auto-generated method stub return null; } public Record searchRecord(String search_string) { // TODO Auto-generated method stub return null; } public Track searchTrack(String search_string) { // TODO Auto-generated method stub return null; } public static void main(String[] args) throws ArtistNotFoundException { Searcher searcher = new SearcherImpl(); searcher.searchArtist("Guns N Roses"); } }
package net.sf.picard.sam; import net.sf.picard.PicardException; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.cmdline.Usage; import net.sf.picard.reference.ReferenceSequence; import net.sf.picard.reference.ReferenceSequenceFile; import net.sf.picard.reference.ReferenceSequenceFileFactory; import net.sf.samtools.*; import net.sf.samtools.util.StringUtil; import java.io.File; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Create a SAM/BAM file from a fasta containing reference sequence. The output SAM file contains a header but no * SAMRecords, and the header contains only sequence records. */ public class CreateSequenceDictionary extends CommandLineProgram { // The following attributes define the command-line arguments @Usage public String USAGE = "Usage: " + getClass().getName() + " [options]\n\n" + "Read fasta or fasta.gz containing reference sequences, and write as a SAM or BAM file with only sequence dictionary.\n"; @Option(doc = "Input reference fasta or fasta.gz", shortName = StandardOptionDefinitions.REFERENCE_SHORT_NAME) public File REFERENCE; @Option(doc = "Output SAM or BAM file containing only the sequence dictionary", shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME) public File OUTPUT; @Option(doc = "Put into AS field of sequence dictionary entry if supplied", optional = true) public String GENOME_ASSEMBLY; @Option(doc = "Put into UR field of sequence dictionary entry. If not supplied, input reference file is used", optional = true) public String URI; @Option(doc = "Put into SP field of sequence dictionary entry", optional = true) public String SPECIES; @Option(doc = "Make sequence name the first word from the > line in the fasta file. " + "By default the entire contents of the > line is used, excluding leading and trailing whitespace.") public boolean TRUNCATE_NAMES_AT_WHITESPACE = true; @Option(doc = "Stop after writing this many sequences. For testing.") public int NUM_SEQUENCES = Integer.MAX_VALUE; private final MessageDigest md5; public CreateSequenceDictionary() { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new PicardException("MD5 algorithm not found", e); } } public static void main(final String[] argv) { System.exit(new CreateSequenceDictionary().instanceMain(argv)); } /** * Use reference filename to create URI to go into header if URI was not passed on cmd line. */ protected String[] customCommandLineValidation() { if (URI == null) { URI = "file:" + REFERENCE.getAbsolutePath(); } return null; } /** * Do the work after command line has been parsed. * RuntimeException may be thrown by this method, and are reported appropriately. * * @return program exit status. */ protected int doWork() { if (OUTPUT.exists()) { throw new PicardException(OUTPUT.getAbsolutePath() + " already exists. Delete this file and try again, or specify a different output file."); } final SAMSequenceDictionary sequences = makeSequenceDictionary(REFERENCE); final SAMFileHeader samHeader = new SAMFileHeader(); samHeader.setSequenceDictionary(sequences); final SAMFileWriter samWriter = new SAMFileWriterFactory().makeSAMWriter(samHeader, false, OUTPUT); samWriter.close(); return 0; } /** * Read all the sequences from the given reference file, and convert into SAMSequenceRecords * @param referenceFile fasta or fasta.gz * @return SAMSequenceRecords containing info from the fasta, plus from cmd-line arguments. */ SAMSequenceDictionary makeSequenceDictionary(final File referenceFile) { final ReferenceSequenceFile refSeqFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(referenceFile, TRUNCATE_NAMES_AT_WHITESPACE); ReferenceSequence refSeq; final List<SAMSequenceRecord> ret = new ArrayList<SAMSequenceRecord>(); final Set<String> sequenceNames = new HashSet<String>(); for (int numSequences = 0; numSequences < NUM_SEQUENCES && (refSeq = refSeqFile.nextSequence()) != null; ++numSequences) { if (sequenceNames.contains(refSeq.getName())) { throw new PicardException("Sequence name appears more than once in reference: " + refSeq.getName()); } sequenceNames.add(refSeq.getName()); ret.add(makeSequenceRecord(refSeq)); } return new SAMSequenceDictionary(ret); } /** * Create one SAMSequenceRecord from a single fasta sequence */ private SAMSequenceRecord makeSequenceRecord(final ReferenceSequence refSeq) { final SAMSequenceRecord ret = new SAMSequenceRecord(refSeq.getName(), refSeq.length()); // Compute MD5 of upcased bases final byte[] bases = refSeq.getBases(); for (int i = 0; i < bases.length; ++i) { bases[i] = StringUtil.toUpperCase(bases[i]); } ret.setAttribute(SAMSequenceRecord.MD5_TAG, md5Hash(bases)); if (GENOME_ASSEMBLY != null) { ret.setAttribute(SAMSequenceRecord.ASSEMBLY_TAG, GENOME_ASSEMBLY); } ret.setAttribute(SAMSequenceRecord.URI_TAG, URI); if (SPECIES != null) { ret.setAttribute(SAMSequenceRecord.SPECIES_TAG, SPECIES); } return ret; } private String md5Hash(final byte[] bytes) { md5.reset(); md5.update(bytes); String s = new BigInteger(1, md5.digest()).toString(16); if (s.length() != 32) { final String zeros = "00000000000000000000000000000000"; s = zeros.substring(0, 32 - s.length()) + s; } return s; } }
package org.mwc.cmap.core.DataTypes.TrackData; import Debrief.Tools.Tote.WatchableList; /** * @author ian.mayo * */ public interface TrackDataProvider { public static interface TrackDataListener { /** find out that the primary has changed * * @param primary the primary track */ public void primaryUpdated(WatchableList primary); /** find out that the secondaries have changed * * @param secondaries list of secondary tracks */ public void secondariesUpdated(WatchableList[] secondaries); } /** declare that we want to be informed about changes * in selected tracks */ public void addTrackDataListener(TrackDataListener listener); /** forget that somebody wants to know about track changes * */ public void removeTrackDataListener(TrackDataListener listener); /** find out what the primary track is * */ public WatchableList getPrimaryTrack(); /** find out what the secondary track is * */ public WatchableList[] getSecondaryTracks(); }
/** * * Resource.java * @author echeng (table2type.pl) * * the Resource * * */ package edu.yu.einstein.wasp.model; import java.util.Date; import java.util.List; import javax.persistence.*; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; import org.hibernate.validator.constraints.*; import org.codehaus.jackson.annotate.JsonIgnore; @Entity @Audited @Table(name="resource") public class Resource extends WaspModel { /** * resourceId * */ @Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected int resourceId; /** * setResourceId(int resourceId) * * @param resourceId * */ public void setResourceId (int resourceId) { this.resourceId = resourceId; } /** * getResourceId() * * @return resourceId * */ public int getResourceId () { return this.resourceId; } /** * platform * */ @Column(name="platform") protected String platform; /** * setPlatform(String platform) * * @param platform * */ public void setPlatform (String platform) { this.platform = platform; } /** * getPlatform() * * @return platform * */ public String getPlatform () { return this.platform; } /** * iName * */ @Column(name="iname") @NotEmpty protected String iName; /** * setIName(String iName) * * @param iName * */ public void setIName (String iName) { this.iName = iName; } /** * getIName() * * @return iName * */ public String getIName () { return this.iName; } /** * name * */ @Column(name="name") @NotEmpty protected String name; /** * setName(String name) * * @param name * */ public void setName (String name) { this.name = name; } /** * getName() * * @return name * */ public String getName () { return this.name; } /** * typeResourceId * */ @Column(name="typeresourceid") @Range(min=1) protected int typeResourceId; /** * setTypeResourceId(int typeResourceId) * * @param typeResourceId * */ public void setTypeResourceId (int typeResourceId) { this.typeResourceId = typeResourceId; } /** * getTypeResourceId() * * @return typeResourceId * */ public int getTypeResourceId () { return this.typeResourceId; } /** * isActive * */ @Column(name="isactive") protected int isActive; /** * setIsActive(int isActive) * * @param isActive * */ public void setIsActive (int isActive) { this.isActive = isActive; } /** * getIsActive() * * @return isActive * */ public int getIsActive () { return this.isActive; } /** * lastUpdTs * */ @Column(name="lastupdts") protected Date lastUpdTs; /** * setLastUpdTs(Date lastUpdTs) * * @param lastUpdTs * */ public void setLastUpdTs (Date lastUpdTs) { this.lastUpdTs = lastUpdTs; } /** * getLastUpdTs() * * @return lastUpdTs * */ public Date getLastUpdTs () { return this.lastUpdTs; } /** * lastUpdUser * */ @Column(name="lastupduser") protected int lastUpdUser; /** * setLastUpdUser(int lastUpdUser) * * @param lastUpdUser * */ public void setLastUpdUser (int lastUpdUser) { this.lastUpdUser = lastUpdUser; } /** * getLastUpdUser() * * @return lastUpdUser * */ public int getLastUpdUser () { return this.lastUpdUser; } /** * typeResource * */ @NotAudited @ManyToOne @JoinColumn(name="typeresourceid", insertable=false, updatable=false) protected TypeResource typeResource; /** * setTypeResource (TypeResource typeResource) * * @param typeResource * */ public void setTypeResource (TypeResource typeResource) { this.typeResource = typeResource; this.typeResourceId = typeResource.typeResourceId; } /** * getTypeResource () * * @return typeResource * */ public TypeResource getTypeResource () { return this.typeResource; } /** * resourceMeta * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<ResourceMeta> resourceMeta; /** * getResourceMeta() * * @return resourceMeta * */ public List<ResourceMeta> getResourceMeta() { return this.resourceMeta; } /** * setResourceMeta * * @param resourceMeta * */ public void setResourceMeta (List<ResourceMeta> resourceMeta) { this.resourceMeta = resourceMeta; } /** * jobResource * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<JobResource> jobResource; /** * getJobResource() * * @return jobResource * */ public List<JobResource> getJobResource() { return this.jobResource; } /** * setJobResource * * @param jobResource * */ public void setJobResource (List<JobResource> jobResource) { this.jobResource = jobResource; } /** * jobDraftresource * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<JobDraftresource> jobDraftresource; /** * getJobDraftresource() * * @return jobDraftresource * */ public List<JobDraftresource> getJobDraftresource() { return this.jobDraftresource; } /** * setJobDraftresource * * @param jobDraftresource * */ public void setJobDraftresource (List<JobDraftresource> jobDraftresource) { this.jobDraftresource = jobDraftresource; } /** * resourceBarcode * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<ResourceBarcode> resourceBarcode; /** * getResourceBarcode() * * @return resourceBarcode * */ public List<ResourceBarcode> getResourceBarcode() { return this.resourceBarcode; } /** * setResourceBarcode * * @param resourceBarcode * */ public void setResourceBarcode (List<ResourceBarcode> resourceBarcode) { this.resourceBarcode = resourceBarcode; } /** * workflowresource * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<Workflowresource> workflowresource; /** * getWorkflowresource() * * @return workflowresource * */ public List<Workflowresource> getWorkflowresource() { return this.workflowresource; } /** * setWorkflowresource * * @param workflowresource * */ public void setWorkflowresource (List<Workflowresource> workflowresource) { this.workflowresource = workflowresource; } /** * resourceLane * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<ResourceLane> resourceLane; /** * getResourceLane() * * @return resourceLane * */ public List<ResourceLane> getResourceLane() { return this.resourceLane; } /** * setResourceLane * * @param resourceLane * */ public void setResourceLane (List<ResourceLane> resourceLane) { this.resourceLane = resourceLane; } /** * run * */ @NotAudited @OneToMany @JoinColumn(name="resourceid", insertable=false, updatable=false) protected List<Run> run; /** * getRun() * * @return run * */ public List<Run> getRun() { return this.run; } /** * setRun * * @param run * */ public void setRun (List<Run> run) { this.run = run; } }
package org.apache.commons.beanutils; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections.FastHashMap; public class PropertyUtils { /** * The delimiter that preceeds the zero-relative subscript for an * indexed reference. */ public static final char INDEXED_DELIM = '['; /** * The delimiter that follows the zero-relative subscript for an * indexed reference. */ public static final char INDEXED_DELIM2 = ']'; /** * The delimiter that preceeds the key of a mapped property. */ public static final char MAPPED_DELIM = '('; /** * The delimiter that follows the key of a mapped property. */ public static final char MAPPED_DELIM2 = ')'; /** * The delimiter that separates the components of a nested reference. */ public static final char NESTED_DELIM = '.'; /** * The debugging detail level for this component. */ private static int debug = 0; public static int getDebug() { return (debug); } public static void setDebug(int newDebug) { debug = newDebug; } /** * The cache of PropertyDescriptor arrays for beans we have already * introspected, keyed by the java.lang.Class of this object. */ private static FastHashMap descriptorsCache = null; private static FastHashMap mappedDescriptorsCache = null; static { descriptorsCache = new FastHashMap(); descriptorsCache.setFast(true); mappedDescriptorsCache = new FastHashMap(); mappedDescriptorsCache.setFast(true); } /** * Clear any cached property descriptors information for all classes * loaded by any class loaders. This is useful in cases where class * loaders are thrown away to implement class reloading. */ public static void clearDescriptors() { descriptorsCache.clear(); mappedDescriptorsCache.clear(); Introspector.flushCaches(); } public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (dest == null) throw new IllegalArgumentException ("No destination bean specified"); if (orig == null) throw new IllegalArgumentException("No origin bean specified"); PropertyDescriptor origDescriptors[] = getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (getPropertyDescriptor(dest, name) != null) { Object value = getSimpleProperty(orig, name); try { setSimpleProperty(dest, name, value); } catch (NoSuchMethodException e) { ; // Skip non-matching property } } } } // FIXME - does not account for mapped properties public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); PropertyDescriptor descriptors[] = PropertyUtils.getPropertyDescriptors(bean); Map description = new HashMap(descriptors.length); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (descriptors[i].getReadMethod() != null) description.put(name, getProperty(bean, name)); } return (description); } public static Object getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Identify the index of the requested individual property int delim = name.indexOf(INDEXED_DELIM); int delim2 = name.indexOf(INDEXED_DELIM2); if ((delim < 0) || (delim2 <= delim)) throw new IllegalArgumentException("Invalid indexed property '" + name + "'"); int index = -1; try { String subscript = name.substring(delim + 1, delim2); index = Integer.parseInt(subscript); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid indexed property '" + name + "'"); } name = name.substring(0, delim); // Request the specified indexed property value return (getIndexedProperty(bean, name, index)); } public static Object getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) throw new NoSuchMethodException("Unknown property '" + name + "'"); // Call the indexed getter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method readMethod = ((IndexedPropertyDescriptor) descriptor). getIndexedReadMethod(); if (readMethod != null) { Object subscript[] = new Object[1]; subscript[0] = new Integer(index); try { return (readMethod.invoke(bean, subscript)); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof ArrayIndexOutOfBoundsException) throw (ArrayIndexOutOfBoundsException) e.getTargetException(); else throw e; } } } // Otherwise, the underlying property must be an array Method readMethod = getReadMethod(descriptor); if (readMethod == null) throw new NoSuchMethodException("Property '" + name + "' has no getter method"); // Call the property getter and return the value Object value = readMethod.invoke(bean, new Object[0]); if (!value.getClass().isArray()) throw new IllegalArgumentException("Property '" + name + "' is not indexed"); return (Array.get(value, index)); } public static Object getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Identify the index of the requested individual property int delim = name.indexOf(MAPPED_DELIM); int delim2 = name.indexOf(MAPPED_DELIM2); if ((delim < 0) || (delim2 <= delim)) throw new IllegalArgumentException ("Invalid mapped property '" + name + "'"); // Isolate the name and the key String key = name.substring(delim + 1, delim2); name = name.substring(0, delim); // Request the specified indexed property value return (getMappedProperty(bean, name, key)); } public static Object getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); if (key == null) throw new IllegalArgumentException("No key specified"); Object result = null; // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) throw new NoSuchMethodException("Unknown property '" + name + "'"); if (descriptor instanceof MappedPropertyDescriptor) { // Call the keyed getter method if there is one Method readMethod = ((MappedPropertyDescriptor)descriptor). getMappedReadMethod(); if (readMethod != null) { Object keyArray[] = new Object[1]; keyArray[0] = key; result = readMethod.invoke(bean, keyArray); } else { throw new NoSuchMethodException("Property '" + name + "' has no mapped getter method"); } } return result; } /** * Return the mapped property descriptors for this bean. * * @param bean Bean to be introspected */ public static FastHashMap getMappedPropertyDescriptors(Object bean) { if (bean == null) return null; // Look up any cached descriptors for this bean class Class beanClass = bean.getClass(); return (FastHashMap) mappedDescriptorsCache.get(beanClass); } public static Object getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); int indexOfINDEXED_DELIM = -1; int indexOfMAPPED_DELIM = -1; while (true) { int period = name.indexOf(NESTED_DELIM); if (period < 0) break; String next = name.substring(0, period); indexOfINDEXED_DELIM = next.indexOf(INDEXED_DELIM); indexOfMAPPED_DELIM = next.indexOf(MAPPED_DELIM); if (indexOfMAPPED_DELIM >= 0 && (indexOfINDEXED_DELIM <0 || indexOfMAPPED_DELIM < indexOfINDEXED_DELIM)) bean = getMappedProperty(bean, next); else { if (indexOfINDEXED_DELIM >= 0) bean = getIndexedProperty(bean, next); else bean = getSimpleProperty(bean, next); } if (bean == null) throw new IllegalArgumentException ("Null property value for '" + name.substring(0, period) + "'"); name = name.substring(period + 1); } /* if (name.indexOf(INDEXED_DELIM) >= 0) return (getIndexedProperty(bean, name)); else return (getSimpleProperty(bean, name)); */ indexOfINDEXED_DELIM = name.indexOf(INDEXED_DELIM); indexOfMAPPED_DELIM = name.indexOf(MAPPED_DELIM); if (indexOfMAPPED_DELIM >= 0 && (indexOfINDEXED_DELIM <0 || indexOfMAPPED_DELIM < indexOfINDEXED_DELIM)) bean = getMappedProperty(bean, name); else { if (indexOfINDEXED_DELIM >= 0) bean = getIndexedProperty(bean, name); else bean = getSimpleProperty(bean, name); } return bean; } public static Object getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } public static PropertyDescriptor getPropertyDescriptor(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Resolve nested references while (true) { int period = name.indexOf(NESTED_DELIM); if (period < 0) break; String next = name.substring(0, period); int indexOfINDEXED_DELIM = next.indexOf(INDEXED_DELIM); int indexOfMAPPED_DELIM = next.indexOf(MAPPED_DELIM); if (indexOfMAPPED_DELIM >= 0 && (indexOfINDEXED_DELIM <0 || indexOfMAPPED_DELIM < indexOfINDEXED_DELIM)) bean = getMappedProperty(bean, next); else { if (indexOfINDEXED_DELIM >= 0) bean = getIndexedProperty(bean, next); else bean = getSimpleProperty(bean, next); } if (bean == null) throw new IllegalArgumentException ("Null property value for '" + name.substring(0, period) + "'"); name = name.substring(period + 1); } // Remove any subscript from the final name value int left = name.indexOf(INDEXED_DELIM); if (left >= 0) name = name.substring(0, left); left = name.indexOf(MAPPED_DELIM); if (left >= 0) name = name.substring(0, left); // Look up and return this property from our cache // creating and adding it to the cache if not found. if ((bean == null) || (name == null)) return (null); PropertyDescriptor descriptors[] = getPropertyDescriptors(bean); if (descriptors != null) { for (int i = 0; i < descriptors.length; i++) { if (name.equals(descriptors[i].getName())) return (descriptors[i]); } } PropertyDescriptor result = null; FastHashMap mappedDescriptors = getMappedPropertyDescriptors(bean); if (mappedDescriptors != null) { result = (PropertyDescriptor) mappedDescriptors.get(name); } if (result==null) { // not found, try to create it try { result = new MappedPropertyDescriptor(name, bean.getClass()); } catch (IntrospectionException ie) { } } if (result!=null) { if (mappedDescriptors==null) { mappedDescriptors = new FastHashMap(); mappedDescriptors.setFast(true); mappedDescriptorsCache.put (bean.getClass(), mappedDescriptors); } mappedDescriptors.put(name, result); } return result; } public static PropertyDescriptor[] getPropertyDescriptors(Object bean) { if (bean == null) throw new IllegalArgumentException("No bean specified"); // Look up any cached descriptors for this bean class Class beanClass = bean.getClass(); PropertyDescriptor descriptors[] = null; descriptors = (PropertyDescriptor[]) descriptorsCache.get(beanClass); if (descriptors != null) return (descriptors); // Introspect the bean and cache the generated descriptors BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(bean.getClass()); } catch (IntrospectionException e) { return (new PropertyDescriptor[0]); } descriptors = beanInfo.getPropertyDescriptors(); if (descriptors == null) descriptors = new PropertyDescriptor[0]; descriptorsCache.put(beanClass, descriptors); return (descriptors); } public static Class getPropertyEditorClass(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor != null) return (descriptor.getPropertyEditorClass()); else return (null); } public static Class getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) return (null); else if (descriptor instanceof IndexedPropertyDescriptor) return (((IndexedPropertyDescriptor) descriptor). getIndexedPropertyType()); else return (descriptor.getPropertyType()); } /** * Return an accessible property getter method for this property, * if there is one; otherwise return <code>null</code>. * * @param descriptor Property descriptor to return a getter for */ public static Method getReadMethod(PropertyDescriptor descriptor) { return (getAccessibleMethod(descriptor.getReadMethod())); } public static Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Validate the syntax of the property name if (name.indexOf(NESTED_DELIM) >= 0) throw new IllegalArgumentException ("Nested property names are not allowed"); else if (name.indexOf(INDEXED_DELIM) >= 0) throw new IllegalArgumentException ("Indexed property names are not allowed"); else if (name.indexOf(MAPPED_DELIM) >= 0) throw new IllegalArgumentException ("Mapped property names are not allowed"); // Retrieve the property getter method for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) throw new NoSuchMethodException("Unknown property '" + name + "'"); Method readMethod = getReadMethod(descriptor); if (readMethod == null) throw new NoSuchMethodException("Property '" + name + "' has no getter method"); // Call the property getter and return the value Object value = readMethod.invoke(bean, new Object[0]); return (value); } /** * Return an accessible property setter method for this property, * if there is one; otherwise return <code>null</code>. * * @param descriptor Property descriptor to return a setter for */ public static Method getWriteMethod(PropertyDescriptor descriptor) { return (getAccessibleMethod(descriptor.getWriteMethod())); } public static void setIndexedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Identify the index of the requested individual property int delim = name.indexOf(INDEXED_DELIM); int delim2 = name.indexOf(INDEXED_DELIM2); if ((delim < 0) || (delim2 <= delim)) throw new IllegalArgumentException("Invalid indexed property '" + name + "'"); int index = -1; try { String subscript = name.substring(delim + 1, delim2); index = Integer.parseInt(subscript); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid indexed property '" + name + "'"); } name = name.substring(0, delim); // Set the specified indexed property value setIndexedProperty(bean, name, index, value); } public static void setIndexedProperty(Object bean, String name, int index, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) throw new NoSuchMethodException("Unknown property '" + name + "'"); // Call the indexed setter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method writeMethod = ((IndexedPropertyDescriptor) descriptor). getIndexedWriteMethod(); if (writeMethod != null) { Object subscript[] = new Object[2]; subscript[0] = new Integer(index); subscript[1] = value; try { writeMethod.invoke(bean, subscript); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof ArrayIndexOutOfBoundsException) throw (ArrayIndexOutOfBoundsException) e.getTargetException(); else throw e; } return; } } // Otherwise, the underlying property must be an array Method readMethod = descriptor.getReadMethod(); if (readMethod == null) throw new NoSuchMethodException("Property '" + name + "' has no getter method"); // Call the property getter to get the array Object array = readMethod.invoke(bean, new Object[0]); if (!array.getClass().isArray()) throw new IllegalArgumentException("Property '" + name + "' is not indexed"); // Modify the specified value Array.set(array, index, value); } public static void setMappedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Identify the index of the requested individual property int delim = name.indexOf(MAPPED_DELIM); int delim2 = name.indexOf(MAPPED_DELIM2); if ((delim < 0) || (delim2 <= delim)) throw new IllegalArgumentException ("Invalid mapped property '" + name + "'"); // Isolate the name and the key String key = name.substring(delim + 1, delim2); name = name.substring(0, delim); // Request the specified indexed property value setMappedProperty(bean, name, key, value); } public static void setMappedProperty(Object bean, String name, String key, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); if (key == null) throw new IllegalArgumentException("No key specified"); // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) throw new NoSuchMethodException("Unknown property '" + name + "'"); if (descriptor instanceof MappedPropertyDescriptor) { // Call the keyed setter method if there is one Method mappedWriteMethod = ((MappedPropertyDescriptor)descriptor). getMappedWriteMethod(); if (mappedWriteMethod != null) { Object params[] = new Object[2]; params[0] = key; params[1] = value; mappedWriteMethod.invoke(bean, params); } else { throw new NoSuchMethodException ("Property '" + name + "' has no mapped setter method"); } } } public static void setNestedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); int indexOfINDEXED_DELIM = -1; int indexOfMAPPED_DELIM = -1; while (true) { int delim = name.indexOf(NESTED_DELIM); if (delim < 0) break; String next = name.substring(0, delim); indexOfINDEXED_DELIM = next.indexOf(INDEXED_DELIM); indexOfMAPPED_DELIM = next.indexOf(MAPPED_DELIM); if (indexOfMAPPED_DELIM >= 0 && (indexOfINDEXED_DELIM <0 || indexOfMAPPED_DELIM < indexOfINDEXED_DELIM)) bean = getMappedProperty(bean, next); else { if (indexOfINDEXED_DELIM >= 0) bean = getIndexedProperty(bean, next); else bean = getSimpleProperty(bean, next); } if (bean == null) throw new IllegalArgumentException ("Null property value for '" + name.substring(0, delim) + "'"); name = name.substring(delim + 1); } /* if (name.indexOf(INDEXED_DELIM) >= 0) setIndexedProperty(bean, name, value); else setSimpleProperty(bean, name, value); */ indexOfINDEXED_DELIM = name.indexOf(INDEXED_DELIM); indexOfMAPPED_DELIM = name.indexOf(MAPPED_DELIM); if (indexOfMAPPED_DELIM >= 0 && (indexOfINDEXED_DELIM <0 || indexOfMAPPED_DELIM < indexOfINDEXED_DELIM)) setMappedProperty(bean, name, value); else { if (indexOfINDEXED_DELIM >= 0) setIndexedProperty(bean, name, value); else setSimpleProperty(bean, name, value); } } public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { setNestedProperty(bean, name, value); } public static void setSimpleProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) throw new IllegalArgumentException("No bean specified"); if (name == null) throw new IllegalArgumentException("No name specified"); // Validate the syntax of the property name if (name.indexOf(NESTED_DELIM) >= 0) throw new IllegalArgumentException ("Nested property names are not allowed"); else if (name.indexOf(INDEXED_DELIM) >= 0) throw new IllegalArgumentException ("Indexed property names are not allowed"); else if (name.indexOf(MAPPED_DELIM) >= 0) throw new IllegalArgumentException ("Mapped property names are not allowed"); // Retrieve the property setter method for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) throw new NoSuchMethodException("Unknown property '" + name + "'"); Method writeMethod = getWriteMethod(descriptor); if (writeMethod == null) throw new NoSuchMethodException("Property '" + name + "' has no setter method"); // Call the property setter method Object values[] = new Object[1]; values[0] = value; writeMethod.invoke(bean, values); } /** * Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified Method. If no such method * can be found, return <code>null</code>. * * @param method The method that we wish to call */ private static Method getAccessibleMethod(Method method) { // Make sure we have a method to check if (method == null) { return (null); } // If the requested method is not public we cannot call it if (!Modifier.isPublic(method.getModifiers())) { return (null); } // If the declaring class is public, we are done Class clazz = method.getDeclaringClass(); if (Modifier.isPublic(clazz.getModifiers())) { return (method); } // Check the implemented interfaces and subinterfaces String methodName = method.getName(); Class[] parameterTypes = method.getParameterTypes(); method = getAccessibleMethodFromInterfaceNest(clazz, method.getName(), method.getParameterTypes()); return (method); /* Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { // Is this interface public? if (!Modifier.isPublic(interfaces[i].getModifiers())) { continue; } // Does the method exist on this interface? try { method = interfaces[i].getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { continue; } // We have found what we are looking for return (method); } // We are out of luck return (null); */ } /** * Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified method, by scanning through * all implemented interfaces and subinterfaces. If no such Method * can be found, return <code>null</code>. * * @param clazz Parent class for the interfaces to be checked * @param methodName Method name of the method we wish to call * @param parameterTypes The parameter type signatures */ private static Method getAccessibleMethodFromInterfaceNest (Class clazz, String methodName, Class parameterTypes[]) { Method method = null; // Check the implemented interfaces of the parent class Class interfaces[] = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { // Is this interface public? if (!Modifier.isPublic(interfaces[i].getModifiers())) continue; // Does the method exist on this interface? try { method = interfaces[i].getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { ; } if (method != null) break; // Recursively check our parent interfaces method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes); if (method != null) break; } // Return whatever we have found return (method); } }
package gl8080.lifegame.web.json; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import com.fasterxml.jackson.databind.ObjectMapper; import gl8080.lifegame.web.resource.LifeGameDto; @Provider @Consumes(MediaType.APPLICATION_JSON) public class JsonReader implements MessageBodyReader<LifeGameDto> { private ObjectMapper mapper = new ObjectMapper(); @Override public boolean isReadable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) { // firefox application/json;charset=UTF-8 equals return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType.APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype()); } @Override public LifeGameDto readFrom(Class<LifeGameDto> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> header, InputStream input) throws IOException, WebApplicationException { return this.mapper.readValue(input, LifeGameDto.class); } }
package org.apache.velocity.test; import java.util.Properties; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.io.IOException; import java.io.FileInputStream; import java.io.BufferedInputStream; import org.apache.velocity.runtime.Runtime; import junit.framework.*; /** * Test suite for Apache Velocity. * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> * @version $Id: VelocityTestSuite.java,v 1.13 2000/12/20 06:31:06 jvanzyl Exp $ */ public class VelocityTestSuite extends TestSuite { /** * Properties file that lists which template tests to run. */ private final static String TEST_CASE_PROPERTIES = "../test/test.properties"; /** * Path for templates. This property will override the * value in the default velocity properties file. */ private final static String FILE_RESOURCE_LOADER_PATH = "../test/templates"; private Properties testProperties; /** * Creates an instace of the Apache Velocity test suite. */ public VelocityTestSuite () { super("Apache Velocity test suite"); try { Runtime.setDefaultProperties(); Runtime.setSourceProperty( Runtime.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH); Runtime.init(); testProperties = new Properties(); testProperties.load(new FileInputStream(TEST_CASE_PROPERTIES)); } catch (Exception e) { System.err.println("Cannot setup VelocityTestSuite!"); e.printStackTrace(); System.exit(1); } /* * Add test cases here. */ /* * test 1 : template test cases */ List templateTestCases = getTemplateTestCases(); for (Iterator iter = templateTestCases.iterator(); iter.hasNext(); ) { addTest(new TemplateTestCase((String)iter.next())); } /* * test 2 : context safety test case */ System.out.println("Adding ContextSafetyTestCase."); addTest( new ContextSafetyTestCase() ); } /** * Returns a list of the template test cases to run. * * @return A <code>List</code> of <code>String</code> objects naming the * test cases. */ private List getTemplateTestCases () { String template; List testCases = new ArrayList(); for (int i = 1 ;; i++) { template = testProperties.getProperty( "test.template." + Integer.toString(i)); if (template == null) break; System.out.println("Adding TemplateTestCase : " + template); testCases.add(template); } return testCases; } }
package info.fingo.urlopia.user; import info.fingo.urlopia.ad.ActiveDirectory; import info.fingo.urlopia.ad.LocalTeam; import info.fingo.urlopia.ad.LocalUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; /** * @author Tomasz Urbas */ @Component public class UserFactory { @Autowired ActiveDirectory activeDirectory; @Value("${ad.user.master.leader}") String masterLeader; public UserDTO create(User userDB) { long id = userDB.getId(); String mail = userDB.getMail(); Optional<LocalUser> userAD = activeDirectory.getUser(mail); if (userAD.isPresent()) { boolean admin = userDB.isAdmin(); String lang = userDB.getLang(); String firstName = userAD.get().getName(); String lastName = userAD.get().getSurname(); boolean leader = masterLeader.equals(userAD.get().getPrincipalName()) || userAD.get().isLeader(); boolean B2B = userAD.get().isB2B(); boolean EC = userAD.get().isEC(); boolean urlopiaTeam = userAD.get().isUrlopiaTeam(); float workTime = userDB.getWorkTime(); List<LocalTeam> teams = userAD.get().getTeams(); mail = userAD.get().getMail(); String principalName = userAD.get().getPrincipalName(); Set<UserDTO.Role> roles = new HashSet<>(); roles.add(UserDTO.Role.WORKER); if (leader) { roles.add(UserDTO.Role.LEADER); } if (admin) { roles.add(UserDTO.Role.ADMIN); } return new UserDTO(id, principalName, mail, firstName, lastName, admin, leader, B2B, EC, urlopiaTeam, lang, workTime, teams, roles); } else { return new UserDTO(id, mail); } } }
package org.jdesktop.swingx; import static java.awt.RenderingHints.KEY_ANTIALIASING; import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jdesktop.swingx.color.ColorUtil; import org.jdesktop.swingx.color.EyeDropperColorChooserPanel; import org.jdesktop.swingx.plaf.UIManagerExt; import org.jdesktop.swingx.util.OS; /** * A button which allows the user to select a single color. The button has a platform * specific look. Ex: on Mac OS X it will mimic an NSColorWell. When the user * clicks the button it will open a color chooser set to the current background * color of the button. The new selected color will be stored in the background * property and can be retrieved using the getBackground() method. As the user is * choosing colors within the color chooser the background property will be updated. * By listening to this property developers can make other parts of their programs * update. * * @author joshua@marinacci.org */ public class JXColorSelectionButton extends JButton { private BufferedImage colorwell; private JDialog dialog = null; private JColorChooser chooser = null; /** * Creates a new instance of JXColorSelectionButton */ public JXColorSelectionButton() { this(Color.red); } /** * Creates a new instance of JXColorSelectionButton set to the specified color. * @param col The default color */ public JXColorSelectionButton(Color col) { setBackground(col); this.addActionListener(new ActionHandler()); this.setContentAreaFilled(false); this.setOpaque(false); try { colorwell = ImageIO.read(this.getClass().getResourceAsStream("color/colorwell.png")); } catch (Exception ex) { ex.printStackTrace(); } this.addPropertyChangeListener("background",new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { getChooser().setColor(getBackground()); } }); } /** * A listener class to update the button's background when the selected * color changes. */ private class ColorChangeListener implements ChangeListener { public JXColorSelectionButton button; public ColorChangeListener(JXColorSelectionButton button) { this.button = button; } public void stateChanged(ChangeEvent changeEvent) { button.setBackground(button.getChooser().getColor()); } } /** * {@inheritDoc} */ protected void paintComponent(Graphics g) { // want disabledForeground when disabled, current colour otherwise final Color FILL_COLOR = isEnabled() ? ColorUtil.removeAlpha(getBackground()) : UIManagerExt.getSafeColor("Button.disabledForeground", Color.LIGHT_GRAY); // draw the colorwell image (should only be on OSX) if(OS.isMacOSX() && colorwell != null) { Insets ins = new Insets(5,5,5,5); ColorUtil.tileStretchPaint(g, this, colorwell, ins); // fill in the color area g.setColor(FILL_COLOR); g.fillRect(ins.left, ins.top, getWidth() - ins.left - ins.right, getHeight() - ins.top - ins.bottom); // draw the borders g.setColor(ColorUtil.setBrightness(FILL_COLOR,0.85f)); g.drawRect(ins.left, ins.top, getWidth() - ins.left - ins.right - 1, getHeight() - ins.top - ins.bottom - 1); g.drawRect(ins.left + 1, ins.top + 1, getWidth() - ins.left - ins.right - 3, getHeight() - ins.top - ins.bottom - 3); }else{ Graphics2D g2 = (Graphics2D) g.create(); try { g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); g2.setColor(Color.LIGHT_GRAY); final int DIAM = Math.min(getWidth(), getHeight()); final int inset = 3; g2.fill(new Ellipse2D.Float(inset, inset, DIAM-2*inset, DIAM-2*inset)); g2.setColor(FILL_COLOR); final int border = 1; g2.fill(new Ellipse2D.Float(inset+border, inset+border, DIAM-2*inset-2*border, DIAM-2*inset-2*border)); } finally { g2.dispose(); } } } // /** // * Sample usage of JXColorSelectionButton // * @param args not used // */ // public static void main(String[] args) { // javax.swing.JFrame frame = new javax.swing.JFrame("Color Button Test"); // frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); // javax.swing.JPanel panel = new javax.swing.JPanel(); // javax.swing.JComponent btn = new JXColorSelectionButton(); // btn.setEnabled(true); // panel.add(btn); // panel.add(new javax.swing.JLabel("ColorSelectionButton test")); // frame.add(panel); // frame.pack(); // frame.setVisible(true); /** * Conditionally create and show the color chooser dialog. */ private void showDialog() { final Color oldColor = getBackground(); if (dialog == null) { dialog = JColorChooser.createDialog(JXColorSelectionButton.this, "Choose a color", true, getChooser(), new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { Color color = getChooser().getColor(); if (color != null) { setBackground(color); } } }, new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { setBackground(oldColor); } }); dialog.getContentPane().add(getChooser()); getChooser().getSelectionModel().addChangeListener( new ColorChangeListener(JXColorSelectionButton.this)); } dialog.setVisible(true); } /** * Get the JColorChooser that is used by this JXColorSelectionButton. This * chooser instance is shared between all invocations of the chooser, but is unique to * this instance of JXColorSelectionButton. * @return the JColorChooser used by this JXColorSelectionButton */ public JColorChooser getChooser() { if(chooser == null) { chooser = new JColorChooser(); // add the eyedropper color chooser panel chooser.addChooserPanel(new EyeDropperColorChooserPanel()); } return chooser; } /** * Set the JColorChooser that is used by this JXColorSelectionButton. * chooser instance is shared between all invocations of the chooser, * but is unique to * this instance of JXColorSelectionButton. * @param chooser The new JColorChooser to use. */ public void setChooser(JColorChooser chooser) { JColorChooser oldChooser = getChooser(); this.chooser = chooser; firePropertyChange("chooser",oldChooser,chooser); } /** * {@inheritDoc} */ @Override public Dimension getPreferredSize() { if (isPreferredSizeSet() || colorwell == null) { return super.getPreferredSize(); } return new Dimension(colorwell.getWidth(), colorwell.getHeight()); } /** * A private class to conditionally create and show the color chooser * dialog. */ private class ActionHandler implements ActionListener { public void actionPerformed(ActionEvent actionEvent) { showDialog(); } } }
package io.github.binaryoverload; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import java.io.*; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; /** * Main config class used to represent a json file * accessible by "paths" * * @author BinaryOverload * @version 1.0.1 * @since 1.0 */ public class JSONConfig { private JsonObject object; private String pathSeparator = "."; private static Gson GSON = new Gson(); /** * Recommended constructor for most file based applications * <br> * <i>Uses the default path separator</i> * * @param file The file must exist and not be a directory * @throws FileNotFoundException if the file does not exist, * is a directory rather than a regular file, * or for some other reason cannot be opened for * reading. * @throws NullPointerException if the passed variable is null * * @see FileInputStream * @see File * @since 1.0 */ public JSONConfig(File file) throws FileNotFoundException, NullPointerException { Objects.requireNonNull(file); this.object = GSON.fromJson(new JsonReader(new FileReader(file)), JsonObject.class); } public JSONConfig(File file, String pathSeparator) throws FileNotFoundException { Objects.requireNonNull(file); Objects.requireNonNull(pathSeparator); GeneralUtils.checkStringLength(pathSeparator, 1); this.object = GSON.fromJson(new JsonReader(new FileReader(file)), JsonObject.class); setPathSeparator(pathSeparator); } /** * More advanced constructor allowing users to specify their own input stream * * @param stream The stream to be used for the JSON Object <i>This cannot be null</i> * @throws NullPointerException if the stream is null * @see InputStream * @since 1.0 */ public JSONConfig(InputStream stream) { Objects.requireNonNull(stream); this.object = GSON.fromJson(new JsonReader(new InputStreamReader(stream)), JsonObject.class); } public JSONConfig(InputStream stream, String pathSeparator) { Objects.requireNonNull(stream); Objects.requireNonNull(pathSeparator); GeneralUtils.checkStringLength(pathSeparator, 1); setPathSeparator(pathSeparator); } /** * Basic constructor that directly sets the JSONObject * * @param object The object to assign to the config <i>Cannot be null</i> * @throws NullPointerException if the object is null * @since 1.0 * @see JsonObject */ public JSONConfig(JsonObject object) { Objects.requireNonNull(object); this.object = object; } public JSONConfig(JsonObject object, String pathSeparator) { Objects.requireNonNull(object); this.object = object; GeneralUtils.checkStringLength(pathSeparator, 1); setPathSeparator(pathSeparator); } /** * Gets the path separator for this config * * @return The path separator * @since 1.0 */ public String getPathSeparator() { return pathSeparator; } public void setPathSeparator(String pathSeparator) { Objects.requireNonNull(pathSeparator); GeneralUtils.checkStringLength(pathSeparator, 1); this.pathSeparator = pathSeparator; } /** * Gets the JSON object associated with this config * * @return The JSON Object associated with this config * @since 1.0 */ public JsonObject getObject() { return object; } /** * Sets the JSON object for this config * * @param object The object to be set <i>Cannot be null</i> * @throws NullPointerException if the object is null * @since 1.0 */ public void setObject(JsonObject object) { Objects.requireNonNull(object); this.object = object; } public JsonElement getElement(JsonObject json, String path) { String[] subpaths = path.split("\\."); for (int i = 0; i < subpaths.length; i++) { String subpath = subpaths[i]; if (json.isJsonNull()) { return null; } else if (json.get(subpath).isJsonObject()) { if (subpaths.length == 1 && subpaths[0].isEmpty()) { return json; } return getElement(json.get(subpath).getAsJsonObject(), Arrays.stream(subpaths).skip(i + 1).collect(Collectors.joining("."))); } else { return json.get(subpath); } } return null; } public JsonElement getElement(String path) { return getElement(this.object, path); } public void set(String path, Object object) { JsonObject json = this.object; JsonObject root = json; String[] subpaths = path.split("\\."); for (int j = 0; j < subpaths.length; j++) { if (root.get(subpaths[j]) == null) { root.add(subpaths[j], new JsonObject()); if (j == subpaths.length - 1) { root.add(subpaths[j], GSON.toJsonTree(object)); } else { root = root.get(subpaths[j]).getAsJsonObject(); } } else { if (j == subpaths.length - 1) { root.add(subpaths[j], GSON.toJsonTree(object)); } else { root = root.get(subpaths[j]).getAsJsonObject(); } } if (j == subpaths.length - 1) { root = json; } } } }
package org.jdesktop.swingx.icon; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JFrame; import javax.swing.JLabel; /** * Icon class for rendering icon which indicates user control of * column visibility. * @author Amy Fowler * @version 1.0 */ public class ColumnControlIcon implements Icon { private int width = 10; private int height = 10; /**@todo: need to support small, medium, large */ public ColumnControlIcon() { } public int getIconWidth() { return width; } public int getIconHeight() { return height; } public void paintIcon(Component c, Graphics g, int x, int y) { Color color = c.getForeground(); g.setColor(color); // draw horizontal lines g.drawLine(x, y, x+8, y); g.drawLine(x, y+2, x+8, y+2); g.drawLine(x, y+8, x+2, y+8); // draw vertical lines g.drawLine(x, y+1, x, y+7); g.drawLine(x+4, y+1, x+4, y+4); g.drawLine(x+8, y+1, x+8, y+4); // draw arrow g.drawLine(x+3, y+6, x+9, y+6); g.drawLine(x+4, y+7, x+8, y+7); g.drawLine(x+5, y+8, x+7, y+8); g.drawLine(x+6, y+9, x+6, y+9); } public static void main(String args[]) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel(new ColumnControlIcon()); frame.getContentPane().add(BorderLayout.CENTER, label); frame.pack(); frame.setVisible(true); } }
package io.github.classgraph; import java.io.File; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import nonapi.io.github.classgraph.utils.JarUtils; import nonapi.io.github.classgraph.utils.Join; import nonapi.io.github.classgraph.utils.ReflectionUtils; /** * Information on the module path. Note that this will only include module system parameters actually listed in * commandline arguments -- in particular this does not include classpath elements from the traditional classpath, * or system modules. */ public class ModulePathInfo { /** * The module path provided on the commandline by the {@code --module-path} or {@code -p} switch, as an ordered * set of module names, in the order they were listed on the commandline. * * <p> * Note that some modules (such as system modules) will not be in this set, as they are added to the module * system automatically by the runtime. Call {@link ClassGraph#getModules()} or {@link ScanResult#getModules()} * to get all modules visible at runtime. */ public final Set<String> modulePath = new LinkedHashSet<>(); public final Set<String> addModules = new LinkedHashSet<>(); /** * The module patch directives listed on the commandline using the {@code --patch-module} switch, as an ordered * set of strings in the format {@code <module>=<file>}, in the order they were listed on the commandline. */ public final Set<String> patchModules = new LinkedHashSet<>(); /** * The module {@code exports} directives added on the commandline using the {@code --add-exports} switch, as an * ordered set of strings in the format {@code <source-module>/<package>=<target-module>(,<target-module>)*}, in * the order they were listed on the commandline. Additionally, if this {@link ModulePathInfo} object was * obtained from {@link ScanResult#getModulePathInfo()} rather than {@link ClassGraph#getModulePathInfo()}, any * additional {@code Add-Exports} entries found in manifest files during classpath scanning will be appended to * this list, in the format {@code <source-module>/<package>=ALL-UNNAMED}. */ public final Set<String> addExports = new LinkedHashSet<>(); /** * The module {@code opens} directives added on the commandline using the {@code --add-opens} switch, as an * ordered set of strings in the format {@code <source-module>/<package>=<target-module>(,<target-module>)*}, in * the order they were listed on the commandline. Additionally, if this {@link ModulePathInfo} object was * obtained from {@link ScanResult#getModulePathInfo()} rather than {@link ClassGraph#getModulePathInfo()}, any * additional {@code Add-Opens} entries found in manifest files during classpath scanning will be appended to * this list, in the format {@code <source-module>/<package>=ALL-UNNAMED}. */ public final Set<String> addOpens = new LinkedHashSet<>(); /** * The module {@code reads} directives added on the commandline using the {@code --add-reads} switch, as an * ordered set of strings in the format {@code <source-module>=<target-module>}, in the order they were listed * on the commandline. */ public final Set<String> addReads = new LinkedHashSet<>(); /** The fields. */ private final List<Set<String>> fields = Arrays.asList( modulePath, addModules, patchModules, addExports, addOpens, addReads ); /** The module path commandline switches. */ private static final List<String> argSwitches = Arrays.asList( "--module-path=", "--add-modules=", "--patch-module=", "--add-exports=", "--add-opens=", "--add-reads=" ); /** The module path commandline switch value delimiters. */ private static final List<Character> argPartSeparatorChars = Arrays.asList( File.pathSeparatorChar, // --module-path (delimited path format) ',', // --add-modules (comma-delimited) '\0', // --patch-module (only one param per switch) '\0', // --add-exports (only one param per switch) '\0', // --add-opens (only one param per switch) '\0' // --add-reads (only one param per switch) ); /** Construct a {@link ModulePathInfo}. */ public ModulePathInfo() { // Read the raw commandline arguments to get the module path override parameters. // If the java.management module is not present in the deployed runtime (for JDK 9+), or the runtime // does not contain the java.lang.management package (e.g. the Android build system, which also does // not support JPMS currently), then skip trying to read the commandline arguments (#404). final Class<?> managementFactory = ReflectionUtils .classForNameOrNull("java.lang.management.ManagementFactory"); final Object runtimeMXBean = managementFactory == null ? null : ReflectionUtils.invokeStaticMethod(managementFactory, "getRuntimeMXBean", /* throwException = */ false); @SuppressWarnings("unchecked") final List<String> commandlineArguments = runtimeMXBean == null ? null : (List<String>) ReflectionUtils.invokeMethod(runtimeMXBean, "getInputArguments", /* throwException = */ false); if (commandlineArguments != null) { for (final String arg : commandlineArguments) { for (int i = 0; i < fields.size(); i++) { final String argSwitch = argSwitches.get(i); if (arg.startsWith(argSwitch)) { final String argParam = arg.substring(argSwitch.length()); final Set<String> argField = fields.get(i); final char sepChar = argPartSeparatorChars.get(i); if (sepChar == '\0') { // Only one param per switch argField.add(argParam); } else { // Split arg param into parts for (final String argPart : JarUtils.smartPathSplit(argParam, sepChar, /* scanSpec = */ null)) { argField.add(argPart); } } } } } } } /** * Return the module path info in commandline format. * * @return the module path commandline string. */ @Override public String toString() { final StringBuilder buf = new StringBuilder(1024); if (!modulePath.isEmpty()) { buf.append("--module-path="); buf.append(Join.join(File.pathSeparator, modulePath)); } if (!addModules.isEmpty()) { if (buf.length() > 0) { buf.append(' '); } buf.append("--add-modules="); buf.append(Join.join(",", addModules)); } for (final String patchModulesEntry : patchModules) { if (buf.length() > 0) { buf.append(' '); } buf.append("--patch-module="); buf.append(patchModulesEntry); } for (final String addExportsEntry : addExports) { if (buf.length() > 0) { buf.append(' '); } buf.append("--add-exports="); buf.append(addExportsEntry); } for (final String addOpensEntry : addOpens) { if (buf.length() > 0) { buf.append(' '); } buf.append("--add-opens="); buf.append(addOpensEntry); } for (final String addReadsEntry : addReads) { if (buf.length() > 0) { buf.append(' '); } buf.append("--add-reads="); buf.append(addReadsEntry); } return buf.toString(); } }
package burlap.testing.Domain; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import burlap.oomdp.auxiliary.DomainGenerator; import burlap.oomdp.core.Attribute; import burlap.oomdp.core.Domain; import burlap.oomdp.core.ObjectClass; import burlap.oomdp.core.ObjectInstance; import burlap.oomdp.core.PropositionalFunction; import burlap.oomdp.core.State; import burlap.oomdp.singleagent.Action; import burlap.oomdp.singleagent.SADomain; public class BlockDude implements DomainGenerator { public static final String ATTX = "x"; public static final String ATTY = "y"; public static final String ATTDIR = "dir"; public static final String ATTHOLD = "holding"; public static final String ATTHEIGHT = "height"; public static final String CLASSAGENT = "agent"; public static final String CLASSBLOCK = "block"; public static final String CLASSPLATFORM = "platform"; public static final String CLASSEXIT = "exit"; public static final String ACTIONUP = "up"; public static final String ACTIONEAST = "east"; public static final String ACTIONWEST = "west"; public static final String ACTIONPICKUP = "pickup"; public static final String ACTIONPUTDOWN = "putdown"; public static final String PFHOLDINGBLOCK = "holdingBlock"; public static final String PFATEXIT = "atExit"; public int minx = 0; public int maxx = 25; public int miny = 0; public int maxy = 25; public static boolean useSemiDeep = false; public BlockDude(){ //do nothing } public BlockDude(int maxx, int maxy){ this.maxx = maxx; this.maxy = maxy; } public BlockDude(int minx, int maxx, int miny, int maxy){ this.minx = minx; this.miny = miny; this.maxx = maxx; this.maxy = maxy; } @Override public Domain generateDomain() { Domain domain = new SADomain(); //setup attributes Attribute xAtt = new Attribute(domain, ATTX, Attribute.AttributeType.DISC); xAtt.setDiscValuesForRange(minx, maxx, 1); Attribute yAtt = new Attribute(domain, ATTY, Attribute.AttributeType.DISC); yAtt.setDiscValuesForRange(miny, miny, 1); Attribute dirAtt = new Attribute(domain, ATTDIR, Attribute.AttributeType.DISC); dirAtt.setDiscValuesForRange(0, 1, 1); Attribute holdAtt = new Attribute(domain, ATTHOLD, Attribute.AttributeType.DISC); holdAtt.setDiscValuesForRange(0, 1, 1); Attribute heightAtt = new Attribute(domain, ATTHEIGHT, Attribute.AttributeType.DISC); heightAtt.setDiscValuesForRange(miny, maxy, 1); //setup object classes ObjectClass aclass = new ObjectClass(domain, CLASSAGENT); aclass.addAttribute(xAtt); aclass.addAttribute(yAtt); aclass.addAttribute(dirAtt); aclass.addAttribute(holdAtt); ObjectClass bclass = new ObjectClass(domain, CLASSBLOCK); bclass.addAttribute(xAtt); bclass.addAttribute(yAtt); ObjectClass pclass = new ObjectClass(domain, CLASSPLATFORM); pclass.addAttribute(xAtt); pclass.addAttribute(heightAtt); ObjectClass eclass = new ObjectClass(domain, CLASSEXIT); eclass.addAttribute(xAtt); eclass.addAttribute(yAtt); //setup actions Action upAction = new UpAction(ACTIONUP, domain, ""); Action eastAction = new EastAction(ACTIONEAST, domain, ""); Action westAction = new WestAction(ACTIONWEST, domain, ""); Action pickupAction = new PickupAction(ACTIONPICKUP, domain, ""); Action putdownAction = new PutdownAction(ACTIONPUTDOWN, domain, ""); //setup propositional functions PropositionalFunction holdingBlockPF = new HoldingBlockPF(PFHOLDINGBLOCK, domain, new String[]{CLASSAGENT, CLASSBLOCK}); PropositionalFunction atExitPF = new AtExitPF(PFATEXIT, domain, new String[]{CLASSAGENT, CLASSEXIT}); return domain; } public static State getCleanState(Domain domain, List <Integer> platformX, List <Integer> platformH, int nb){ State s = new State(); //start by creating the platform objects for(int i = 0; i < platformX.size(); i++){ int x = platformX.get(i); int h = platformH.get(i); ObjectInstance plat = new ObjectInstance(domain.getObjectClass(CLASSPLATFORM), CLASSPLATFORM+x); plat.setValue(ATTX, x); plat.setValue(ATTHEIGHT, h); s.addObject(plat); } //create n blocks for(int i = 0; i < nb; i++){ s.addObject(new ObjectInstance(domain.getObjectClass(CLASSBLOCK), CLASSBLOCK+i)); } //create exit s.addObject(new ObjectInstance(domain.getObjectClass(CLASSEXIT), CLASSEXIT+0)); //create agent s.addObject(new ObjectInstance(domain.getObjectClass(CLASSAGENT), CLASSAGENT+0)); return s; } public static void setAgent(State s, int x, int y, int dir, int holding){ ObjectInstance agent = s.getObjectsOfTrueClass(CLASSAGENT).get(0); agent.setValue(ATTX, x); agent.setValue(ATTY, y); agent.setValue(ATTDIR, dir); agent.setValue(ATTHOLD, holding); } public static void setExit(State s, int x, int y){ ObjectInstance exit = s.getObjectsOfTrueClass(CLASSEXIT).get(0); exit.setValue(ATTX, x); exit.setValue(ATTY, y); } public static void setBlock(State s, int i, int x, int y){ ObjectInstance block = s.getObjectsOfTrueClass(CLASSBLOCK).get(i); block.setValue(ATTX, x); block.setValue(ATTY, y); } public static void moveHorizontally(State s, int dx){ ObjectInstance agent = s.getObjectsOfTrueClass(CLASSAGENT).get(0); //always set direction if(dx > 0){ agent.setValue(ATTDIR, 1); } else{ agent.setValue(ATTDIR, 0); } int ax = agent.getDiscValForAttribute(ATTX); int ay = agent.getDiscValForAttribute(ATTY); int nx = ax+dx; int heightAtNX = totalHeightAtXPos(s, nx); //can only move if new position is below agent height if(heightAtNX >= ay){ return ; //do nothing; walled off } int ny = heightAtNX + 1; //stand on top of stack agent.setValue(ATTX, nx); agent.setValue(ATTY, ny); moveCarriedBlockToNewAgentPosition(s, agent, ax, ay, nx, ny); } public static void moveUp(State s){ ObjectInstance agent = s.getObjectsOfTrueClass(CLASSAGENT).get(0); int ax = agent.getDiscValForAttribute(ATTX); int ay = agent.getDiscValForAttribute(ATTY); int dir = agent.getDiscValForAttribute(ATTDIR); if(dir == 0){ dir = -1; } int nx = ax+dir; int ny = ay+1; int heightAtNX = totalHeightAtXPos(s, nx); //in order to move up, the height of world in new x position must be at the same current agent position if(heightAtNX != ay){ return ; //not a viable move up condition, so do nothing } agent.setValue(ATTX, nx); agent.setValue(ATTY, ny); moveCarriedBlockToNewAgentPosition(s, agent, ax, ay, nx, ny); } public static void pickupBlock(State s){ ObjectInstance agent = s.getObjectsOfTrueClass(CLASSAGENT).get(0); int holding = agent.getDiscValForAttribute(ATTHOLD); if(holding == 1){ return; //already holding a block } int ax = agent.getDiscValForAttribute(ATTX); int ay = agent.getDiscValForAttribute(ATTY); int dir = agent.getDiscValForAttribute(ATTDIR); if(dir == 0){ dir = -1; } //can only pick up blocks one unit away in agent facing direction and at same height as agent int bx = ax+dir; ObjectInstance block = getBlockAt(s, bx, ay); if(block != null){ //make sure that block is the top of the world, otherwise something is stacked above it and you cannot pick it up int mxh = totalHeightAtXPos(s, bx); if(mxh > block.getDiscValForAttribute(ATTY)){ return; } block.setValue(ATTX, ax); block.setValue(ATTY, ay+1); agent.setValue(ATTHOLD, 1); } } public static void putdownBlock(State s){ ObjectInstance agent = s.getObjectsOfTrueClass(CLASSAGENT).get(0); int holding = agent.getDiscValForAttribute(ATTHOLD); if(holding == 0){ return; //not holding a block } int ax = agent.getDiscValForAttribute(ATTX); int ay = agent.getDiscValForAttribute(ATTY); int dir = agent.getDiscValForAttribute(ATTDIR); if(dir == 0){ dir = -1; } int nx = ax + dir; int heightAtNX = totalHeightAtXPos(s, nx); if(heightAtNX > ay){ return; //cannot drop block if walled off from throw position } ObjectInstance block = getBlockAt(s, ax, ay+1); //carried block is one unit above agent block.setValue(ATTX, nx); block.setValue(ATTY, heightAtNX+1); //stacked on top of this position agent.setValue(ATTHOLD, 0); } private static void moveCarriedBlockToNewAgentPosition(State s, ObjectInstance agent, int ax, int ay, int nx, int ny){ int holding = agent.getDiscValForAttribute(ATTHOLD); if(holding == 1){ //then move the box being carried too ObjectInstance carriedBlock = getBlockAt(s, ax, ay+1); //carried block is one unit above agent carriedBlock.setValue(ATTX, nx); carriedBlock.setValue(ATTY, ny+1); } } private static ObjectInstance getBlockAt(State s, int x, int y){ List<ObjectInstance> blocks = s.getObjectsOfTrueClass(CLASSBLOCK); for(ObjectInstance block : blocks){ int bx = block.getDiscValForAttribute(ATTX); int by = block.getDiscValForAttribute(ATTY); if(bx == x && by == y){ return block; } } return null; } private static int totalHeightAtXPos(State s, int x){ //first see if there are any blocks at this x pos and if so, what highest one is List<ObjectInstance> blocks = s.getObjectsOfTrueClass(CLASSBLOCK); int maxBlock = -1; for(ObjectInstance block : blocks){ int bx = block.getDiscValForAttribute(ATTX); if(bx != x){ continue; } int by = block.getDiscValForAttribute(ATTY); if(by > maxBlock){ maxBlock = by; } } if(maxBlock > -1){ return maxBlock; //there are stacked blocks here which must be the highest point } //get platform at pos x ObjectInstance plat = s.getObject(CLASSPLATFORM+x); if(plat != null){ return plat.getDiscValForAttribute(ATTHEIGHT); } return -1; } public class UpAction extends Action{ public UpAction(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public UpAction(String name, Domain domain, String [] parameterClasses){ super(name, domain, parameterClasses); } @Override protected State performActionHelper(State st, String[] params) { moveUp(st); return st; } } public class EastAction extends Action{ public EastAction(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public EastAction(String name, Domain domain, String [] parameterClasses){ super(name, domain, parameterClasses); } @Override protected State performActionHelper(State st, String[] params) { moveHorizontally(st, 1); return st; } } public class WestAction extends Action{ public WestAction(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public WestAction(String name, Domain domain, String [] parameterClasses){ super(name, domain, parameterClasses); } @Override protected State performActionHelper(State st, String[] params) { moveHorizontally(st, -1); return st; } } public class PickupAction extends Action{ public PickupAction(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public PickupAction(String name, Domain domain, String [] parameterClasses){ super(name, domain, parameterClasses); } @Override protected State performActionHelper(State st, String[] params) { pickupBlock(st); return st; } } public class PutdownAction extends Action{ public PutdownAction(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public PutdownAction(String name, Domain domain, String [] parameterClasses){ super(name, domain, parameterClasses); } @Override protected State performActionHelper(State st, String[] params) { putdownBlock(st); return st; } } public class HoldingBlockPF extends PropositionalFunction{ public HoldingBlockPF(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public HoldingBlockPF(String name, Domain domain, String [] parameterClasses) { super(name, domain, parameterClasses); } @Override public boolean isTrue(State st, String[] params) { ObjectInstance agent = st.getObject(params[0]); ObjectInstance block = st.getObject(params[1]); int ax = agent.getDiscValForAttribute(ATTX); int ay = agent.getDiscValForAttribute(ATTY); int ah = agent.getDiscValForAttribute(ATTHOLD); int bx = block.getDiscValForAttribute(ATTX); int by = block.getDiscValForAttribute(ATTY); if(ax == bx && ay == by-1 && ah == 1){ return true; } return false; } } public class AtExitPF extends PropositionalFunction{ public AtExitPF(String name, Domain domain, String parameterClasses) { super(name, domain, parameterClasses); } public AtExitPF(String name, Domain domain, String [] parameterClasses) { super(name, domain, parameterClasses); } @Override public boolean isTrue(State st, String[] params) { ObjectInstance agent = st.getObject(params[0]); ObjectInstance exit = st.getObject(params[1]); int ax = agent.getDiscValForAttribute(ATTX); int ay = agent.getDiscValForAttribute(ATTY); int ex = exit.getDiscValForAttribute(ATTX); int ey = exit.getDiscValForAttribute(ATTY); if(ax == ex && ay == ey){ return true; } return false; } } }
package jsettlers.logic.movable.testmap; import java.util.LinkedList; import jsettlers.common.Color; import jsettlers.common.CommonConstants; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.landscape.EResourceType; import jsettlers.common.map.EDebugColorModes; import jsettlers.common.map.IGraphicsBackgroundListener; import jsettlers.common.map.IGraphicsGrid; import jsettlers.common.map.partition.IPartitionSettings; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.mapobject.IMapObject; import jsettlers.common.material.EMaterialType; import jsettlers.common.material.ESearchType; import jsettlers.common.movable.EDirection; import jsettlers.common.movable.IMovable; import jsettlers.common.position.ShortPoint2D; import jsettlers.logic.algorithms.path.IPathCalculatable; import jsettlers.logic.algorithms.path.Path; import jsettlers.logic.algorithms.path.astar.normal.HexAStar; import jsettlers.logic.algorithms.path.astar.normal.IAStarPathMap; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableBearer; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableBricklayer; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableDigger; import jsettlers.logic.map.newGrid.partition.manager.manageables.IManageableWorker; import jsettlers.logic.map.newGrid.partition.manager.materials.interfaces.IMaterialRequest; import jsettlers.logic.movable.Movable; import jsettlers.logic.movable.interfaces.AbstractNewMovableGrid; import jsettlers.logic.movable.interfaces.IAttackable; import jsettlers.logic.objects.stack.StackMapObject; import jsettlers.logic.player.Player; import networklib.synchronic.random.RandomSingleton; public class MovableTestsMap implements IGraphicsGrid, IAStarPathMap { private final short width; private final short height; private final Player defaultPlayer; private final Movable movableMap[][]; private final EMaterialType materialTypeMap[][]; private final byte materialAmmountMap[][]; private final HexAStar aStar; public MovableTestsMap(int width, int height, Player defaultPlayer) { this.width = (short) width; this.height = (short) height; this.defaultPlayer = defaultPlayer; this.movableMap = new Movable[width][height]; this.materialTypeMap = new EMaterialType[width][height]; this.materialAmmountMap = new byte[width][height]; aStar = new HexAStar(this, this.width, this.height); } @Override public short getHeight() { return height; } @Override public int nextDrawableX(int x, int y, int maxX) { return x + 1; } @Override public short getWidth() { return width; } @Override public IMovable getMovableAt(int x, int y) { return movableMap[x][y]; } @Override public IMapObject getMapObjectsAt(int x, int y) { if (materialTypeMap[x][y] != null && materialAmmountMap[x][y] > 0) { return new StackMapObject(materialTypeMap[x][y], materialAmmountMap[x][y]); } else { return null; } } @Override public byte getHeightAt(int x, int y) { return 0; } @Override public ELandscapeType getLandscapeTypeAt(int x, int y) { return ELandscapeType.GRASS; } @Override public int getDebugColorAt(int x, int y, EDebugColorModes debugColorMode) { return -1; } @Override public boolean isBorder(int x, int y) { return false; } @Override public byte getPlayerIdAt(int x, int y) { return 0; } @Override public byte getVisibleStatus(int x, int y) { return CommonConstants.FOG_OF_WAR_VISIBLE; } @Override public boolean isFogOfWarVisible(int x, int y) { return true; } @Override public void setBackgroundListener(IGraphicsBackgroundListener backgroundListener) { } private final AbstractNewMovableGrid movableGrid = new AbstractNewMovableGrid() { private static final long serialVersionUID = 610513829074598238L; @Override public void leavePosition(ShortPoint2D position, Movable movable) { if (movableMap[position.x][position.y] == movable) { movableMap[position.x][position.y] = null; } } @Override public boolean hasNoMovableAt(short x, short y) { return isInBounds(x, y) && movableMap[x][y] == null; } @Override public boolean isFreePosition(ShortPoint2D position) { short x = position.x; short y = position.y; return isInBounds(x, y) && !isBlocked(x, y) && movableMap[x][y] == null; } @Override public boolean isInBounds(short x, short y) { return 0 <= x && x < width && 0 <= y && y < height; } @Override public Path calculatePathTo(IPathCalculatable pathRequester, ShortPoint2D targetPos) { return aStar.findPath(pathRequester, targetPos); } @Override public void addJobless(IManageableBearer bearer) { if (!materials.isEmpty()) { ShortPoint2D source = materials.pop(); final ShortPoint2D targetPos = new ShortPoint2D(RandomSingleton.getInt(0, width - 1), RandomSingleton.getInt(0, height - 1)); bearer.deliver(materialTypeMap[source.x][source.y], source, new IMaterialRequest() { @Override public ShortPoint2D getPos() { return targetPos; } @Override public boolean isActive() { return true; } @Override public void deliveryFulfilled() { } @Override public void deliveryAccepted() { } @Override public void deliveryAborted() { } }); } } private LinkedList<ShortPoint2D> materials = new LinkedList<ShortPoint2D>(); @Override public boolean takeMaterial(ShortPoint2D pos, EMaterialType materialType) { if (materialTypeMap[pos.x][pos.y] == materialType && materialAmmountMap[pos.x][pos.y] > 0) { materialAmmountMap[pos.x][pos.y] return true; } else { return false; } } @Override public boolean dropMaterial(ShortPoint2D pos, EMaterialType materialType, boolean offer) { materialTypeMap[pos.x][pos.y] = materialType; materialAmmountMap[pos.x][pos.y]++; materials.add(pos); return true; } @Override public Movable getMovableAt(short x, short y) { return movableMap[x][y]; } @Override public boolean isBlocked(short x, short y) { return false; } @Override public void addJobless(IManageableWorker worker) { } @Override public void addJobless(IManageableDigger digger) { } @Override public float getResourceProbabilityAround(short x, short y, EResourceType type, int radius) { return 0; } @Override public EDirection getDirectionOfSearched(ShortPoint2D position, ESearchType searchType) { return null; } @Override public boolean executeSearchType(ShortPoint2D pos, ESearchType searchType) { return false; } @Override public EMaterialType popToolProductionRequest(ShortPoint2D pos) { return null; } @Override public void placePigAt(ShortPoint2D pos, boolean place) { } @Override public boolean hasPigAt(ShortPoint2D position) { return false; } @Override public boolean isPigAdult(ShortPoint2D position) { return false; } @Override public void placeSmoke(ShortPoint2D position, boolean smokeOn) { } @Override public boolean canPushMaterial(ShortPoint2D position) { return false; } @Override public boolean canPop(ShortPoint2D position, EMaterialType material) { return false; } @Override public byte getHeightAt(ShortPoint2D position) { return 0; } @Override public boolean isMarked(ShortPoint2D position) { return false; } @Override public void setMarked(ShortPoint2D position, boolean marked) { } @Override public Path searchDijkstra(IPathCalculatable pathCalculateable, short centerX, short centerY, short radius, ESearchType searchType) { return null; } @Override public Path searchInArea(IPathCalculatable pathCalculateable, short centerX, short centerY, short radius, ESearchType searchType) { return null; } @Override public void addJobless(IManageableBricklayer bricklayer) { } @Override public void changeHeightTowards(short x, short y, byte targetHeight) { } @Override public boolean isValidPosition(IPathCalculatable pathRequester, ShortPoint2D position) { short x = position.x, y = position.y; return isInBounds(x, y) && !isBlocked(x, y) && (!pathRequester.needsPlayersGround() || pathRequester.getPlayerId() == getPlayerIdAt(x, y)); } @Override public boolean isProtected(short x, short y) { return false; } @Override public boolean isBlockedOrProtected(short x, short y) { return isBlocked(x, y) || isProtected(x, y); } @Override public boolean fitsSearchType(IPathCalculatable pathCalculateable, ShortPoint2D pos, ESearchType searchType) { return false; } @Override public void changePlayerAt(ShortPoint2D pos, Player player) { } @Override public void removeJobless(IManageableBearer bearer) { } @Override public void removeJobless(IManageableWorker worker) { } @Override public void removeJobless(IManageableDigger digger) { } @Override public void removeJobless(IManageableBricklayer bricklayer) { } @Override public ELandscapeType getLandscapeTypeAt(short x, short y) { return ELandscapeType.GRASS; } @Override public Movable getEnemyInSearchArea(ShortPoint2D centerPos, IAttackable attackable, short searchRadius, boolean includeTowers) { return null; } @Override public void enterPosition(ShortPoint2D position, Movable movable, boolean informFullArea) { movableMap[position.x][position.y] = movable; } @Override public void addSelfDeletingMapObject(ShortPoint2D position, EMapObjectType mapObjectType, float duration, Player player) { } @Override public ShortPoint2D calcDecentralizeVector(short x, short y) { return new ShortPoint2D(0, 0); } @Override public void addArrowObject(ShortPoint2D attackedPos, ShortPoint2D shooterPos, byte shooterPlayerId, float hitStrength) { } @Override public Player getPlayerAt(ShortPoint2D position) { return defaultPlayer; } @Override public void decreaseResourceAround(short x, short y, EResourceType resourceType, int radius, int amount) { // TODO Auto-generated method stub } }; public AbstractNewMovableGrid getMovableGrid() { return movableGrid; } @Override public boolean isBlocked(IPathCalculatable requester, int x, int y) { return false; } @Override public float getCost(int sx, int sy, int tx, int ty) { return 1; } @Override public void markAsOpen(int x, int y) { } @Override public void markAsClosed(int x, int y) { } @Override public void setDebugColor(int x, int y, Color color) { } @Override public short getBlockedPartition(int x, int y) { return 1; } @Override public IPartitionSettings getPartitionSettings(int x, int y) { return null; } }
package org.drooms.impl.util; import java.io.File; import java.io.FileReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.drools.builder.KnowledgeBuilder; import org.drooms.api.CustomPathBasedStrategy; import org.drooms.api.Edge; import org.drooms.api.Node; import org.drooms.api.Player; import org.drooms.api.Strategy; import org.drooms.impl.GameController; import edu.uci.ics.jung.algorithms.shortestpath.ShortestPath; import edu.uci.ics.jung.algorithms.shortestpath.UnweightedShortestPath; import edu.uci.ics.jung.graph.Graph; /** * A helper class to load {@link Strategy} implementations for all requested * {@link Player}s. */ public class PlayerAssembly { private static class DefaultPathBasedStrategy implements CustomPathBasedStrategy { private final Strategy strategy; public DefaultPathBasedStrategy(final Strategy nonCustomPathBasedStrategy) { if (nonCustomPathBasedStrategy == null) { throw new IllegalArgumentException("The strategy may not be null!"); } if (nonCustomPathBasedStrategy instanceof CustomPathBasedStrategy) { throw new IllegalArgumentException("The strategy must not provide its own path-finding algorithm!"); } this.strategy = nonCustomPathBasedStrategy; } @Override public boolean enableAudit() { return this.strategy.enableAudit(); } @Override public boolean equals(final Object obj) { return this.strategy.equals(obj); } @Override public KnowledgeBuilder getKnowledgeBuilder(final ClassLoader cls) { return this.strategy.getKnowledgeBuilder(cls); } @Override public String getName() { return this.strategy.getName(); } @Override public ShortestPath<Node, Edge> getShortestPathAlgorithm(final Graph<Node, Edge> graph) { return new UnweightedShortestPath<>(graph); } @Override public int hashCode() { return this.strategy.hashCode(); } @Override public String toString() { return this.strategy.toString(); } } private static URL uriToUrl(final URI uri) { try { return uri.toURL(); } catch (final MalformedURLException e) { throw new IllegalArgumentException("Invalid URL: " + uri, e); } } private final Properties config; private final Map<URI, ClassLoader> strategyClassloaders = new HashMap<>(); private final Map<String, Strategy> strategyInstances = new HashMap<>(); /** * Initialize the class. * * @param f * Game config as described in * {@link GameController#play(org.drooms.api.Playground, Properties, Collection, File)} * . */ public PlayerAssembly(final File f) { try (FileReader fr = new FileReader(f)) { this.config = new Properties(); this.config.load(fr); } catch (final Exception e) { throw new IllegalArgumentException("Cannot read player config file.", e); } } /** * Perform all the strategy resolution and return a list of fully * initialized players. * * @return The unmodifiable collection of players, in the order in which * they come up in the data file. */ public List<Player> assemblePlayers() { // parse a list of players final Map<String, String> playerStrategies = new HashMap<>(); final Map<String, URI> strategyJars = new HashMap<>(); for (final String playerName : this.config.stringPropertyNames()) { final String strategyDescr = this.config.getProperty(playerName); final String[] parts = strategyDescr.split("\\Q@\\E"); if (parts.length != 2) { throw new IllegalArgumentException("Invalid strategy descriptor: " + strategyDescr); } final String strategyClass = parts[0]; if (strategyClass.startsWith("org.drooms.impl.")) { throw new IllegalStateException("Strategy musn't belong to the game implementation package."); } try { final URI strategyJar = new URI(parts[1]); playerStrategies.put(playerName, strategyClass); strategyJars.put(strategyClass, strategyJar); } catch (final URISyntaxException e) { throw new IllegalArgumentException("Invalid URL in the strategy descriptor: " + strategyDescr, e); } } // load strategies for players final List<Player> players = new ArrayList<>(); for (final Map.Entry<String, String> entry : playerStrategies.entrySet()) { final String playerName = entry.getKey(); final String strategyClass = entry.getValue(); final URI strategyJar = strategyJars.get(strategyClass); CustomPathBasedStrategy strategy; try { final Strategy s = this.loadStrategy(strategyClass, strategyJar); if (s instanceof CustomPathBasedStrategy) { strategy = (CustomPathBasedStrategy) s; } else { // if the strategy doesn't care about path, provide the // default one strategy = new DefaultPathBasedStrategy(s); } } catch (final Exception e) { throw new IllegalArgumentException("Failed loading: " + strategyClass, e); } players.add(new Player(playerName, strategy, this.loadJar(strategyJar))); } return Collections.unmodifiableList(players); } /** * Load a strategy JAR file in its own class-loader, effectively isolating * the strategies from each other. * * @param strategyJar * The JAR coming from the player config. * @return The class-loader used to load the strategy jar. */ private ClassLoader loadJar(final URI strategyJar) { if (!this.strategyClassloaders.containsKey(strategyJar)) { final ClassLoader loader = URLClassLoader.newInstance(new URL[] { PlayerAssembly.uriToUrl(strategyJar) }, this.getClass().getClassLoader()); this.strategyClassloaders.put(strategyJar, loader); } return this.strategyClassloaders.get(strategyJar); } private Strategy loadStrategy(final String strategyClass, final URI strategyJar) throws Exception { if (!this.strategyInstances.containsKey(strategyClass)) { final Class<?> clz = Class.forName(strategyClass, true, this.loadJar(strategyJar)); final Strategy strategy = (Strategy) clz.newInstance(); this.strategyInstances.put(strategyClass, strategy); } return this.strategyInstances.get(strategyClass); } }
package com.datatorrent.stram.webapp; import java.io.IOException; import java.lang.reflect.Field; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.apache.commons.beanutils.BeanMap; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.webapp.NotFoundException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.Version; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.module.SimpleModule; import org.codehaus.jackson.map.ser.std.SerializerBase; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.impl.DTLoggerFactory; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.datatorrent.api.AttributeMap.Attribute; import com.datatorrent.api.DAGContext; import com.datatorrent.api.Operator; import com.datatorrent.api.Operator.InputPort; import com.datatorrent.api.Operator.OutputPort; import com.datatorrent.api.StringCodec; import com.datatorrent.api.annotation.InputPortFieldAnnotation; import com.datatorrent.api.annotation.OutputPortFieldAnnotation; import com.datatorrent.lib.util.JacksonObjectMapperProvider; import com.datatorrent.stram.StramAppContext; import com.datatorrent.stram.StramChildAgent; import com.datatorrent.stram.StreamingContainerManager; import com.datatorrent.stram.StringCodecs; import com.datatorrent.stram.codec.LogicalPlanSerializer; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta; import com.datatorrent.stram.plan.logical.LogicalPlanConfiguration; import com.datatorrent.stram.plan.logical.LogicalPlanRequest; import com.datatorrent.stram.util.OperatorBeanUtils; /** * * The web services implementation in the stram<p> * <br> * This class would ensure the the caller is authorized and then provide access to all the dag data stored * in the stram<br> * <br> * * @since 0.3.2 */ @Path(StramWebServices.PATH) public class StramWebServices { private static final Logger LOG = LoggerFactory.getLogger(StramWebServices.class); public static final String PATH = WebServices.PATH + "/" + WebServices.VERSION + "/stram"; public static final String PATH_INFO = "info"; public static final String PATH_PHYSICAL_PLAN = "physicalPlan"; public static final String PATH_PHYSICAL_PLAN_OPERATORS = PATH_PHYSICAL_PLAN + "/operators"; public static final String PATH_PHYSICAL_PLAN_STREAMS = PATH_PHYSICAL_PLAN + "/streams"; public static final String PATH_PHYSICAL_PLAN_CONTAINERS = PATH_PHYSICAL_PLAN + "/containers"; public static final String PATH_SHUTDOWN = "shutdown"; public static final String PATH_RECORDINGS = "recordings"; public static final String PATH_RECORDINGS_START = PATH_RECORDINGS + "/start"; public static final String PATH_RECORDINGS_STOP = PATH_RECORDINGS + "/stop"; public static final String PATH_LOGICAL_PLAN = "logicalPlan"; public static final String PATH_LOGICAL_PLAN_OPERATORS = PATH_LOGICAL_PLAN + "/operators"; public static final String PATH_OPERATOR_CLASSES = "operatorClasses"; public static final String PATH_ALERTS = "alerts"; public static final String PATH_LOGGERS = "loggers"; //public static final String PATH_ACTION_OPERATOR_CLASSES = "actionOperatorClasses"; private final StramAppContext appCtx; @Context private HttpServletResponse httpResponse; @Inject @Nullable private StreamingContainerManager dagManager; private final OperatorDiscoverer operatorDiscoverer = new OperatorDiscoverer(); private final ObjectMapper objectMapper = new JacksonObjectMapperProvider().getContext(null); private boolean initialized = false; @Inject public StramWebServices(final StramAppContext context) { this.appCtx = context; } Boolean hasAccess(HttpServletRequest request) { String remoteUser = request.getRemoteUser(); if (remoteUser != null) { UserGroupInformation callerUGI = UserGroupInformation.createRemoteUser(remoteUser); if (callerUGI != null) { return false; } } return true; } @SuppressWarnings({"rawtypes", "unchecked"}) private void init() { //clear content type httpResponse.setContentType(null); if (!initialized) { Map<Class<?>, Class<? extends StringCodec<?>>> codecs = dagManager.getApplicationAttributes().get(DAGContext.STRING_CODECS); if (codecs != null) { StringCodecs.loadConverters(codecs); SimpleModule sm = new SimpleModule("DTSerializationModule", new Version(1, 0, 0, null)); for (Map.Entry<Class<?>, Class<? extends StringCodec<?>>> entry : codecs.entrySet()) { try { final StringCodec<Object> codec = (StringCodec<Object>)entry.getValue().newInstance(); sm.addSerializer(new SerializerBase(entry.getKey()) { @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(codec.toString(value)); } }); } catch (Exception ex) { LOG.error("Caught exception when instantiating codec for class {}", entry.getKey().getName(), ex); } } objectMapper.registerModule(sm); } initialized = true; } } void checkAccess(HttpServletRequest request) { if (!hasAccess(request)) { throw new SecurityException(); } } @GET @Produces(MediaType.APPLICATION_JSON) public JSONObject get() throws Exception { return getAppInfo(); } @GET @Path(PATH_INFO) @Produces(MediaType.APPLICATION_JSON) public JSONObject getAppInfo() throws Exception { init(); return new JSONObject(objectMapper.writeValueAsString(new AppInfo(this.appCtx))); } @GET @Path(PATH_PHYSICAL_PLAN) @Produces(MediaType.APPLICATION_JSON) public JSONObject getPhysicalPlan() throws Exception { Map<String, Object> result = new HashMap<String, Object>(); result.put("operators", dagManager.getOperatorInfoList()); result.put("streams", dagManager.getStreamInfoList()); return new JSONObject(objectMapper.writeValueAsString(result)); } @GET @Path(PATH_PHYSICAL_PLAN_OPERATORS) @Produces(MediaType.APPLICATION_JSON) public JSONObject getOperatorsInfo() throws Exception { init(); OperatorsInfo nodeList = new OperatorsInfo(); nodeList.operators = dagManager.getOperatorInfoList(); // To get around the nasty JAXB problem for lists return new JSONObject(objectMapper.writeValueAsString(nodeList)); } @GET @Path(PATH_PHYSICAL_PLAN_STREAMS) @Produces(MediaType.APPLICATION_JSON) public JSONObject getStreamsInfo() throws Exception { init(); StreamsInfo streamList = new StreamsInfo(); streamList.streams = dagManager.getStreamInfoList(); return new JSONObject(objectMapper.writeValueAsString(streamList)); } @GET @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId}") @Produces(MediaType.APPLICATION_JSON) public JSONObject getOperatorInfo(@PathParam("operatorId") int operatorId) throws Exception { init(); OperatorInfo oi = dagManager.getOperatorInfo(operatorId); if (oi == null) { throw new NotFoundException(); } return new JSONObject(objectMapper.writeValueAsString(oi)); } @GET @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId}/ports") @Produces(MediaType.APPLICATION_JSON) public JSONObject getPortsInfo(@PathParam("operatorId") int operatorId) throws Exception { init(); Map<String, Object> map = new HashMap<String, Object>(); OperatorInfo oi = dagManager.getOperatorInfo(operatorId); if (oi == null) { throw new NotFoundException(); } map.put("ports", oi.ports); return new JSONObject(objectMapper.writeValueAsString(map)); } @GET @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId}/ports/{portName}") @Produces(MediaType.APPLICATION_JSON) public JSONObject getPortsInfo(@PathParam("operatorId") int operatorId, @PathParam("portName") String portName) throws Exception { init(); OperatorInfo oi = dagManager.getOperatorInfo(operatorId); if (oi == null) { throw new NotFoundException(); } for (PortInfo pi : oi.ports) { if (pi.name.equals(portName)) { return new JSONObject(objectMapper.writeValueAsString(pi)); } } throw new NotFoundException(); } @GET @Path(PATH_OPERATOR_CLASSES) @Produces(MediaType.APPLICATION_JSON) public JSONObject getOperatorClasses(@QueryParam("parent") String parent) { JSONObject result = new JSONObject(); JSONArray classNames = new JSONArray(); if (parent != null) { if (parent.equals("chart")) { parent = "com.datatorrent.lib.chart.ChartOperator"; } else if (parent.equals("filter")) { parent = "com.datatorrent.lib.util.SimpleFilterOperator"; } } try { Set<Class<? extends Operator>> operatorClasses = operatorDiscoverer.getOperatorClasses(parent); for (Class<?> clazz : operatorClasses) { JSONObject j = new JSONObject(); j.put("name", clazz.getName()); classNames.put(j); } result.put("classes", classNames); } catch (ClassNotFoundException ex) { throw new NotFoundException(); } catch (JSONException ex) { } return result; } @GET @Path(PATH_OPERATOR_CLASSES + "/{className}") @Produces(MediaType.APPLICATION_JSON) public JSONObject describeOperator(@PathParam("className") String className) { if (className == null) { throw new UnsupportedOperationException(); } try { Class<?> clazz = Class.forName(className); if (OperatorDiscoverer.isInstantiableOperatorClass(clazz)) { JSONObject response = new JSONObject(); JSONArray inputPorts = new JSONArray(); JSONArray outputPorts = new JSONArray(); JSONArray properties = OperatorBeanUtils.getClassProperties(clazz, 0); Field[] fields = clazz.getFields(); Arrays.sort(fields, new Comparator<Field>() { @Override public int compare(Field a, Field b) { return a.getName().compareTo(b.getName()); } }); for (Field field : fields) { InputPortFieldAnnotation inputAnnotation = field.getAnnotation(InputPortFieldAnnotation.class); if (inputAnnotation != null) { JSONObject inputPort = new JSONObject(); inputPort.put("name", inputAnnotation.name()); inputPort.put("optional", inputAnnotation.optional()); inputPorts.put(inputPort); continue; } else if (InputPort.class.isAssignableFrom(field.getType())) { JSONObject inputPort = new JSONObject(); inputPort.put("name", field.getName()); inputPort.put("optional", false); // input port that is not annotated is default to be non-optional inputPorts.put(inputPort); continue; } OutputPortFieldAnnotation outputAnnotation = field.getAnnotation(OutputPortFieldAnnotation.class); if (outputAnnotation != null) { JSONObject outputPort = new JSONObject(); outputPort.put("name", outputAnnotation.name()); outputPort.put("optional", outputAnnotation.optional()); outputPorts.put(outputPort); //continue; } else if (OutputPort.class.isAssignableFrom(field.getType())) { JSONObject outputPort = new JSONObject(); outputPort.put("name", field.getName()); outputPort.put("optional", true); // output port that is not annotated is default to be optional outputPorts.put(outputPort); //continue; } } response.put("properties", properties); response.put("inputPorts", inputPorts); response.put("outputPorts", outputPorts); return response; } else { throw new UnsupportedOperationException(); } } catch (ClassNotFoundException ex) { throw new NotFoundException(); } catch (Exception ex) { throw new RuntimeException(ex); } } @POST // not supported by WebAppProxyServlet, can only be called directly @Path(PATH_SHUTDOWN) @Produces(MediaType.APPLICATION_JSON) public JSONObject shutdown() { LOG.debug("Shutdown requested"); dagManager.shutdownAllContainers("Shutdown requested externally."); return new JSONObject(); } @POST @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId}/" + PATH_RECORDINGS_START) @Produces(MediaType.APPLICATION_JSON) public JSONObject startRecording(@PathParam("opId") String opId) { LOG.debug("Start recording on {} requested", opId); JSONObject response = new JSONObject(); dagManager.startRecording(Integer.valueOf(opId), null); return response; } @POST @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId}/ports/{portName}/" + PATH_RECORDINGS_START) @Produces(MediaType.APPLICATION_JSON) public JSONObject startRecording(@PathParam("opId") String opId, @PathParam("portName") String portName) { LOG.debug("Start recording on {}.{} requested", opId, portName); JSONObject response = new JSONObject(); dagManager.startRecording(Integer.valueOf(opId), portName); return response; } @POST @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId}/" + PATH_RECORDINGS_STOP) @Produces(MediaType.APPLICATION_JSON) public JSONObject stopRecording(@PathParam("opId") int opId) { LOG.debug("Start recording on {} requested", opId); JSONObject response = new JSONObject(); dagManager.stopRecording(opId, null); return response; } @POST @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{opId}/ports/{portName}/" + PATH_RECORDINGS_STOP) @Produces(MediaType.APPLICATION_JSON) public JSONObject stopRecording(@PathParam("opId") int opId, @PathParam("portName") String portName) { LOG.debug("Stop recording on {}.{} requested", opId, portName); JSONObject response = new JSONObject(); dagManager.stopRecording(opId, portName); return response; } @GET @Path(PATH_PHYSICAL_PLAN_CONTAINERS) @Produces(MediaType.APPLICATION_JSON) public JSONObject listContainers(@QueryParam("states") String states) throws Exception { init(); Set<String> stateSet = null; if (states != null) { stateSet = new HashSet<String>(); stateSet.addAll(Arrays.asList(StringUtils.split(states, ','))); } ContainersInfo ci = new ContainersInfo(); for (ContainerInfo containerInfo : dagManager.getCompletedContainerInfo()) { if (stateSet == null || stateSet.contains(containerInfo.state)) { ci.add(containerInfo); } } Collection<StramChildAgent> containerAgents = dagManager.getContainerAgents(); // add itself (app master container) ContainerInfo appMasterContainerInfo = dagManager.getAppMasterContainerInfo(); if (stateSet == null || stateSet.contains(appMasterContainerInfo.state)) { ci.add(appMasterContainerInfo); } for (StramChildAgent sca : containerAgents) { ContainerInfo containerInfo = sca.getContainerInfo(); if (stateSet == null || stateSet.contains(containerInfo.state)) { ci.add(containerInfo); } } // To get around the nasty JAXB problem for lists return new JSONObject(objectMapper.writeValueAsString(ci)); } @GET @Path(PATH_PHYSICAL_PLAN_CONTAINERS + "/{containerId}") @Produces(MediaType.APPLICATION_JSON) public JSONObject getContainer(@PathParam("containerId") String containerId) throws Exception { init(); ContainerInfo ci = null; if (containerId.equals(System.getenv(ApplicationConstants.Environment.CONTAINER_ID.toString()))) { ci = dagManager.getAppMasterContainerInfo(); } else { for (ContainerInfo containerInfo : dagManager.getCompletedContainerInfo()) { if (containerInfo.id.equals(containerId)) { ci = containerInfo; } } if (ci == null) { StramChildAgent sca = dagManager.getContainerAgent(containerId); if (sca == null) { throw new NotFoundException(); } ci = sca.getContainerInfo(); } } return new JSONObject(objectMapper.writeValueAsString(ci)); } @POST // not supported by WebAppProxyServlet, can only be called directly @Path(PATH_PHYSICAL_PLAN_CONTAINERS + "/{containerId}/kill") @Produces(MediaType.APPLICATION_JSON) public JSONObject killContainer(@PathParam("containerId") String containerId) { JSONObject response = new JSONObject(); if (containerId.equals(System.getenv(ApplicationConstants.Environment.CONTAINER_ID.toString()))) { LOG.info("Received a kill request on application master container. Exiting."); new Thread() { @Override public void run() { try { Thread.sleep(3000); System.exit(1); } catch (InterruptedException ex) { LOG.info("Received interrupt, aborting exit."); } } }.start(); } else { dagManager.stopContainer(containerId); } return response; } @GET @Path(PATH_LOGICAL_PLAN_OPERATORS) @Produces(MediaType.APPLICATION_JSON) public JSONObject getLogicalOperators() throws Exception { LogicalOperatorsInfo nodeList = new LogicalOperatorsInfo(); nodeList.operators = dagManager.getLogicalOperatorInfoList(); return new JSONObject(objectMapper.writeValueAsString(nodeList)); } @GET @Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}") @Produces(MediaType.APPLICATION_JSON) public JSONObject getLogicalOperator(@PathParam("operatorName") String operatorName) throws Exception { OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new NotFoundException(); } LogicalOperatorInfo logicalOperatorInfo = dagManager.getLogicalOperatorInfo(operatorName); return new JSONObject(objectMapper.writeValueAsString(logicalOperatorInfo)); } @POST // not supported by WebAppProxyServlet, can only be called directly @Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JSONObject setOperatorProperties(JSONObject request, @PathParam("operatorName") String operatorName) { init(); OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new NotFoundException(); } JSONObject response = new JSONObject(); try { @SuppressWarnings("unchecked") Iterator<String> keys = request.keys(); while (keys.hasNext()) { String key = keys.next(); String val = request.getString(key); LOG.debug("Setting property for {}: {}={}", operatorName, key, val); dagManager.setOperatorProperty(operatorName, key, val); } } catch (JSONException ex) { LOG.warn("Got JSON Exception: ", ex); } catch (Exception ex) { LOG.error("Caught exception: ", ex); throw new RuntimeException(ex); } return response; } @POST // not supported by WebAppProxyServlet, can only be called directly @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId}/properties") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JSONObject setPhysicalOperatorProperties(JSONObject request, @PathParam("operatorId") int operatorId) { init(); JSONObject response = new JSONObject(); try { @SuppressWarnings("unchecked") Iterator<String> keys = request.keys(); while (keys.hasNext()) { String key = keys.next(); String val = request.getString(key); dagManager.setPhysicalOperatorProperty(operatorId, key, val); } } catch (JSONException ex) { LOG.warn("Got JSON Exception: ", ex); } return response; } @GET @Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/attributes") @Produces(MediaType.APPLICATION_JSON) public JSONObject getOperatorAttributes(@PathParam("operatorName") String operatorName, @QueryParam("attributeName") String attributeName) { OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new NotFoundException(); } HashMap<String, Object> map = new HashMap<String, Object>(); for (Entry<Attribute<?>, Object> entry : dagManager.getOperatorAttributes(operatorName).entrySet()) { if (attributeName == null || entry.getKey().name.equals(attributeName)) { map.put(entry.getKey().name, entry.getValue()); } } return new JSONObject(map); } @GET @Path(PATH_LOGICAL_PLAN + "/attributes") @Produces(MediaType.APPLICATION_JSON) public JSONObject getApplicationAttributes(@QueryParam("attributeName") String attributeName) { HashMap<String, Object> map = new HashMap<String, Object>(); for (Entry<Attribute<?>, Object> entry : dagManager.getApplicationAttributes().entrySet()) { if (attributeName == null || entry.getKey().name.equals(attributeName)) { map.put(entry.getKey().name, entry.getValue()); } } return new JSONObject(map); } @GET @Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/{portName}/attributes") @Produces(MediaType.APPLICATION_JSON) public JSONObject getPortAttributes(@PathParam("operatorName") String operatorName, @PathParam("portName") String portName, @QueryParam("attributeName") String attributeName) { OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new NotFoundException(); } HashMap<String, Object> map = new HashMap<String, Object>(); for (Entry<Attribute<?>, Object> entry : dagManager.getPortAttributes(operatorName, portName).entrySet()) { if (attributeName == null || entry.getKey().name.equals(attributeName)) { map.put(entry.getKey().name, entry.getValue()); } } return new JSONObject(map); } @GET @Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/properties") @Produces(MediaType.APPLICATION_JSON) public JSONObject getOperatorProperties(@PathParam("operatorName") String operatorName, @QueryParam("propertyName") String propertyName) throws IOException, JSONException { init(); OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName); if (logicalOperator == null) { throw new NotFoundException(); } BeanMap operatorProperties = LogicalPlanConfiguration.getOperatorProperties(logicalOperator.getOperator()); Map<String, Object> m = new HashMap<String, Object>(); @SuppressWarnings("rawtypes") Iterator entryIterator = operatorProperties.entryIterator(); while (entryIterator.hasNext()) { try { @SuppressWarnings("unchecked") Map.Entry<String, Object> entry = (Map.Entry<String, Object>)entryIterator.next(); if (propertyName == null) { m.put(entry.getKey(), entry.getValue()); } else if (propertyName.equals(entry.getKey())) { m.put(entry.getKey(), entry.getValue()); break; } } catch (Exception ex) { LOG.warn("Caught exception", ex); } } return new JSONObject(objectMapper.writeValueAsString(m)); } @GET @Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId}/properties") @Produces(MediaType.APPLICATION_JSON) public JSONObject getPhysicalOperatorProperties(@PathParam("operatorId") int operatorId, @QueryParam("propertyName") String propertyName) { Map<String, Object> m = dagManager.getPhysicalOperatorProperty(operatorId); try { if (propertyName == null) { return new JSONObject(new ObjectMapper().writeValueAsString(m)); } else { Map<String, Object> m1 = new HashMap<String, Object>(); m1.put(propertyName, m.get(propertyName)); return new JSONObject(new ObjectMapper().writeValueAsString(m1)); } } catch (Exception ex) { LOG.warn("Caught exception", ex); throw new RuntimeException(ex); } } @GET @Path(PATH_LOGICAL_PLAN) @Produces(MediaType.APPLICATION_JSON) public JSONObject getLogicalPlan() throws JSONException, IOException { LogicalPlan lp = dagManager.getLogicalPlan(); return new JSONObject(objectMapper.writeValueAsString(LogicalPlanSerializer.convertToMap(lp))); } @POST // not supported by WebAppProxyServlet, can only be called directly @Path(PATH_LOGICAL_PLAN) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JSONObject logicalPlanModification(JSONObject request) { JSONObject response = new JSONObject(); try { JSONArray jsonArray = request.getJSONArray("requests"); List<LogicalPlanRequest> requests = new ArrayList<LogicalPlanRequest>(); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObj = (JSONObject)jsonArray.get(i); LogicalPlanRequest requestObj = (LogicalPlanRequest)Class.forName(LogicalPlanRequest.class.getPackage().getName() + "." + jsonObj.getString("requestType")).newInstance(); @SuppressWarnings("unchecked") Map<String, Object> properties = BeanUtils.describe(requestObj); @SuppressWarnings("unchecked") Iterator<String> keys = jsonObj.keys(); while (keys.hasNext()) { String key = keys.next(); if (!key.equals("requestType")) { properties.put(key, jsonObj.get(key)); } } BeanUtils.populate(requestObj, properties); requests.add(requestObj); } Future<?> fr = dagManager.logicalPlanModification(requests); fr.get(3000, TimeUnit.MILLISECONDS); } catch (Exception ex) { LOG.error("Error processing plan change", ex); try { if (ex instanceof ExecutionException) { response.put("error", ex.getCause().toString()); } else { response.put("error", ex.toString()); } } catch (Exception e) { // ignore } } return response; } @PUT @Path(PATH_ALERTS + "/{name}") @Produces(MediaType.APPLICATION_JSON) public Object createAlert(String content, @PathParam("name") String name) throws JSONException, IOException { return dagManager.getAlertsManager().createAlert(name, content); } @DELETE @Path(PATH_ALERTS + "/{name}") @Produces(MediaType.APPLICATION_JSON) public Object deleteAlert(@PathParam("name") String name) throws JSONException, IOException { return dagManager.getAlertsManager().deleteAlert(name); } @GET @Path(PATH_ALERTS + "/{name}") @Produces(MediaType.APPLICATION_JSON) public Object getAlert(@PathParam("name") String name) throws JSONException, IOException { JSONObject alert = dagManager.getAlertsManager().getAlert(name); if (alert == null) { throw new NotFoundException(); } return alert; } @GET @Path(PATH_ALERTS) @Produces(MediaType.APPLICATION_JSON) public Object listAlerts() throws JSONException, IOException { return dagManager.getAlertsManager().listAlerts(); } /* @GET @Path(PATH_ACTION_OPERATOR_CLASSES) @Produces(MediaType.APPLICATION_JSON) public Object listActionOperatorClasses(@PathParam("appId") String appId) throws JSONException { JSONObject response = new JSONObject(); JSONArray jsonArray = new JSONArray(); List<Class<? extends Operator>> operatorClasses = operatorDiscoverer.getActionOperatorClasses(); for (Class<? extends Operator> clazz : operatorClasses) { jsonArray.put(clazz.getName()); } response.put("classes", jsonArray); return response; } */ @POST @Path(PATH_LOGGERS) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JSONObject setLoggersLevel(JSONObject request) { init(); JSONObject response = new JSONObject(); Map<String, String> targetChanges = Maps.newHashMap(); try { @SuppressWarnings("unchecked") JSONArray loggerArray = request.getJSONArray("loggers"); for (int i = 0; i < loggerArray.length(); i++) { JSONObject loggerNode = loggerArray.getJSONObject(i); String target = loggerNode.getString("target"); String level = loggerNode.getString("logLevel"); LOG.debug("change logger level for {} to {}", target, level); targetChanges.put(target, level); } if (!targetChanges.isEmpty()) { dagManager.setLoggersLevel(Collections.unmodifiableMap(targetChanges)); //Changing the levels on Stram after sending the message to all containers. DTLoggerFactory.get().changeLoggersLevel(targetChanges); } } catch (JSONException ex) { LOG.warn("Got JSON Exception: ", ex); } return response; } @GET @Path(PATH_LOGGERS + "/search") @Produces(MediaType.APPLICATION_JSON) public JSONObject searchLoggersLevel(@QueryParam("pattern") String pattern) { init(); JSONObject response = new JSONObject(); JSONArray loggersArray = new JSONArray(); try { if (pattern != null) { Map<String, String> matches = DTLoggerFactory.get().getClassesMatching(pattern); for (Entry<String, String> match : matches.entrySet()) { JSONObject node = new JSONObject(); node.put("name", match.getKey()); node.put("level", match.getValue()); loggersArray.put(node); } } response.put("matches", loggersArray); } catch (JSONException ex) { LOG.warn("Got JSON Exception: ", ex); } return response; } }
package k2b6s9j.BoatCraft.render; import k2b6s9j.BoatCraft.entity.boat.EntityCustomBoat; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelBoat; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; public class RenderBoat extends Render implements IItemRenderer { private static ResourceLocation texture; /** instance of ModelBoat for rendering */ protected ModelBase modelBoat; protected final RenderBlocks field_94145_f; public RenderBoat () { this.shadowSize = 0.5F; this.modelBoat = new ModelBoat(); this.field_94145_f = new RenderBlocks(); } public void renderBoat(EntityCustomBoat boat, double par2, double par4, double par6, float par8, float par9) { GL11.glPushMatrix(); GL11.glTranslatef((float)par2, (float)par4, (float)par6); GL11.glRotatef(180.0F - par8, 0.0F, 1.0F, 0.0F); float f2 = (float)boat.getTimeSinceHit() - par9; float f3 = boat.getDamageTaken() - par9; if (f3 < 0.0F) { f3 = 0.0F; } if (f2 > 0.0F) { GL11.glRotatef(MathHelper.sin(f2) * f2 * f3 / 10.0F * (float)boat.getForwardDirection(), 1.0F, 0.0F, 0.0F); } int j = boat.getDisplayTileOffset(); Block block = boat.getDisplayTile(); int k = boat.getDisplayTileData(); if (block != null) { GL11.glPushMatrix(); this.func_110776_a(TextureMap.field_110575_b); float f8 = 0.75F; GL11.glScalef(f8, f8, f8); GL11.glTranslatef(0.0F, (float)j / 16.0F, 0.0F); this.renderBlockInBoat(boat, par9, block, k); GL11.glPopMatrix(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.func_110777_b(boat); } float f4 = 0.75F; GL11.glScalef(f4, f4, f4); GL11.glScalef(1.0F / f4, 1.0F / f4, 1.0F / f4); this.func_110777_b(boat); GL11.glScalef(-1.0F, -1.0F, 1.0F); this.modelBoat.render(boat, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F); GL11.glPopMatrix(); } /** * Renders the block that is inside the boat. */ protected void renderBlockInBoat(EntityCustomBoat boat, float par2, Block par3Block, int par4) { float f1 = boat.getBrightness(par2); GL11.glPushMatrix(); this.field_94145_f.renderBlockAsItem(par3Block, par4, f1); GL11.glPopMatrix(); } protected ResourceLocation func_110781_a(Entity par1Entity) { return getTexture(); } protected ResourceLocation func_110775_a(Entity par1Entity) { return this.func_110781_a((Entity)par1Entity); } @Override public void doRender(Entity entity, double d0, double d1, double d2, float f, float f1) { this.renderBoat((EntityCustomBoat)entity, d0, d1, d2, f, f1); } @Override protected ResourceLocation getEntityTexture(Entity entity) { return null; } @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { switch (type) { case EQUIPPED_FIRST_PERSON: return true; case EQUIPPED: return true; case INVENTORY: return false; //For now... Until I find a way. case ENTITY: return true; default: return false; } } @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return false; } @Override public void renderItem(ItemRenderType type, ItemStack item, Object ... var3) { switch (type) { default: GL11.glPushMatrix(); Minecraft.getMinecraft().renderEngine.func_110577_a(func_110781_a(getEntity())); float defaultScale = 1F; GL11.glScalef(defaultScale, defaultScale, defaultScale); GL11.glRotatef(90, -1, 0, 0); GL11.glRotatef(90, 0, 0, 1); GL11.glRotatef(180, 0, 1, 0); GL11.glRotatef(90, 1, 0, 0); GL11.glTranslatef(-0.1F, -0.5F, 0F); // Left-Right // Forward-Backwards Up-Down modelBoat.render(getEntity(), 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.05F); GL11.glPopMatrix(); } } public ResourceLocation getTexture() { return new ResourceLocation("textures/entity/boat.png"); } public EntityCustomBoat getEntity() { EntityCustomBoat entity = null; return entity; } }
package main.java.com.bag.client; import bftsmart.communication.client.ReplyReceiver; import bftsmart.tom.ServiceProxy; import bftsmart.tom.core.messages.TOMMessage; import bftsmart.tom.core.messages.TOMMessageType; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; import main.java.com.bag.operations.CreateOperation; import main.java.com.bag.operations.DeleteOperation; import main.java.com.bag.operations.IOperation; import main.java.com.bag.operations.UpdateOperation; import main.java.com.bag.util.*; import main.java.com.bag.util.storage.NodeStorage; import main.java.com.bag.util.storage.RelationshipStorage; import org.jetbrains.annotations.NotNull; import java.io.Closeable; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Class handling the client. */ public class TestClient extends ServiceProxy implements BAGClient, ReplyReceiver, Closeable, AutoCloseable { /** * Should the transaction runNetty in secure mode? */ private boolean secureMode = true; /** * The place the local config file is. This + the cluster id will contain the concrete cluster config location. */ private static final String LOCAL_CONFIG_LOCATION = "local%d/config"; /** * The place the global config files is. */ private static final String GLOBAL_CONFIG_LOCATION = "global/config"; /** * Sets to log reads, updates, deletes and node creations. */ private ArrayList<NodeStorage> readsSetNode; private ArrayList<RelationshipStorage> readsSetRelationship; private ArrayList<IOperation> writeSet; /** * Local timestamp of the current transaction. */ private long localTimestamp = -1; /** * The id of the local server process the client is communicating with. */ private final int serverProcess; /** * Lock object to let the thread wait for a read return. */ private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>(); /** * The last object in read queue. */ public static final Object FINISHED_READING = new Object(); /** * Id of the local cluster. */ private final int localClusterId; /** * Checks if its the first read of the client. */ private boolean firstRead = true; /** * The proxy to use during communication with the globalCluster. */ private ServiceProxy globalProxy; /** * Create a threadsafe version of kryo. */ private KryoFactory factory = () -> { Kryo kryo = new Kryo(); kryo.register(NodeStorage.class, 100); kryo.register(RelationshipStorage.class, 200); kryo.register(CreateOperation.class, 250); kryo.register(DeleteOperation.class, 300); kryo.register(UpdateOperation.class, 350); return kryo; }; public TestClient(final int processId, final int serverId, final int localClusterId) { super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId)); if(localClusterId != -1) { globalProxy = new ServiceProxy(100 + getProcessId(), "global/config"); } secureMode = true; this.serverProcess = serverId; this.localClusterId = localClusterId; initClient(); System.out.println("Starting client " + processId); } /** * Initiates the client maps and registers necessary operations. */ private void initClient() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Get the blocking queue. * @return the queue. */ @Override public BlockingQueue<Object> getReadQueue() { return readQueue; } /** * write requests. (Only reach database on commit) */ @Override public void write(final Object identifier, final Object value) { if(identifier == null && value == null) { Log.getLogger().warn("Unsupported write operation"); return; } //Must be a create request. if(identifier == null) { handleCreateRequest(value); return; } //Must be a delete request. if(value == null) { handleDeleteRequest(identifier); return; } handleUpdateRequest(identifier, value); } /** * Fills the updateSet in the case of an update request. * @param identifier the value to write to. * @param value what should be written. */ private void handleUpdateRequest(Object identifier, Object value) { //todo edit create request if equal. if(identifier instanceof NodeStorage && value instanceof NodeStorage) { writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value)); } else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage) { writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value)); } else { Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa"); } } /** * Fills the createSet in the case of a create request. * @param value object to fill in the createSet. */ private void handleCreateRequest(Object value) { if(value instanceof NodeStorage) { writeSet.add(new CreateOperation<>((NodeStorage) value)); } else if(value instanceof RelationshipStorage) { readsSetNode.add(((RelationshipStorage) value).getStartNode()); readsSetNode.add(((RelationshipStorage) value).getEndNode()); writeSet.add(new CreateOperation<>((RelationshipStorage) value)); } } /** * Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet. * @param identifier the object to delete. */ private void handleDeleteRequest(Object identifier) { //todo we can delete creates here. if(identifier instanceof NodeStorage) { writeSet.add(new DeleteOperation<>((NodeStorage) identifier)); } else if(identifier instanceof RelationshipStorage) { writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier)); } } /** * ReadRequests.(Directly read database) send the request to the db. * @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage */ @Override public void read(final Object...identifiers) { long timeStampToSend = firstRead ? -1 : localTimestamp; for(final Object identifier: identifiers) { if (identifier instanceof NodeStorage) { //this sends the message straight to server 0 not to the others. sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else if (identifier instanceof RelationshipStorage) { sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST); } else { Log.getLogger().warn("Unsupported identifier: " + identifier.toString()); } } firstRead = false; } /** * Receiving read requests replies here * @param reply the received message. */ @Override public void replyReceived(final TOMMessage reply) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); Log.getLogger().info("reply"); if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST) { final Input input = new Input(reply.getContent()); switch(kryo.readObject(input, String.class)) { case Constants.READ_MESSAGE: processReadReturn(input); break; case Constants.GET_PRIMARY: case Constants.COMMIT_RESPONSE: Log.getLogger().warn("Read only Commit return"); super.replyReceived(reply); break; default: Log.getLogger().info("Unexpected message type!"); break; } input.close(); } else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST) { Log.getLogger().warn("Commit return" + reply.getReqType().name()); processCommitReturn(reply.getContent()); } else { Log.getLogger().info("Receiving other type of request." + reply.getReqType().name()); } super.replyReceived(reply); } /** * Processes the return of a read request. Filling the readsets. * @param input the received bytes in an input.. */ private void processReadReturn(final Input input) { if(input == null) { Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!"); return; } final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final String result = kryo.readObject(input, String.class); this.localTimestamp = kryo.readObject(input, Long.class); if(Constants.ABORT.equals(result)) { input.close(); pool.release(kryo); resetSets(); readQueue.add(FINISHED_READING); return; } final List nodes = kryo.readObject(input, ArrayList.class); final List relationships = kryo.readObject(input, ArrayList.class); if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage) { for (NodeStorage storage : (ArrayList<NodeStorage>) nodes) { NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties()); try { tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for node", e); } readsSetNode.add(tempStorage); } } if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage) { for (RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships) { RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode()); try { tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage)); } catch (NoSuchAlgorithmException e) { Log.getLogger().warn("Couldn't add hash for relationship", e); } readsSetRelationship.add(tempStorage); } } readQueue.add(FINISHED_READING); input.close(); pool.release(kryo); } private void processCommitReturn(final byte[] result) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); if(result == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return; } final Input input = new Input(result); final String type = kryo.readObject(input, String.class); if(!Constants.COMMIT_RESPONSE.equals(type)) { Log.getLogger().warn("Incorrect response to commit message"); input.close(); return; } final String decision = kryo.readObject(input, String.class); localTimestamp = kryo.readObject(input, Long.class); if(Constants.COMMIT.equals(decision)) { Log.getLogger().info("Transaction succesfully committed"); } else { Log.getLogger().info("Transaction commit denied - transaction being aborted"); } Log.getLogger().warn("Reset after commit"); resetSets(); input.close(); pool.release(kryo); } /** * Commit reaches the server, if secure commit send to all, else only send to one */ @Override public void commit() { firstRead = true; final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final boolean readOnly = isReadOnly(); Log.getLogger().info("Starting commit"); if (readOnly && !secureMode) { Log.getLogger().warn(String.format("Read only unsecure Transaction with local transaction id: %d successfully committed", localTimestamp)); firstRead = true; resetSets(); return; } Log.getLogger().warn("Starting commit process for: " + this.localTimestamp); final byte[] bytes = serializeAll(); if (readOnly) { Log.getLogger().warn("Commit with snapshotId: " + this.localTimestamp); final byte[] answer = localClusterId == -1 ? this.invokeUnordered(bytes) : this.invokeUnordered(bytes); final Input input = new Input(answer); Log.getLogger().warn("Committed with snapshotId " + this.localTimestamp); final String messageType = kryo.readObject(input, String.class); if (!Constants.COMMIT_RESPONSE.equals(messageType)) { Log.getLogger().warn("Incorrect response type to client from server!" + getProcessId()); resetSets(); firstRead = true; return; } final boolean commit = Constants.COMMIT.equals(kryo.readObject(input, String.class)); if (commit) { localTimestamp = kryo.readObject(input, Long.class); resetSets(); firstRead = true; Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp)); return; } Log.getLogger().info(String.format("Read-only Transaction with local transaction id: %d resend to the server", localTimestamp)); } if (localClusterId == -1) { Log.getLogger().info("Distribute commit with snapshotId: " + this.localTimestamp); invokeOrdered(bytes); } else { Log.getLogger().warn("Commit with snapshotId directly to global cluster. TimestampId: " + this.localTimestamp); Log.getLogger().warn("WriteSet: " + writeSet.size() + " readSetNode: " + readsSetNode.size() + " readSetRs: " + readsSetRelationship.size()); processCommitReturn(globalProxy.invokeOrdered(bytes)); } } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String request) { KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); Kryo kryo = pool.borrow(); Output output = new Output(0, 256); kryo.writeObject(output, request); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes the data and returns it in byte format. * @return the data in byte format. */ private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args) { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final Output output = new Output(0, 100024); kryo.writeObject(output, reason); kryo.writeObject(output, localTimestamp); for(final Object identifier: args) { if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage) { kryo.writeObject(output, identifier); } } byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Serializes all sets and returns it in byte format. * @return the data in byte format. */ private byte[] serializeAll() { final KryoPool pool = new KryoPool.Builder(factory).softReferences().build(); final Kryo kryo = pool.borrow(); final Output output = new Output(0, 400024); kryo.writeObject(output, Constants.COMMIT_MESSAGE); //Write the timeStamp to the server kryo.writeObject(output, localTimestamp); //Write the readSet. kryo.writeObject(output, readsSetNode); kryo.writeObject(output, readsSetRelationship); //Write the writeSet. kryo.writeObject(output, writeSet); byte[] bytes = output.getBuffer(); output.close(); pool.release(kryo); return bytes; } /** * Resets all the read and write sets. */ private void resetSets() { readsSetNode = new ArrayList<>(); readsSetRelationship = new ArrayList<>(); writeSet = new ArrayList<>(); } /** * Checks if the transaction has made any changes to the update sets. * @return true if not. */ private boolean isReadOnly() { return writeSet.isEmpty(); } /** * Get the primary of the cluster. * @param kryo the kryo instance. * @return the primary id. */ private int getPrimary(final Kryo kryo) { byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST); if(response == null) { Log.getLogger().warn("Server returned null, something went incredibly wrong there"); return -1; } final Input input = new Input(response); kryo.readObject(input, String.class); final int primaryId = kryo.readObject(input, Integer.class); Log.getLogger().info("Received id: " + primaryId); input.close(); return primaryId; } }
package modtweaker.mods.chisel; import static modtweaker.helpers.InputHelper.toStack; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import minetweaker.api.item.IItemStack; import com.cricketcraft.chisel.api.carving.CarvingUtils; import com.cricketcraft.chisel.api.carving.ICarvingGroup; import com.cricketcraft.chisel.api.carving.ICarvingVariation; public class ChiselHelper { public static ICarvingGroup getGroup(String name) { return CarvingUtils.getChiselRegistry().getGroup(name); } public static ICarvingGroup getGroup(IItemStack stack) { return CarvingUtils.getChiselRegistry().getGroup(Block.getBlockFromItem(toStack(stack).getItem()), stack.getDamage()); } public static ICarvingVariation getVariation(IItemStack stack) { ICarvingGroup g = getGroup(stack); if (g != null) { for (ICarvingVariation v : g.getVariations()) { if (v.getBlock() == Block.getBlockFromItem(toStack(stack).getItem()) && v.getBlockMeta() == stack.getDamage()) { return v; } } } return null; } public static ICarvingVariation makeVariation(IItemStack stack) { return new CarvingVariation(Block.getBlockFromItem(toStack(stack).getItem()), stack.getDamage()); } public static boolean groupContainsVariation(ICarvingGroup group, ICarvingVariation variation) { for(ICarvingVariation otherVariation : group.getVariations()) { if(otherVariation.getBlock()==variation.getBlock() && otherVariation.getBlockMeta()==variation.getBlockMeta()) return true; } return false; } static class CarvingVariation implements ICarvingVariation { Block block; int meta; public CarvingVariation(Block block, int meta) { this.block=block; this.meta=meta; } @Override public Block getBlock() { return block; } @Override public int getBlockMeta() { return meta; } @Override public int getItemMeta() { return meta; } @Override public int getOrder() { return 99; } } }
package modtweaker.mods.imc.handler; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Scanner; import cpw.mods.fml.common.event.FMLInterModComms; public class Message { public static String destination; public File[] files; public Scanner fileReader; public Message(String destination) { this.destination = destination; files = new File(destination).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.toLowerCase().endsWith(".imc")) { return true; } return false; } }); try { for (File file : files) { this.fileReader = new Scanner(file); while (fileReader.hasNextLine()) { String command = fileReader.nextLine().trim(); if (command.toLowerCase().startsWith("sendimc(") && command.substring(command.length() - 1).equals(";")) { command = command.substring("sendimc(".length()).replace(command.substring(command.length() - 1), "").replace(command.substring(command.length() - 1), "").replaceAll("\"", ""); String[] input = command.split(","); FMLInterModComms.sendMessage(input[0], input[1], input[2]); System.out.println(input[0] + ", " + input[1] + ", " + input[2]); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
package net.pixelcop.sewer.util; import java.util.concurrent.ArrayBlockingQueue; import net.pixelcop.sewer.Event; import net.pixelcop.sewer.Sink; /** * Helper for adding batch append capabilities to a {@link Sink} * * @author chetan * */ public class BatchHelper { private final ArrayBlockingQueue<Event> batch; public BatchHelper(int batchSize) { batch = new ArrayBlockingQueue<Event>(batchSize); } /** * Add the given event to the queue, if there is room. * * @param event * @return true if room was available, else false */ public boolean append(Event event) { return batch.offer(event); } public boolean isEmpty() { return batch.isEmpty(); } /** * Retrieves the current batch as an array and clears the queue * * @return */ public Event[] getBatch() { Event[] b = (Event[]) batch.toArray(); batch.clear(); return b; } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.io.File; import java.net.URI; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import nl.mpi.arbil.XsdChecker; import nl.mpi.arbil.data.ImdiLoader; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.gedcomimport.GedcomImporter; public class GedcomImportPanel extends JPanel { private EntityCollection entityCollection; private JTabbedPane jTabbedPane1; public GedcomImportPanel(EntityCollection entityCollectionLocal, JTabbedPane jTabbedPaneLocal) { jTabbedPane1 = jTabbedPaneLocal; entityCollection = entityCollectionLocal; // private ImdiTree leftTree; //// private GraphPanel graphPanel; //// private JungGraph jungGraph; // private ImdiTable previewTable; // private ImdiTableModel imdiTableModel; // private DragTransferHandler dragTransferHandler; } public void startImport(File importFile) { startImport(importFile, null); } public void startImport(String importFileString) { startImport(null, importFileString); } public void startImport(final File importFile, final String importFileString) { new Thread() { @Override public void run() { JTextArea importTextArea = new JTextArea(); JScrollPane importScrollPane = new JScrollPane(importTextArea); GedcomImportPanel.this.setLayout(new BorderLayout()); GedcomImportPanel.this.add(importScrollPane, BorderLayout.CENTER); jTabbedPane1.add("Import", GedcomImportPanel.this); jTabbedPane1.setSelectedComponent(GedcomImportPanel.this); JProgressBar progressBar = new JProgressBar(0, 100); GedcomImportPanel.this.add(progressBar, BorderLayout.PAGE_END); progressBar.setVisible(true); GedcomImporter gedcomImporter = new GedcomImporter(); gedcomImporter.setProgressBar(progressBar); URI[] treeNodesArray; if (importFileString != null) { treeNodesArray = gedcomImporter.importTestFile(importTextArea, importFileString); } else { treeNodesArray = gedcomImporter.importTestFile(importTextArea, importFile); } progressBar.setVisible(false); if (treeNodesArray != null) { // ArrayList<ImdiTreeObject> tempArray = new ArrayList<ImdiTreeObject>(); for (URI currentNodeUri : treeNodesArray) { // try { // ImdiTreeObject currentImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentNodeString)); // tempArray.add(currentImdiObject); // JTextPane fileText = new JTextPane(); XsdChecker xsdChecker = new XsdChecker(); if (xsdChecker.simpleCheck(new File(currentNodeUri), currentNodeUri) != null) { jTabbedPane1.add("XSD Error on Import", xsdChecker); xsdChecker.checkXML(ImdiLoader.getSingleInstance().getImdiObject(null, currentNodeUri)); xsdChecker.setDividerLocation(0.5); } // currentImdiObject.reloadNode(); // try { // fileText.setPage(currentNodeString); // } catch (IOException iOException) { // fileText.setText(iOException.getMessage()); // jTabbedPane1.add("ImportedFile", fileText); // } catch (URISyntaxException exception) { // GuiHelper.linorgBugCatcher.logError(exception); // todo: possibly create a new diagram with a sample of the imported entities for the user } // todo: it might be more efficient to only update the new files entityCollection.createDatabase(); // leftTree.rootNodeChildren = tempArray.toArray(new ImdiTreeObject[]{}); // imdiTableModel.removeAllImdiRows(); // imdiTableModel.addImdiObjects(leftTree.rootNodeChildren); } // leftTree.requestResort(); // GraphData graphData = new GraphData(); // graphData.readData(); // graphPanel.drawNodes(graphData); } }.start(); } }