answer
stringlengths
17
10.2M
package org.duracloud.security.vote; import org.duracloud.client.ContentStore; import org.duracloud.error.ContentStoreException; import static org.duracloud.security.vote.VoterUtil.debugText; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.Authentication; import org.springframework.security.ConfigAttribute; import org.springframework.security.ConfigAttributeDefinition; import org.springframework.security.intercept.web.FilterInvocation; import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken; import org.springframework.security.vote.AccessDecisionVoter; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; public abstract class SpaceAccessVoter implements AccessDecisionVoter { private final Logger log = LoggerFactory.getLogger(getClass()); private Map<String, ContentStore.AccessType> spaceCache = new HashMap<String, ContentStore.AccessType>(); /** * This method checks the access state of the arg resource * (space and provider) and makes denies access to anonymous principals if * the space is closed. * * @param auth principal seeking AuthZ * @param resource that is under protection * @param config access-attributes defined on resource * @return vote (AccessDecisionVoter.ACCESS_GRANTED, ACCESS_DENIED, ACCESS_ABSTAIN) */ public int vote(Authentication auth, Object resource, ConfigAttributeDefinition config) { String label = "SpaceAccessVoterImpl"; if (resource != null && !supports(resource.getClass())) { log.debug(debugText(label, auth, config, resource, ACCESS_ABSTAIN)); return ACCESS_ABSTAIN; } HttpServletRequest httpRequest = getHttpServletRequest(resource); if (null == httpRequest) { log.debug(debugText(label, auth, config, resource, ACCESS_DENIED)); return ACCESS_DENIED; } // If space is 'open' or 'closed' only matters if user is anonymous. if (!(auth instanceof AnonymousAuthenticationToken)) { log.debug(debugText(label, auth, config, resource, ACCESS_GRANTED)); return ACCESS_GRANTED; } ContentStore.AccessType access = getSpaceAccess(httpRequest); int grant = ACCESS_DENIED; if (access.equals(ContentStore.AccessType.OPEN)) { grant = ACCESS_GRANTED; } log.debug(debugText(label, auth, config, resource, grant)); return grant; } private ContentStore.AccessType getSpaceAccess(HttpServletRequest request) { String host = "localhost"; String port = Integer.toString(request.getLocalPort()); String storeId = getStoreId(request); String spaceId = getSpaceId(request); if (null == spaceId) { return ContentStore.AccessType.CLOSED; } if (spaceId.equals("spaces") || spaceId.equals("stores")) { return ContentStore.AccessType.OPEN; } ContentStore.AccessType access = getAccessFromCache(storeId, spaceId); if (access != null) { return access; } ContentStore store = getContentStore(host, port, storeId); if (null == store) { return ContentStore.AccessType.CLOSED; } access = ContentStore.AccessType.CLOSED; try { access = store.getSpaceAccess(spaceId); } catch (ContentStoreException e) { } return access; } private String getStoreId(HttpServletRequest httpRequest) { String storeId = null; String query = httpRequest.getQueryString(); if (null == query) { return null; } query = query.toLowerCase(); String name = "storeid"; int storeIdIndex = query.indexOf(name); if (storeIdIndex > -1) { int idIndex = query.indexOf("=", storeIdIndex) + 1; if (idIndex == storeIdIndex + name.length() + 1) { int nextParamIndex = query.indexOf("&", idIndex); int end = nextParamIndex > -1 ? nextParamIndex : query.length(); storeId = query.substring(idIndex, end); } } return storeId; } private String getSpaceId(HttpServletRequest httpRequest) { String spaceId = httpRequest.getPathInfo(); if (null == spaceId) { return null; } if (spaceId.startsWith("/")) { spaceId = spaceId.substring(1); } int slashIndex = spaceId.indexOf("/"); if (slashIndex > 0) { spaceId = spaceId.substring(0, slashIndex); } return spaceId; } private ContentStore.AccessType getAccessFromCache(String storeId, String spaceId) { // TODO: implement cache return null; } /** * This method is abstract to provide entry-point for alternate * implementations of ContentStore. */ abstract protected ContentStore getContentStore(String host, String port, String storeId); private HttpServletRequest getHttpServletRequest(Object resource) { FilterInvocation invocation = (FilterInvocation) resource; HttpServletRequest request = invocation.getHttpRequest(); if (null == request) { String msg = "null request: '" + resource + "'"; log.warn("HttpServletRequest was null! " + msg); } return request; } /** * This method always returns true because all configAttributes are able * to be handled by this voter. * * @param configAttribute any att * @return true */ public boolean supports(ConfigAttribute configAttribute) { return true; } /** * This methods returns true if the arg class is an instance of or * subclass of FilterInvocation. * No other classes can be handled by this voter. * * @param aClass to be analyized for an AuthZ vote. * @return true if is an instance of or subclass of FilterInvocation */ public boolean supports(Class aClass) { return FilterInvocation.class.isAssignableFrom(aClass); } }
package org.sejda.impl.sambox; import static java.util.Optional.ofNullable; import static org.sejda.common.ComponentsUtility.nullSafeCloseQuietly; import static org.sejda.core.notification.dsl.ApplicationEventsNotifier.notifyEvent; import static org.sejda.core.support.io.IOUtils.createTemporaryBuffer; import static org.sejda.impl.sambox.component.SignatureClipper.clipSignatures; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sejda.common.LookupTable; import org.sejda.core.support.io.OutputWriters; import org.sejda.core.support.io.SingleOutputWriter; import org.sejda.impl.sambox.component.*; import org.sejda.model.exception.TaskException; import org.sejda.model.input.FileIndexAndPage; import org.sejda.model.input.PdfSource; import org.sejda.model.input.PdfSourceOpener; import org.sejda.model.parameter.CombineReorderParameters; import org.sejda.model.task.BaseTask; import org.sejda.model.task.TaskExecutionContext; import org.sejda.sambox.pdmodel.PDPage; import org.sejda.sambox.pdmodel.PageNotFoundException; import org.sejda.sambox.pdmodel.common.PDRectangle; import org.sejda.sambox.pdmodel.interactive.annotation.PDAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * SAMBox implementation of a task that allows combining multiple pdf sources, allowing reordering of the pdf pages regardless of the ordering in the original sources. * * @author Andrea Vacondio * */ public class CombineReorderTask extends BaseTask<CombineReorderParameters> { private static final Logger LOG = LoggerFactory.getLogger(CombineReorderTask.class); private SingleOutputWriter outputWriter; private PdfSourceOpener<PDDocumentHandler> sourceOpener; private PDDocumentHandler destinationDocument; private List<PDDocumentHandler> documents = new ArrayList<>(); private Map<PDDocumentHandler, String> documentNames = new HashMap<>(); private AcroFormsMerger acroFormsMerger; private Map<PDDocumentHandler, LookupTable<PDPage>> pagesLookup = new HashMap<>(); private OutlineMerger outlineMerger; @Override public void before(CombineReorderParameters parameters, TaskExecutionContext executionContext) throws TaskException { super.before(parameters, executionContext); sourceOpener = new DefaultPdfSourceOpener(); outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext); outlineMerger = new OutlineMerger(parameters.getOutlinePolicy()); } @Override public void execute(CombineReorderParameters parameters) throws TaskException { File tmpFile = createTemporaryBuffer(parameters.getOutput()); outputWriter.taskOutput(tmpFile); LOG.debug("Temporary output set to {}", tmpFile); this.destinationDocument = new PDDocumentHandler(); this.destinationDocument.setCreatorOnPDDocument(); this.destinationDocument.setVersionOnPDDocument(parameters.getVersion()); this.destinationDocument.setCompress(parameters.isCompress()); this.acroFormsMerger = new AcroFormsMerger(parameters.getAcroFormPolicy(), this.destinationDocument.getUnderlyingPDDocument()); for (PdfSource<?> input : parameters.getSourceList()) { LOG.debug("Opening {}", input.getSource()); PDDocumentHandler sourceDocumentHandler = input.open(sourceOpener); documents.add(sourceDocumentHandler); documentNames.put(sourceDocumentHandler, input.getName()); pagesLookup.put(sourceDocumentHandler, new LookupTable<>()); } int currentStep = 0; int totalSteps = parameters.getPages().size() + documents.size(); PdfRotator rotator = new PdfRotator(destinationDocument.getUnderlyingPDDocument()); PDPage lastPage = null; for (int i = 0; i < parameters.getPages().size(); i++) { executionContext().assertTaskNotCancelled(); FileIndexAndPage filePage = parameters.getPages().get(i); int pageNum = filePage.getPage(); if (filePage.isAddBlankPage()) { PDRectangle mediaBox = PDRectangle.A4; if (lastPage != null) { mediaBox = lastPage.getMediaBox(); } destinationDocument.addBlankPage(mediaBox); } else { try { PDDocumentHandler documentHandler = documents.get(filePage.getFileIndex()); PDPage page = documentHandler.getPage(pageNum); PDPage newPage = destinationDocument.importPage(page); lastPage = newPage; pagesLookup.get(documentHandler).addLookupEntry(page, newPage); rotator.rotate(i + 1, filePage.getRotation()); } catch (PageNotFoundException e) { executionContext().assertTaskIsLenient(e); notifyEvent(executionContext().notifiableTaskMetadata()) .taskWarning(String.format("Page %d was skipped, could not be processed", pageNum), e); } } notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(++currentStep).outOf(totalSteps); } for (PDDocumentHandler document : documents) { LookupTable<PDPage> lookupTable = pagesLookup.get(document); outlineMerger.updateOutline(document.getUnderlyingPDDocument(), documentNames.get(document), lookupTable); LookupTable<PDAnnotation> annotationsLookup = new AnnotationsDistiller(document.getUnderlyingPDDocument()) .retainRelevantAnnotations(lookupTable); clipSignatures(annotationsLookup.values()); acroFormsMerger.mergeForm(document.getUnderlyingPDDocument().getDocumentCatalog().getAcroForm(), annotationsLookup); notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(++currentStep).outOf(totalSteps); } if (outlineMerger.hasOutline()) { LOG.debug("Adding generated outline"); destinationDocument.setDocumentOutline(outlineMerger.getOutline()); } ofNullable(acroFormsMerger.getForm()).filter(f -> !f.getFields().isEmpty()).ifPresent(f -> { LOG.debug("Adding generated AcroForm"); destinationDocument.setDocumentAcroForm(f); }); destinationDocument.savePDDocument(tmpFile); closeResources(); parameters.getOutput().accept(outputWriter); LOG.debug("Input documents merged correctly and written to {}", parameters.getOutput()); } @Override public void after() { closeResources(); outputWriter = null; documents.clear(); documentNames.clear(); pagesLookup.clear(); } private void closeResources() { for (PDDocumentHandler document : documents) { nullSafeCloseQuietly(document); } nullSafeCloseQuietly(destinationDocument); } }
package org.xwiki.test.rest; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.ws.rs.core.MediaType; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.util.URIUtil; import org.junit.Assert; import org.junit.Test; import org.xwiki.rest.Relations; import org.xwiki.rest.model.jaxb.Attachment; import org.xwiki.rest.model.jaxb.Attachments; import org.xwiki.rest.resources.attachments.AttachmentHistoryResource; import org.xwiki.rest.resources.attachments.AttachmentResource; import org.xwiki.rest.resources.attachments.AttachmentsAtPageVersionResource; import org.xwiki.rest.resources.attachments.AttachmentsResource; import org.xwiki.test.rest.framework.AbstractHttpTest; public class AttachmentsResourceTest extends AbstractHttpTest { private final String SPACE_NAME = "Main"; private final String PAGE_NAME = "WebHome"; private final String ADMIN_USERNAME = "Admin"; private final String ADMIN_PASSWORD = "admin"; @Override @Test public void testRepresentation() throws Exception { /* Everything is done in test methods */ } @Test public void testPUTAttachment() throws Exception { /* Test normal random UUID method */ String randomStr = String.format("%s.txt", UUID.randomUUID()); /* Test filenames requiring url encoding */ putAttachmentFilename(randomStr,"random"); putAttachmentFilename("my attach.txt","space"); putAttachmentFilename("^caret.txt","caret"); putAttachmentFilename("#pound.txt","pound"); putAttachmentFilename("%percent.txt","percent"); putAttachmentFilename("{brace}.txt","braces"); putAttachmentFilename("[bracket].txt","brackets"); /** Causes XWIKI-7874 **/ putAttachmentFilename("plus+plus.txt","plus"); } protected void putAttachmentFilename(String attachmentName, String type) throws Exception{ String content = "ATTACHMENT CONTENT"; /* Encode the filename ourselves, UriBuilder.build() doesn't seem to encode all chars. eg '[' */ String encodedAttachmentName = URIUtil.encodePath(attachmentName); String encodedPageName = URIUtil.encodePath(PAGE_NAME); String encodedSpaceName = URIUtil.encodePath(SPACE_NAME); /* Use UriBuilder.buildFromEncoded so we don't double encode the % */ String attachmentUri = getUriBuilder(AttachmentResource.class).buildFromEncoded(getWiki(), encodedSpaceName, encodedPageName, encodedAttachmentName).toString(); GetMethod getMethod = executeGet(attachmentUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_NOT_FOUND, getMethod.getStatusCode()); PutMethod putMethod = executePut(attachmentUri, content, MediaType.TEXT_PLAIN, ADMIN_USERNAME, ADMIN_PASSWORD); Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_CREATED, putMethod.getStatusCode()); getMethod = executeGet(attachmentUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Assert.assertEquals(content, getMethod.getResponseBodyAsString()); } @Test public void testPUTAttachmentNoRights() throws Exception { String attachmentName = String.format("%s.txt", UUID.randomUUID()); String content = "ATTACHMENT CONTENT"; String attachmentUri = getUriBuilder(AttachmentResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentName).toString(); GetMethod getMethod = executeGet(attachmentUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_NOT_FOUND, getMethod.getStatusCode()); PutMethod putMethod = executePut(attachmentUri, content, MediaType.TEXT_PLAIN); Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_UNAUTHORIZED, putMethod.getStatusCode()); } @Test public void testGETAttachments() throws Exception { String attachmentsUri = getUriBuilder(AttachmentsResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME).toString(); GetMethod getMethod = executeGet(attachmentsUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertTrue(attachments.getAttachments().size() > 0); } @Test public void testDELETEAttachment() throws Exception { String attachmentsUri = getUriBuilder(AttachmentsResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME).toString(); GetMethod getMethod = executeGet(attachmentsUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertTrue(attachments.getAttachments().size() > 0); String attachmentName = attachments.getAttachments().get(0).getName(); String attachmentUri = getUriBuilder(AttachmentResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentName).toString(); DeleteMethod deleteMethod = executeDelete(attachmentUri, ADMIN_USERNAME, ADMIN_PASSWORD); Assert.assertEquals(getHttpMethodInfo(deleteMethod), HttpStatus.SC_NO_CONTENT, deleteMethod.getStatusCode()); getMethod = executeGet(attachmentUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_NOT_FOUND, getMethod.getStatusCode()); } @Test public void testDELETEAttachmentNoRights() throws Exception { String attachmentName = String.format("%d.txt", System.currentTimeMillis()); String content = "ATTACHMENT CONTENT"; String attachmentUri = getUriBuilder(AttachmentResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentName).toString(); PutMethod putMethod = executePut(attachmentUri, content, MediaType.TEXT_PLAIN, ADMIN_USERNAME, ADMIN_PASSWORD); Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_CREATED, putMethod.getStatusCode()); DeleteMethod deleteMethod = executeDelete(attachmentUri); Assert.assertEquals(getHttpMethodInfo(deleteMethod), HttpStatus.SC_UNAUTHORIZED, deleteMethod.getStatusCode()); GetMethod getMethod = executeGet(attachmentUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); } @Test public void testGETAttachmentsAtPageVersion() throws Exception { final int NUMBER_OF_ATTACHMENTS = 4; String[] attachmentNames = new String[NUMBER_OF_ATTACHMENTS]; String[] pageVersions = new String[NUMBER_OF_ATTACHMENTS]; for (int i = 0; i < NUMBER_OF_ATTACHMENTS; i++) { attachmentNames[i] = String.format("%s.txt", UUID.randomUUID()); } String content = "ATTACHMENT CONTENT"; /* Create NUMBER_OF_ATTACHMENTS attachments */ for (int i = 0; i < NUMBER_OF_ATTACHMENTS; i++) { String attachmentUri = getUriBuilder(AttachmentResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentNames[i]) .toString(); PutMethod putMethod = executePut(attachmentUri, content, MediaType.TEXT_PLAIN, ADMIN_USERNAME, ADMIN_PASSWORD); Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_CREATED, putMethod.getStatusCode()); Attachment attachment = (Attachment) this.unmarshaller.unmarshal(putMethod.getResponseBodyAsStream()); pageVersions[i] = attachment.getPageVersion(); } /* * For each page version generated, check that the attachments that are supposed to be there are actually there. * We do the following: at pageVersion[i] we check that all attachmentNames[0..i] are there. */ for (int i = 0; i < NUMBER_OF_ATTACHMENTS; i++) { String attachmentsUri = getUriBuilder(AttachmentsAtPageVersionResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, pageVersions[i]).toString(); GetMethod getMethod = executeGet(attachmentsUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); /* * Check that all attachmentNames[0..i] are present in the list of attachments of page at version * pageVersions[i] */ for (int j = 0; j <= i; j++) { boolean found = false; for (Attachment attachment : attachments.getAttachments()) { if (attachment.getName().equals(attachmentNames[j])) { if (attachment.getPageVersion().equals(pageVersions[i])) { found = true; break; } } } Assert.assertTrue(String.format("%s is not present in attachments list of the page at version %s", attachmentNames[j], pageVersions[i]), found); } /* Check links */ for (Attachment attachment : attachments.getAttachments()) { checkLinks(attachment); } } } @Test public void testGETAttachmentVersions() throws Exception { final int NUMBER_OF_VERSIONS = 4; String attachmentName = String.format("%s.txt", UUID.randomUUID().toString()); Map<String, String> versionToContentMap = new HashMap<String, String>(); /* Create NUMBER_OF_ATTACHMENTS attachments */ for (int i = 0; i < NUMBER_OF_VERSIONS; i++) { String attachmentUri = getUriBuilder(AttachmentResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentName) .toString(); String content = String.format("CONTENT %d", i); PutMethod putMethod = executePut(attachmentUri, content, MediaType.TEXT_PLAIN, ADMIN_USERNAME, ADMIN_PASSWORD); if (i == 0) { Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_CREATED, putMethod.getStatusCode()); } else { Assert.assertEquals(getHttpMethodInfo(putMethod), HttpStatus.SC_ACCEPTED, putMethod.getStatusCode()); } Attachment attachment = (Attachment) this.unmarshaller.unmarshal(putMethod.getResponseBodyAsStream()); versionToContentMap.put(attachment.getVersion(), content); } String attachmentsUri = getUriBuilder(AttachmentHistoryResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentName) .toString(); GetMethod getMethod = executeGet(attachmentsUri); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Attachments attachments = (Attachments) this.unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); for (Attachment attachment : attachments.getAttachments()) { getMethod = executeGet(getFirstLinkByRelation(attachment, Relations.ATTACHMENT_DATA).getHref()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Assert.assertEquals(versionToContentMap.get(attachment.getVersion()), getMethod.getResponseBodyAsString()); } } @Test public void testPOSTAttachment() throws Exception { final String attachmentName = String.format("%s.txt", UUID.randomUUID()); final String content = "ATTACHMENT CONTENT"; String attachmentsUri = getUriBuilder(AttachmentsResource.class).build(getWiki(), SPACE_NAME, PAGE_NAME, attachmentName).toString(); HttpClient httpClient = new HttpClient(); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ADMIN_USERNAME, ADMIN_PASSWORD)); httpClient.getParams().setAuthenticationPreemptive(true); Part[] parts = new Part[1]; ByteArrayPartSource baps = new ByteArrayPartSource(attachmentName, content.getBytes()); parts[0] = new FilePart(attachmentName, baps); PostMethod postMethod = new PostMethod(attachmentsUri); MultipartRequestEntity mpre = new MultipartRequestEntity(parts, postMethod.getParams()); postMethod.setRequestEntity(mpre); httpClient.executeMethod(postMethod); Assert.assertEquals(getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); this.unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Header location = postMethod.getResponseHeader("location"); GetMethod getMethod = executeGet(location.getValue()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Assert.assertEquals(content, getMethod.getResponseBodyAsString()); } }
package org.arnolds.agileappproject.agileappmodule.ui.frags; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import org.arnolds.agileappproject.agileappmodule.R; import org.arnolds.agileappproject.agileappmodule.git.GitHubBroker; import org.arnolds.agileappproject.agileappmodule.git.GitHubBrokerListener; import org.arnolds.agileappproject.agileappmodule.ui.activities.DrawerLayoutFragmentActivity; import org.arnolds.agileappproject.agileappmodule.utils.AgileAppModuleUtils; import org.kohsuke.github.GHRepository; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class NavigationDrawerFragment extends Fragment { private static final long REPOS_POLL_RATE_SECONDS = Long.MAX_VALUE; private static int LAST_SELECTED_ITEM_INDEX = 0; private NavigationDrawerCallbacks mCallbacks; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private ListView mDrawerListView; private View mFragmentContainerView; private int latestMenuItemSelected = -1; private Spinner mRepoSelectionSpinner; private String latestSelectedRepoName = ""; private final SelectionListener selectionListener = new SelectionListener(); @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(Boolean.TRUE); } private class SelectionListener extends GitHubBrokerListener { @Override public void onRepoSelected(boolean result) { try { mCallbacks.onNewRepoSelected(latestSelectedRepoName); } catch (NullPointerException ex) { } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View ret = inflater.inflate( R.layout.fragment_navigation_drawer_layout, container, false); mDrawerListView = (ListView) ret.findViewById(R.id.navigation_drawer_list_view); mRepoSelectionSpinner = (Spinner) ret.findViewById(R.id.repo_selector_view); mRepoSelectionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { LAST_SELECTED_ITEM_INDEX = position; String repoName = mRepoSelectionSpinner.getItemAtPosition(position).toString(); if (!repoName.isEmpty() && !repoName.contentEquals(latestSelectedRepoName)) { NavigationDrawerFragment.this.latestSelectedRepoName = repoName; try { GitHubBroker.getInstance().selectRepo(repoName, selectionListener); } catch (GitHubBroker.AlreadyNotConnectedException e) { Log.wtf("debug", e.getClass().getName(), e); } catch (GitHubBroker.NullArgumentException e) { Log.wtf("debug", e.getClass().getName(), e); } mCallbacks.onStartLoad(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mRepoSelectionSpinner.setBackgroundColor(getResources().getColor(R.color.theme_white)); mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); latestMenuItemSelected = position; } }); mDrawerListView .setAdapter(new NavigationDrawerArrayAdapter()); initializeAutoUpdaterRepoSelector(mRepoSelectionSpinner); return ret; } private final void initializeAutoUpdaterRepoSelector(final Spinner selectionSpinner) { final ScheduledExecutorService reposFetchService = Executors .newScheduledThreadPool(1); reposFetchService.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (isDrawerOpen()) { return; } try { GitHubBroker.getInstance().getAllRepos(new GitHubBrokerListener() { @Override public void onAllReposRetrieved(boolean success, Collection<GHRepository> repositories) { if (success) { final List<String> allRepositories = new ArrayList<String>(); for (GHRepository repository : repositories) allRepositories.add(repository.getName()); try { final ArrayAdapter<String> adapter = new ArrayAdapter<String>( getActivity().getApplicationContext(), R.layout.repo_selector_spinner_selected_item, allRepositories); adapter.setDropDownViewResource( R.layout.repo_selector_dropdown_item); final String newSelectedRepoName = selectionSpinner.getSelectedItem() == null ? "" : selectionSpinner.getSelectedItem().toString(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { selectionSpinner.setAdapter(adapter); adapter.notifyDataSetChanged(); if (newSelectedRepoName.isEmpty()) { selectionSpinner .setSelection(LAST_SELECTED_ITEM_INDEX); } } }); } catch (NullPointerException ex) { } } } }); } catch (GitHubBroker.AlreadyNotConnectedException e) { Log.wtf("debug", e.getClass().getName(), e); } } }, 0, REPOS_POLL_RATE_SECONDS, TimeUnit.SECONDS); } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } /** * Users of this fragment must call this method to set up the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ public void setUp(int fragmentId, DrawerLayout drawerLayout) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(Boolean.TRUE); actionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( getActivity(), /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) { return; } restoreActionBar(); getActivity().invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); showGlobalContextActionBar(); } }; // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } private void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(Boolean.TRUE); actionBar.setTitle( AgileAppModuleUtils.getString(getActivity(), "title_section" + ( DrawerLayoutFragmentActivity.getLastSelectedFragmentIndex() + 1), "Home" ) ); } private void selectItem(int position) { if (mDrawerListView != null) { mDrawerListView.setItemChecked(position, true); } if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mDrawerLayout != null) { if (isDrawerOpen()) { showGlobalContextActionBar(); } } super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } /** * Per the navigation drawer design guidelines, updates the action bar to show the actionbar app * 'context', rather than just what's in the current screen. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(Boolean.TRUE); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setTitle(R.string.app_name); } private ActionBar getActionBar() { return getActivity().getActionBar(); } /** * Callbacks interface that all activities using this fragment must implement. */ public static interface NavigationDrawerCallbacks { /** * Called when an item in the navigation drawer is selected. */ void onNavigationDrawerItemSelected(int position); void onNewRepoSelected(String repoName); void onStartLoad(); } private class NavigationDrawerArrayAdapter extends BaseAdapter { private final int mResource = R.layout.list_item_navigation_drawer_list; @Override public int getCount() { Context context = getActivity().getApplicationContext(); for (int i = 1; ; i++) { if (AgileAppModuleUtils.getString(context, "title_section" + i, null) == null) { return i - 1; } } } @Override public Object getItem(int i) { int temp = i + 1; return AgileAppModuleUtils .getString(getActivity().getApplicationContext(), "title_section" + temp, ""); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(mResource, parent, false); int temp = position + 1; TextView textView = (TextView) convertView.findViewById(R.id.navigation_drawer_item_title); ImageView imageView = (ImageView) convertView.findViewById(R.id.navigation_drawer_item_icon); if (latestMenuItemSelected != -1) if (position==(DrawerLayoutFragmentActivity.getLastSelectedFragmentIndex())){ convertView.setBackgroundColor(Color.GRAY); textView.setTypeface(null, Typeface.BOLD); } textView.setText(AgileAppModuleUtils .getString(getActivity().getApplicationContext(), "title_section" + +temp, "")); imageView.setImageResource( AgileAppModuleUtils.getDrawableAsId("icon_section" + temp, -1)); return convertView; } } }
package de.sonumina.simpledance; import org.teavm.dom.canvas.CanvasRenderingContext2D; import de.sonumina.simpledance.core.graphics.Color; import de.sonumina.simpledance.core.graphics.Context; import de.sonumina.simpledance.core.graphics.Point; import de.sonumina.simpledance.core.graphics.RGB; public class CanvasContext extends Context { private CanvasRenderingContext2D context; /** * Convert the given color into a html one. * * @param color * @return */ private String htmlColor(Color color) { if (color == null) return "black"; String redString = Integer.toHexString(color.getRed() | 0x100).substring(1); String greenString = Integer.toHexString(color.getGreen() | 0x100).substring(1); String blueString = Integer.toHexString(color.getBlue() | 0x100).substring(1); return "#" + redString + greenString + blueString; } public CanvasContext(CanvasRenderingContext2D context) { this.context = context; } @Override public void putPixel(int x, int y) { // TODO Auto-generated method stub } @Override public void drawPolyline(int[] data) { if (data.length < 2) return; context.setStrokeStyle(htmlColor(foreground)); preparePolygon(data); context.stroke(); } @Override public void drawPolygon(int[] data) { if (data.length < 2) return; context.setStrokeStyle(htmlColor(foreground)); preparePolygon(data); context.closePath(); context.stroke(); } @Override public void fillPolygon(int[] data) { if (data.length < 2) return; context.setFillStyle(htmlColor(background)); preparePolygon(data); context.fill(); } private void preparePolygon(int[] data) { context.beginPath(); context.moveTo(data[0], data[1]); for (int i=2; i < data.length; i+=2) context.lineTo(data[i], data[i+1]); } @Override public void drawLine(int x0, int y0, int x1, int y1) { // TODO Auto-generated method stub } @Override public void drawOval(int x, int y, int mx, int my) { // TODO Auto-generated method stub } @Override public void drawText(String string, int x, int y, boolean transparent) { // TODO Auto-generated method stub } @Override public Point stringExtent(String string) { // TODO Implement this correctly. return new Point(1,1); } @Override public void gradientPolygon(int[] newData, RGB startRGB, RGB endRGB, int angle) { // TODO Auto-generated method stub } @Override public Color allocateColor(int r, int g, int b) { return new Color(r, g, b) { }; } @Override public void deallocateColor(Color color) { } @Override public void applyRotateTransformation(float angle) { context.rotate(angle); } @Override public void applyTranslationTransformation(float x, float y) { context.translate(x, y); } @Override public void applyScaleTransformation(float scale) { context.scale(scale, scale); } @Override public void applyScaleXTransformation(float f) { context.scale(f, 1); } @Override public void printCurrentTransform() { // TODO Auto-generated method stub } @Override public void pushCurrentTransform() { context.save(); } @Override public void popCurrentTransform() { context.restore(); } @Override public void applyTransformation(int[] sourcePointArray, int[] destPointArray) { // TODO Auto-generated method stub } }
package com.azoft.carousellayoutmanager.sample; import android.databinding.DataBindingUtil; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.azoft.carousellayoutmanager.CarouselLayoutManager; import com.azoft.carousellayoutmanager.CarouselZoomPostLayoutListener; import com.azoft.carousellayoutmanager.CenterScrollListener; import com.azoft.carousellayoutmanager.DefaultChildSelectionListener; import com.azoft.carousellayoutmanager.sample.databinding.ActivityCarouselPreviewBinding; import com.azoft.carousellayoutmanager.sample.databinding.ItemViewBinding; import java.util.Locale; import java.util.Random; public class CarouselPreviewActivity extends AppCompatActivity { @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActivityCarouselPreviewBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_carousel_preview); setSupportActionBar(binding.toolbar); final TestAdapter adapter = new TestAdapter(); // create layout manager with needed params: vertical, cycle initRecyclerView(binding.listHorizontal, new CarouselLayoutManager(CarouselLayoutManager.HORIZONTAL, false), adapter); initRecyclerView(binding.listVertical, new CarouselLayoutManager(CarouselLayoutManager.VERTICAL, true), adapter); // fab button will add element to the end of the list binding.fabScroll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { /* final int itemToRemove = adapter.mItemsCount; if (10 != itemToRemove) { adapter.mItemsCount++; adapter.notifyItemInserted(itemToRemove); } */ binding.listHorizontal.smoothScrollToPosition(adapter.getItemCount() - 2); binding.listVertical.smoothScrollToPosition(adapter.getItemCount() - 2); } }); // fab button will remove element from the end of the list binding.fabChangeData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { /* final int itemToRemove = adapter.mItemsCount - 1; if (0 <= itemToRemove) { adapter.mItemsCount--; adapter.notifyItemRemoved(itemToRemove); } */ binding.listHorizontal.smoothScrollToPosition(1); binding.listVertical.smoothScrollToPosition(1); } }); } private void initRecyclerView(final RecyclerView recyclerView, final CarouselLayoutManager layoutManager, final TestAdapter adapter) { // enable zoom effect. this line can be customized layoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener()); layoutManager.setMaxVisibleItems(2); recyclerView.setLayoutManager(layoutManager); // we expect only fixed sized item for now recyclerView.setHasFixedSize(true); // sample adapter with random data recyclerView.setAdapter(adapter); // enable center post scrolling recyclerView.addOnScrollListener(new CenterScrollListener()); // enable center post touching on item and item click listener DefaultChildSelectionListener.initCenterItemListener(new DefaultChildSelectionListener.OnCenterItemClickListener() { @Override public void onCenterItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v) { final int position = recyclerView.getChildLayoutPosition(v); final String msg = String.format(Locale.US, "Item %1$d was clicked", position); Toast.makeText(CarouselPreviewActivity.this, msg, Toast.LENGTH_SHORT).show(); } }, recyclerView, layoutManager); layoutManager.addOnItemSelectionListener(new CarouselLayoutManager.OnCenterItemSelectionListener() { @Override public void onCenterItemChanged(final int adapterPosition) { if (CarouselLayoutManager.INVALID_POSITION != adapterPosition) { final int value = adapter.mPosition[adapterPosition]; /* adapter.mPosition[adapterPosition] = (value % 10) + (value / 10 + 1) * 10; adapter.notifyItemChanged(adapterPosition); */ } } }); } private static final class TestAdapter extends RecyclerView.Adapter<TestViewHolder> { @SuppressWarnings("UnsecureRandomNumberGeneration") private final Random mRandom = new Random(); private final int[] mColors; private final int[] mPosition; private int mItemsCount = 10; TestAdapter() { mColors = new int[mItemsCount]; mPosition = new int[mItemsCount]; for (int i = 0; mItemsCount > i; ++i) { //noinspection MagicNumber mColors[i] = Color.argb(255, mRandom.nextInt(256), mRandom.nextInt(256), mRandom.nextInt(256)); mPosition[i] = i; } } @Override public TestViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) { return new TestViewHolder(ItemViewBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false)); } @Override public void onBindViewHolder(final TestViewHolder holder, final int position) { holder.mItemViewBinding.cItem1.setText(String.valueOf(mPosition[position])); holder.mItemViewBinding.cItem2.setText(String.valueOf(mPosition[position])); holder.itemView.setBackgroundColor(mColors[position]); } @Override public int getItemCount() { return mItemsCount; } } private static class TestViewHolder extends RecyclerView.ViewHolder { private final ItemViewBinding mItemViewBinding; TestViewHolder(final ItemViewBinding itemViewBinding) { super(itemViewBinding.getRoot()); mItemViewBinding = itemViewBinding; } } }
package io.ifar.skidroad.upload; import com.google.common.collect.ImmutableSet; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Gauge; import com.yammer.metrics.core.HealthCheck; import com.yammer.metrics.core.Meter; import io.ifar.goodies.AutoCloseableIterator; import io.ifar.goodies.IterableIterator; import io.ifar.goodies.Iterators; import io.ifar.goodies.Pair; import io.ifar.skidroad.LogFile; import io.ifar.skidroad.scheduling.SimpleQuartzScheduler; import io.ifar.skidroad.tracking.LogFileStateListener; import io.ifar.skidroad.tracking.LogFileTracker; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import static io.ifar.skidroad.tracking.LogFileState.*; /** * Manages UploadWorkers. * * Note there is no UploadWorker interface. Uses a UploadWorkerFactory * to create worker runnables. * * TODO (future): Nearly identical code to PrepWorkerManager. Consolidate? */ public class UploadWorkerManager implements LogFileStateListener { private final static Logger LOG = LoggerFactory.getLogger(UploadWorkerManager.class); private final static int PEEK_DEPTH = 50; //when randomly selecting an item to retry, how many of the available items to rifle through private final UploadWorkerFactory workerFactory; private final LogFileTracker tracker; private final SimpleQuartzScheduler scheduler; public final int retryIntervalSeconds; private final int maxConcurrentUploads; private ExecutorService executor; private final Set<String> activeFiles; public final HealthCheck healthcheck; private final AtomicInteger queueDepth = new AtomicInteger(0); private final Gauge<Integer> queueDepthGauge = Metrics.newGauge(this.getClass(), "queue_depth", new Gauge<Integer>() { @Override public Integer value() { return queueDepth.get(); } }); private final Gauge<Integer> uploadingGauge = Metrics.newGauge(this.getClass(), "files_uploading", new Gauge<Integer>() { @Override public Integer value() { return tracker.getCount(UPLOADING); } }); private final Gauge<Integer> errorGauge = Metrics.newGauge(this.getClass(), "files_in_error", new Gauge<Integer>() { @Override public Integer value() { return tracker.getCount(UPLOAD_ERROR); } }); private final Meter errorMeter = Metrics.newMeter(this.getClass(), "upload_errors", "errors", TimeUnit.SECONDS); private final Meter successMeter = Metrics.newMeter(this.getClass(), "upload_successes", "successes", TimeUnit.SECONDS); /** * @param workerFactory Provides workers to perform the LogFile uploads. * @param tracker Provides access to LogFile metadata. * @param scheduler Quartz * @param retryIntervalSeconds How often to look for files that can be retried. * @param maxConcurrentWork Size of thread pool executing the workers. * @param unhealthyQueueDepthThreshold HealthCheck returns unhealthy when work queue reaches this size. */ public UploadWorkerManager(UploadWorkerFactory workerFactory, LogFileTracker tracker, SimpleQuartzScheduler scheduler, int retryIntervalSeconds, int maxConcurrentWork, final int unhealthyQueueDepthThreshold) { this.workerFactory = workerFactory; this.tracker = tracker; this.scheduler = scheduler; this.retryIntervalSeconds = retryIntervalSeconds; this.maxConcurrentUploads = maxConcurrentWork; this.activeFiles = new HashSet<String>(); this.healthcheck = new HealthCheck("upload_worker_manager") { protected Result check() throws Exception { //Would be better to measure latency than depth, but that's more expensive. if (queueDepth.get() < unhealthyQueueDepthThreshold) return Result.healthy(String.format("%d files queued or in-flight.", queueDepth.get())); else return Result.unhealthy(String.format("%d files queued or in-flight exceeds threshold (%d).", queueDepth.get(), unhealthyQueueDepthThreshold)); } }; } @Override public void stateChanged(final LogFile logFile) { LOG.trace("State change received: {} for {}", logFile.getState(), logFile); switch (logFile.getState()) { case PREPARED: processAsync(logFile); break; case UPLOAD_ERROR: errorMeter.mark(); break; case UPLOADED: successMeter.mark(); break; default: //ignore } } /** * Wraps increment/decrement of queueDepth around provided worker * @param worker * @param logFile * @return */ private Callable<Boolean> wrapWorker(final Callable<Boolean> worker, final LogFile logFile) { return new Callable<Boolean>() { @Override public Boolean call() throws Exception { LOG.debug("Uploading {} from {}.", logFile, logFile.getPrepPath()); queueDepth.incrementAndGet(); try { return worker.call(); } finally { queueDepth.decrementAndGet(); } } }; } /** * Synchronously processes the provided LogFile. Used by by retry handler for testing of whether * uploads are working again. * @param logFile * @return True if successful, False if LogFile could not be claimed. Exception thrown if failed. */ private Boolean processSync(final LogFile logFile) throws Exception { if (claim(logFile)) { try { final Callable<Boolean> worker = wrapWorker(workerFactory.buildWorker(logFile, tracker),logFile); return worker.call(); } finally { release(logFile); } } else { LOG.trace("{} is already being uploaded on another thread. No-op on this thread.", logFile); return Boolean.FALSE; } } /** * Submits provided LogFile for async upload processing */ private void processAsync(final LogFile logFile) { if (claim(logFile)) { try { final Callable<Boolean> worker = wrapWorker(workerFactory.buildWorker(logFile, tracker), logFile); executor.submit(worker); } finally { release(logFile); } } else { LOG.trace("{} is already being uploaded on another thread. No-op on this thread.", logFile); } } public void start() { LOG.info("Starting {}.", UploadWorkerManager.class.getSimpleName()); this.executor = new ThreadPoolExecutor(0, maxConcurrentUploads, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); tracker.addListener(this); Map<String,Object> retryConfiguration = new HashMap<>(1); retryConfiguration.put(RetryJob.UPLOAD_WORKER_MANAGER, this); scheduler.schedule(this.getClass().getSimpleName() + "_retry", RetryJob.class, retryIntervalSeconds * 1000, retryConfiguration); } public void stop() { LOG.info("Stopping {}.",UploadWorkerManager.class.getSimpleName()); tracker.removeListener(this); this.executor.shutdown(); } /** * Manages concurrency between listener-invoked and scheduler-invoked processing * @return true if this LogFile may be processed */ private boolean claim(LogFile f) { synchronized (activeFiles) { return activeFiles.add(f.getID()); } } /** * Releases processing lock on specified LogFile. * Caller responsible for ensuring that release is called if and only if claim returned true */ private void release(LogFile f) { synchronized (activeFiles) { activeFiles.remove(f.getID()); } } /** * @return true if this LogFile may be processed */ private boolean isClaimed(LogFile f) { synchronized (activeFiles) { return activeFiles.contains(f.getID()); } } @DisallowConcurrentExecution public static class RetryJob implements Job { public static final String UPLOAD_WORKER_MANAGER = "upload_worker_manager"; private static final Logger LOG = LoggerFactory.getLogger(RetryJob.class); public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap m = context.getMergedJobDataMap(); UploadWorkerManager mgr = (UploadWorkerManager) m.get(UPLOAD_WORKER_MANAGER); try { try (AutoCloseableIterator<LogFile> iterator = mgr.tracker.findMine(ImmutableSet.of(UPLOADING, PREPARED, UPLOAD_ERROR))){ tryOneThenRetryAll(iterator, mgr); } } catch (Exception e) { //Observed causes: // findMine throws org.skife.jdbi.v2.exceptions.UnableToCreateStatementException: org.postgresql.util.PSQLException: This connection has been closed. // findMine throws org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException: org.postgresql.util.PSQLException: An I/O error occured while sending to the backend. throw new JobExecutionException("Failure retrying upload jobs.", e); } } /** * Guards against situation where there are many files to retry and retries are failing. Attempt one and, * if it succeeds, retry the others. Otherwise wait. Selection of one to try is random within the first * PEEK_DEPTH records returned by the database. This avoids iterating the whole result set. * @param iterator * @param mgr */ private void tryOneThenRetryAll(Iterator<LogFile> iterator, UploadWorkerManager mgr) { Pair<LogFile,IterableIterator<LogFile>> oneSelected = Iterators.takeOneFromTopN(iterator, PEEK_DEPTH); if (oneSelected.left != null) { //claim check not required for thread safety, but avoid spurious WARNs about retrying items while they are in-flight for the first time LogFile trialLogFile = oneSelected.left; if (!mgr.isClaimed(trialLogFile)) { try { logRetryMessageForState(trialLogFile); if (mgr.processSync(trialLogFile)) { if (oneSelected.right.hasNext()) { LOG.info("First retry succeeded. Will queue others."); for (LogFile logFile : oneSelected.right) { //claim check not required for thread safety, but avoid spurious WARNs about retrying items while they are in-flight for the first time if (!mgr.isClaimed(logFile)) { logRetryMessageForState(logFile); mgr.processAsync(logFile); } } } else { LOG.info("First retry succeeded. There are no others left."); } } else { LOG.warn("Another thread claimed {} since last checked. Are two retry jobs running at once?", trialLogFile); } } catch (Exception e) { if (oneSelected.right.hasNext()) { LOG.warn("Retry of trial record {} failed. Will not try any others this time.", trialLogFile); } else { LOG.warn("Retry of trial record {} failed. There are no others left.", trialLogFile); } } } } } private void logRetryMessageForState(LogFile logFile) { switch (logFile.getState()) { case PREPARED: LOG.info("Found stale {} record for {}. Perhaps server was previously terminated before uploading it.", logFile.getState(), logFile); break; case UPLOADING: LOG.info("Found stale {} record for {}. Perhaps server was previously terminated while uploading it.", logFile.getState(), logFile); break; case UPLOAD_ERROR: LOG.info("Found {} record for {}. Perhaps a transient error occurred while uploading it.", logFile.getState(), logFile); break; default: throw new IllegalStateException(String.format("Did not expect to be processing %s record for %s. Bug!", logFile.getState(), logFile)); } } } }
package org.waterforpeople.mapping.portal.client.widgets.component.standardscoring; import java.util.ArrayList; import java.util.Iterator; import org.waterforpeople.mapping.app.gwt.client.standardscoring.CompoundStandardDto; import org.waterforpeople.mapping.app.gwt.client.standardscoring.CompoundStandardDto.Operator; import org.waterforpeople.mapping.app.gwt.client.standardscoring.StandardScoringDto; import org.waterforpeople.mapping.app.gwt.client.standardscoring.StandardScoringManagerServiceAsync; import org.waterforpeople.mapping.app.gwt.client.util.TextConstants; import com.gallatinsystems.framework.gwt.component.DataTableBinder; import com.gallatinsystems.framework.gwt.component.DataTableHeader; import com.gallatinsystems.framework.gwt.component.DataTableListener; import com.gallatinsystems.framework.gwt.component.PaginatedDataTable; import com.gallatinsystems.framework.gwt.dto.client.ResponseDto; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; public class CompoundStandardDetail extends Composite implements HasText, DataTableBinder<CompoundStandardDto>, DataTableListener<CompoundStandardDto> { private static CompoundStandardDetailUiBinder uiBinder = GWT .create(CompoundStandardDetailUiBinder.class); interface CompoundStandardDetailUiBinder extends UiBinder<Widget, CompoundStandardDetail> { } public CompoundStandardDetail() { initWidget(uiBinder.createAndBindUi(this)); } public CompoundStandardDetail(String standardType, StandardScoringManagerServiceAsync svc) { setStandardType(standardType); initWidget(uiBinder.createAndBindUi(this)); this.svc = svc; loadPanel(); } @UiField Button saveButton; @UiField Button cancelButton; @UiField ListBox lbLeftHandRule; @UiField ListBox lbRightHandRule; @UiField Label labelOperator; @UiField ListBox operator; @UiField TextBox compoundRuleID; @UiField VerticalPanel listPanel; @UiField VerticalPanel detailPanel; @UiField TextBox tbRuleName; void loadPanel() { init(); listPanel.add(vp); } @UiHandler("saveButton") void onSaveClick(ClickEvent e) { Long compoundRuleIDValue = null; String value = compoundRuleID.getText().trim(); if (!value.equals("")) { compoundRuleIDValue = Long.parseLong(compoundRuleID.getText()); } String name = tbRuleName.getText(); Long leftRuleId = Integer.valueOf( lbLeftHandRule.getValue(lbLeftHandRule.getSelectedIndex())) .longValue(); Long rightRuleId = Integer.valueOf( lbRightHandRule.getValue(lbRightHandRule.getSelectedIndex())) .longValue(); String operatorValue = operator.getValue(operator.getSelectedIndex()); svc.saveCompoundRule(compoundRuleIDValue, name, standardType, leftRuleId, rightRuleId, operatorValue, new AsyncCallback<Long>() { @Override public void onFailure(Throwable caught) { // TODO Auto-generated method stub } @Override public void onSuccess(Long result) { compoundRuleID.setText(result.toString()); Window.alert("Saved Compound Rule"); } }); } @UiHandler("lbLeftHandRule") void onLbLeftHandRuleChange(ChangeEvent e) { setupOperatorControl(); } @UiHandler("lbRightHandRule") void onLbRightHandRuleChange(ChangeEvent e) { setupOperatorControl(); } private void setupOperatorControl() { labelOperator.setVisible(true); operator.addItem("And"); operator.addItem("Or"); operator.setVisible(true); saveButton.setEnabled(true); } @Override public String getText() { // TODO Auto-generated method stub return null; } @Override public void setText(String text) { // TODO Auto-generated method stub } private void loadStandards(final CompoundStandardDto csItem) { Long standardKey = null; operator.addItem("and"); operator.addItem("or"); if (csItem != null) { compoundRuleID.setText(csItem.getKeyId().toString()); tbRuleName.setText(csItem.getName()); if (csItem.getOperator().equals(Operator.AND)) { operator.setSelectedIndex(0); } else { operator.setSelectedIndex(1); } } if (standardType.equalsIgnoreCase("waterpointlevelofservice")) { standardKey = 0L; } else { standardKey = 1L; } svc.listStandardScoring( standardKey, null, new AsyncCallback<ResponseDto<ArrayList<StandardScoringDto>>>() { @Override public void onFailure(Throwable caught) { // TODO Auto-generated method stub } @Override public void onSuccess( ResponseDto<ArrayList<StandardScoringDto>> result) { int i = 0; for (StandardScoringDto item : result.getPayload()) { if (item != null && item.getCriteriaType() != null && item.getCriteriaType() .equals("Distance")) { lbLeftHandRule.addItem( "Distance Rule for " + item.getCountryCode() + ":" + item.getDisplayName(), item .getKeyId().toString()); lbRightHandRule.addItem( "Distance Rule for " + item.getCountryCode() + ":" + item.getDisplayName(), item .getKeyId().toString()); } else { lbLeftHandRule.addItem(item.getDisplayName(), item.getKeyId().toString()); if (csItem != null) { if (item.getDisplayName().equalsIgnoreCase( csItem.getStandardLeftDesc())) { lbLeftHandRule.setSelectedIndex(i); } } lbRightHandRule.addItem(item.getDisplayName(), item.getKeyId().toString()); if (csItem != null) { if (item.getDisplayName().equalsIgnoreCase( csItem.getStandardRightDesc())) { lbRightHandRule.setSelectedIndex(i); } } } i++; } lbLeftHandRule.setVisible(true); lbRightHandRule.setVisible(true); detailPanel.setVisible(true); } }); } private static TextConstants TEXT_CONSTANTS = GWT .create(TextConstants.class); private VerticalPanel vp = new VerticalPanel(); private PaginatedDataTable<CompoundStandardDto> ft = null; private String standardType = null; private StandardScoringManagerServiceAsync svc = null; private static final String EDITED_ROW_CSS = "gridCell-edited"; private static final DataTableHeader HEADERS[] = { new DataTableHeader("Id", "key", true), new DataTableHeader(TEXT_CONSTANTS.name(), "name", true), new DataTableHeader("Left Hand Rule ", "standardLeftDesc", true), new DataTableHeader(TEXT_CONSTANTS.positiveOperator(), "operator", true), new DataTableHeader("Right Hand Rule", "standardRightDesc", true), new DataTableHeader("Action") }; private static final String DEFAULT_SORT_FIELD = "name"; private static final Integer PAGE_SIZE = 20; private void init() { ft = new PaginatedDataTable<CompoundStandardDto>(DEFAULT_SORT_FIELD, this, this, true, true); getVp().add(ft); requestData(null, false); } public void setStandardType(String standardType) { this.standardType = standardType; } @Override public void bindRow(final Grid grid, CompoundStandardDto item, final int row) { // ft.insertRow(row); TextBox id = new TextBox(); if (item.getKeyId() != null) id.setText(item.getKeyId().toString()); grid.setWidget(row, 0, id); TextBox name = new TextBox(); if (item.getName() != null) name.setText(item.getName()); grid.setWidget(row, 1, name); TextBox leftHandRuleDesc = new TextBox(); if (item.getStandardLeftDesc() != null) leftHandRuleDesc.setText(item.getStandardLeftDesc()); grid.setWidget(row, 2, leftHandRuleDesc); TextBox operator = new TextBox(); if (item.getOperator() != null) operator.setText(item.getOperator().toString()); grid.setWidget(row, 3, operator); TextBox rightHandRuleDesc = new TextBox(); if (item.getStandardRightDesc() != null) rightHandRuleDesc.setText(item.getStandardRightDesc()); grid.setWidget(row, 4, rightHandRuleDesc); HorizontalPanel hpanel = new HorizontalPanel(); Button editRow = new Button("Edit"); editRow.setTitle(new Integer(row).toString()); Button deleteRow = new Button("Delete"); deleteRow.setTitle(new Integer(row).toString()); hpanel.add(editRow); editRow.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { TextBox idBox = (TextBox) grid.getWidget(row, 0); CompoundStandardDto item = formStandardScoringDto(row); loadStandards(item); } }); hpanel.add(deleteRow); grid.setWidget(row, 5, hpanel); } public CompoundStandardDto formStandardScoringDto(Integer row) { CompoundStandardDto item = new CompoundStandardDto(); Grid grid = ft.getGrid(); TextBox id = (TextBox) grid.getWidget(row, 0); TextBox name = (TextBox) grid.getWidget(row, 1); TextBox leftHandRuleDesc = (TextBox) grid.getWidget(row, 2); TextBox operator = (TextBox) grid.getWidget(row, 3); TextBox rightHandRuleDesc = (TextBox) grid.getWidget(row, 4); if (id.getText() != null) item.setKeyId(Long.parseLong(id.getText())); if (name.getText() != null) item.setName(name.getText().trim()); if (leftHandRuleDesc.getText() != null) item.setStandardLeftDesc(leftHandRuleDesc.getText().trim()); if (rightHandRuleDesc.getText() != null) item.setStandardRightDesc(rightHandRuleDesc.getText().trim()); if (operator.getText() != null) { if (operator.getText().equalsIgnoreCase("and")) { item.setOperator(Operator.AND); } else { item.setOperator(Operator.OR); } } return item; } public String getStandardType() { return standardType; } public void setSvc(StandardScoringManagerServiceAsync svc) { this.svc = svc; } public StandardScoringManagerServiceAsync getSvc() { return svc; } public void setVp(VerticalPanel vp) { this.vp = vp; } public VerticalPanel getVp() { return vp; } @Override public void onItemSelected(CompoundStandardDto item) { // TODO Auto-generated method stub } @Override public void requestData(String cursor, final boolean isResort) { final boolean isNew = (cursor == null); svc.listCompoundRule( standardType, new AsyncCallback<ResponseDto<ArrayList<CompoundStandardDto>>>() { @Override public void onFailure(Throwable caught) { // TODO Auto-generated method stub } @Override public void onSuccess( ResponseDto<ArrayList<CompoundStandardDto>> result) { if (result.getPayload().size() > 0) { ft.bindData(result.getPayload(), result.getCursorString(), isNew, isResort); }else{ loadStandards(null); } } }); } @Override public DataTableHeader[] getHeaders() { return HEADERS; } @Override public Integer getPageSize() { return PAGE_SIZE; } }
package net.sourceforge.texlipse.actions; import java.util.Arrays; import net.sourceforge.texlipse.TexlipsePlugin; import net.sourceforge.texlipse.editor.TexAutoIndentStrategy; import net.sourceforge.texlipse.editor.TexEditorTools; import net.sourceforge.texlipse.properties.TexlipseProperties; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; /** * @author Laura Takkinen * @author Boris von Loesch * * Handles indentation quick fix when user selects text area * and performs "Correct Indentation" action. (Correct Indentation button or Ctrl+I) */ public class TexCorrectIndentationAction implements IEditorActionDelegate { private IEditorPart targetEditor; private TexSelections selection; private TexEditorTools tools; private String indentationString = ""; private String[] indentationItems; private int tabWidth; /* (non-Javadoc) * @see org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface.action.IAction, org.eclipse.ui.IEditorPart) */ public void setActiveEditor(IAction action, IEditorPart targetEditor) { this.targetEditor = targetEditor; } /** * Returns the TexEditor. */ private ITextEditor getTexEditor() { if (targetEditor instanceof ITextEditor) { return (ITextEditor) targetEditor; } else { throw new RuntimeException("Expecting text editor. Found:"+targetEditor.getClass().getName()); } } /* (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */ public void run(IAction action) { setIndetationPreferenceInfo(); //no environments to indent if (this.indentationItems.length == 0) { return; } else { //check if environments have change selection = new TexSelections(getTexEditor()); if (selection != null) { this.tools = new TexEditorTools(); try { indent(); } catch(BadLocationException e) { TexlipsePlugin.log("TexCorrectIndentationAction.run", e); } } } } /** * Initializes indentation information from preferences */ private void setIndetationPreferenceInfo() { indentationItems = TexlipsePlugin.getPreferenceArray(TexlipseProperties.INDENTATION_ENVS); Arrays.sort(indentationItems); //this.tabWidth = editorPreferenceStore.getInt(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); indentationString = TexAutoIndentStrategy.getIndentationString(); } /** * Checks if selection needs indentation and corrects it when necessary. * @throws BadLocationException */ private void indent() throws BadLocationException { //FIXME: Refactor int index = 0; boolean fix = false; IDocument document = selection.getDocument(); selection.selectCompleteLines(); String delimiter = document.getLineDelimiter(selection.getStartLineIndex()); String[] lines; try { lines = document.get(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength()).split(delimiter); } catch(BadLocationException e) {//for example new empty file return; } //fix lines on at the time String selectedLine = ""; String originalIndentation = ""; String correctIndentation = ""; for (int line = selection.getStartLineIndex(); index < lines.length; line++) { selectedLine = document.get(document.getLineOffset(line), document.getLineLength(line)); originalIndentation = this.tools.getIndentation(selectedLine, this.tabWidth); correctIndentation = ""; //first line of end of document if (line == 0 || line == document.getLength()-1) { } else if (line >= document.getLength()){ return; } else if (selectedLine.indexOf("\\end") != -1) { //selected line is \end{...} -line String endText = this.tools.getEndLine(selectedLine.trim(), "\\end"); if (Arrays.binarySearch(this.indentationItems, this.tools.getEnvironment(endText)) >= 0) { int matchingBegin = this.tools.findMatchingBeginEquation(document, line, this.tools.getEnvironment(endText)); if (matchingBegin < selection.getStartLineIndex()) { correctIndentation = this.tools.getIndentation(document, matchingBegin, "\\begin", this.tabWidth); } else { correctIndentation = this.tools.getIndentation(lines[matchingBegin-selection.getStartLineIndex()], this.tabWidth); } } } else { //otherwise indentation is determined by the previous line String lineText = ""; //previous line is outside the selection if (index == 0) { lineText = document.get(document.getLineOffset(line-1), document.getLineLength(line-1)); } else { //previous line is inside the selection lineText = lines[index-1]; } //previous line is \begin{...} -line if (lineText.indexOf("\\begin") != -1) { String endText = this.tools.getEndLine(lineText.trim(), "\\begin"); if (Arrays.binarySearch(this.indentationItems, this.tools.getEnvironment(endText)) >= 0) { correctIndentation = this.tools.getIndentation(lineText, this.tabWidth) + this.indentationString; } } else { //previous line is something else correctIndentation = this.tools.getIndentation(lineText, this.tabWidth); } } if (!correctIndentation.equals(originalIndentation)) { fix = true; } lines[index] = correctIndentation.concat(lines[index].trim()); index++; } String newText = lines[0]; for (int i = 1; i < lines.length; i++) { newText += delimiter; newText += lines[i]; } if (fix) { document.replace(document.getLineOffset(selection.getStartLineIndex()), selection.getSelLength(), newText); } } /* (non-Javadoc) * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection) */ public void selectionChanged(IAction action, ISelection selection) { if (selection instanceof ITextSelection) { action.setEnabled(true); return; } action.setEnabled( targetEditor instanceof ITextEditor); } }
package default_package; import java.io.File; public class VoidFile extends File{ private boolean isVCEncrypted; private String path; public VoidFile(String path) { super(path); this.path = path; isVCEncrypted = getExtension().substring(0,1).equals("VC"); } public boolean getIsVCEncrypted() { return isVCEncrypted; } public void setIsVCEncrypted() { isVCEncrypted = getExtension().substring(0,1).equals("VC"); } public String getExtension() { if (this.path.lastIndexOf('.') > 0) { return path.substring(path.lastIndexOf('.')+1); } return null; } public void setExtension(String path) { VoidFile vf = new VoidFile(path.replace("\\", "/")); vf.renameTo(new File(path + "VC" + getExtension())); } }
package edu.mines.alterego; import java.util.ArrayList; import java.util.Locale; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.Pair; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class GameActivity extends FragmentActivity { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; ArrayAdapter gameDbAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter( getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a DummySectionFragment (defined as a static inner class // below) with the page number as its lone argument. Fragment fragment = new DummySectionFragment(); Bundle args = new Bundle(); args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1); fragment.setArguments(args); return fragment; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } /** * A dummy fragment representing a section of the app, but that simply * displays dummy text. */ public static class DummySectionFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ public static final String ARG_SECTION_NUMBER = "section_number"; public DummySectionFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false); TextView dummyTextView = (TextView) rootView .findViewById(R.id.section_label); dummyTextView.setText(Integer.toString(getArguments().getInt( ARG_SECTION_NUMBER))); return rootView; } } }
package com.ea.orbit.actors.extensions.dynamodb; import com.ea.orbit.actors.extensions.StorageExtension; import com.ea.orbit.actors.extensions.json.ActorReferenceModule; import com.ea.orbit.actors.runtime.DefaultDescriptorFactory; import com.ea.orbit.actors.runtime.RemoteReference; import com.ea.orbit.concurrent.Task; import com.ea.orbit.exception.UncheckedException; import com.ea.orbit.util.ExceptionUtils; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.DescribeTableResult; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; public class DynamoDBStorageExtension implements StorageExtension { public enum AmazonCredentialType { DEFAULT_PROVIDER_CHAIN, BASIC_CREDENTIALS, BASIC_SESSION_CREDENTIALS } private AmazonDynamoDBAsyncClient dynamoClient; private DynamoDB dynamoDB; private ConcurrentHashMap<String, Table> tableHashMap; private ObjectMapper mapper; private String name = "default"; private String endpoint = "http://localhost:8000/"; private AmazonCredentialType credentialType = AmazonCredentialType.DEFAULT_PROVIDER_CHAIN; private String accessKey; private String secretKey; private String sessionToken; private boolean shouldCreateTables = true; public DynamoDBStorageExtension() { } @Override public Task<Void> start() { tableHashMap = new ConcurrentHashMap<>(); mapper = new ObjectMapper(); mapper.registerModule(new ActorReferenceModule(DefaultDescriptorFactory.get())); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withCreatorVisibility(JsonAutoDetect.Visibility.NONE)); switch(credentialType) { case BASIC_CREDENTIALS: dynamoClient = new AmazonDynamoDBAsyncClient(new BasicAWSCredentials(accessKey, secretKey)); break; case BASIC_SESSION_CREDENTIALS: dynamoClient = new AmazonDynamoDBAsyncClient(new BasicSessionCredentials(accessKey, secretKey, sessionToken)); break; case DEFAULT_PROVIDER_CHAIN: default: dynamoClient = new AmazonDynamoDBAsyncClient(new DefaultAWSCredentialsProviderChain()); break; } dynamoClient.setEndpoint(endpoint); dynamoDB = new DynamoDB(dynamoClient); return Task.done(); } @Override public String getName() { return name; } @Override public Task<Void> clearState(final RemoteReference<?> reference, final Object state) { return getOrCreateTable(RemoteReference.getInterfaceClass(reference).getSimpleName()) .thenAccept(table -> table.deleteItem("_id", String.valueOf(RemoteReference.getId(reference)))); } @Override public Task<Void> stop() { return Task.done(); } @Override @SuppressWarnings("unchecked") public Task<Boolean> readState(final RemoteReference<?> reference, final Object state) { return getOrCreateTable(RemoteReference.getInterfaceClass(reference).getSimpleName()) .thenApply(table -> table.getItem("_id", String.valueOf(RemoteReference.getId(reference)))) .thenApply(item -> { if (item != null) { try { mapper.readerForUpdating(state).readValue(item.getJSON("_state")); return true; } catch (IOException e) { throw new UncheckedException(e); } } else { return false; } }); } @Override @SuppressWarnings("unchecked") public Task<Void> writeState(final RemoteReference<?> reference, final Object state) { try { final String serializedState = mapper.writeValueAsString(state); return getOrCreateTable(RemoteReference.getInterfaceClass(reference).getSimpleName()) .thenAccept(table -> table.putItem(new Item().withPrimaryKey("_id", String.valueOf(RemoteReference.getId(reference))).withJSON("_state", serializedState))); } catch (JsonProcessingException e) { throw new UncheckedException(e); } } private Task<Table> getOrCreateTable(final String tableName) { final Table table = tableHashMap.get(tableName); if (table != null) { return Task.fromValue(table); } else { return Task.fromFuture(dynamoClient.describeTableAsync(tableName)) .thenApply(DescribeTableResult::getTable) .thenApply(descriptor -> dynamoDB.getTable(descriptor.getTableName())) .exceptionally(e -> { if (shouldCreateTables && ExceptionUtils.isCauseInChain(ResourceNotFoundException.class, e)) { final Table newTable = dynamoDB.createTable(tableName, Collections.singletonList( new KeySchemaElement("_id", KeyType.HASH)), Collections.singletonList( new AttributeDefinition("_id", ScalarAttributeType.S)), new ProvisionedThroughput(10L, 10L)); try { newTable.waitForActive(); } catch(Exception ex) { throw new UncheckedException(ex); } tableHashMap.putIfAbsent(tableName, newTable); return newTable; } else { throw new UncheckedException(e); } }); } } public void setName(final String name) { this.name = name; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public AmazonCredentialType getCredentialType() { return credentialType; } public void setCredentialType(AmazonCredentialType credentialType) { this.credentialType = credentialType; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getSessionToken() { return sessionToken; } public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public boolean getShouldCreateTables() { return shouldCreateTables; } public void setShouldCreateTables(boolean shouldCreateTables) { this.shouldCreateTables = shouldCreateTables; } }
package org.openhab.binding.avmfritz.handler; import static org.openhab.binding.avmfritz.BindingConstants.*; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingStatusInfo; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler; import org.eclipse.smarthome.core.types.Command; import org.openhab.binding.avmfritz.BindingConstants; import org.openhab.binding.avmfritz.config.AvmFritzConfiguration; import org.openhab.binding.avmfritz.internal.ahamodel.DeviceModel; import org.openhab.binding.avmfritz.internal.ahamodel.SwitchModel; import org.openhab.binding.avmfritz.internal.hardware.FritzahaWebInterface; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Handler for a FRITZ!Box device. Handles polling of values from AHA devices. * * @author Robert Bausdorf * */ public class BoxHandler extends BaseBridgeHandler implements IFritzHandler { /** * Logger */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * the refresh interval which is used to poll values from the fritzaha. * server (optional, defaults to 15 s) */ private long refreshInterval = 15; /** * Interface object for querying the FRITZ!Box web interface */ private FritzahaWebInterface connection; /** * Holder for last data received from the box. */ private Map<String, DeviceModel> deviceList; /** * Job which will do the FRITZ!Box polling */ private DeviceListPolling pollingRunnable; /** * Schedule for polling */ private ScheduledFuture<?> pollingJob; /** * Constructor * * @param bridge * Bridge object representing a FRITZ!Box */ public BoxHandler(Bridge bridge) { super(bridge); this.deviceList = new TreeMap<String, DeviceModel>(); this.pollingRunnable = new DeviceListPolling(this); } /** * Initializes the bridge. */ @Override public void initialize() { logger.debug("About to initialize bridge " + BindingConstants.BRIDGE_FRITZBOX); Bridge bridge = this.getThing(); AvmFritzConfiguration config = this.getConfigAs(AvmFritzConfiguration.class); logger.debug("discovered fritzaha bridge initialized: " + config.toString()); this.refreshInterval = config.getPollingInterval(); this.connection = new FritzahaWebInterface(config, this); if (config.getPassword() != null) { this.onUpdate(); } else { bridge.setStatusInfo( new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "no password set")); } } /** * Disposes the bridge. */ @Override public void dispose() { logger.debug("Handler disposed."); if (pollingJob != null && !pollingJob.isCancelled()) { pollingJob.cancel(true); pollingJob = null; } } /** * {@inheritDoc} */ @Override public void addDeviceList(DeviceModel model) { try { logger.debug("set device model: " + model.toString()); this.deviceList.put(model.getIdentifier(), model); ThingUID thingUID = this.getThingUID(model); Thing thing = this.getThingByUID(thingUID); if (thing != null) { logger.debug("update thing " + thingUID + " with device model: " + model.toString()); this.updateThingFromDevice(thing, model); } } catch (Exception e) { logger.error(e.getLocalizedMessage(), e); } } /** * {@inheritDoc} */ @Override public FritzahaWebInterface getWebInterface() { return this.connection; } /** * Updates things from device model. * * @param thing * Thing to be updated. * @param device * Device model with new data. */ private void updateThingFromDevice(Thing thing, DeviceModel device) { if (thing == null || device == null) { throw new IllegalArgumentException("thing or device null, cannot perform update"); } logger.debug("about to update " + thing.getUID() + " from " + device.toString()); if (device.isTempSensor()) { Channel channel = thing.getChannel(CHANNEL_TEMP); this.updateState(channel.getUID(), new DecimalType(device.getTemperature().getCelsius())); } if (device.isPowermeter()) { Channel channelEnergy = thing.getChannel(CHANNEL_ENERGY); this.updateState(channelEnergy.getUID(), new DecimalType(device.getPowermeter().getEnergy())); Channel channelPower = thing.getChannel(CHANNEL_POWER); this.updateState(channelPower.getUID(), new DecimalType(device.getPowermeter().getPower())); } if (device.isSwitchableOutlet()) { Channel channel = thing.getChannel(CHANNEL_SWITCH); if (device.getSwitch().getState().equals(SwitchModel.ON)) { this.updateState(channel.getUID(), OnOffType.ON); } else if (device.getSwitch().getState().equals(SwitchModel.OFF)) { this.updateState(channel.getUID(), OnOffType.OFF); } else { logger.warn("unknown state " + device.getSwitch().getState() + " for channel " + channel.getUID()); } } } public ThingUID getThingUID(DeviceModel device) { ThingUID bridgeUID = this.getThing().getUID(); ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, device.getProductName().replaceAll("[^a-zA-Z0-9_]", "_")); if (BindingConstants.SUPPORTED_DEVICE_THING_TYPES_UIDS.contains(thingTypeUID)) { String thingName = device.getIdentifier().replaceAll("[^a-zA-Z0-9_]", "_"); ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, thingName); return thingUID; } else { return null; } } /** * Start the polling. */ private synchronized void onUpdate() { if (this.getThing() != null) { if (pollingJob == null || pollingJob.isCancelled()) { logger.debug("start polling job at intervall " + refreshInterval); pollingJob = scheduler.scheduleWithFixedDelay(pollingRunnable, 1, refreshInterval, TimeUnit.SECONDS); } else { logger.debug("pollingJob active"); } } else { logger.warn("bridge is null"); } } /** * Just logging - nothing to do. */ @Override public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("update " + channelUID.getAsString() + " with " + command.toString()); } /** * Called from {@link FritzahaWebInterface#authenticate()} to update * the bridge status because updateStatus is protected. * * @param status Bridge status * @param statusDetail Bridge status detail * @param description Bridge status description */ @Override public void setStatusInfo(ThingStatus status, ThingStatusDetail statusDetail, String description) { super.updateStatus(status, statusDetail, description); } }
package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitbip; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.content.Context; import android.net.Uri; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Locale; import java.util.Set; import java.util.SimpleTimeZone; import java.util.UUID; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiFWHelper; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiWeatherConditions; import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitbip.AmazfitBipFWHelper; import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitbip.AmazfitBipService; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2Service; import nodomain.freeyourgadget.gadgetbridge.model.CallSpec; import nodomain.freeyourgadget.gadgetbridge.model.DeviceType; import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec; import nodomain.freeyourgadget.gadgetbridge.model.NotificationType; import nodomain.freeyourgadget.gadgetbridge.model.RecordedDataTypes; import nodomain.freeyourgadget.gadgetbridge.model.Weather; import nodomain.freeyourgadget.gadgetbridge.model.WeatherSpec; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.ConditionalWriteAction; import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.alertnotification.AlertCategory; import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.alertnotification.AlertNotificationProfile; import nodomain.freeyourgadget.gadgetbridge.service.btle.profiles.alertnotification.NewAlert; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitbip.operations.AmazfitBipFetchLogsOperation; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.HuamiIcon; import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.NotificationStrategy; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.miband2.MiBand2Support; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.miband2.operations.FetchActivityOperation; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.miband2.operations.FetchSportsSummaryOperation; import nodomain.freeyourgadget.gadgetbridge.util.Prefs; import nodomain.freeyourgadget.gadgetbridge.util.StringUtils; import nodomain.freeyourgadget.gadgetbridge.util.Version; public class AmazfitBipSupport extends MiBand2Support { private static final Logger LOG = LoggerFactory.getLogger(AmazfitBipSupport.class); public AmazfitBipSupport() { super(LOG); } @Override public NotificationStrategy getNotificationStrategy() { return new AmazfitBipTextNotificationStrategy(this); } @Override public void onNotification(NotificationSpec notificationSpec) { if (notificationSpec.type == NotificationType.GENERIC_ALARM_CLOCK) { onAlarmClock(notificationSpec); return; } String senderOrTiltle = StringUtils.getFirstOf(notificationSpec.sender, notificationSpec.title); String message = StringUtils.truncate(senderOrTiltle, 32) + "\0"; if (notificationSpec.subject != null) { message += StringUtils.truncate(notificationSpec.subject, 128) + "\n\n"; } if (notificationSpec.body != null) { message += StringUtils.truncate(notificationSpec.body, 128); } try { TransactionBuilder builder = performInitialized("new notification"); AlertNotificationProfile<?> profile = new AlertNotificationProfile(this); profile.setMaxLength(230); byte customIconId = HuamiIcon.mapToIconId(notificationSpec.type); AlertCategory alertCategory = AlertCategory.CustomHuami; // The SMS icon for AlertCategory.SMS is unique and not available as iconId if (notificationSpec.type == NotificationType.GENERIC_SMS) { alertCategory = AlertCategory.SMS; } // EMAIL icon does not work in FW 0.0.8.74, it did in 0.0.7.90 else if (customIconId == HuamiIcon.EMAIL) { alertCategory = AlertCategory.Email; } NewAlert alert = new NewAlert(alertCategory, 1, message, customIconId); profile.newAlert(builder, alert); builder.queue(getQueue()); } catch (IOException ex) { LOG.error("Unable to send notification to Amazfit Bip", ex); } } @Override public void onFindDevice(boolean start) { CallSpec callSpec = new CallSpec(); callSpec.command = start ? CallSpec.CALL_INCOMING : CallSpec.CALL_END; callSpec.name = "Gadgetbridge"; onSetCallState(callSpec); } @Override public void handleButtonEvent() { // ignore } @Override protected AmazfitBipSupport setDisplayItems(TransactionBuilder builder) { if (gbDevice.getType() != DeviceType.AMAZFITBIP) { return this; // Disable for Cor for now } if (gbDevice.getFirmwareVersion() == null) { LOG.warn("Device not initialized yet, won't set menu items"); return this; } Version version = new Version(gbDevice.getFirmwareVersion()); if (version.compareTo(new Version("0.1.1.14")) < 0) { LOG.warn("Won't set menu items since firmware is too low to be safe"); return this; } Prefs prefs = GBApplication.getPrefs(); Set<String> pages = prefs.getStringSet("bip_display_items", null); LOG.info("Setting display items to " + (pages == null ? "none" : pages)); byte[] command = AmazfitBipService.COMMAND_CHANGE_SCREENS.clone(); boolean shortcut_weather = false; boolean shortcut_alipay = false; if (pages != null) { if (pages.contains("status")) { command[1] |= 0x02; } if (pages.contains("activity")) { command[1] |= 0x04; } if (pages.contains("weather")) { command[1] |= 0x08; } if (pages.contains("alarm")) { command[1] |= 0x10; } if (pages.contains("timer")) { command[1] |= 0x20; } if (pages.contains("compass")) { command[1] |= 0x40; } if (pages.contains("settings")) { command[1] |= 0x80; } if (pages.contains("alipay")) { command[2] |= 0x01; } if (pages.contains("shortcut_weather")) { shortcut_weather = true; } if (pages.contains("shortcut_alipay")) { shortcut_alipay = true; } } builder.write(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION), command); setShortcuts(builder, shortcut_weather, shortcut_alipay); return this; } private void setShortcuts(TransactionBuilder builder, boolean weather, boolean alipay) { LOG.info("Setting shortcuts: weather=" + weather + " alipay=" + alipay); // Basically a hack to put weather first always, if alipay is the only enabled one // there are actually two alipays set but the second one disabled.... :P byte[] command = new byte[]{0x10, (byte) ((alipay || weather) ? 0x80 : 0x00), (byte) (weather ? 0x02 : 0x01), (byte) ((alipay && weather) ? 0x81 : 0x01), 0x01, }; builder.write(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION), command); } @Override public void onSendWeather(WeatherSpec weatherSpec) { if (gbDevice.getFirmwareVersion() == null) { LOG.warn("Device not initialized yet, so not sending weather info"); return; } boolean supportsConditionString = false; Version version = new Version(gbDevice.getFirmwareVersion()); if (version.compareTo(new Version("0.0.8.74")) >= 0) { supportsConditionString = true; } int tz_offset_hours = SimpleTimeZone.getDefault().getOffset(weatherSpec.timestamp * 1000L) / (1000 * 60 * 60); try { TransactionBuilder builder; builder = performInitialized("Sending current temp"); byte condition = HuamiWeatherConditions.mapToAmazfitBipWeatherCode(weatherSpec.currentConditionCode); int length = 8; if (supportsConditionString) { length += weatherSpec.currentCondition.getBytes().length + 1; } ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 2); buf.putInt(weatherSpec.timestamp); buf.put((byte) (tz_offset_hours * 4)); buf.put(condition); buf.put((byte) (weatherSpec.currentTemp - 273)); if (supportsConditionString) { buf.put(weatherSpec.currentCondition.getBytes()); buf.put((byte) 0); } builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (Exception ex) { LOG.error("Error sending current weather", ex); } if (gbDevice.getType() != DeviceType.AMAZFITCOR) { try { TransactionBuilder builder; builder = performInitialized("Sending air quality index"); int length = 8; String aqiString = "(n/a)"; if (supportsConditionString) { length += aqiString.getBytes().length + 1; } ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 4); buf.putInt(weatherSpec.timestamp); buf.put((byte) (tz_offset_hours * 4)); buf.putShort((short) 0); if (supportsConditionString) { buf.put(aqiString.getBytes()); buf.put((byte) 0); } builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (IOException ex) { LOG.error("Error sending air quality"); } } try { TransactionBuilder builder = performInitialized("Sending weather forecast"); final byte NR_DAYS = (byte) (1 + weatherSpec.forecasts.size()); int bytesPerDay = 4; int conditionsLength = 0; if (supportsConditionString) { bytesPerDay = 5; conditionsLength = weatherSpec.currentCondition.getBytes().length; for (WeatherSpec.Forecast forecast : weatherSpec.forecasts) { conditionsLength += Weather.getConditionString(forecast.conditionCode).getBytes().length; } } int length = 7 + bytesPerDay * NR_DAYS + conditionsLength; ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 1); buf.putInt(weatherSpec.timestamp); buf.put((byte) (tz_offset_hours * 4)); buf.put(NR_DAYS); byte condition = HuamiWeatherConditions.mapToAmazfitBipWeatherCode(weatherSpec.currentConditionCode); buf.put(condition); buf.put(condition); buf.put((byte) (weatherSpec.todayMaxTemp - 273)); buf.put((byte) (weatherSpec.todayMinTemp - 273)); if (supportsConditionString) { buf.put(weatherSpec.currentCondition.getBytes()); buf.put((byte) 0); } for (WeatherSpec.Forecast forecast : weatherSpec.forecasts) { condition = HuamiWeatherConditions.mapToAmazfitBipWeatherCode(forecast.conditionCode); buf.put(condition); buf.put(condition); buf.put((byte) (forecast.maxTemp - 273)); buf.put((byte) (forecast.minTemp - 273)); if (supportsConditionString) { buf.put(Weather.getConditionString(forecast.conditionCode).getBytes()); buf.put((byte) 0); } } builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (Exception ex) { LOG.error("Error sending weather forecast", ex); } if (gbDevice.getType() == DeviceType.AMAZFITCOR) { try { TransactionBuilder builder; builder = performInitialized("Sending forecast location"); int length = 2 + weatherSpec.location.getBytes().length; ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 8); buf.put(weatherSpec.location.getBytes()); buf.put((byte) 0); builder.write(getCharacteristic(AmazfitBipService.UUID_CHARACTERISTIC_WEATHER), buf.array()); builder.queue(getQueue()); } catch (Exception ex) { LOG.error("Error sending current forecast location", ex); } } } @Override public void onFetchRecordedData(int dataTypes) { try { // FIXME: currently only one data type supported, these are meant to be flags if (dataTypes == RecordedDataTypes.TYPE_ACTIVITY) { new FetchActivityOperation(this).perform(); } else if (dataTypes == RecordedDataTypes.TYPE_GPS_TRACKS) { new FetchSportsSummaryOperation(this).perform(); } else if (dataTypes == RecordedDataTypes.TYPE_DEBUGLOGS) { new AmazfitBipFetchLogsOperation(this).perform(); } else { LOG.warn("fetching multiple data types at once is not supported yet"); } } catch (IOException ex) { LOG.error("Unable to fetch recorded data types" + dataTypes, ex); } } @Override public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { boolean handled = super.onCharacteristicChanged(gatt, characteristic); if (!handled) { UUID characteristicUUID = characteristic.getUuid(); if (MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION.equals(characteristicUUID)) { return handleConfigurationInfo(characteristic.getValue()); } } return false; } private boolean handleConfigurationInfo(byte[] value) { if (value == null || value.length < 4) { return false; } if (value[0] == 0x10 && value[1] == 0x0e && value[2] == 0x01) { String gpsVersion = new String(value, 3, value.length - 3); LOG.info("got gps version = " + gpsVersion); gbDevice.setFirmwareVersion2(gpsVersion); return true; } return false; } // this probably does more than only getting the GPS version... private AmazfitBipSupport requestGPSVersion(TransactionBuilder builder) { LOG.info("Requesting GPS version"); builder.write(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION), AmazfitBipService.COMMAND_REQUEST_GPS_VERSION); return this; } private AmazfitBipSupport setLanguage(TransactionBuilder builder) { String language = Locale.getDefault().getLanguage(); String country = Locale.getDefault().getCountry(); LOG.info("Setting watch language, phone language = " + language + " country = " + country); final byte[] command_new; final byte[] command_old; String localeString; switch (GBApplication.getPrefs().getInt("amazfitbip_language", -1)) { case 0: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SIMPLIFIED_CHINESE; localeString = "zh_CN"; break; case 1: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_TRADITIONAL_CHINESE; localeString = "zh_TW"; break; case 2: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_ENGLISH; localeString = "en_US"; break; case 3: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SPANISH; localeString = "es_ES"; break; default: switch (language) { case "zh": if (country.equals("TW") || country.equals("HK") || country.equals("MO")) { // Taiwan, Hong Kong, Macao command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_TRADITIONAL_CHINESE; localeString = "zh_TW"; } else { command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SIMPLIFIED_CHINESE; localeString = "zh_CN"; } break; case "es": command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_SPANISH; localeString = "es_ES"; break; default: command_old = AmazfitBipService.COMMAND_SET_LANGUAGE_ENGLISH; localeString = "en_US"; break; } } command_new = AmazfitBipService.COMMAND_SET_LANGUAGE_NEW_TEMPLATE; System.arraycopy(localeString.getBytes(), 0, command_new, 3, localeString.getBytes().length); builder.add(new ConditionalWriteAction(getCharacteristic(MiBand2Service.UUID_CHARACTERISTIC_3_CONFIGURATION)) { @Override protected byte[] checkCondition() { if (gbDevice.getType() == DeviceType.MIBAND3 || (gbDevice.getType() == DeviceType.AMAZFITBIP && new Version(gbDevice.getFirmwareVersion()).compareTo(new Version("0.1.0.77")) >= 0)) { return command_new; } else { return command_old; } } }); return this; } @Override public void phase2Initialize(TransactionBuilder builder) { super.phase2Initialize(builder); LOG.info("phase2Initialize..."); setLanguage(builder); requestGPSVersion(builder); } @Override public HuamiFWHelper createFWHelper(Uri uri, Context context) throws IOException { return new AmazfitBipFWHelper(uri, context); } }
package de.jtem.jrworkspace.plugin.aggregators; import static java.util.Collections.sort; import java.awt.Component; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.swing.Action; import javax.swing.JToolBar; import javax.swing.JToolBar.Separator; import de.jtem.jrworkspace.plugin.Plugin; import de.jtem.jrworkspace.plugin.flavor.ToolBarFlavor; public abstract class ToolBarAggregator extends Plugin implements ToolBarFlavor { private HashMap<Class<?>, HashSet<ToolBarItem>> itemMap = new HashMap<Class<?>, HashSet<ToolBarItem>>(); private JToolBar toolbar = new JToolBar(); public ToolBarAggregator() { toolbar.setName(getPluginInfo().name); } private class ToolBarItem implements Comparable<ToolBarItem> { public Object item = null; public double priority = 0.0; public ToolBarItem(Object item, double priority) { this.item = item; this.priority = priority; } public int compareTo(ToolBarItem o) { if (priority == o.priority) { return getName().compareTo(o.getName()); } return priority < o.priority ? -1 : 1; } public String getName() { if (item instanceof Action) { Action a = (Action)item; return (String)a.getValue(Action.NAME); } if (item instanceof Component) { Component c = (Component)item; if (c.getName() != null) { return c.getName(); } else { return ""; } } return ""; } } private void updateToolBar() { List<ToolBarItem> itemList = new LinkedList<ToolBarItem>(); for (Set<ToolBarItem> mSet : itemMap.values()) { itemList.addAll(mSet); } sort(itemList); toolbar.removeAll(); for (ToolBarItem tba : itemList) { if (tba.item instanceof Action) { toolbar.add((Action)tba.item); } else if (tba.item instanceof Separator) { toolbar.addSeparator(); } else if (tba.item instanceof Component) { toolbar.add((Component)tba.item); } } } private void addItem(Class<?> context, ToolBarItem item) { if (!itemMap.containsKey(context)) { itemMap.put(context, new HashSet<ToolBarItem>()); } Set<ToolBarItem> set = itemMap.get(context); set.add(item); updateToolBar(); } private void removeItem(Class<?> context, Object item) { Set<ToolBarItem> set = itemMap.get(context); if (set == null) { return; } ToolBarItem entry = null; for (ToolBarItem i : set) { if (i.item == item) { entry = i; break; } } if (entry != null) { set.remove(entry); updateToolBar(); } } public void addAction(Class<?> context, double priority, Action a) { ToolBarItem item = new ToolBarItem(a, priority); addItem(context, item); } public void addTool(Class<?> context, double priority, Component c) { ToolBarItem item = new ToolBarItem(c, priority); addItem(context, item); } public void addSeparator(Class<?> context, double priority) { Separator separator = new Separator(); ToolBarItem item = new ToolBarItem(separator, priority); addItem(context, item); } public void removeAll(Class<?> context) { itemMap.remove(context); updateToolBar(); } public void removeAction(Class<?> context, Action a) { removeItem(context, a); } public void removeTool(Class<?> context, Component c) { removeItem(context, c); } public Component getToolBarComponent() { return toolbar; } public double getToolBarPriority() { return 0; } public void setFloatable(boolean fl) { toolbar.setFloatable(fl); } }
package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitneo; import android.content.Context; import android.net.Uri; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import nodomain.freeyourgadget.gadgetbridge.GBApplication; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiCoordinator; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiFWHelper; import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiService; import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitneo.AmazfitNeoFWHelper; import nodomain.freeyourgadget.gadgetbridge.model.ActivityUser; import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec; import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions; import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.miband5.MiBand5Support; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.operations.UpdateFirmwareOperation; import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.operations.UpdateFirmwareOperation2020; public class AmazfitNeoSupport extends MiBand5Support { private static final Logger LOG = LoggerFactory.getLogger(AmazfitNeoSupport.class); @Override protected boolean notificationHasExtraHeader() { return false; } @Override protected AmazfitNeoSupport setDisplayItems(TransactionBuilder builder) { setDisplayItemsNew(builder, false, false, R.array.pref_neo_display_items_default); return this; } @Override protected AmazfitNeoSupport setFitnessGoal(TransactionBuilder builder) { LOG.info("Attempting to set Fitness Goal..."); setNeoFitnessGoal(builder); return this; } @Override protected AmazfitNeoSupport setGoalNotification(TransactionBuilder builder) { LOG.info("Attempting to set goal notification..."); setNeoFitnessGoal(builder); return this; } private void setNeoFitnessGoal(TransactionBuilder builder) { int fitnessGoal = GBApplication.getPrefs().getInt(ActivityUser.PREF_USER_STEPS_GOAL, ActivityUser.defaultUserStepsGoal); boolean fitnessGoalNotification = HuamiCoordinator.getGoalNotification(gbDevice.getAddress()); LOG.info("Setting Amazfit Neo fitness goal to: " + fitnessGoal + ", notification: " + fitnessGoalNotification); byte[] bytes = ArrayUtils.addAll( new byte[] { 0x3a, 1, 0, 0, 0, (byte) (fitnessGoalNotification ? 1 : 0 ) }, BLETypeConversions.fromUint16(fitnessGoal)); bytes = ArrayUtils.addAll(bytes, HuamiService.COMMAND_SET_FITNESS_GOAL_END); writeToChunked(builder, 2, bytes); } @Override public HuamiFWHelper createFWHelper(Uri uri, Context context) throws IOException { return new AmazfitNeoFWHelper(uri, context); } @Override public UpdateFirmwareOperation createUpdateFirmwareOperation(Uri uri) { return new UpdateFirmwareOperation2020(uri, this); } }
package org.csstudio.nams.common.material.regelwerk; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.csstudio.nams.common.fachwert.MessageKeyEnum; import org.csstudio.nams.common.fachwert.Millisekunden; import org.csstudio.nams.common.material.AlarmNachricht; import org.csstudio.nams.service.logging.declaration.ILogger; /** * @author Goesta Steen * */ public class StringRegel implements VersandRegel { private static ILogger logger; public static void staticInject(final ILogger o) { StringRegel.logger = o; } private final StringRegelOperator operator; private final String compareString; private final MessageKeyEnum messageKey; private final SimpleDateFormat amsDateFormat; public StringRegel(final StringRegelOperator operator, final MessageKeyEnum messageKey, final String compareString) { this.operator = operator; this.messageKey = messageKey; this.compareString = compareString; this.amsDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); } /* * (non-Javadoc) * * @see de.c1wps.desy.ams.allgemeines.regelwerk.VersandRegel#pruefeNachrichtAufBestaetigungsUndAufhebungsNachricht(de.c1wps.desy.ams.allgemeines.AlarmNachricht, * de.c1wps.desy.ams.allgemeines.regelwerk.Pruefliste) */ @Override public void pruefeNachrichtAufBestaetigungsUndAufhebungsNachricht( final AlarmNachricht nachricht, final Pruefliste bisherigesErgebnis) { // nothing to do here } /* * (non-Javadoc) * * @see de.c1wps.desy.ams.allgemeines.regelwerk.VersandRegel#pruefeNachrichtAufTimeOuts(de.c1wps.desy.ams.allgemeines.regelwerk.Pruefliste, * de.c1wps.desy.ams.allgemeines.Millisekunden) */ @Override public Millisekunden pruefeNachrichtAufTimeOuts( final Pruefliste bisherigesErgebnis, final Millisekunden verstricheneZeitSeitErsterPruefung) { // nothing to do here return null; } /* * (non-Javadoc) * * @see de.c1wps.desy.ams.allgemeines.regelwerk.VersandRegel#pruefeNachrichtErstmalig(de.c1wps.desy.ams.allgemeines.AlarmNachricht, * de.c1wps.desy.ams.allgemeines.regelwerk.Pruefliste) */ @Override public Millisekunden pruefeNachrichtErstmalig( final AlarmNachricht nachricht, final Pruefliste ergebnisListe) { boolean istGueltig = false; final String value = nachricht.getValueFor(this.messageKey); try { switch (this.operator) { // text compare case OPERATOR_TEXT_EQUAL: istGueltig = this.wildcardStringCompare(value, this.compareString); break; case OPERATOR_TEXT_NOT_EQUAL: istGueltig = !this.wildcardStringCompare(value, this.compareString); break; // numeric compare case OPERATOR_NUMERIC_LT: if (!value.isEmpty()) { istGueltig = this.numericCompare(value, this.compareString) < 0; } else { istGueltig = false; } break; case OPERATOR_NUMERIC_LT_EQUAL: if (!value.isEmpty()) { istGueltig = this.numericCompare(value, this.compareString) <= 0; } else { istGueltig = false; } break; case OPERATOR_NUMERIC_EQUAL: if (!value.isEmpty()) { istGueltig = this.numericCompare(value, this.compareString) == 0; } else { istGueltig = false; } break; case OPERATOR_NUMERIC_GT_EQUAL: if (!value.isEmpty()) { istGueltig = this.numericCompare(value, this.compareString) >= 0; } else { istGueltig = false; } break; case OPERATOR_NUMERIC_GT: if (!value.isEmpty()) { istGueltig = this.numericCompare(value, this.compareString) > 0; } else { istGueltig = false; } break; case OPERATOR_NUMERIC_NOT_EQUAL: if (!value.isEmpty()) { istGueltig = this.numericCompare(value, this.compareString) != 0; } else { istGueltig = false; } break; // time compare case OPERATOR_TIME_BEFORE: istGueltig = this.timeCompare(value, this.compareString) < 0; break; case OPERATOR_TIME_BEFORE_EQUAL: istGueltig = this.timeCompare(value, this.compareString) <= 0; break; case OPERATOR_TIME_EQUAL: istGueltig = this.timeCompare(value, this.compareString) == 0; break; case OPERATOR_TIME_AFTER_EQUAL: istGueltig = this.timeCompare(value, this.compareString) >= 0; break; case OPERATOR_TIME_AFTER: istGueltig = this.timeCompare(value, this.compareString) > 0; break; case OPERATOR_TIME_NOT_EQUAL: istGueltig = this.timeCompare(value, this.compareString) != 0; break; } } catch (final Exception e) { if(StringRegel.logger != null) { StringRegel.logger.logErrorMessage(this, "An error occured during parsing of : " + nachricht); } istGueltig = true; } if (istGueltig) { ergebnisListe.setzeErgebnisFuerRegelFallsVeraendert(this, RegelErgebnis.ZUTREFFEND); } else { ergebnisListe.setzeErgebnisFuerRegelFallsVeraendert(this, RegelErgebnis.NICHT_ZUTREFFEND); } return null; } @Override public String toString() { final StringBuilder stringBuilder = new StringBuilder("StringRegel: "); stringBuilder.append("messageKey: "); stringBuilder.append(this.messageKey); stringBuilder.append(" operator: "); stringBuilder.append(this.operator); stringBuilder.append(" compareString: "); stringBuilder.append(this.compareString); return stringBuilder.toString(); } private int numericCompare(final String value, final String compare) throws NumberFormatException { final double dVal = Double.parseDouble(value); final double dCompVal = Double.parseDouble(compare); return Double.compare(dVal, dCompVal); } private int timeCompare(final String value, final String compare) throws ParseException { // final Date dateValue = DateFormat.getDateInstance(DateFormat.SHORT, // Locale.US).parse(value); // final Date dateCompValue = DateFormat.getDateInstance(DateFormat.SHORT, // Locale.US).parse(compare); final Date dateValue = amsDateFormat.parse(value); final Date dateCompValue = amsDateFormat.parse(compare); return dateValue.compareTo(dateCompValue); } private boolean wildcardStringCompare(final String value, final String wildcardString2) { try { return WildcardStringCompare.compare(value, wildcardString2); } catch (final Exception e) { // TODO handle Exception return true; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((compareString == null) ? 0 : compareString.hashCode()); result = prime * result + ((messageKey == null) ? 0 : messageKey.hashCode()); result = prime * result + ((operator == null) ? 0 : operator.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final StringRegel other = (StringRegel) obj; if (compareString == null) { if (other.compareString != null) return false; } else if (!compareString.equals(other.compareString)) return false; if (messageKey == null) { if (other.messageKey != null) return false; } else if (!messageKey.equals(other.messageKey)) return false; if (operator == null) { if (other.operator != null) return false; } else if (!operator.equals(other.operator)) return false; return true; } }
package xmlviewer; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.swing.Action; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import javax.swing.tree.DefaultMutableTreeNode; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * * @author Phystem */ public class XmlTreeNode extends DefaultMutableTreeNode implements TableModel { private String name; private String text; private final List<String[]> attributes = new ArrayList<>(); private Action onValueChangeAction; private Boolean commented = false; public XmlTreeNode(Element element) { this.name = element.getNodeName(); this.text = getFirstLevelTextContent(element); for (int i = 0; i < element.getAttributes().getLength(); i++) { Node node = element.getAttributes().item(i); attributes.add(new String[]{node.getNodeName(), node.getTextContent()}); } } public XmlTreeNode(String name) { this.name = name; this.text = ""; } public void setOnValueChangeAction(Action onValueChangeAction) { this.onValueChangeAction = onValueChangeAction; } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public void addTableModelListener(TableModelListener l) { } @Override public void removeTableModelListener(TableModelListener l) { } @Override public int getRowCount() { return 1 + 1 + attributes.size(); } @Override public int getColumnCount() { return 2; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return !(columnIndex == 0 && rowIndex < 2); } @Override public String getColumnName(int column) { if (column == 0) { return "Property"; } return "Value"; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { switch (rowIndex) { case 0: return "NodeText"; case 1: return "Xpath"; default: return attributes.get(rowIndex - 2)[0]; } } else { switch (rowIndex) { case 0: return text; case 1: return getXpath(this); default: return attributes.get(rowIndex - 2)[1]; } } } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (!Objects.equals(getValueAt(rowIndex, columnIndex), aValue)) { if (columnIndex == 0) { switch (rowIndex) { case 0: case 1: break; default: attributes.get(rowIndex - 2)[0] = aValue.toString(); notifyChange("AttributeName", attributes.get(rowIndex - 2)[0], aValue.toString()); break; } } else { switch (rowIndex) { case 0: setText(aValue.toString()); break; case 1: break; default: attributes.get(rowIndex - 2)[1] = aValue.toString(); notifyChange("AttributeVal", attributes.get(rowIndex - 2)[0], aValue.toString()); break; } } } } private void notifyChange(String type, String name, String value) { if (onValueChangeAction != null) { onValueChangeAction.putValue("Type", type); onValueChangeAction.putValue("Name", name); onValueChangeAction.putValue("Value", value); onValueChangeAction.actionPerformed(null); } } public void modifyValueByAction(Action action) { String type = action.getValue("Type").toString(); String nameVal = action.getValue("Name").toString(); String value = action.getValue("Value").toString(); switch (type) { case "NodeText": text = value; break; case "AttributeName": int index = getAttrIndexByName(nameVal); if (index != -1) { attributes.get(index)[0] = value; } break; case "AttributeVal": int aindex = getAttrIndexByName(nameVal); if (aindex != -1) { attributes.get(aindex)[1] = value; } break; } } private int getAttrIndexByName(String name) { for (int i = 0; i < attributes.size(); i++) { if (attributes.get(i)[0].equals(name)) { return i; } } return -1; } private String getXpath(XmlTreeNode node) { return getElementXpath(node); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getXpath() { return getXpath(this); } public List<String[]> getAttributes() { return attributes; } public String getText() { return text; } public void setText(String text) { this.text = text; notifyChange("NodeText", "", text); } @Override public String toString() { return name + " [" + getElementIndex(this) + "]"; } public Boolean isCommented() { return commented; } public void setCommented(Boolean commented) { this.commented = commented; if (getChildCount() > 0) { for (int i = 0; i < getChildCount(); i++) { ((XmlTreeNode) getChildAt(i)).setCommented(commented); } } } private static String getElementXpath(XmlTreeNode elt) { String path = ""; try { for (; elt != null; elt = (XmlTreeNode) elt.getParent()) { int idx = getElementIndex(elt); String xname = elt.name; if (idx >= 1) { xname += "[" + idx + "]"; } path = "/" + xname + path; } } catch (Exception ee) { } return path; } private static int getElementIndex(XmlTreeNode original) { int count = 1; for (XmlTreeNode node = (XmlTreeNode) original.getPreviousSibling(); node != null; node = (XmlTreeNode) node.getPreviousSibling()) { if (node.name.equals(original.name)) { count++; } } return count; } private static String getFirstLevelTextContent(Node node) { NodeList list = node.getChildNodes(); StringBuilder textContent = new StringBuilder(); for (int i = 0; i < list.getLength(); ++i) { Node child = list.item(i); if (child.getNodeType() == Node.TEXT_NODE) { textContent.append(child.getTextContent().trim()); } } return textContent.toString().trim(); } }
package com.google.api.ads.adwords.jaxws.extensions.report.model.entities; import com.google.api.ads.adwords.jaxws.extensions.report.model.csv.annotation.CsvField; import com.google.api.ads.adwords.jaxws.extensions.report.model.csv.annotation.CsvReport; import com.google.api.ads.adwords.jaxws.extensions.report.model.util.UrlHashUtil; import com.google.api.ads.adwords.lib.jaxb.v201402.ReportDefinitionReportType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * Specific report class for ReportKeyword * * @author [email protected] (Julian Toledo) * @author [email protected] (Gustavo Moreira) * @author [email protected] (Nafis Zebarjadi) */ @Entity @com.googlecode.objectify.annotation.Entity @Table(name = "AW_ReportURL") @CsvReport(value = ReportDefinitionReportType.URL_PERFORMANCE_REPORT, reportExclusions = {"AveragePosition", "Device", "ClickType"}) public class ReportUrl extends ReportBase { @Column(name = "AD_FORMAT") @CsvField(value = "Ad type", reportField = "AdFormat") private String adFormat; @Column(name = "AD_GROUP_CRITERION_STATUS") @CsvField(value = "Keyword/Placement state", reportField = "AdGroupCriterionStatus") private String adGroupCriterionStatus; @Column(name = "AD_GROUP_ID") @CsvField(value = "Ad group ID", reportField = "AdGroupId") private Long adGroupId; @Column(name = "AD_GROUP_NAME") @CsvField(value = "Ad group", reportField = "AdGroupName") private String adGroupName; @Column(name = "AD_GROUP_STATUS") @CsvField(value = "Ad group state", reportField = "AdGroupStatus") private String adGroupStatus; @Column(name = "CAMPAIGN_ID") @CsvField(value = "Campaign ID", reportField = "CampaignId") private Long campaignId; @Column(name = "CAMPAIGN_NAME") @CsvField(value = "Campaign", reportField = "CampaignName") private String campaignName; @Column(name = "CAMPAIGN_STATUS") @CsvField(value = "Campaign state", reportField = "CampaignStatus") private String campaignStatus; @Column(name = "CRITERIA_PARAMETERS") @CsvField(value = "Keyword / Placement", reportField = "CriteriaParameters") public String criteriaParameters; @Column(name = "DISPLAY_NAME", length = 2048) @CsvField(value = "Criteria Display Name", reportField = "DisplayName") private String displayName; @Column(name = "DOMAIN") @CsvField(value = "Domain", reportField = "Domain") private String domain; @Column(name = "IS_AUTO_OPTIMIZED") @CsvField(value = "Targeting Mode", reportField = "IsAutoOptimized") private String isAutoOptimized; @Column(name = "IS_BID_ON_PATH") @CsvField(value = "Added", reportField = "IsBidOnPath") private String isBidOnPath; @Column(name = "IS_PATH_EXCLUDED") @CsvField(value = "Excluded", reportField = "IsPathExcluded") private String isPathExcluded; @Column(name = "URL", length = 2048) @CsvField(value = "URL", reportField = "Url") private String url; /** * Hibernate needs an empty constructor */ public ReportUrl() {} public ReportUrl(Long topAccountId, Long accountId) { this.topAccountId = topAccountId; this.accountId = accountId; } @Override public void setId() { // Generating unique id after having accountId, campaignId, adGroupId and date this.id = ""; if (this.getAccountId() != null) { this.id += this.getAccountId() + "-"; } if (this.getCampaignId() != null) { this.id += this.getCampaignId() + "-"; } if (this.getAdGroupId() != null) { this.id += this.getAdGroupId() + "-"; } // Generating a SHA-1 Hash of the URLs for ID generation if (this.getUrl() != null) { this.id += UrlHashUtil.createUrlHash(this.getUrl()); } this.id += setIdDates(); // Adding extra fields for unique ID if (this.getAdNetwork() != null && this.getAdNetwork().length() > 0) { this.id += "-" + this.getAdNetwork(); } if (this.getAdNetworkPartners() != null && this.getAdNetworkPartners().length() > 0) { this.id += "-" + this.getAdNetworkPartners(); } } public String getAdFormat() { return adFormat; } public void setAdFormat(String adFormat) { this.adFormat = adFormat; } public String getAdGroupCriterionStatus() { return adGroupCriterionStatus; } public void setAdGroupCriterionStatus(String adGroupCriterionStatus) { this.adGroupCriterionStatus = adGroupCriterionStatus; } public Long getAdGroupId() { return adGroupId; } public void setAdGroupId(Long adGroupId) { this.adGroupId = adGroupId; } public String getAdGroupName() { return adGroupName; } public void setAdGroupName(String adGroupName) { this.adGroupName = adGroupName; } public String getAdGroupStatus() { return adGroupStatus; } public void setAdGroupStatus(String adGroupStatus) { this.adGroupStatus = adGroupStatus; } public Long getCampaignId() { return campaignId; } public void setCampaignId(Long campaignId) { this.campaignId = campaignId; } public String getCampaignName() { return campaignName; } public void setCampaignName(String campaignName) { this.campaignName = campaignName; } public String getCampaignStatus() { return campaignStatus; } public void setCampaignStatus(String campaignStatus) { this.campaignStatus = campaignStatus; } public String getCriteriaParameters() { return criteriaParameters; } public void setCriteriaParameters(String criteriaParameters) { this.criteriaParameters = criteriaParameters; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getIsAutoOptimized() { return isAutoOptimized; } public void setIsAutoOptimized(String isAutoOptimized) { this.isAutoOptimized = isAutoOptimized; } public String getIsBidOnPath() { return isBidOnPath; } public void setIsBidOnPath(String isBidOnPath) { this.isBidOnPath = isBidOnPath; } public String getIsPathExcluded() { return isPathExcluded; } public void setIsPathExcluded(String isPathExcluded) { this.isPathExcluded = isPathExcluded; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package com.streamsets.pipeline.lib.stage.processor.fieldvaluereplacer; import com.streamsets.pipeline.api.ComplexField; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigDef.Type; import com.streamsets.pipeline.api.Field; import com.streamsets.pipeline.api.FieldSelector; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.Record; import com.streamsets.pipeline.api.StageDef; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.base.SingleLaneRecordProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; @GenerateResourceBundle @StageDef( version="1.0.0", label="Value Replacer", icon="replacer.svg") public class FieldValueReplacer extends SingleLaneRecordProcessor { private static final Logger LOG = LoggerFactory.getLogger(FieldValueReplacer.class); @ConfigDef(label = "Fields to NULL", required = false, type = Type.MODEL, defaultValue="", description="Replaces field values with null value.") @FieldSelector public List<String> fieldsToNull; @ConfigDef(label = "Replace Null values", required = false, type = Type.MODEL, defaultValue="", description="Replaces the null values in a field with a specified value.") @ComplexField public List<FieldValueReplacerConfig> fieldsToReplaceIfNull; @Override protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException { if(fieldsToNull != null && !fieldsToNull.isEmpty()) { for (String fieldToNull : fieldsToNull) { if(record.has(fieldToNull)) { Field field = record.get(fieldToNull); record.set(fieldToNull, Field.create(field, null)); } else { LOG.warn("Record {} does not have field {}. Ignoring field replacement.", record.getHeader().getSourceId(), fieldToNull); } } } if(fieldsToReplaceIfNull !=null && !fieldsToReplaceIfNull.isEmpty()) { for (FieldValueReplacerConfig fieldValueReplacerConfig : fieldsToReplaceIfNull) { for (String fieldToReplace : fieldValueReplacerConfig.fields) { if(record.has(fieldToReplace)) { Field field = record.get(fieldToReplace); if (field.getValue() == null) { record.set(fieldToReplace, Field.create(field, convertToType( fieldValueReplacerConfig.newValue, field.getType()))); } else { LOG.debug("Field {} in Record {} is not null. Ignoring field replacement.", fieldToReplace, record.getHeader().getSourceId()); } } else { LOG.warn("Record {} does not have field {}. Ignoring field replacement.", record.getHeader().getSourceId(), fieldToReplace); } } } } batchMaker.addRecord(record); } private Object convertToType(String stringValue, Field.Type fieldType) { switch (fieldType) { case BOOLEAN: return Boolean.valueOf(stringValue); case BYTE: return Byte.valueOf(stringValue); case BYTE_ARRAY: return stringValue.getBytes(); case CHAR: return stringValue.charAt(0); case DATE: DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); Date date; try { date = dateFormat.parse(stringValue); } catch (ParseException e) { throw new RuntimeException(e); } return date; case DATETIME: DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ", Locale.ENGLISH); Date dateTime; try { dateTime = dateTimeFormat.parse(stringValue); } catch (ParseException e) { throw new RuntimeException(e); } return dateTime; case DECIMAL: return new BigDecimal(stringValue); case DOUBLE: return Double.valueOf(stringValue); case FLOAT: return Float.valueOf(stringValue); case INTEGER: return Integer.valueOf(stringValue); case LONG: return Long.valueOf(stringValue); case LIST: case MAP: case SHORT: return Short.valueOf(stringValue); default: return stringValue; } } public static class FieldValueReplacerConfig { @ConfigDef(label = "Fields to Replace", required = true,type = Type.MODEL, defaultValue="") @FieldSelector public List<String> fields; @ConfigDef(label = "Replacement value", required = true,type = Type.STRING, defaultValue="", description="Value to replace null values") public String newValue; } }
package org.bitrepository.integrityservice.web; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.bitrepository.common.utils.TimeUtils; import org.bitrepository.integrityservice.IntegrityService; import org.bitrepository.integrityservice.IntegrityServiceFactory; import org.bitrepository.common.utils.FileSizeUtils; import org.bitrepository.service.workflow.WorkflowTimerTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/IntegrityService") public class RestIntegrityService { private final Logger log = LoggerFactory.getLogger(getClass()); private IntegrityService service; public RestIntegrityService() { this.service = IntegrityServiceFactory.getIntegrityService(); } /** * Method to get the checksum errors per pillar in a given collection. * @param collectionID, the collectionID from which to return checksum errors * @param pillarID, the ID of the pillar in the collection from which to return checksum errors * @param pageNumber, the page number for calculating offsets (@see pageSize) * @param pageSize, the number of checksum errors per page. */ @GET @Path("/getChecksumErrorFileIDs/") @Produces(MediaType.APPLICATION_JSON) public List<String> getChecksumErrors( @QueryParam("collectionID") String collectionID, @QueryParam("pillarID") String pillarID, @QueryParam("pageNumber") int pageNumber, @DefaultValue("100") @QueryParam("pageSize") int pageSize) { int firstID = (pageNumber - 1) * pageSize; int lastID = (pageNumber * pageSize) - 1; List<String> ids = service.getChecksumErrors(collectionID, pillarID, firstID, lastID); return ids; } /** * Method to get the list of missing files per pillar in a given collection. * @param collectionID, the collectionID from which to return missing files * @param pillarID, the ID of the pillar in the collection from which to return missing files * @param pageNumber, the page number for calculating offsets (@see pageSize) * @param pageSize, the number of checksum errors per page. */ @GET @Path("/getMissingFileIDs/") @Produces(MediaType.APPLICATION_JSON) public List<String> getMissingFileIDs( @QueryParam("collectionID") String collectionID, @QueryParam("pillarID") String pillarID, @QueryParam("pageNumber") int pageNumber, @DefaultValue("100") @QueryParam("pageSize") int pageSize) { int firstID = (pageNumber - 1) * pageSize; int lastID = (pageNumber * pageSize) - 1; List<String> ids = service.getMissingFiles(collectionID, pillarID, firstID, lastID); return ids; } /** * Method to get the list of present files on a pillar in a given collection. * @param collectionID, the collectionID from which to return present file list * @param pillarID, the ID of the pillar in the collection from which to return present file list * @param pageNumber, the page number for calculating offsets (@see pageSize) * @param pageSize, the number of checksum errors per page. */ @GET @Path("/getAllFileIDs/") @Produces(MediaType.APPLICATION_JSON) public List<String> getAllFileIDs( @QueryParam("collectionID") String collectionID, @QueryParam("pillarID") String pillarID, @QueryParam("pageNumber") int pageNumber, @DefaultValue("100") @QueryParam("pageSize") int pageSize) { int firstID = (pageNumber - 1) * pageSize; int lastID = (pageNumber * pageSize) - 1; List<String> ids = service.getAllFileIDs(collectionID, pillarID, firstID, lastID); return ids; } /** * Get the listing of integrity status as a JSON array */ @GET @Path("/getIntegrityStatus/") @Produces(MediaType.APPLICATION_JSON) public String getIntegrityStatus(@QueryParam("collectionID") String collectionID) { JSONArray array = new JSONArray(); for(String pillar : service.getPillarList(collectionID)) { array.put(makeIntegrityStatusObj(pillar, collectionID)); } return array.toString(); } /*** * Get the current workflows setup as a JSON array */ @GET @Path("/getWorkflowSetup/") @Produces(MediaType.APPLICATION_JSON) public String getWorkflowSetup(@QueryParam("collectionID") String collectionID) { try { JSONArray array = new JSONArray(); Collection<WorkflowTimerTask> workflows = service.getScheduledWorkflows(collectionID); for(WorkflowTimerTask workflow : workflows) { array.put(makeWorkflowSetupObj(workflow)); } return array.toString(); } catch (RuntimeException e) { log.error("Failed to getWorkflowSetup ", e); throw e; } } /** * Get the list of possible workflows as a JSON array */ @GET @Path("/getWorkflowList/") @Produces(MediaType.APPLICATION_JSON) public List<String> getWorkflowList(@QueryParam("collectionID") String collectionID) { Collection<WorkflowTimerTask> workflows = service.getScheduledWorkflows(collectionID); List<String> workflowIDs = new ArrayList<String>(); for(WorkflowTimerTask workflow : workflows) { workflowIDs.add(workflow.getWorkflowID().getWorkflowName()); } return workflowIDs; } /** * Start a named workflow. */ @POST @Path("/startWorkflow/") @Consumes("application/x-www-form-urlencoded") @Produces("text/html") public String startWorkflow(@FormParam("workflowID") String workflowID, @FormParam("collectionID") String collectionID) { Collection<WorkflowTimerTask> workflows = service.getScheduledWorkflows(collectionID); for(WorkflowTimerTask workflowTask : workflows) { if(workflowTask.getWorkflowID().getWorkflowName().equals(workflowID)) { return workflowTask.runWorkflow(); } } return "No workflow named '" + workflowID + "' was found!"; } /** * Start a named workflow. */ @GET @Path("/getCollectionInformation/") @Produces(MediaType.APPLICATION_JSON) public String getCollectionInformation(@QueryParam("collectionID") String collectionID) { JSONObject obj = new JSONObject(); Date lastIngest = service.getDateForNewestFileInCollection(collectionID); Long collectionDataSize = service.getCollectionSize(collectionID); Long numberOfFiles = service.getNumberOfFilesInCollection(collectionID); String lastIngestStr = lastIngest == null ? "No files ingested yet" : TimeUtils.shortDate(lastIngest); try { obj.put("lastIngest", lastIngestStr); obj.put("collectionSize", FileSizeUtils.toHumanShort(collectionDataSize == null ? 0 : collectionDataSize)); obj.put("numberOfFiles", numberOfFiles == null ? 0 : numberOfFiles); } catch (JSONException e) { obj = (JSONObject) JSONObject.NULL; } return obj.toString(); } private JSONObject makeIntegrityStatusObj(String pillarID, String collectionID) { JSONObject obj = new JSONObject(); try { obj.put("pillarID", pillarID); obj.put("totalFileCount", service.getNumberOfFiles(pillarID, collectionID)); obj.put("missingFilesCount",service.getNumberOfMissingFiles(pillarID, collectionID)); obj.put("checksumErrorCount", service.getNumberOfChecksumErrors(pillarID, collectionID)); return obj; } catch (JSONException e) { return (JSONObject) JSONObject.NULL; } } private JSONObject makeWorkflowSetupObj(WorkflowTimerTask workflowTask) { JSONObject obj = new JSONObject(); try { obj.put("workflowID", workflowTask.getWorkflowID().getWorkflowName()); obj.put("workflowDescription", workflowTask.getDescription()); obj.put("nextRun", TimeUtils.shortDate(workflowTask.getNextRun())); if (workflowTask.getLastRunStatistics().getFinish() == null) { obj.put("lastRun", "Workflow hasn't finished a run yet"); } else { obj.put("lastRun", TimeUtils.shortDate(workflowTask.getLastRunStatistics().getFinish())); } obj.put("lastRunDetails", workflowTask.getLastRunStatistics().getFullStatistics()); obj.put("executionInterval", TimeUtils.millisecondsToHuman(workflowTask.getIntervalBetweenRuns())); obj.put("currentState", workflowTask.getCurrentRunStatistics().getPartStatistics()); return obj; } catch (JSONException e) { return (JSONObject) JSONObject.NULL; } } }
package org.codingmatters.value.objects.generation; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import org.codingmatters.value.objects.spec.PropertySpec; import java.util.LinkedList; import java.util.List; import java.util.Objects; import static javax.lang.model.element.Modifier.*; import static org.codingmatters.value.objects.generation.PropertyHelper.propertyType; public class ValueImplementation { private final String packageName; private final String interfaceName; private final MethodSpec constructor; private final List<FieldSpec> fields; private final List<MethodSpec> getters; private MethodSpec equalsMethod; public ValueImplementation(String packageName, String interfaceName, List<PropertySpec> propertySpecs) { this.packageName = packageName; this.interfaceName = interfaceName; this.constructor = this.createConstructor(propertySpecs); this.fields = this.createFields(propertySpecs); this.getters = this.createGetters(propertySpecs); this.equalsMethod = this.createEquals(propertySpecs); } public TypeSpec type() { return TypeSpec.classBuilder(interfaceName + "Impl") .addSuperinterface(ClassName.get(this.packageName, interfaceName)) .addModifiers(PUBLIC) .addMethod(this.constructor) .addMethods(this.getters) .addMethod(this.equalsMethod) .addFields(this.fields) .build(); } private MethodSpec createConstructor(List<PropertySpec> propertySpecs) { MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder(); for (PropertySpec propertySpec : propertySpecs) { constructorBuilder .addParameter(propertyType(propertySpec), propertySpec.name()) .addStatement("this.$N = $N", propertySpec.name(), propertySpec.name()) ; } return constructorBuilder.build(); } private List<FieldSpec> createFields(List<PropertySpec> propertySpecs) { List<FieldSpec> fields = new LinkedList<>(); for (PropertySpec propertySpec : propertySpecs) { fields.add( FieldSpec.builder(propertyType(propertySpec), propertySpec.name(), PRIVATE, FINAL).build() ); } return fields; } private List<MethodSpec> createGetters(List<PropertySpec> propertySpecs) { List<MethodSpec> getters = new LinkedList<>(); for (PropertySpec propertySpec : propertySpecs) { getters.add( MethodSpec.methodBuilder(propertySpec.name()) .returns(propertyType(propertySpec)) .addModifiers(PUBLIC) .addStatement("return this.$N", propertySpec.name()) .build() ); } return getters; } private MethodSpec createEquals(List<PropertySpec> propertySpecs) { /* if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PropertySpec that = (PropertySpec) o; return Objects.equals(name, that.name) && Objects.equals(type, that.type); */ String equalsStatement; List<Object> equalsStatementParameters= new LinkedList<>(); if(propertySpecs.size() > 0) { equalsStatement = "return "; boolean started = false; for (PropertySpec propertySpec : propertySpecs) { if(started) { equalsStatement += " && \n"; } started = true; equalsStatement += "$T.equals(" + propertySpec.name() + ", that." + propertySpec.name() + ")"; equalsStatementParameters.add(ClassName.get(Objects.class)); } } else { equalsStatement = "return true"; } ClassName className = ClassName.get(this.packageName, this.interfaceName + "Impl"); return MethodSpec.methodBuilder("equals") .addModifiers(PUBLIC) .addParameter(ClassName.bestGuess(Object.class.getName()), "o") .returns(boolean.class) .addAnnotation(ClassName.get(Override.class)) .addStatement("if (this == o) return true") .addStatement("if (o == null || getClass() != o.getClass()) return false") .addStatement("$T that = ($T) o", className, className) .addStatement(equalsStatement, equalsStatementParameters.toArray()) .build(); } }
package org.kuali.kra.subaward.lookup.keyvalue; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.sys.framework.keyvalue.FormViewAwareUifKeyValuesFinderBase; import org.kuali.kra.subaward.document.SubAwardDocument; import org.kuali.rice.core.api.util.ConcreteKeyValue; import org.kuali.rice.core.api.util.KeyValue; import java.text.SimpleDateFormat; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class SubAwardAmountInfoTransactionValuesFinder extends FormViewAwareUifKeyValuesFinderBase { private static final ConcreteKeyValue SELECT = new ConcreteKeyValue("", "select"); @Override public List<KeyValue> getKeyValues() { final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); return Stream.concat(Stream.of(SELECT), ((SubAwardDocument) getDocument()).getSubAward().getAllSubAwardAmountInfos() .stream() .filter(info -> StringUtils.isNotEmpty(info.getModificationTypeCode())) .filter(info -> info.getModificationEffectiveDate() != null) .peek(info -> { if (info.getModificationType() == null) { info.refreshReferenceObject("modificationType"); } }) .map(info -> new ConcreteKeyValue(info.getSubAwardAmountInfoId().toString(), info.getModificationType().getDescription() + " - " + sdf.format(info.getEffectiveDate())))) .collect(Collectors.toList()); } }
package it.unibz.inf.ontop.iq.optimizer.impl.lj; import com.google.common.collect.*; import it.unibz.inf.ontop.dbschema.ForeignKeyConstraint; import it.unibz.inf.ontop.dbschema.RelationDefinition; import it.unibz.inf.ontop.dbschema.UniqueConstraint; import it.unibz.inf.ontop.injection.CoreSingletons; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.injection.OptimizationSingletons; import it.unibz.inf.ontop.iq.BinaryNonCommutativeIQTree; import it.unibz.inf.ontop.iq.IQTree; import it.unibz.inf.ontop.iq.node.*; import it.unibz.inf.ontop.iq.node.normalization.impl.RightProvenanceNormalizer; import it.unibz.inf.ontop.iq.transform.impl.DefaultNonRecursiveIQTreeTransformer; import it.unibz.inf.ontop.iq.transform.impl.DefaultRecursiveIQTreeVisitingTransformer; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.substitution.InjectiveVar2VarSubstitution; import it.unibz.inf.ontop.substitution.SubstitutionFactory; import it.unibz.inf.ontop.utils.ImmutableCollectors; import it.unibz.inf.ontop.utils.VariableGenerator; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.IntStream; import java.util.stream.Stream; public abstract class AbstractJoinTransferLJTransformer extends DefaultNonRecursiveIQTreeTransformer { private final Supplier<VariableNullability> variableNullabilitySupplier; // LAZY private VariableNullability variableNullability; protected final VariableGenerator variableGenerator; protected final RequiredExtensionalDataNodeExtractor requiredDataNodeExtractor; protected final RightProvenanceNormalizer rightProvenanceNormalizer; protected final OptimizationSingletons optimizationSingletons; private final IntermediateQueryFactory iqFactory; private final TermFactory termFactory; private final SubstitutionFactory substitutionFactory; protected AbstractJoinTransferLJTransformer(Supplier<VariableNullability> variableNullabilitySupplier, VariableGenerator variableGenerator, RequiredExtensionalDataNodeExtractor requiredDataNodeExtractor, RightProvenanceNormalizer rightProvenanceNormalizer, OptimizationSingletons optimizationSingletons) { this.variableNullabilitySupplier = variableNullabilitySupplier; this.variableGenerator = variableGenerator; this.requiredDataNodeExtractor = requiredDataNodeExtractor; this.rightProvenanceNormalizer = rightProvenanceNormalizer; this.optimizationSingletons = optimizationSingletons; CoreSingletons coreSingletons = optimizationSingletons.getCoreSingletons(); this.iqFactory = coreSingletons.getIQFactory(); this.termFactory = coreSingletons.getTermFactory(); this.substitutionFactory = coreSingletons.getSubstitutionFactory(); } @Override public IQTree transformLeftJoin(IQTree tree, LeftJoinNode rootNode, IQTree leftChild, IQTree rightChild) { IQTree transformedLeftChild = transform(leftChild); // Cannot reuse IQTree transformedRightChild = preTransformLJRightChild(rightChild); return furtherTransformLeftJoin(rootNode, transformedLeftChild, transformedRightChild) .orElseGet(() -> transformedLeftChild.equals(leftChild) && transformedRightChild.equals(rightChild) ? tree : iqFactory.createBinaryNonCommutativeIQTree(rootNode, transformedLeftChild, transformedRightChild)) .normalizeForOptimization(variableGenerator); } /** * Returns empty if no optimization has been applied */ protected Optional<IQTree> furtherTransformLeftJoin(LeftJoinNode rootNode, IQTree leftChild, IQTree rightChild) { ImmutableSet<ExtensionalDataNode> leftDataNodes = requiredDataNodeExtractor.extractSomeRequiredNodes(leftChild, true) .collect(ImmutableCollectors.toSet()); if (leftDataNodes.isEmpty()) return Optional.empty(); ImmutableSet<ExtensionalDataNode> rightDataNodes = extractRightUniqueDataNodes(rightChild); if (rightDataNodes.isEmpty()) return Optional.empty(); ImmutableSet<SelectedNode> selectedRightDataNodes = selectRightDataNodesToTransfer( leftDataNodes, rightDataNodes); if (selectedRightDataNodes.isEmpty()) return Optional.empty(); return Optional.of(transfer(rootNode, leftChild, rightChild, selectedRightDataNodes) .normalizeForOptimization(variableGenerator)); } protected ImmutableSet<SelectedNode> selectRightDataNodesToTransfer( ImmutableSet<ExtensionalDataNode> leftDataNodes, ImmutableSet<ExtensionalDataNode> rightDataNodes) { ImmutableMultimap<RelationDefinition, ExtensionalDataNode> leftDataNodeMultimap = leftDataNodes.stream() .collect(ImmutableCollectors.toMultimap( ExtensionalDataNode::getRelationDefinition, n -> n )); return rightDataNodes.stream() .map(r -> selectForTransfer(r, leftDataNodeMultimap)) .flatMap(o -> o .map(Stream::of) .orElseGet(Stream::empty)) .collect(ImmutableCollectors.toSet()); } protected abstract Optional<SelectedNode> selectForTransfer(ExtensionalDataNode rightDataNode, ImmutableMultimap<RelationDefinition, ExtensionalDataNode> leftMultimap); /** * Does not consider nodes co-occurring multiple times on the right. This allows to guarantee * that the position of node in the tree can be found again. * This looks fair as such co-occurrences are likely to be eliminated by other optimizations. */ private ImmutableSet<ExtensionalDataNode> extractRightUniqueDataNodes(IQTree rightChild) { ImmutableMultiset<ExtensionalDataNode> multiset = extractRightDataNodes(rightChild) .collect(ImmutableCollectors.toMultiset()); return multiset.entrySet().stream() .filter(e -> e.getCount() == 1) .map(Multiset.Entry::getElement) .collect(ImmutableCollectors.toSet()); } protected synchronized VariableNullability getInheritedVariableNullability() { if (variableNullability == null) variableNullability = variableNullabilitySupplier.get(); return variableNullability; } /** * Matches an unique constraint whose determinants are nullable in the tree */ protected Optional<ImmutableList<Integer>> matchUniqueConstraint(UniqueConstraint uniqueConstraint, ImmutableSet<ExtensionalDataNode> sameRelationLeftNodes, ImmutableMap<Integer, ? extends VariableOrGroundTerm> rightArgumentMap) { ImmutableList<Integer> indexes = uniqueConstraint.getDeterminants().stream() .map(a -> a.getIndex() - 1) .collect(ImmutableCollectors.toList()); if (!rightArgumentMap.keySet().containsAll(indexes)) return Optional.empty(); VariableNullability variableNullability = getInheritedVariableNullability(); if (indexes.stream().anyMatch(i -> Optional.of(rightArgumentMap.get(i)) .filter(t -> (t instanceof Variable) && variableNullability.isPossiblyNullable((Variable) t)) .isPresent())) return Optional.empty(); return sameRelationLeftNodes.stream() .map(ExtensionalDataNode::getArgumentMap) .filter(leftArgumentMap -> leftArgumentMap.keySet().containsAll(indexes) && indexes.stream().allMatch( i -> leftArgumentMap.get(i).equals(rightArgumentMap.get(i)))) .findAny() .map(n -> indexes); } protected Optional<ImmutableList<Integer>> matchForeignKey(ForeignKeyConstraint fk, ImmutableCollection<ExtensionalDataNode> leftNodes, ImmutableMap<Integer,? extends VariableOrGroundTerm> rightArgumentMap) { // NB: order matters ImmutableList<Integer> leftIndexes = fk.getComponents().stream() .map(c -> c.getAttribute().getIndex() - 1) .collect(ImmutableCollectors.toList()); ImmutableList<Integer> rightIndexes = fk.getComponents().stream() .map(c -> c.getReferencedAttribute().getIndex() - 1) .collect(ImmutableCollectors.toList()); return leftNodes.stream() .map(ExtensionalDataNode::getArgumentMap) .filter(lMap -> IntStream.range(0, leftIndexes.size()) .allMatch(i -> Optional.ofNullable(lMap.get(leftIndexes.get(i))) .filter(t -> !(t instanceof Variable) || !variableNullability.isPossiblyNullable((Variable)t)) .filter(l -> Optional.ofNullable(rightArgumentMap.get(rightIndexes.get(i))) .filter(l::equals) .isPresent()) .isPresent())) .findAny() .map(l -> rightIndexes); } /** * Can be overridden to put restrictions */ protected Stream<ExtensionalDataNode> extractRightDataNodes(IQTree rightChild) { return requiredDataNodeExtractor.extractSomeRequiredNodes(rightChild, true); } private IQTree transfer(LeftJoinNode rootNode, IQTree leftChild, IQTree rightChild, ImmutableSet<SelectedNode> selectedNodes) { if (selectedNodes.isEmpty()) throw new IllegalArgumentException("selectedNodes must not be empty"); ImmutableSet<DataNodeAndReplacement> nodesToTransferAndReplacements = selectedNodes.stream() .map(n -> n.transformForTransfer(variableGenerator, iqFactory)) .collect(ImmutableCollectors.toSet()); IQTree newLeftChild = iqFactory.createNaryIQTree( iqFactory.createInnerJoinNode(), Stream.concat( Stream.of(leftChild), nodesToTransferAndReplacements.stream() .map(n -> n.extensionalDataNode)) .collect(ImmutableCollectors.toList())); RenamingAndEqualities renamingAndEqualities = RenamingAndEqualities.extract( nodesToTransferAndReplacements.stream().map(n -> n.replacement), termFactory, substitutionFactory); Optional<ImmutableExpression> newLeftJoinCondition = termFactory.getConjunction( Stream.concat( rootNode.getOptionalFilterCondition() .map(renamingAndEqualities.renamingSubstitution::applyToBooleanExpression) .map(Stream::of) .orElseGet(Stream::empty), renamingAndEqualities.equalities.stream())); IQTree simplifiedRightChild = replaceSelectedNodesAndRename(selectedNodes, rightChild, renamingAndEqualities.renamingSubstitution); RightProvenanceNormalizer.RightProvenance rightProvenance = rightProvenanceNormalizer.normalizeRightProvenance( simplifiedRightChild, newLeftChild.getVariables(), newLeftJoinCondition, variableGenerator); BinaryNonCommutativeIQTree newLeftJoinTree = iqFactory.createBinaryNonCommutativeIQTree( iqFactory.createLeftJoinNode(newLeftJoinCondition), newLeftChild, rightProvenance.getRightTree()); ConstructionNode constructionNode = createConstructionNode(leftChild, rightChild, renamingAndEqualities.renamingSubstitution, rightProvenance.getProvenanceVariable()); return iqFactory.createUnaryIQTree(constructionNode, newLeftJoinTree); } /** * NB: nodes to be replaced by TrueNodes should be safe to do so (should have been already checked before) * In this context, renaming is safe to apply after. */ private IQTree replaceSelectedNodesAndRename(ImmutableSet<SelectedNode> selectedNodes, IQTree rightChild, InjectiveVar2VarSubstitution renamingSubstitution) { ReplaceNodeByTrueTransformer transformer = new ReplaceNodeByTrueTransformer( selectedNodes.stream() .map(n -> n.extensionalDataNode) .collect(ImmutableCollectors.toSet()), iqFactory); return rightChild.acceptTransformer(transformer) .applyFreshRenaming(renamingSubstitution); } private ConstructionNode createConstructionNode(IQTree leftChild, IQTree rightChild, InjectiveVar2VarSubstitution renamingSubstitution, Variable provenanceVariable) { ImmutableSet<Variable> projectedVariables = Sets.union(leftChild.getVariables(), rightChild.getVariables()) .immutableCopy(); ImmutableExpression condition = termFactory.getDBIsNotNull(provenanceVariable); ImmutableMap<Variable, ImmutableTerm> substitutionMap = renamingSubstitution.getImmutableMap().entrySet().stream() .collect(ImmutableCollectors.toMap( Map.Entry::getKey, e -> termFactory.getIfElseNull(condition, e.getValue()) )); return iqFactory.createConstructionNode(projectedVariables, substitutionFactory.getSubstitution(substitutionMap)); } @Override public IQTree transformFilter(IQTree tree, FilterNode rootNode, IQTree child) { // Recursive return transformUnaryNode(tree, rootNode, child, this::transform); } @Override public IQTree transformDistinct(IQTree tree, DistinctNode rootNode, IQTree child) { // Recursive return transformUnaryNode(tree, rootNode, child, this::transform); } @Override public IQTree transformSlice(IQTree tree, SliceNode sliceNode, IQTree child) { // Recursive return transformUnaryNode(tree, sliceNode, child, this::transform); } @Override public IQTree transformOrderBy(IQTree tree, OrderByNode rootNode, IQTree child) { // Recursive return transformUnaryNode(tree, rootNode, child, this::transform); } @Override public IQTree transformInnerJoin(IQTree tree, InnerJoinNode rootNode, ImmutableList<IQTree> children) { // Recursive return transformNaryCommutativeNode(tree, rootNode, children, this::transform); } @Override protected IQTree transformUnaryNode(IQTree tree, UnaryOperatorNode rootNode, IQTree child) { return transformUnaryNode(tree, rootNode, child, this::transformBySearchingFromScratch); } protected IQTree transformUnaryNode(IQTree tree, UnaryOperatorNode rootNode, IQTree child, Function<IQTree, IQTree> childTransformation) { IQTree newChild = childTransformation.apply(child); return newChild.equals(child) ? tree : iqFactory.createUnaryIQTree(rootNode, newChild) .normalizeForOptimization(variableGenerator); } @Override protected IQTree transformNaryCommutativeNode(IQTree tree, NaryOperatorNode rootNode, ImmutableList<IQTree> children) { return transformNaryCommutativeNode(tree, rootNode, children, this::transformBySearchingFromScratch); } protected IQTree transformNaryCommutativeNode(IQTree tree, NaryOperatorNode rootNode, ImmutableList<IQTree> children, Function<IQTree, IQTree> childTransformation) { ImmutableList<IQTree> newChildren = children.stream() .map(childTransformation) .collect(ImmutableCollectors.toList()); return newChildren.equals(children) ? tree : iqFactory.createNaryIQTree(rootNode, newChildren) .normalizeForOptimization(variableGenerator); } @Override protected IQTree transformBinaryNonCommutativeNode(IQTree tree, BinaryNonCommutativeOperatorNode rootNode, IQTree leftChild, IQTree rightChild) { return transformBinaryNonCommutativeNode(tree, rootNode, leftChild, rightChild, this::transformBySearchingFromScratch); } protected IQTree transformBinaryNonCommutativeNode(IQTree tree, BinaryNonCommutativeOperatorNode rootNode, IQTree leftChild, IQTree rightChild, Function<IQTree, IQTree> childTransformation) { IQTree newLeftChild = childTransformation.apply(leftChild); IQTree newRightChild = childTransformation.apply(rightChild); return newLeftChild.equals(leftChild) && newRightChild.equals(rightChild) ? tree : iqFactory.createBinaryNonCommutativeIQTree(rootNode, newLeftChild, newRightChild) .normalizeForOptimization(variableGenerator); } protected abstract IQTree transformBySearchingFromScratch(IQTree tree); /** * Can be overridden */ protected IQTree preTransformLJRightChild(IQTree rightChild) { return transformBySearchingFromScratch(rightChild); } protected static class SelectedNode { public final ImmutableList<Integer> determinantIndexes; public final ExtensionalDataNode extensionalDataNode; public SelectedNode(ImmutableList<Integer> determinantIndexes, ExtensionalDataNode extensionalDataNode) { this.determinantIndexes = determinantIndexes; this.extensionalDataNode = extensionalDataNode; } /** * The determinants are preserved, while the other arguments are replaced by a fresh variable */ public DataNodeAndReplacement transformForTransfer(VariableGenerator variableGenerator, IntermediateQueryFactory iqFactory) { ImmutableMap<Integer, ? extends VariableOrGroundTerm> initialArgumentMap = extensionalDataNode.getArgumentMap(); ImmutableMap<Integer, VariableOrGroundTerm> newArgumentMap = initialArgumentMap.entrySet().stream() .collect(ImmutableCollectors.toMap( Map.Entry::getKey, e -> determinantIndexes.contains(e.getKey()) ? e.getValue() : Optional.of(e.getValue()) .filter(t -> t instanceof Variable) .map(v -> ((Variable) v).getName()) .map(variableGenerator::generateNewVariable) .orElseGet(variableGenerator::generateNewVariable))); ImmutableMultimap<? extends VariableOrGroundTerm, Variable> replacement = initialArgumentMap.entrySet().stream() .filter(e -> !determinantIndexes.contains(e.getKey())) .filter(e -> !newArgumentMap.get(e.getKey()).equals(e.getValue())) .collect(ImmutableCollectors.toMultimap( Map.Entry::getValue, e -> (Variable) newArgumentMap.get(e.getKey()) )); return new DataNodeAndReplacement( iqFactory.createExtensionalDataNode(extensionalDataNode.getRelationDefinition(), newArgumentMap), replacement); } } protected static class DataNodeAndReplacement { public final ExtensionalDataNode extensionalDataNode; // Key: replaced argument, value: the replacing variable public final ImmutableMultimap<? extends VariableOrGroundTerm, Variable> replacement; public DataNodeAndReplacement(ExtensionalDataNode extensionalDataNode, ImmutableMultimap<? extends VariableOrGroundTerm, Variable> replacement) { this.extensionalDataNode = extensionalDataNode; this.replacement = replacement; } } protected static class RenamingAndEqualities { public final InjectiveVar2VarSubstitution renamingSubstitution; public final ImmutableSet<ImmutableExpression> equalities; private RenamingAndEqualities(InjectiveVar2VarSubstitution renamingSubstitution, ImmutableSet<ImmutableExpression> equalities) { this.renamingSubstitution = renamingSubstitution; this.equalities = equalities; } public static RenamingAndEqualities extract( Stream<ImmutableMultimap<? extends VariableOrGroundTerm, Variable>> replacementStream, TermFactory termFactory, SubstitutionFactory substitutionFactory) { ImmutableMap<? extends VariableOrGroundTerm, Collection<Variable>> replacement = replacementStream .flatMap(m -> m.entries().stream()) .collect(ImmutableCollectors.toMultimap()).asMap(); ImmutableMap<Variable, Variable> renamingSubstitutionMap = replacement.entrySet().stream() .filter(e -> e.getKey() instanceof Variable) .collect(ImmutableCollectors.toMap( e -> (Variable) e.getKey(), e -> e.getValue().iterator().next())); Stream<ImmutableExpression> varEqualities = replacement.values().stream() .filter(variables -> variables.size() > 1) .map(variables -> termFactory.getStrictEquality(ImmutableList.copyOf(variables))); Stream<ImmutableExpression> groundTermEqualities = replacement.entrySet().stream() .filter(e -> e.getKey() instanceof GroundTerm) .map(e -> termFactory.getStrictEquality(e.getKey(), e.getValue().iterator().next())); ImmutableSet<ImmutableExpression> equalities = Stream.concat(varEqualities, groundTermEqualities) .collect(ImmutableCollectors.toSet()); return new RenamingAndEqualities( substitutionFactory.getInjectiveVar2VarSubstitution(renamingSubstitutionMap), equalities); } } protected static class ReplaceNodeByTrueTransformer extends DefaultRecursiveIQTreeVisitingTransformer { private final ImmutableSet<ExtensionalDataNode> dataNodesToReplace; protected ReplaceNodeByTrueTransformer(ImmutableSet<ExtensionalDataNode> dataNodesToReplace, IntermediateQueryFactory iqFactory) { super(iqFactory); this.dataNodesToReplace = dataNodesToReplace; } @Override public IQTree transformExtensionalData(ExtensionalDataNode dataNode) { return dataNodesToReplace.contains(dataNode) ? iqFactory.createTrueNode() : dataNode; } } }
package org.objectweb.proactive.core.remoteobject; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.security.AccessControlException; import java.security.PublicKey; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.body.future.MethodCallResult; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.mop.ClassNotReifiableException; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.mop.MethodCallExecutionFailedException; import org.objectweb.proactive.core.mop.ReifiedCastException; import org.objectweb.proactive.core.mop.StubObject; import org.objectweb.proactive.core.remoteobject.adapter.Adapter; import org.objectweb.proactive.core.security.PolicyServer; import org.objectweb.proactive.core.security.ProActiveSecurityManager; import org.objectweb.proactive.core.security.SecurityContext; import org.objectweb.proactive.core.security.TypedCertificate; import org.objectweb.proactive.core.security.crypto.KeyExchangeException; import org.objectweb.proactive.core.security.crypto.SessionException; import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException; import org.objectweb.proactive.core.security.exceptions.SecurityNotAvailableException; import org.objectweb.proactive.core.security.securityentity.Entities; import org.objectweb.proactive.core.security.securityentity.Entity; /** * Implementation of a remote object. * * */ public class RemoteObjectImpl<T> implements RemoteObject, Serializable { protected Object target; protected String className; protected String proxyClassName; protected Adapter<T> adapter; protected ProActiveSecurityManager psm; public RemoteObjectImpl(String className, T target) { this(className, target, null); } public RemoteObjectImpl(String className, T target, Adapter<T> adapter) { this(className, target, adapter, null); } public RemoteObjectImpl(String className, T target, Adapter<T> adapter, ProActiveSecurityManager psm) { this.target = target; this.className = className; this.proxyClassName = SynchronousProxy.class.getName(); this.adapter = adapter; this.psm = psm; } public Reply receiveMessage(Request message) throws RenegotiateSessionException, ProActiveException { try { if (message.isCiphered() && (this.psm != null)) { message.decrypt(this.psm); } Object o; if (message instanceof RemoteObjectRequest) { o = message.getMethodCall().execute(this); } else { o = (message).getMethodCall().execute(this.target); } return new SynchronousReplyImpl(new MethodCallResult(o, null)); } catch (MethodCallExecutionFailedException e) { // e.printStackTrace(); throw new ProActiveException(e); } catch (InvocationTargetException e) { return new SynchronousReplyImpl(new MethodCallResult(null, e.getCause())); } } public TypedCertificate getCertificate() throws SecurityNotAvailableException, IOException { if (this.psm != null) { return this.psm.getCertificate(); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#getEntities() */ public Entities getEntities() throws SecurityNotAvailableException, IOException { if (this.psm != null) { return this.psm.getEntities(); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#getPolicy(org.objectweb.proactive.core.security.securityentity.Entities, org.objectweb.proactive.core.security.securityentity.Entities) */ public SecurityContext getPolicy(Entities local, Entities distant) throws SecurityNotAvailableException { if (this.psm == null) { throw new SecurityNotAvailableException(); } return this.psm.getPolicy(local, distant); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#getPublicKey() */ public PublicKey getPublicKey() throws SecurityNotAvailableException, IOException { if (this.psm != null) { return this.psm.getPublicKey(); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#publicKeyExchange(long, byte[]) */ public byte[] publicKeyExchange(long sessionID, byte[] signature) throws SecurityNotAvailableException, RenegotiateSessionException, KeyExchangeException, IOException { if (this.psm != null) { return this.psm.publicKeyExchange(sessionID, signature); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#randomValue(long, byte[]) */ public byte[] randomValue(long sessionID, byte[] clientRandomValue) throws SecurityNotAvailableException, RenegotiateSessionException, IOException { if (this.psm != null) { return this.psm.randomValue(sessionID, clientRandomValue); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#secretKeyExchange(long, byte[], byte[], byte[], byte[], byte[]) */ public byte[][] secretKeyExchange(long sessionID, byte[] encodedAESKey, byte[] encodedIVParameters, byte[] encodedClientMacKey, byte[] encodedLockData, byte[] parametersSignature) throws SecurityNotAvailableException, RenegotiateSessionException, IOException { if (this.psm != null) { return this.psm.secretKeyExchange(sessionID, encodedAESKey, encodedIVParameters, encodedClientMacKey, encodedLockData, parametersSignature); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#startNewSession(long, org.objectweb.proactive.core.security.SecurityContext, org.objectweb.proactive.core.security.TypedCertificate) */ public long startNewSession(long distantSessionID, SecurityContext policy, TypedCertificate distantCertificate) throws SecurityNotAvailableException, SessionException { if (this.psm != null) { return this.psm.startNewSession(distantSessionID, policy, distantCertificate); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#terminateSession(long) */ public void terminateSession(long sessionID) throws SecurityNotAvailableException, IOException { if (this.psm != null) { this.psm.terminateSession(sessionID); } throw new SecurityNotAvailableException(); } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.RemoteObject#getObjectProxy() */ public Object getObjectProxy() throws ProActiveException { try { Object reifiedObjectStub = MOP .createStubObject(this.className, target.getClass(), new Class[] {}); if (adapter != null) { // Constructor myConstructor = adapter.getClass().getConstructor(new Class[] {Class.forName(this.className)}); // Adapter ad = (Adapter) myConstructor.newInstance(new Object[] { MOP.createStubObject(this.className, target.getClass(), new Class[] {})}); Adapter<Object> ad = adapter.getClass().newInstance(); ad.setAdapter(reifiedObjectStub); return ad; } else { return reifiedObjectStub; } } catch (ClassNotReifiableException e) { e.printStackTrace(); } catch (ReifiedCastException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.RemoteObject#getObjectProxy(org.objectweb.proactive.core.remoteobject.RemoteRemoteObject) */ public Object getObjectProxy(RemoteRemoteObject rro) throws ProActiveException { try { Object reifiedObjectStub = MOP .createStubObject(this.className, target.getClass(), new Class[] {}); ((StubObject) reifiedObjectStub).setProxy(new SynchronousProxy(null, new Object[] { rro })); if (adapter != null) { // Constructor myConstructor = adapter.getClass().getConstructor(new Class[] {Class.forName(this.className)}); // Adapter ad = (Adapter) myConstructor.newInstance(new Object[] { MOP.createStubObject(this.className, target.getClass(), new Class[] {})}); Adapter<Object> ad = adapter.getClass().newInstance(); ad.setAdapter(reifiedObjectStub); return ad; } else { return reifiedObjectStub; } } catch (ClassNotReifiableException e) { e.printStackTrace(); } catch (ReifiedCastException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.RemoteObject#getClassName() */ public String getClassName() { return this.className; } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.RemoteObject#getProxyName() */ public String getProxyName() { return this.proxyClassName; } public Object getTarget() { return target; } public void setTarget(Object target) { this.target = target; } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.RemoteObject#getTargetClass() */ public Class<?> getTargetClass() { try { return Class.forName(className); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.RemoteObject#getAdapterClass() */ public Class<?> getAdapterClass() { if (adapter != null) { return adapter.getClass(); } return null; } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#getProActiveSecurityManager(org.objectweb.proactive.core.security.securityentity.Entity) */ public ProActiveSecurityManager getProActiveSecurityManager(Entity user) throws SecurityNotAvailableException, AccessControlException { if (this.psm == null) { throw new SecurityNotAvailableException(); } return this.psm.getProActiveSecurityManager(user); } /* (non-Javadoc) * @see org.objectweb.proactive.core.security.SecurityEntity#setProActiveSecurityManager(org.objectweb.proactive.core.security.securityentity.Entity, org.objectweb.proactive.core.security.PolicyServer) */ public void setProActiveSecurityManager(Entity user, PolicyServer policyServer) throws SecurityNotAvailableException, AccessControlException { if (this.psm == null) { throw new SecurityNotAvailableException(); } this.psm.setProActiveSecurityManager(user, policyServer); } }
package blog.semant; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import blog.absyn.Absyn; import blog.absyn.ArrayTy; import blog.absyn.BooleanExpr; import blog.absyn.Dec; import blog.absyn.DistinctSymbolDec; import blog.absyn.DistributionDec; import blog.absyn.DistributionExpr; import blog.absyn.DoubleExpr; import blog.absyn.EvidenceStmt; import blog.absyn.ExplicitSetExpr; import blog.absyn.Expr; import blog.absyn.ExprList; import blog.absyn.ExprTupleList; import blog.absyn.FieldList; import blog.absyn.FixedFuncDec; import blog.absyn.FuncCallExpr; import blog.absyn.FunctionDec; import blog.absyn.IfExpr; import blog.absyn.ImplicitSetExpr; import blog.absyn.IntExpr; import blog.absyn.ListInitExpr; import blog.absyn.MapInitExpr; import blog.absyn.NameTy; import blog.absyn.NullExpr; import blog.absyn.NumberDec; import blog.absyn.NumberExpr; import blog.absyn.OpExpr; import blog.absyn.OriginFieldList; import blog.absyn.OriginFuncDec; import blog.absyn.ParameterDec; import blog.absyn.QuantifiedFormulaExpr; import blog.absyn.QueryStmt; import blog.absyn.RandomFuncDec; import blog.absyn.Stmt; import blog.absyn.StmtList; import blog.absyn.StringExpr; import blog.absyn.SymbolArrayList; import blog.absyn.SymbolEvidence; import blog.absyn.SymbolExpr; import blog.absyn.TupleSetExpr; import blog.absyn.Ty; import blog.absyn.TypeDec; import blog.absyn.ValueEvidence; import blog.common.Util; import blog.distrib.EqualsCPD; import blog.model.ArgSpec; import blog.model.ArgSpecQuery; import blog.model.ArrayType; import blog.model.BuiltInFunctions; import blog.model.BuiltInTypes; import blog.model.CardinalitySpec; import blog.model.Clause; import blog.model.ComparisonFormula; import blog.model.ComparisonFormula.Operator; import blog.model.ConjFormula; import blog.model.ConstantInterp; import blog.model.DependencyModel; import blog.model.DisjFormula; import blog.model.EqualityFormula; import blog.model.Evidence; import blog.model.ExistentialFormula; import blog.model.ExplicitSetSpec; import blog.model.Formula; import blog.model.FormulaQuery; import blog.model.FuncAppTerm; import blog.model.Function; import blog.model.FunctionSignature; import blog.model.ImplicFormula; import blog.model.ImplicitSetSpec; import blog.model.ListSpec; import blog.model.MapSpec; import blog.model.MatrixSpec; import blog.model.Model; import blog.model.ModelEvidenceQueries; import blog.model.NegFormula; import blog.model.NonRandomFunction; import blog.model.OriginFunction; import blog.model.POP; import blog.model.Query; import blog.model.RandomFunction; import blog.model.SkolemConstant; import blog.model.SymbolEvidenceStatement; import blog.model.SymbolTerm; import blog.model.Term; import blog.model.TrueFormula; import blog.model.TupleSetSpec; import blog.model.Type; import blog.model.UniversalFormula; import blog.model.ValueEvidenceStatement; import blog.msg.ErrorMsg; import blog.type.Timestep; /** * @author leili * @author amatsukawa * @author rbharath * @author awong * @date 2014/2/11 */ public class Semant { private ErrorMsg errorMsg; private Model model; private Evidence evidence; private List<Query> queries; List<String> packages; // Maintains the currently active function private Function currFunction; public Semant(ErrorMsg msg) { this(new Model(), new Evidence(), new ArrayList<Query>(), msg); } public Semant(ModelEvidenceQueries meq, ErrorMsg msg) { this(meq.model, meq.evidence, meq.queries, msg); } public Semant(Model m, Evidence e, List<Query> qs, ErrorMsg msg) { model = m; evidence = e; errorMsg = msg; queries = qs; initialize(); } void error(int line, int col, String msg) { errorMsg.error(line, col, msg); } /** * search the pre-loaded packages for the classname of the distribution * function * * @param classname * @return */ Class getClassWithName(String classname) { for (String pkg : packages) { String name; if (pkg.isEmpty()) { name = classname; } else { name = pkg + '.' + classname; } try { return Class.forName(name); } catch (ClassNotFoundException e) { // continue loop } } Util.fatalError( "Could not load class '" + classname + "'; looked in the following packages: " + packages); return null; } protected boolean checkSymbolDup(int line, int col, String name) { if (getFunction(name, Collections.EMPTY_LIST) == null) { return true; } else { error(line, col, "Function/Symbol " + name + " without argument has already been declared."); return false; } } protected Function getFunction(String name, List<Type> argTypeList) { Function f = model.getFunction(new FunctionSignature(name, argTypeList)); if ((f == null) && (evidence != null)) { f = evidence.getSkolemConstant(name); } return f; } /** * translate the NameTy to internal BLOG type * * @param type * @return * internal BLOG type * if not found, it will produce an error message */ Type getNameType(NameTy type) { Type ty = null; String name = type.name.toString(); ty = Type.getType(name); if (ty == null) { error(type.line, type.col, "Type " + name + " undefined!"); } return ty; } // // TODO: fix list type!!! // Type getListType(Ty type) { // Type ty = null; // if (type instanceof ListTy) { // Type elementType = getNameType(((ListTy) type).typ); // String name = "List<" + elementType.getName() + ">"; // System.out.println(name); // Type listType = model.getType(name); // if (listType == null) { // error(type.line, type.col, "Type " + name + " undefined!"); // } else { // error(type.line, type.col, "Type not allowed!"); // return ty; ArrayType getArrayType(ArrayTy type) { Type termType = getType(type.typ); if (termType == null) { error(type.line, type.col, "Type " + type.typ.toString() + " undefined!"); } ArrayType arrType = new ArrayType(termType); arrType = (ArrayType) Type.getType(arrType.getName()); return arrType; } /** * check whether e is a list of symbol names (function call without argument) * * @param e * @return a list of Symbol names */ List<String> getSymbolList(ExprList e) { List<String> res = new ArrayList<String>(); for (; e != null; e = e.next) { Expr h = e.head; if (h instanceof FuncCallExpr) { FuncCallExpr fc = (FuncCallExpr) h; String fn = fc.func.toString(); if (fc.args == null) checkSymbolDup(fc.line, fc.col, fn); else { error(fc.line, fc.col, "Invalid expression: expecting No argument"); } res.add(fn); } else if (h instanceof SymbolExpr) { SymbolExpr var = (SymbolExpr) h; String sym = var.name.toString(); checkSymbolDup(var.line, var.col, sym); res.add(sym); } else { error(h.line, h.col, "Invalid expression: expecting Symbol names"); } } return res; } Type getType(Ty type) { if (type instanceof NameTy) { return getNameType((NameTy) type); } // TODO list type // else if (type instanceof ListTy) { // return getListType(type); else if (type instanceof ArrayTy) { return getArrayType((ArrayTy) type); } if (type != null) error(type.line, type.col, "Type not allowed!"); return null; } /** * create default library search packages for distribution function class */ protected void initialize() { packages = new ArrayList<String>(); packages.add(""); packages.add("blog.distrib"); } public void addPackages(List<String> pkgs) { packages.addAll(pkgs); } void transDec(Dec e) { if (e instanceof TypeDec) { transDec((TypeDec) e); } else if (e instanceof DistinctSymbolDec) { transDec((DistinctSymbolDec) e); } else if (e instanceof DistributionDec) { // TODO } else if (e instanceof FunctionDec) { transDec((FunctionDec) e); } else if (e instanceof NumberDec) { transDec((NumberDec) e); } else if (e instanceof ParameterDec) { // TODO } } /** * translate the Distinct symbol declaration to internal model representation * * @param e */ void transDec(DistinctSymbolDec e) { Type type = getType(e.type); for (SymbolArrayList sa = e.symbols; sa != null; sa = sa.next) { if (sa.head == null) { error(sa.head.line, sa.head.col, "Symbol mistake!"); } else { int sz = sa.head.size; String name = sa.head.name.toString(); if (checkSymbolDup(sa.line, sa.col, name)) if (sz == 1) { model.addEnumeratedObject(name, type); } else { for (int i = 0; i < sz; i++) { model.addEnumeratedObject(name + "[" + i + "]", type); } } } } } /** * translate Function declaration to internal representation * for nonrandom and random functions, this step will not process the body * * @param e */ void transDec(FunctionDec e) { Type resTy = getType(e.result); if (resTy == null) { error(e.line, e.col, "Symbol at line " + e.result.line + " col " + e.result.col + " does not have a type!"); return; } List<Type> argTy = new ArrayList<Type>(); List<String> argVars = new ArrayList<String>(); for (FieldList fl = e.params; fl != null; fl = fl.next) { Type ty = getType(fl.head.typ); argTy.add(ty); if (fl.head.var != null) { String vn = fl.head.var.toString(); if (argVars.contains(vn)) { error(fl.line, fl.col, "Variable " + vn + " used multiple times"); } else { argVars.add(vn); } } } // Handling to attach array type to list expression // TODO need to remove this part. // if (e.result instanceof ArrayTy) { // if (e.body instanceof ListInitExpr) { // ((ListInitExpr) e.body).type = e.result; // } else if (e.body instanceof DistributionExpr) { // // Nothing yet // } else if (e.body instanceof SymbolExpr) { // // Nothing yet // } else if (e.body instanceof IfExpr) { // // Nothing yet // } else { // error(e.line, e.col, "Cannot create array from non-list syntax!"); String name = e.name.toString(); Function fun = getFunction(name, argTy); if (fun != null) { error(e.line, e.col, "Function " + name + " already defined"); } if (!(model.getOverlappingFuncs(name, (Type[]) argTy.toArray(new Type[argTy.size()])).isEmpty())) { error(e.line, e.col, "Function " + name + " overlapped"); } if (e instanceof FixedFuncDec) { NonRandomFunction f; if (argTy.size() == 0) { f = NonRandomFunction.createConstant(name, resTy, e.body); } else { f = new NonRandomFunction(name, argTy, resTy); } fun = f; } else if (e instanceof RandomFuncDec) { // dependency statement will added later RandomFunction f = new RandomFunction(name, argTy, resTy, null); f.setArgVars(argVars); fun = f; } else if (e instanceof OriginFuncDec) { if (argTy.size() != 1) { error(e.line, e.col, "Incorrect number of arguments: origin function expecting exactly One argument"); } if (e.body != null) { error( e.line, e.col, "Invalid origin function definition: the body of origin functions should be empty"); } OriginFunction f = new OriginFunction(name, argTy, resTy); fun = f; } model.addFunction(fun); } /** * translate the function body * only nonrandom and random functions will be processed in this step. * * @param e */ void transFuncBody(FunctionDec e) { if (e instanceof OriginFuncDec) return; List<Type> argTy = new ArrayList<Type>(); for (FieldList fl = e.params; fl != null; fl = fl.next) { Type ty = getType(fl.head.typ); argTy.add(ty); } String name = e.name.toString(); Function fun = getFunction(name, argTy); currFunction = fun; if (e instanceof FixedFuncDec) { if (e.body == null) { error(e.line, e.col, "empty fixed function body"); } else if (argTy.size() > 0) { if (e.body instanceof FuncCallExpr) { FuncCallExpr fc = (FuncCallExpr) e.body; List<ArgSpec> args = transExprList(fc.args, false); Class cls = getClassWithName(fc.func.toString()); ((NonRandomFunction) fun).setInterpretation(cls, args); } else if (e.body instanceof DoubleExpr) { List<Object> args = new ArrayList<Object>(); args.add(((DoubleExpr) e.body).value); ConstantInterp constant = new ConstantInterp(args); ((NonRandomFunction) fun).setInterpretation(constant); } else if (e.body instanceof IntExpr) { List<Object> args = new ArrayList<Object>(); args.add(((IntExpr) e.body).value); ConstantInterp constant = new ConstantInterp(args); ((NonRandomFunction) fun).setInterpretation(constant); } else if (e.body instanceof StringExpr) { List<Object> args = new ArrayList<Object>(); args.add(((StringExpr) e.body).value); ConstantInterp constant = new ConstantInterp(args); ((NonRandomFunction) fun).setInterpretation(constant); } else { // TODO: Implement more general fixed functions } } else { // note will do type checking later Object funcBody = transExpr(e.body); ArgSpec funcValue = (ArgSpec) funcBody; ((NonRandomFunction) fun).setInterpretation( blog.model.ConstantInterp.class, Collections.singletonList(funcValue)); } } else if (e instanceof RandomFuncDec) { DependencyModel dm = transDependency(e.body, fun.getRetType(), fun.getDefaultValue()); ((RandomFunction) fun).setDepModel(dm); } currFunction = null; } /** * check whether the actual type matches the expected type. * * @param ty * @param value * @return */ ArgSpec getTypedValue(Type ty, ArgSpec value) { if (value instanceof Term) { Type valuetype = ((Term) value).getType(); if (valuetype.isSubtypeOf(ty)) return value; else return null; } else if (value instanceof Formula) { if (ty == BuiltInTypes.BOOLEAN) return value; else return null; } else if (value instanceof MatrixSpec) { if (ty.isSubtypeOf(BuiltInTypes.REAL_MATRIX)) { return value; } else { return null; } } else if (value instanceof ListSpec) { if (ty.isSubtypeOf(BuiltInTypes.REAL_MATRIX)) { return ((ListSpec) value).transferToMatrix(); } else if (ty.isSubtypeOf(BuiltInTypes.REAL_ARRAY)) { return ((ListSpec) value).transferToMatrix(); } else { return null; } } else return null; } DependencyModel transDependency(Expr e, Type resTy, Object defVal) { Object body = transExpr(e); List<Clause> cl = new ArrayList<Clause>(1); if (body instanceof Term || body instanceof Formula) { cl.add(new Clause(TrueFormula.TRUE, EqualsCPD.class, Collections .<ArgSpec> emptyList(), Collections.singletonList((ArgSpec) body))); } else if (body instanceof Clause) { cl.add((Clause) body); } else if (e instanceof IfExpr) { cl = (List<Clause>) body; } else { error(e.line, e.col, "invalid body of dependency clause"); } return new DependencyModel(cl, resTy, defVal); } /** * semantic checking for evidence statement and translate to internal * representation * * @param e */ void transEvi(EvidenceStmt e) { if (e instanceof ValueEvidence) { transEvi((ValueEvidence) e); } else if (e instanceof SymbolEvidence) { transEvi((SymbolEvidence) e); } else { error(e.line, e.col, "Unsupported Evidence type: " + e); } } /** * valid evidence format include (will be checked in semantic checking) * * - general form: random expression = fixed expression * - number_evidence: # implicit_set = int constant * * @param e */ void transEvi(ValueEvidence e) { Object left = transExpr(e.left); if (left instanceof CardinalitySpec) { // number evidence // # implicit_set = int constant ArgSpec value = null; if (e.right instanceof IntExpr) { value = (ArgSpec) transExpr(e.right); } else { error(e.right.line, e.right.col, "Number evidence expecting integer(natural number) on the right side"); } evidence.addValueEvidence(new ValueEvidenceStatement( (CardinalitySpec) left, value)); } else if (left instanceof ArgSpec) { // general value expression Object value = transExpr(e.right); if (value instanceof ArgSpec) { // need more semantic checking on type match // if (left instanceof Term) { // value = getTypedValue(((Term) left).getType(), (ArgSpec) value); // let us use the type checking in Evidence, if (value != null) evidence.addValueEvidence(new ValueEvidenceStatement((ArgSpec) left, (ArgSpec) value)); else error(e.line, e.col, "type mistach for observation or translation error"); } else { error(e.right.line, e.right.col, "Invalid expression on the right side of evidence."); } } else { error(e.left.line, e.left.col, "Invalid expression on the left side of evidence."); } } /** * symbol_evidence format: implicit_set = explicit_set * * @param e */ void transEvi(SymbolEvidence e) { Object left = transExpr(e.left); if (left instanceof ImplicitSetSpec) { // symbol evidence // implicit set = set of ids ImplicitSetSpec leftset = (ImplicitSetSpec) left; List<String> value = null; if (e.right instanceof ExplicitSetExpr) { value = getSymbolList(((ExplicitSetExpr) e.right).values); } else { error( e.right.line, e.right.col, "Invalid expression on right side of symbol evidence: explicit set of symbols expected"); } SymbolEvidenceStatement sevid = new SymbolEvidenceStatement(leftset, value); if (!evidence.addSymbolEvidence(sevid)) { error(e.right.line, e.right.col, "Duplicate names in symbol evidence."); } for (SkolemConstant obj : sevid.getSkolemConstants()) { model.addFunction(obj); } // // add value evidence of this cardinality spec also!!! // evidence.addValueEvidence(new ValueEvidenceStatement(new // CardinalitySpec( // leftset), createSpecFromInt(value.size()))); } else { error( e.left.line, e.left.col, "Invalid expression on left side of symbool evidence: implicit set of symbols expected"); } } /** * translate number statement to model representation * * @param e */ void transDec(NumberDec e) { Type typ = getType(e.typ); List<OriginFunction> fs = new ArrayList<OriginFunction>(); List<String> argVars = new ArrayList<String>(); for (OriginFieldList fl = e.params; fl != null; fl = fl.next) { String name = fl.func.toString(); Function f = getFunction(name, Collections.singletonList(typ)); if (f == null) { error(fl.line, fl.col, "function undefined: " + name); } else if (!(f instanceof OriginFunction)) { error(fl.line, fl.col, "Function " + name + " with argument type " + typ.getName() + " has not been declared as an origin function."); } else if (fs.contains(f)) { error(fl.line, fl.col, "Origin function " + name + " used more than once"); } else { fs.add((OriginFunction) f); } String vn = fl.var.toString(); if (argVars.contains(vn)) { error(fl.line, fl.col, "Variable " + vn + " used multiple times"); } else { argVars.add(vn); } } POP pop = new POP(typ, fs, transDependency(e.body, BuiltInTypes.NATURAL_NUM, new Integer(0))); if (typ.getPOPWithOriginFuncs(pop.getOriginFuncSet()) != null) { error(e.line, e.col, "number statement #" + typ.getName() + " uses same origin functions as earlier number statement."); } else { typ.addPOP(pop); } pop.setGenObjVars(argVars); } /** * add the declared type to model * * @param e */ void transDec(TypeDec e) { String name = e.name.toString(); if (Type.getType(name) != null) { error(e.line, e.col, "Type " + name + " already defined!"); } else { model.addType(name); // BuiltInTypes.addArrayTypes(name); } } Clause transExpr(DistributionExpr e) { /* * TODO 1: Handle map expressions, not just lists */ Class cls = getClassWithName(e.name.toString()); if (cls == null) { error(e.line, e.col, "Class not found: " + e.name); } List<ArgSpec> as = null; if (e.args != null) { as = transExprList(e.args, true); } Clause c = new Clause(TrueFormula.TRUE, cls, as); c.setLocation(e.line); return c; } ArgSpec transExpr(DoubleExpr e) { // TODO is there a better way than using function? Term t = new FuncAppTerm(BuiltInFunctions.getLiteral( String.valueOf(e.value), BuiltInTypes.REAL, e.value), Collections.EMPTY_LIST); t.setLocation(e.line); return t; } Object transExpr(Expr e) { if (e instanceof DistributionExpr) { return transExpr((DistributionExpr) e); } else if (e instanceof BooleanExpr) { return transExpr((BooleanExpr) e); } else if (e instanceof DoubleExpr) { return transExpr((DoubleExpr) e); } else if (e instanceof IntExpr) { return transExpr((IntExpr) e); } else if (e instanceof StringExpr) { return transExpr((StringExpr) e); } else if (e instanceof NumberExpr) { return transExpr((NumberExpr) e); } else if (e instanceof ImplicitSetExpr) { return transExpr((ImplicitSetExpr) e); } else if (e instanceof ExplicitSetExpr) { return transExpr((ExplicitSetExpr) e); } else if (e instanceof TupleSetExpr) { return transExpr((TupleSetExpr) e); } else if (e instanceof IfExpr) { return transExpr((IfExpr) e); } else if (e instanceof OpExpr) { return transExpr((OpExpr) e); } else if (e instanceof FuncCallExpr) { return transExpr((FuncCallExpr) e); } else if (e instanceof ListInitExpr) { return transExpr((ListInitExpr) e); } else if (e instanceof MapInitExpr) { return transExpr((MapInitExpr) e); } else if (e instanceof SymbolExpr) { return transExpr((SymbolExpr) e); } else if (e instanceof NullExpr) { return transExpr((NullExpr) e); } else if (e instanceof QuantifiedFormulaExpr) { return transExpr((QuantifiedFormulaExpr) e); } return null; } ArgSpec transExpr(NullExpr e) { Term t = new FuncAppTerm(BuiltInFunctions.NULL, Collections.EMPTY_LIST); t.setLocation(e.line); return t; } ArgSpec transExpr(SymbolExpr e) { Term t = new SymbolTerm(e.name.toString()); t.setLocation(e.line); return t; } ArgSpec transExpr(FuncCallExpr e) { List<ArgSpec> args = transExprList(e.args, true); List<Type> argTypes = new ArrayList<Type>(); // TODO put type checking code here for (ArgSpec as : args) { // argTypes.add(as.get) // to add type for this argspec } Term t = new FuncAppTerm(e.func.toString(), args.toArray(new ArgSpec[args .size()])); t.setLocation(e.line); return t; } ArgSpec transExpr(ListInitExpr e) { List<ArgSpec> values = transExprList(e.values, true); // todo support stack and concatenation return new ListSpec(values, getType(e.type)); } MapSpec transExpr(MapInitExpr e) { List<ArgSpec> probKeys = new ArrayList<ArgSpec>(); List<Object> probs = new ArrayList<Object>(); ExprTupleList mapExprs = e.values; while (mapExprs != null) { probKeys.add((ArgSpec) transExpr(mapExprs.from)); probs.add(transExpr(mapExprs.to)); mapExprs = mapExprs.next; } MapSpec m = new MapSpec(probKeys, probs); return m; } Formula transExpr(QuantifiedFormulaExpr e) { Object quantExpr = transExpr(e.formula); if (!(quantExpr instanceof Formula)) { return null; } Formula quantFormula = (Formula) quantExpr; Type quantType = getType(e.type); if (e.quantifier == QuantifiedFormulaExpr.FORALL) { return new UniversalFormula(e.var.toString(), quantType, quantFormula); } else if (e.quantifier == QuantifiedFormulaExpr.EXISTS) { return new ExistentialFormula(e.var.toString(), quantType, quantFormula); } else { return null; } } /** * combine clauses from if * * @param test * @param value * @param clauses */ void combineFormula(Formula test, Object value, List<Clause> clauses) { if (value instanceof Clause) { Clause c = (Clause) value; clauses.add(addTestConditionToClause(test, c)); } else if (value instanceof List<?>) { for (Object v : ((List<?>) value)) { Clause c = (Clause) v; clauses.add(addTestConditionToClause(test, c)); } } else { // should be ArgSpec clauses.add(new Clause(test, EqualsCPD.class, Collections .<ArgSpec> emptyList(), Collections.singletonList((ArgSpec) value))); } } private Clause addTestConditionToClause(Formula test, Clause c) { Formula old = c.getCond(); Formula ne = createConjunction(test, old); c.setCond(ne); return c; } private Formula createConjunction(Formula c1, Formula c2) { if (c2 == TrueFormula.TRUE) return c1; if (c1 == TrueFormula.TRUE) return c2; return new ConjFormula(c1, c2); } /** * combine clauses from else * * @param value * @param clauses */ void combineFormula(Object value, List<Clause> clauses) { if (value instanceof Clause) { clauses.add((Clause) value); } else if (value instanceof List<?>) { clauses.addAll((List<Clause>) value); } else { // should be ArgSpec clauses.add(new Clause(TrueFormula.TRUE, EqualsCPD.class, Collections .<ArgSpec> emptyList(), Collections.singletonList((ArgSpec) value))); } } List<Clause> transExpr(IfExpr e) { ArrayList<Clause> clauses = new ArrayList<Clause>(); Formula test = TrueFormula.TRUE; // TODO: write a test for the SymbolTerm case to exclude non-Boolean // variables/functions Object cond = transExpr(e.test); if (cond instanceof Formula) { test = (Formula) cond; } else if (cond instanceof Term) { test = new EqualityFormula((Term) cond, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } else { error(e.test.line, e.test.col, "Cannot use non-Boolean value as predicate for if clause"); System.exit(1); } Object thenClause = transExpr(e.thenclause); combineFormula(test, thenClause, clauses); if (e.elseclause != null) { Object elseClause = transExpr(e.elseclause); combineFormula(elseClause, clauses); } return clauses; } ArgSpec transExpr(BooleanExpr e) { Term t = new FuncAppTerm(BuiltInFunctions.getLiteral( String.valueOf(e.value), BuiltInTypes.BOOLEAN, e.value)); t.setLocation(e.line); return t; } ArgSpec transExpr(IntExpr e) { Term t = new FuncAppTerm(BuiltInFunctions.getLiteral( String.valueOf(e.value), BuiltInTypes.INTEGER, e.value)); t.setLocation(e.line); return t; } ArgSpec transExpr(StringExpr e) { Term t = new FuncAppTerm(BuiltInFunctions.getLiteral("\"" + e.value + "\"", BuiltInTypes.STRING, e.value)); t.setLocation(e.line); return t; } ExplicitSetSpec transExpr(ExplicitSetExpr e) { List terms = new ArrayList(); ExprList currTerm = e.values; while (currTerm != null) { terms.add(transExpr(currTerm.head)); currTerm = currTerm.next; } return new ExplicitSetSpec(terms); } ImplicitSetSpec transExpr(ImplicitSetExpr e) { Type typ = getType(e.typ); String vn; if (e.var != null) { vn = e.var.toString(); } else { vn = "_"; } Formula cond = TrueFormula.TRUE; if (e.cond != null) { Object c = transExpr(e.cond); if (c instanceof Formula) { cond = (Formula) c; } else { error( e.cond.line, e.cond.col, "Invalid expression as condition in implicit set: formula(boolean valued expression) expected"); } } return new ImplicitSetSpec(vn, typ, cond); } TupleSetSpec transExpr(TupleSetExpr e) { List<Term> tupleTerms = new ArrayList<Term>(); List<Type> varTypes = new ArrayList<Type>(); List<String> varNames = new ArrayList<String>(); Formula cond = null; while (e.setTuple != null) { Object tuple = transExpr(e.setTuple.head); if (tuple instanceof Term) { tupleTerms.add((Term) tuple); } else { error( e.cond.line, e.cond.col, "Invalid expression as term in tuple set: term (number, string, boolean, or function call) expected"); } e.setTuple = e.setTuple.next; } // TODO: TRANSLATE THE VARIABLE LIST AND TYPES while (e.enumVars != null) { Object varType = this.getType(e.enumVars.head.typ); Object varName = e.enumVars.head.var.toString(); if (varType instanceof Type && varName instanceof String) { varTypes.add((Type) varType); varNames.add((String) varName); } else { error( e.cond.line, e.cond.col, "Invalid expression as logical variable in implicit set: logical variable expected"); } e.enumVars = e.enumVars.next; } if (e.cond != null) { Object c = transExpr(e.cond); if (c instanceof Formula) { cond = (Formula) c; } else { error( e.cond.line, e.cond.col, "Invalid expression as condition in implicit set: formula(boolean valued expression) expected"); } } return new TupleSetSpec(tupleTerms, varTypes, varNames, cond); } /** * number expression translated to CardinalitySpec * * @param e * @return */ CardinalitySpec transExpr(NumberExpr e) { Object r = transExpr(e.values); if (r instanceof ImplicitSetSpec) { return new CardinalitySpec((ImplicitSetSpec) r); } else { error(e.line, e.col, "Number expression expecting implicit set"); } return null; } Object transExpr(OpExpr e) { Object left = null, right = null; Term term; if (e.left != null) { left = transExpr(e.left); } if (e.right != null) { right = transExpr(e.right); } String funcname = null; switch (e.oper) { case OpExpr.PLUS: funcname = BuiltInFunctions.PLUS_NAME; break; case OpExpr.MINUS: funcname = BuiltInFunctions.MINUS_NAME; break; case OpExpr.MULT: funcname = BuiltInFunctions.MULT_NAME; break; case OpExpr.DIV: funcname = BuiltInFunctions.DIV_NAME; break; case OpExpr.MOD: funcname = BuiltInFunctions.MOD_NAME; break; case OpExpr.POWER: funcname = BuiltInFunctions.POWER_NAME; break; case OpExpr.EQ: return new EqualityFormula((Term) left, (Term) right); case OpExpr.NEQ: return new NegFormula(new EqualityFormula((Term) left, (Term) right)); case OpExpr.LT: return new ComparisonFormula((Term) left, (Term) right, Operator.LT); case OpExpr.LEQ: return new ComparisonFormula((Term) left, (Term) right, Operator.LEQ); case OpExpr.GT: return new ComparisonFormula((Term) left, (Term) right, Operator.GT); case OpExpr.GEQ: return new ComparisonFormula((Term) left, (Term) right, Operator.GEQ); case OpExpr.AND: if (left instanceof Term) { left = new EqualityFormula((Term) left, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } if (right instanceof Term) { right = new EqualityFormula((Term) right, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } return new ConjFormula((Formula) left, (Formula) right); case OpExpr.OR: if (left instanceof Term) { left = new EqualityFormula((Term) left, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } if (right instanceof Term) { right = new EqualityFormula((Term) right, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } return new DisjFormula((Formula) left, (Formula) right); case OpExpr.IMPLY: if (left instanceof Term) { left = new EqualityFormula((Term) left, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } if (right instanceof Term) { right = new EqualityFormula((Term) right, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } return new ImplicFormula((Formula) left, (Formula) right); case OpExpr.NOT: if (right instanceof Term) { right = new EqualityFormula((Term) right, BuiltInTypes.BOOLEAN.getCanonicalTerm(true)); } return new NegFormula((Formula) right); case OpExpr.SUB: Function func; if (left instanceof SymbolTerm) { if (e.right instanceof IntExpr) { String objectname = ((SymbolTerm) left).getName() + '[' + ((IntExpr) e.right).value + ']'; Function object = getFunction(objectname, Collections.EMPTY_LIST); if (object != null) return new FuncAppTerm(object); } Object symbolMapping = model .getFuncsWithName(((SymbolTerm) left).getName()).iterator().next(); if (((Function) symbolMapping).getRetType() == BuiltInTypes.REAL_ARRAY) { func = BuiltInFunctions.SUB_REAL_ARRAY; } else if (((Function) symbolMapping).getRetType() == BuiltInTypes.INTEGER_ARRAY) { func = BuiltInFunctions.SUB_INT_ARRAY; } else { func = BuiltInFunctions.SUB_MAT; } } else { // a hack now, need to consider IntegerMatrix as well. func = BuiltInFunctions.SUB_MAT; } term = new FuncAppTerm(func, (ArgSpec) left, (ArgSpec) right); return term; case OpExpr.AT: if (e.left == null && e.right instanceof IntExpr) { Timestep t = Timestep.at(((IntExpr) e.right).value); term = new FuncAppTerm(BuiltInFunctions.getLiteral(t.toString(), BuiltInTypes.TIMESTEP, t)); term.setLocation(e.line); return term; } default: error(e.getLine(), e.getCol(), "The operation could not be applied" + e.toString()); return null; } // TODO remove the following lines after testing. (leili) // if (e.left != null) // sig = new FunctionSignature(funcname, leftType, rightType); // else // sig = new FunctionSignature(funcname, rightType); // NonRandomFunction func = BuiltInFunctions.getFunction(sig); // if (func != null) { if (e.left != null) // term = new FuncAppTerm(func, (Term) left, (Term) right); term = new FuncAppTerm(funcname, (Term) left, (Term) right); else term = new FuncAppTerm(funcname, (Term) right); return term; // } else { // Util.fatalError("No operator " + funcname + " for operands of type " // + leftType + "," + rightType + "!"); } /** * check list of expressions * * @param e * list of expression * @param allowRandom * whether allow terms with random functions in the expression * @return */ List<ArgSpec> transExprList(ExprList e, boolean allowRandom) { List<ArgSpec> args = new ArrayList<ArgSpec>(); for (; e != null; e = e.next) { Object o = transExpr(e.head); if (o != null) { if (o instanceof ArgSpec) { args.add((ArgSpec) o); } else { error(e.line, e.col, "Expression expected! but we get " + o.toString()); } } } // TODO add checking for allowRandom return args; } /** * @param e */ void transQuery(QueryStmt e) { // TODO Auto-generated method stub Object as = transExpr(e.query); Query q; if (as != null) { if (as instanceof Formula) { q = new FormulaQuery((Formula) as); } else { q = new ArgSpecQuery((ArgSpec) as); } queries.add(q); } } void transStmt(Stmt e) { if (e instanceof Dec) { transDec((Dec) e); } else if (e instanceof EvidenceStmt) { transEvi((EvidenceStmt) e); } else if (e instanceof QueryStmt) { transQuery((QueryStmt) e); } } /** * each statement list will be processed twice * first time everything except processing function body for random/nonrandom * functions * second time those function bodies * * @param stl */ void transStmtList(StmtList stl) { } /** * semantic checking and translate the BLOG program to model representation * * @param e * @return whether any error happened during parsing and translating */ public boolean transProg(Absyn e) { if (e instanceof StmtList) { StmtList stl = (StmtList) e; List<Stmt> stmts = new LinkedList<Stmt>(); List<FunctionDec> funs = new LinkedList<FunctionDec>(); for (; stl != null; stl = stl.next) { if (stl.head instanceof Dec) { transStmt(stl.head); if (stl.head instanceof FunctionDec) funs.add((FunctionDec) stl.head); } else { stmts.add(stl.head); } } // second pass translate function body for (FunctionDec fd : funs) transFuncBody(fd); // type checking if (!model.checkTypesAndScope()) { error(0, 0, "type checking failed"); } // third pass: translate observation and statement for (Stmt stm : stmts) { transStmt(stm); } if (!evidence.checkTypesAndScope(model)) { error(0, 0, "type checking failed for evidence"); } for (Iterator iter = queries.iterator(); iter.hasNext();) { Query q = (Query) iter.next(); if (!q.checkTypesAndScope(model)) { error(0, 0, "type checking failed for query"); } } } else { error(0, 0, "Invalid program"); } return errorMsg.OK(); } public ModelEvidenceQueries getModelEvidenceQueries() { return new ModelEvidenceQueries(model, evidence, queries); } }
package org.deviceconnect.android.deviceplugin.sphero; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import orbotix.macro.BackLED; import orbotix.macro.Delay; import orbotix.macro.MacroObject; import orbotix.macro.RGB; import orbotix.robot.base.CollisionDetectedAsyncData; import orbotix.robot.base.CollisionDetectedAsyncData.CollisionPower; import orbotix.robot.base.Robot; import orbotix.robot.base.RobotProvider; import orbotix.robot.sensor.Acceleration; import orbotix.robot.sensor.DeviceSensorsData; import orbotix.robot.sensor.GyroData; import orbotix.robot.sensor.LocatorData; import orbotix.robot.sensor.QuaternionSensor; import orbotix.robot.sensor.ThreeAxisSensor; import orbotix.sphero.ConnectionListener; import orbotix.sphero.DiscoveryListener; import orbotix.sphero.Sphero; import org.deviceconnect.android.deviceplugin.sphero.data.DeviceInfo; import org.deviceconnect.android.deviceplugin.sphero.data.DeviceInfo.DeviceCollisionListener; import org.deviceconnect.android.deviceplugin.sphero.data.DeviceInfo.DeviceSensorListener; import org.deviceconnect.android.deviceplugin.sphero.profile.SpheroLightProfile; import org.deviceconnect.android.deviceplugin.sphero.profile.SpheroProfile; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.profile.DeviceOrientationProfile; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; /** * Sphero. * @author NTT DOCOMO, INC. */ public final class SpheroManager implements DeviceSensorListener, DeviceCollisionListener { /** * Manager. */ public static final SpheroManager INSTANCE = new SpheroManager(); private static final int CONNECTION_TIMEOUT = 30000; private static final int DISCONNECTION_RETRY_NUM = 10; private static final int DISCONNECTION_RETRY_DELAY = 1000; /** * 1G = {@value} . */ private static final double G = 9.81; private ConcurrentHashMap<String, DeviceInfo> mDevices; private boolean mIsDiscovering; private List<Sphero> mFoundDevices; private DeviceDiscoveryListener mDiscoveryListener; /** * Sphere. */ private RobotProvider mRobotProvider; private Object mConnLock; private SpheroDeviceService mService; /** * DeviceInfo. */ private DeviceInfo mCacheDeviceInfo; /** * DeviceSensorsData. */ private DeviceSensorsData mCacheDeviceSensorsData; private long mCacheInterval; /** * SpheroManager. */ private SpheroManager() { mDevices = new ConcurrentHashMap<String, DeviceInfo>(); mRobotProvider = RobotProvider.getDefaultProvider(); mRobotProvider.addConnectionListener(new ConnectionListenerImpl()); mRobotProvider.addDiscoveryListener(new DiscoveryListenerImpl()); mConnLock = new Object(); } /** * . * * @param context . */ public synchronized void startDiscovery(final Context context) { if (mIsDiscovering) { return; } if (BuildConfig.DEBUG) { Log.d("", "start discovery"); } mIsDiscovering = mRobotProvider.startDiscovery(context); } /** * . * * @param listener */ public synchronized void setDiscoveryListener(final DeviceDiscoveryListener listener) { mDiscoveryListener = listener; } public synchronized void stopDiscovery() { if (!mIsDiscovering) { return; } if (BuildConfig.DEBUG) { Log.d("", "stop discovery"); } mRobotProvider.endDiscovery(); mIsDiscovering = false; if (mFoundDevices != null) { mFoundDevices.clear(); } } /** * Sphero. */ public synchronized void shutdown() { stopDiscovery(); mRobotProvider.removeAllControls(); mRobotProvider.removeConnectionListeners(); mRobotProvider.removeDiscoveryListeners(); mRobotProvider.disconnectControlledRobots(); mRobotProvider.shutdown(); mService = null; } /** * . * * @return */ public synchronized List<Sphero> getFoundDevices() { return mFoundDevices; } /** * . * * @return */ public synchronized Collection<DeviceInfo> getConnectedDevices() { return mDevices.values(); } /** * ID. * * @param serviceId ID * @return null */ public DeviceInfo getDevice(final String serviceId) { return mDevices.get(serviceId); } /** * . * * @param serviceId ID * @return null */ public synchronized Sphero getNotConnectedDevice(final String serviceId) { if (mFoundDevices == null) { return null; } for (Sphero s : mFoundDevices) { if (s.getUniqueId().equals(serviceId)) { return s; } } return null; } /** * IDSphero. * * @param id SpheroUUID */ public void disconnect(final String id) { if (id == null) { return; } DeviceInfo removed = mDevices.remove(id); if (removed != null) { final Sphero sphero = removed.getDevice(); for (int i = 0; i < DISCONNECTION_RETRY_NUM; i++) { if (!sphero.isConnected()) { break; } sphero.disconnect(); try { Thread.sleep(DISCONNECTION_RETRY_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * IDSphero. * * @param id SpheroUUID * @return truefalse */ public boolean connect(final String id) { Sphero connected = null; synchronized (this) { if (mFoundDevices == null) { return false; } for (Sphero s : mFoundDevices) { if (s.getUniqueId().equals(id)) { if (s.isConnected()) { return true; } connected = s; break; } } } if (connected != null) { synchronized (mConnLock) { mRobotProvider.connect(connected); try { mConnLock.wait(CONNECTION_TIMEOUT); } catch (InterruptedException e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } connected = null; } } } if (connected != null) { return connected.isConnected(); } return false; } /** * 1. * @param device * @param listener */ public void startSensor(final DeviceInfo device, final DeviceSensorListener listener) { synchronized (device) { if (!device.isSensorStarted()) { device.startSensor(new DeviceSensorListener() { @Override public void sensorUpdated(final DeviceInfo info, final DeviceSensorsData data, final long interval) { if (listener != null) { listener.sensorUpdated(info, data, interval); } if (!hasSensorListener(device.getDevice().getUniqueId())) { stopSensor(device); } } }); } else { if (listener != null) { listener.sensorUpdated(mCacheDeviceInfo, mCacheDeviceSensorsData, mCacheInterval); } } } } /** * . * * @param device */ public void startSensor(final DeviceInfo device) { synchronized (device) { if (!device.isSensorStarted()) { device.startSensor(this); } } } /** * . * * @param device */ public void stopSensor(final DeviceInfo device) { synchronized (device) { if (device.isSensorStarted()) { device.stopSensor(); } } } /** * . * * @param device */ public void startCollision(final DeviceInfo device) { synchronized (device) { if (!device.isCollisionStarted()) { device.startCollistion(this); } } } /** * . * * @param device * @param listener */ public void startCollision(final DeviceInfo device, final DeviceCollisionListener listener) { synchronized (device) { if (!device.isCollisionStarted()) { device.startCollistion(new DeviceCollisionListener() { @Override public void collisionDetected(final DeviceInfo info, final CollisionDetectedAsyncData data) { if (listener != null) { listener.collisionDetected(info, data); } if (!hasCollisionListener(device.getDevice().getUniqueId())) { stopCollision(device); } } }); } } } /** * . * * @param device */ public void stopCollision(final DeviceInfo device) { synchronized (device) { if (device.isCollisionStarted()) { device.stopCollision(); } } } /** * . * * @param service */ public void setService(final SpheroDeviceService service) { mService = service; } /** * . * * @param info * @return truefalse */ public boolean hasSensorEvent(final DeviceInfo info) { List<Event> eventQua = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_QUATERNION, SpheroProfile.ATTR_ON_QUATERNION); List<Event> eventOri = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), DeviceOrientationProfile.PROFILE_NAME, null, DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION); List<Event> eventLoc = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_LOCATOR, SpheroProfile.ATTR_ON_LOCATOR); return (eventOri.size() != 0) || (eventQua.size() != 0) || (eventLoc.size() != 0); } /** * . * * @param info * @param intensity * @param pattern */ public static void flashBackLight(final DeviceInfo info, final int intensity, final long[] pattern) { MacroObject m = new MacroObject(); for (int i = 0; i < pattern.length; i++) { if (i % 2 == 0) { m.addCommand(new BackLED(intensity, 0)); } else { m.addCommand(new BackLED(0, 0)); } m.addCommand(new Delay((int) pattern[i])); } int oriIntensity = (int) (info.getBackBrightness() * SpheroLightProfile.MAX_BRIGHTNESS); m.addCommand(new BackLED(oriIntensity, 0)); info.getDevice().executeMacro(m); } /** * . * * @param info * @param colors * @param pattern */ public static void flashFrontLight(final DeviceInfo info, final int[] colors, final long[] pattern) { MacroObject m = new MacroObject(); for (int i = 0; i < pattern.length; i++) { if (i % 2 == 0) { m.addCommand(new RGB(colors[0], colors[1], colors[2], 0)); } else { m.addCommand(new RGB(0, 0, 0, 0)); } m.addCommand(new Delay((int) pattern[i])); } info.getDevice().executeMacro(m); } /** * Orientation. * @param data * @param interval * @return Orientation */ public static Bundle createOrientation(final DeviceSensorsData data, final long interval) { Acceleration accData = data.getAccelerometerData().getFilteredAcceleration(); Bundle accelerationIncludingGravity = new Bundle(); // SpheroG(1G=9.81m/s^2)Device Connect(m/s^2) DeviceOrientationProfile.setX(accelerationIncludingGravity, accData.x * G); DeviceOrientationProfile.setY(accelerationIncludingGravity, accData.y * G); DeviceOrientationProfile.setZ(accelerationIncludingGravity, accData.z * G); GyroData gyroData = data.getGyroData(); ThreeAxisSensor threeAxisSensor = gyroData.getRotationRateFiltered(); Bundle rotationRate = new Bundle(); DeviceOrientationProfile.setAlpha(rotationRate, 0.1d * threeAxisSensor.x); DeviceOrientationProfile.setBeta(rotationRate, 0.1d * threeAxisSensor.y); DeviceOrientationProfile.setGamma(rotationRate, 0.1d * threeAxisSensor.z); Bundle orientation = new Bundle(); DeviceOrientationProfile.setAccelerationIncludingGravity(orientation, accelerationIncludingGravity); DeviceOrientationProfile.setRotationRate(orientation, rotationRate); DeviceOrientationProfile.setInterval(orientation, interval); return orientation; } /** * Quaternion. * @param data * @param interval * @return Quaternion */ public static Bundle createQuaternion(final DeviceSensorsData data, final long interval) { QuaternionSensor quat = data.getQuaternion(); Bundle quaternion = new Bundle(); quaternion.putDouble(SpheroProfile.PARAM_Q0, quat.q0); quaternion.putDouble(SpheroProfile.PARAM_Q1, quat.q1); quaternion.putDouble(SpheroProfile.PARAM_Q2, quat.q2); quaternion.putDouble(SpheroProfile.PARAM_Q3, quat.q3); quaternion.putLong(SpheroProfile.PARAM_INTERVAL, interval); return quaternion; } /** * Locator. * @param data * @return Locator */ public static Bundle createLocator(final DeviceSensorsData data) { LocatorData loc = data.getLocatorData(); Bundle locator = new Bundle(); locator.putFloat(SpheroProfile.PARAM_POSITION_X, loc.getPositionX()); locator.putFloat(SpheroProfile.PARAM_POSITION_Y, loc.getPositionY()); locator.putFloat(SpheroProfile.PARAM_VELOCITY_X, loc.getVelocityX()); locator.putFloat(SpheroProfile.PARAM_VELOCITY_Y, loc.getVelocityY()); return locator; } /** * Collision. * @param data * @return Collision */ public static Bundle createCollision(final CollisionDetectedAsyncData data) { Bundle collision = new Bundle(); Acceleration impactAccelerationData = data.getImpactAcceleration(); Bundle impactAcceleration = new Bundle(); impactAcceleration.putDouble(SpheroProfile.PARAM_X, impactAccelerationData.x); impactAcceleration.putDouble(SpheroProfile.PARAM_Y, impactAccelerationData.y); impactAcceleration.putDouble(SpheroProfile.PARAM_Z, impactAccelerationData.z); Bundle impactAxis = new Bundle(); impactAxis.putBoolean(SpheroProfile.PARAM_X, data.hasImpactXAxis()); impactAxis.putBoolean(SpheroProfile.PARAM_Y, data.hasImpactYAxis()); CollisionPower power = data.getImpactPower(); Bundle impactPower = new Bundle(); impactPower.putShort(SpheroProfile.PARAM_X, power.x); impactPower.putShort(SpheroProfile.PARAM_Y, power.y); collision.putBundle(SpheroProfile.PARAM_IMPACT_ACCELERATION, impactAcceleration); collision.putBundle(SpheroProfile.PARAM_IMPACT_AXIS, impactAxis); collision.putBundle(SpheroProfile.PARAM_IMPACT_POWER, impactPower); collision.putFloat(SpheroProfile.PARAM_IMPACT_SPEED, data.getImpactSpeed()); collision.putLong(SpheroProfile.PARAM_IMPACT_TIMESTAMP, data.getTimeStamp().getTime()); return collision; } /** * Sphero. * * @param sphero Sphero */ private void onConnected(final Sphero sphero) { DeviceInfo info = new DeviceInfo(); info.setDevice(sphero); info.setBackBrightness(1.f); sphero.enableStabilization(true); if (BuildConfig.DEBUG) { Log.d("", "connected device : " + sphero.toString()); } mDevices.put(sphero.getUniqueId(), info); } /** * . * @param serviceId ID * @return truefalse */ private boolean hasSensorListener(final String serviceId) { List<Event> events = EventManager.INSTANCE.getEventList(serviceId, DeviceOrientationProfile.PROFILE_NAME, null, DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION); if (events != null && events.size() > 0) { return true; } events = EventManager.INSTANCE.getEventList(serviceId, SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_QUATERNION, SpheroProfile.ATTR_ON_QUATERNION); if (events != null && events.size() > 0) { return true; } events = EventManager.INSTANCE.getEventList(serviceId, SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_LOCATOR, SpheroProfile.ATTR_ON_LOCATOR); if (events != null && events.size() > 0) { return true; } return false; } /** * . * @param serviceId ID * @return truefalse */ private boolean hasCollisionListener(final String serviceId) { List<Event> events = EventManager.INSTANCE.getEventList(serviceId, SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_COLLISION, SpheroProfile.ATTR_ON_COLLISION); return events != null && events.size() > 0; } private class DiscoveryListenerImpl implements DiscoveryListener { private List<Sphero> mFounds; private List<Sphero> mLosts; public DiscoveryListenerImpl() { mFounds = new ArrayList<Sphero>(); mLosts = new ArrayList<Sphero>(); } @Override public void discoveryComplete(final List<Sphero> spheros) { synchronized (SpheroManager.this) { checkChangeAndSendDiscoveryMessage(spheros); mFoundDevices = spheros; } } @Override public void onBluetoothDisabled() { stopDiscovery(); mFounds.clear(); mLosts.clear(); mDiscoveryListener.onDeviceLostAll(); } @Override public void onFound(final List<Sphero> spheros) { synchronized (SpheroManager.this) { checkChangeAndSendDiscoveryMessage(spheros); mFoundDevices = spheros; } } /** * . * * @param spheros */ private void checkChangeAndSendDiscoveryMessage(final List<Sphero> spheros) { if (mDiscoveryListener != null) { if (mFoundDevices != null) { for (Sphero s : spheros) { if (!mFoundDevices.contains(s)) { mFounds.add(s); } } for (Sphero s : mFoundDevices) { if (!spheros.contains(s)) { mLosts.add(s); } } } else { mFounds.addAll(spheros); } for (Sphero s : mFounds) { if (BuildConfig.DEBUG) { Log.d("", "============================"); Log.d("", "found : " + s); Log.d("", "connected : " + s.isConnected()); Log.d("", "known : " + s.isKnown()); Log.d("", "corrupt : " + s.isMainAppCorrupt()); Log.d("", "under control : " + s.isUnderControl()); Log.d("", "============================"); } mDiscoveryListener.onDeviceFound(s); } for (Sphero s : mLosts) { if (BuildConfig.DEBUG) { Log.d("", "============================"); Log.d("", "lost : " + s); Log.d("", "connected : " + s.isConnected()); Log.d("", "known : " + s.isKnown()); Log.d("", "corrupt : " + s.isMainAppCorrupt()); Log.d("", "under control : " + s.isUnderControl()); Log.d("", "============================"); } mDiscoveryListener.onDeviceLost(s); } mFounds.clear(); mLosts.clear(); } } } private class ConnectionListenerImpl implements ConnectionListener { @Override public void onConnected(final Robot robot) { if (robot instanceof Sphero) { SpheroManager.this.onConnected((Sphero) robot); if (BuildConfig.DEBUG) { Log.d("", "onConnected!"); } synchronized (mConnLock) { mConnLock.notifyAll(); } } } @Override public void onConnectionFailed(final Robot robot) { // TODO if (BuildConfig.DEBUG) { Log.d("", "connect failed : " + robot); } synchronized (mConnLock) { mConnLock.notifyAll(); } } @Override public void onDisconnected(final Robot robot) { mDevices.remove(robot.getUniqueId()); if (BuildConfig.DEBUG) { Log.d("", "onDisconnected!"); } if (mDiscoveryListener != null) { mDiscoveryListener.onDeviceLost((Sphero) robot); } } } public interface DeviceDiscoveryListener { /** * . * * @param sphero */ void onDeviceFound(Sphero sphero); /** * . * * @param sphero */ void onDeviceLost(Sphero sphero); void onDeviceLostAll(); } @Override public void sensorUpdated(final DeviceInfo info, final DeviceSensorsData data, final long interval) { if (mService == null) { return; } mCacheDeviceInfo = info; mCacheDeviceSensorsData = data; mCacheInterval = interval; List<Event> events = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), DeviceOrientationProfile.PROFILE_NAME, null, DeviceOrientationProfile.ATTRIBUTE_ON_DEVICE_ORIENTATION); if (events.size() != 0) { Bundle orientation = createOrientation(data, interval); synchronized (events) { for (Event e : events) { Intent event = EventManager.createEventMessage(e); DeviceOrientationProfile.setOrientation(event, orientation); mService.sendEvent(event, e.getAccessToken()); } } } events = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_QUATERNION, SpheroProfile.ATTR_ON_QUATERNION); if (events.size() != 0) { Bundle quaternion = createQuaternion(data, interval); synchronized (events) { for (Event e : events) { Intent event = EventManager.createEventMessage(e); event.putExtra(SpheroProfile.PARAM_QUATERNION, quaternion); mService.sendEvent(event, e.getAccessToken()); } } } events = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_LOCATOR, SpheroProfile.ATTR_ON_LOCATOR); if (events.size() != 0) { Bundle locator = createLocator(data); synchronized (events) { for (Event e : events) { Intent event = EventManager.createEventMessage(e); event.putExtra(SpheroProfile.PARAM_LOCATOR, locator); mService.sendEvent(event, e.getAccessToken()); } } } } @Override public void collisionDetected(final DeviceInfo info, final CollisionDetectedAsyncData data) { if (mService == null) { return; } List<Event> events = EventManager.INSTANCE.getEventList(info.getDevice().getUniqueId(), SpheroProfile.PROFILE_NAME, SpheroProfile.INTER_COLLISION, SpheroProfile.ATTR_ON_COLLISION); if (events.size() != 0) { Bundle collision = createCollision(data); synchronized (events) { for (Event e : events) { Intent event = EventManager.createEventMessage(e); event.putExtra(SpheroProfile.PARAM_COLLISION, collision); mService.sendEvent(event, e.getAccessToken()); } } } } }
package org.elasticsearch.shield.transport; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.shield.action.ShieldActionMapper; import org.elasticsearch.shield.authc.AuthenticationService; import org.elasticsearch.shield.authz.AuthorizationService; import org.elasticsearch.shield.authz.accesscontrol.RequestContext; import org.elasticsearch.shield.license.ShieldLicenseState; import org.elasticsearch.shield.support.AutomatonPredicate; import org.elasticsearch.shield.support.Automatons; import org.elasticsearch.shield.transport.netty.ShieldNettyTransport; import org.elasticsearch.tasks.Task; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.Transport; import org.elasticsearch.transport.TransportChannel; import org.elasticsearch.transport.TransportException; import org.elasticsearch.transport.TransportRequest; import org.elasticsearch.transport.TransportRequestHandler; import org.elasticsearch.transport.TransportRequestOptions; import org.elasticsearch.transport.TransportResponse; import org.elasticsearch.transport.TransportResponseHandler; import org.elasticsearch.transport.TransportService; import org.elasticsearch.transport.TransportSettings; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import java.util.function.Supplier; import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_DEFAULT; import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_CLIENT_AUTH_SETTING; import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_PROFILE_CLIENT_AUTH_SETTING; import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_PROFILE_SSL_SETTING; import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_SSL_DEFAULT; import static org.elasticsearch.shield.transport.netty.ShieldNettyTransport.TRANSPORT_SSL_SETTING; public class ShieldServerTransportService extends TransportService { public static final String SETTING_NAME = "shield.type"; // FIXME clean up this hack static final Predicate<String> INTERNAL_PREDICATE = new AutomatonPredicate(Automatons.patterns("internal:*")); protected final AuthenticationService authcService; protected final AuthorizationService authzService; protected final ShieldActionMapper actionMapper; protected final ClientTransportFilter clientFilter; protected final ShieldLicenseState licenseState; protected final Map<String, ServerTransportFilter> profileFilters; @Inject public ShieldServerTransportService(Settings settings, Transport transport, ThreadPool threadPool, AuthenticationService authcService, AuthorizationService authzService, ShieldActionMapper actionMapper, ClientTransportFilter clientTransportFilter, ShieldLicenseState licenseState) { super(settings, transport, threadPool); this.authcService = authcService; this.authzService = authzService; this.actionMapper = actionMapper; this.clientFilter = clientTransportFilter; this.licenseState = licenseState; this.profileFilters = initializeProfileFilters(); } @Override public <T extends TransportResponse> void sendRequest(DiscoveryNode node, String action, TransportRequest request, TransportRequestOptions options, TransportResponseHandler<T> handler) { final ThreadContext.StoredContext original = threadPool.getThreadContext().newStoredContext(); // FIXME this is really just a hack. What happens is that we send a request and we always copy headers over // Sometimes a system action gets executed like a internal create index request or update mappings request // which means that the user is copied over to system actions and these really fail for internal things... if ((clientFilter instanceof ClientTransportFilter.Node) && INTERNAL_PREDICATE.test(action)) { try (ThreadContext.StoredContext ctx = threadPool.getThreadContext().stashContext()) { try { clientFilter.outbound(action, request); super.sendRequest(node, action, request, options, new ContextRestoreResponseHandler<>(original, handler)); } catch (Throwable t) { handler.handleException(new TransportException("failed sending request", t)); } } } else { try { clientFilter.outbound(action, request); super.sendRequest(node, action, request, options, new ContextRestoreResponseHandler<>(original, handler)); } catch (Throwable t) { handler.handleException(new TransportException("failed sending request", t)); } } } @Override public <Request extends TransportRequest> void registerRequestHandler(String action, Supplier<Request> requestFactory, String executor, TransportRequestHandler<Request> handler) { TransportRequestHandler<Request> wrappedHandler = new ProfileSecuredRequestHandler<>(action, handler, profileFilters, licenseState, threadPool.getThreadContext()); super.registerRequestHandler(action, requestFactory, executor, wrappedHandler); } @Override public <Request extends TransportRequest> void registerRequestHandler(String action, Supplier<Request> request, String executor, boolean forceExecution, TransportRequestHandler<Request> handler) { TransportRequestHandler<Request> wrappedHandler = new ProfileSecuredRequestHandler<>(action, handler, profileFilters, licenseState, threadPool.getThreadContext()); super.registerRequestHandler(action, request, executor, forceExecution, wrappedHandler); } protected Map<String, ServerTransportFilter> initializeProfileFilters() { if (!(transport instanceof ShieldNettyTransport)) { return Collections.<String, ServerTransportFilter>singletonMap(TransportSettings.DEFAULT_PROFILE, new ServerTransportFilter.NodeProfile(authcService, authzService, actionMapper, threadPool.getThreadContext(), false)); } Map<String, Settings> profileSettingsMap = settings.getGroups("transport.profiles.", true); Map<String, ServerTransportFilter> profileFilters = new HashMap<>(profileSettingsMap.size() + 1); for (Map.Entry<String, Settings> entry : profileSettingsMap.entrySet()) { Settings profileSettings = entry.getValue(); final boolean profileSsl = profileSettings.getAsBoolean(TRANSPORT_PROFILE_SSL_SETTING, settings.getAsBoolean(TRANSPORT_SSL_SETTING, TRANSPORT_SSL_DEFAULT)); final boolean clientAuth = SSLClientAuth.parse(profileSettings.get(TRANSPORT_PROFILE_CLIENT_AUTH_SETTING, settings.get(TRANSPORT_CLIENT_AUTH_SETTING)), TRANSPORT_CLIENT_AUTH_DEFAULT).enabled(); final boolean extractClientCert = profileSsl && clientAuth; String type = entry.getValue().get(SETTING_NAME, "node"); switch (type) { case "client": profileFilters.put(entry.getKey(), new ServerTransportFilter.ClientProfile(authcService, authzService, actionMapper, threadPool.getThreadContext(), extractClientCert)); break; default: profileFilters.put(entry.getKey(), new ServerTransportFilter.NodeProfile(authcService, authzService, actionMapper, threadPool.getThreadContext(), extractClientCert)); } } if (!profileFilters.containsKey(TransportSettings.DEFAULT_PROFILE)) { final boolean profileSsl = settings.getAsBoolean(TRANSPORT_SSL_SETTING, TRANSPORT_SSL_DEFAULT); final boolean clientAuth = SSLClientAuth.parse(settings.get(TRANSPORT_CLIENT_AUTH_SETTING), TRANSPORT_CLIENT_AUTH_DEFAULT).enabled(); final boolean extractClientCert = profileSsl && clientAuth; profileFilters.put(TransportSettings.DEFAULT_PROFILE, new ServerTransportFilter.NodeProfile(authcService, authzService, actionMapper, threadPool.getThreadContext(), extractClientCert)); } return Collections.unmodifiableMap(profileFilters); } ServerTransportFilter transportFilter(String profile) { return profileFilters.get(profile); } public static class ProfileSecuredRequestHandler<T extends TransportRequest> implements TransportRequestHandler<T> { protected final String action; protected final TransportRequestHandler<T> handler; private final Map<String, ServerTransportFilter> profileFilters; private final ShieldLicenseState licenseState; private final ThreadContext threadContext; public ProfileSecuredRequestHandler(String action, TransportRequestHandler<T> handler, Map<String, ServerTransportFilter> profileFilters, ShieldLicenseState licenseState, ThreadContext threadContext) { this.action = action; this.handler = handler; this.profileFilters = profileFilters; this.licenseState = licenseState; this.threadContext = threadContext; } @Override public void messageReceived(T request, TransportChannel channel, Task task) throws Exception { try (ThreadContext.StoredContext ctx = threadContext.newStoredContext()) { if (licenseState.securityEnabled()) { String profile = channel.getProfileName(); ServerTransportFilter filter = profileFilters.get(profile); if (filter == null) { if (TransportService.DIRECT_RESPONSE_PROFILE.equals(profile)) { // apply the default filter to local requests. We never know what the request is or who sent it... filter = profileFilters.get("default"); } else { throw new IllegalStateException("transport profile [" + profile + "] is not associated with a transport filter"); } } assert filter != null; filter.inbound(action, request, channel); } // FIXME we should remove the RequestContext completely since we have ThreadContext but cannot yet due to the query cache RequestContext context = new RequestContext(request, threadContext); RequestContext.setCurrent(context); handler.messageReceived(request, channel, task); } catch (Throwable t) { channel.sendResponse(t); } finally { RequestContext.removeCurrent(); } } @Override public void messageReceived(T request, TransportChannel channel) throws Exception { throw new UnsupportedOperationException("task parameter is required for this operation"); } } /** * This handler wrapper ensures that the response thread executes with the correct thread context. Before any of the4 handle methods * are invoked we restore the context. */ private final static class ContextRestoreResponseHandler<T extends TransportResponse> implements TransportResponseHandler<T> { private final TransportResponseHandler<T> delegate; private final ThreadContext.StoredContext threadContext; private ContextRestoreResponseHandler(ThreadContext.StoredContext threadContext, TransportResponseHandler<T> delegate) { this.delegate = delegate; this.threadContext = threadContext; } @Override public T newInstance() { return delegate.newInstance(); } @Override public void handleResponse(T response) { threadContext.restore(); delegate.handleResponse(response); } @Override public void handleException(TransportException exp) { threadContext.restore(); delegate.handleException(exp); } @Override public String executor() { return delegate.executor(); } } }
package org.innovateuk.ifs.project.transactional; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.resource.FundingDecision; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.invite.domain.ProjectParticipantRole; import org.innovateuk.ifs.organisation.mapper.OrganisationMapper; import org.innovateuk.ifs.project.domain.PartnerOrganisation; import org.innovateuk.ifs.project.domain.Project; import org.innovateuk.ifs.project.domain.ProjectUser; import org.innovateuk.ifs.project.financechecks.transactional.FinanceChecksGenerator; import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.EligibilityWorkflowHandler; import org.innovateuk.ifs.project.financechecks.workflow.financechecks.configuration.ViabilityWorkflowHandler; import org.innovateuk.ifs.project.grantofferletter.configuration.workflow.GrantOfferLetterWorkflowHandler; import org.innovateuk.ifs.project.mapper.ProjectMapper; import org.innovateuk.ifs.project.mapper.ProjectUserMapper; import org.innovateuk.ifs.project.projectdetails.workflow.configuration.ProjectDetailsWorkflowHandler; import org.innovateuk.ifs.project.repository.ProjectRepository; import org.innovateuk.ifs.project.repository.ProjectUserRepository; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.ProjectUserResource; import org.innovateuk.ifs.project.spendprofile.transactional.CostCategoryTypeStrategy; import org.innovateuk.ifs.project.workflow.configuration.ProjectWorkflowHandler; import org.innovateuk.ifs.user.domain.Organisation; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.user.domain.Role; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.repository.OrganisationRepository; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.Map; import java.util.Optional; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.commons.error.CommonErrors.badRequestError; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.CANNOT_FIND_ORG_FOR_GIVEN_PROJECT_AND_USER; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.PROJECT_SETUP_UNABLE_TO_CREATE_PROJECT_PROCESSES; import static org.innovateuk.ifs.commons.service.ServiceResult.*; import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_PARTNER; import static org.innovateuk.ifs.user.resource.UserRoleType.COLLABORATOR; import static org.innovateuk.ifs.util.CollectionFunctions.*; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; import static org.springframework.http.HttpStatus.NOT_FOUND; @Service public class ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Autowired private ProjectRepository projectRepository; @Autowired private ProjectUserRepository projectUserRepository; @Autowired private ProjectUserMapper projectUserMapper; @Autowired private ProjectMapper projectMapper; @Autowired private OrganisationRepository organisationRepository; @Autowired private OrganisationMapper organisationMapper; @Autowired private ProjectDetailsWorkflowHandler projectDetailsWorkflowHandler; @Autowired private ViabilityWorkflowHandler viabilityWorkflowHandler; @Autowired private EligibilityWorkflowHandler eligibilityWorkflowHandler; @Autowired private GrantOfferLetterWorkflowHandler golWorkflowHandler; @Autowired private ProjectWorkflowHandler projectWorkflowHandler; @Autowired private CostCategoryTypeStrategy costCategoryTypeStrategy; @Autowired private FinanceChecksGenerator financeChecksGenerator; @Override public ServiceResult<ProjectResource> getProjectById(Long projectId) { return getProject(projectId).andOnSuccessReturn(projectMapper::mapToResource); } @Override public ServiceResult<ProjectResource> getByApplicationId(Long applicationId) { return getProjectByApplication(applicationId).andOnSuccessReturn(projectMapper::mapToResource); } @Override @Transactional public ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions) { applicationFundingDecisions.keySet().stream().filter(d -> applicationFundingDecisions.get(d).equals(FundingDecision.FUNDED)).forEach(this::createSingletonProjectFromApplicationId); return serviceSuccess(); } @Override public ServiceResult<List<ProjectResource>> findByUserId(final Long userId) { List<ProjectUser> projectUsers = projectUserRepository.findByUserId(userId); List<Project> projects = simpleMap(projectUsers, ProjectUser::getProcess).parallelStream().distinct().collect(toList()); //Users may have multiple roles (e.g. partner and finance contact, in which case there will be multiple project_user entries, so this is flatting it). return serviceSuccess(simpleMap(projects, projectMapper::mapToResource)); } @Override public ServiceResult<List<ProjectUserResource>> getProjectUsers(Long projectId) { return serviceSuccess(simpleMap(getProjectUsersByProjectId(projectId), projectUserMapper::mapToResource)); } @Override @Transactional public ServiceResult<ProjectUser> addPartner(Long projectId, Long userId, Long organisationId) { return find(getProject(projectId), getOrganisation(organisationId), getUser(userId)). andOnSuccess((project, organisation, user) -> { if (project.getOrganisations(o -> organisationId.equals(o.getId())).isEmpty()) { return serviceFailure(badRequestError("project does not contain organisation")); } addProcessRoles(project, user, organisation); return addProjectPartner(project, user, organisation); }); } private ServiceResult<ProjectUser> addProjectPartner(Project project, User user, Organisation organisation){ List<ProjectUser> partners = project.getProjectUsersWithRole(PROJECT_PARTNER); Optional<ProjectUser> projectUser = simpleFindFirst(partners, p -> p.getUser().getId().equals(user.getId())); if (projectUser.isPresent()) { return serviceSuccess(projectUser.get()); // Already a partner } else { ProjectUser pu = new ProjectUser(user, project, PROJECT_PARTNER, organisation); return serviceSuccess(pu); } } private void addProcessRoles(Project project, User user, Organisation organisation) { Application application = project.getApplication(); Role role = roleRepository.findOneByName(COLLABORATOR.getName()); ProcessRole processRole = new ProcessRole(user, application.getId(), role, organisation.getId()); processRoleRepository.save(processRole); } @Override public ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(Long projectId, Long userId) { ProjectUser projectUser = projectUserRepository.findByProjectIdAndRoleAndUserId(projectId, PROJECT_PARTNER, userId); if (projectUser != null && projectUser.getOrganisation() != null) { return serviceSuccess(organisationMapper.mapToResource(organisationRepository.findOne(projectUser.getOrganisation().getId()))); } else { return serviceFailure(new Error(CANNOT_FIND_ORG_FOR_GIVEN_PROJECT_AND_USER, NOT_FOUND)); } } @Override public ServiceResult<ProjectUserResource> getProjectManager(Long projectId) { return find(projectUserRepository.findByProjectIdAndRole(projectId, ProjectParticipantRole.PROJECT_MANAGER), notFoundError(ProjectUserResource.class, projectId)).andOnSuccessReturn(projectUserMapper::mapToResource); } @Override public ServiceResult<List<ProjectResource>> findAll() { return serviceSuccess(projectsToResources(projectRepository.findAll())); } private List<ProjectResource> projectsToResources(List<Project> filtered) { return simpleMap(filtered, project -> projectMapper.mapToResource(project)); } @Override @Transactional public ServiceResult<ProjectResource> createProjectFromApplication(Long applicationId) { return createSingletonProjectFromApplicationId(applicationId); } private ServiceResult<ProjectResource> createSingletonProjectFromApplicationId(final Long applicationId) { return checkForExistingProjectWithApplicationId(applicationId).handleSuccessOrFailure( failure -> createProjectFromApplicationId(applicationId), success -> serviceSuccess(success) ); } private ServiceResult<ProjectResource> checkForExistingProjectWithApplicationId(Long applicationId) { return getByApplicationId(applicationId); } private ServiceResult<ProjectResource> createProjectFromApplicationId(final Long applicationId) { return getApplication(applicationId).andOnSuccess(application -> { Project project = new Project(); project.setApplication(application); project.setDurationInMonths(application.getDurationInMonths()); project.setName(application.getName()); project.setTargetStartDate(application.getStartDate()); ProcessRole leadApplicantRole = simpleFindFirst(application.getProcessRoles(), ProcessRole::isLeadApplicant).get(); List<ProcessRole> collaborativeRoles = simpleFilter(application.getProcessRoles(), ProcessRole::isCollaborator); List<ProcessRole> allRoles = combineLists(leadApplicantRole, collaborativeRoles); List<ServiceResult<ProjectUser>> correspondingProjectUsers = simpleMap(allRoles, role -> { Organisation organisation = organisationRepository.findOne(role.getOrganisationId()); return createPartnerProjectUser(project, role.getUser(), organisation); }); ServiceResult<List<ProjectUser>> projectUserCollection = aggregate(correspondingProjectUsers); ServiceResult<Project> saveProjectResult = projectUserCollection.andOnSuccessReturn(projectUsers -> { List<Organisation> uniqueOrganisations = removeDuplicates(simpleMap(projectUsers, ProjectUser::getOrganisation)); List<PartnerOrganisation> partnerOrganisations = simpleMap(uniqueOrganisations, org -> new PartnerOrganisation(project, org, org.getId().equals(leadApplicantRole.getOrganisationId()))); project.setProjectUsers(projectUsers); project.setPartnerOrganisations(partnerOrganisations); return projectRepository.save(project); }); return saveProjectResult. andOnSuccess(newProject -> createProcessEntriesForNewProject(newProject). andOnSuccess(() -> generateFinanceCheckEntitiesForNewProject(newProject)). andOnSuccessReturn(() -> projectMapper.mapToResource(newProject))); }); } private ServiceResult<ProjectUser> createPartnerProjectUser(Project project, User user, Organisation organisation) { return createProjectUserForRole(project, user, organisation, PROJECT_PARTNER); } private ServiceResult<ProjectUser> createProjectUserForRole(Project project, User user, Organisation organisation, ProjectParticipantRole role) { return serviceSuccess(new ProjectUser(user, project, role, organisation)); } private ServiceResult<Void> createProcessEntriesForNewProject(Project newProject) { ProjectUser originalLeadApplicantProjectUser = newProject.getProjectUsers().get(0); ServiceResult<Void> projectDetailsProcess = createProjectDetailsProcess(newProject, originalLeadApplicantProjectUser); ServiceResult<Void> viabilityProcesses = createViabilityProcesses(newProject.getPartnerOrganisations(), originalLeadApplicantProjectUser); ServiceResult<Void> eligibilityProcesses = createEligibilityProcesses(newProject.getPartnerOrganisations(), originalLeadApplicantProjectUser); ServiceResult<Void> golProcess = createGOLProcess(newProject, originalLeadApplicantProjectUser); ServiceResult<Void> projectProcess = createProjectProcess(newProject, originalLeadApplicantProjectUser); return processAnyFailuresOrSucceed(projectDetailsProcess, viabilityProcesses, eligibilityProcesses, golProcess, projectProcess); } private ServiceResult<Void> createProjectDetailsProcess(Project newProject, ProjectUser originalLeadApplicantProjectUser) { if (projectDetailsWorkflowHandler.projectCreated(newProject, originalLeadApplicantProjectUser)) { return serviceSuccess(); } else { return serviceFailure(PROJECT_SETUP_UNABLE_TO_CREATE_PROJECT_PROCESSES); } } private ServiceResult<Void> createViabilityProcesses(List<PartnerOrganisation> partnerOrganisations, ProjectUser originalLeadApplicantProjectUser) { List<ServiceResult<Void>> results = simpleMap(partnerOrganisations, partnerOrganisation -> viabilityWorkflowHandler.projectCreated(partnerOrganisation, originalLeadApplicantProjectUser) ? serviceSuccess() : serviceFailure(PROJECT_SETUP_UNABLE_TO_CREATE_PROJECT_PROCESSES)); return aggregate(results).andOnSuccessReturnVoid(); } private ServiceResult<Void> createEligibilityProcesses(List<PartnerOrganisation> partnerOrganisations, ProjectUser originalLeadApplicantProjectUser) { List<ServiceResult<Void>> results = simpleMap(partnerOrganisations, partnerOrganisation -> eligibilityWorkflowHandler.projectCreated(partnerOrganisation, originalLeadApplicantProjectUser) ? serviceSuccess() : serviceFailure(PROJECT_SETUP_UNABLE_TO_CREATE_PROJECT_PROCESSES)); return aggregate(results).andOnSuccessReturnVoid(); } private ServiceResult<Void> createGOLProcess(Project newProject, ProjectUser originalLeadApplicantProjectUser) { if (golWorkflowHandler.projectCreated(newProject, originalLeadApplicantProjectUser)) { return serviceSuccess(); } else { return serviceFailure(PROJECT_SETUP_UNABLE_TO_CREATE_PROJECT_PROCESSES); } } private ServiceResult<Void> createProjectProcess(Project newProject, ProjectUser originalLeadApplicantProjectUser) { if (projectWorkflowHandler.projectCreated(newProject, originalLeadApplicantProjectUser)) { return serviceSuccess(); } else { return serviceFailure(PROJECT_SETUP_UNABLE_TO_CREATE_PROJECT_PROCESSES); } } private ServiceResult<Void> generateFinanceCheckEntitiesForNewProject(Project newProject) { List<Organisation> organisations = newProject.getOrganisations(); List<ServiceResult<Void>> financeCheckResults = simpleMap(organisations, organisation -> financeChecksGenerator.createFinanceChecksFigures(newProject, organisation).andOnSuccess(() -> costCategoryTypeStrategy.getOrCreateCostCategoryTypeForSpendProfile(newProject.getId(), organisation.getId()).andOnSuccess(costCategoryType -> financeChecksGenerator.createMvpFinanceChecksFigures(newProject, organisation, costCategoryType)))); return processAnyFailuresOrSucceed(financeCheckResults); } private ServiceResult<Project> getProjectByApplication(long applicationId) { return find(projectRepository.findOneByApplicationId(applicationId), notFoundError(Project.class, applicationId)); } }
package org.innovateuk.ifs.application.transactional; import org.apache.commons.lang3.tuple.Pair; import org.innovateuk.ifs.application.constant.ApplicationStatusConstants; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.domain.ApplicationStatus; import org.innovateuk.ifs.application.domain.FundingDecisionStatus; import org.innovateuk.ifs.application.mapper.FundingDecisionMapper; import org.innovateuk.ifs.application.resource.FundingDecision; import org.innovateuk.ifs.application.resource.NotificationResource; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.notifications.resource.Notification; import org.innovateuk.ifs.notifications.resource.NotificationTarget; import org.innovateuk.ifs.notifications.resource.SystemNotificationSource; import org.innovateuk.ifs.notifications.resource.UserNotificationTarget; import org.innovateuk.ifs.notifications.service.NotificationService; import org.innovateuk.ifs.transactional.BaseTransactionalService; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.util.EntityLookupCallbacks; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.*; import static org.innovateuk.ifs.application.constant.ApplicationStatusConstants.*; import static org.innovateuk.ifs.application.resource.FundingDecision.FUNDED; import static org.innovateuk.ifs.application.resource.FundingDecision.UNFUNDED; import static org.innovateuk.ifs.application.transactional.ApplicationFundingServiceImpl.Notifications.APPLICATION_FUNDING; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.NOTIFICATIONS_UNABLE_TO_DETERMINE_NOTIFICATION_TARGETS; import static org.innovateuk.ifs.commons.service.ServiceResult.*; import static org.innovateuk.ifs.notifications.resource.NotificationMedium.EMAIL; import static org.innovateuk.ifs.user.resource.UserRoleType.LEADAPPLICANT; import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap; @Service class ApplicationFundingServiceImpl extends BaseTransactionalService implements ApplicationFundingService { @Autowired private NotificationService notificationService; @Autowired private SystemNotificationSource systemNotificationSource; @Autowired private FundingDecisionMapper fundingDecisionMapper; @Autowired private ApplicationService applicationService; @Value("${ifs.web.baseURL}") private String webBaseUrl; enum Notifications { APPLICATION_FUNDED, APPLICATION_NOT_FUNDED, APPLICATION_FUNDING, } @Override public ServiceResult<Void> saveFundingDecisionData(Long competitionId, Map<Long, FundingDecision> applicationFundingDecisions) { return getCompetition(competitionId).andOnSuccess(competition -> { List<Application> applicationsForCompetition = findSubmittedApplicationsForCompetition(competitionId); return saveFundingDecisionData(applicationsForCompetition, applicationFundingDecisions); }); } @Override public ServiceResult<Void> notifyLeadApplicantsOfFundingDecisions(NotificationResource notificationResource) { setApplicationStatus(notificationResource.getFundingDecisions()); List<ServiceResult<Pair<Long, NotificationTarget>>> fundingNotificationTargets = getLeadApplicantNotificationTargets(notificationResource.calculateApplicationIds()); ServiceResult<List<Pair<Long, NotificationTarget>>> aggregatedFundingTargets = aggregate(fundingNotificationTargets); return aggregatedFundingTargets.handleSuccessOrFailure( failure -> serviceFailure(NOTIFICATIONS_UNABLE_TO_DETERMINE_NOTIFICATION_TARGETS), success -> { Notification fundingNotification = createFundingDecisionNotification(notificationResource, aggregatedFundingTargets.getSuccessObject(), APPLICATION_FUNDING); ServiceResult<Void> fundedEmailSendResult = notificationService.sendNotification(fundingNotification, EMAIL); return fundedEmailSendResult.andOnSuccess(() -> aggregate(simpleMap( notificationResource.calculateApplicationIds(), applicationId -> applicationService.setApplicationFundingEmailDateTime(applicationId, LocalDateTime.now())))) .andOnSuccessReturnVoid(); }); } private void setApplicationStatus(Map<Long, FundingDecision> applicationFundingDecisions) { List<Long> applicationIds = new ArrayList<>(applicationFundingDecisions.keySet()); List<Application> applications = findApplicationsByIds(applicationIds); applications.forEach(app -> { FundingDecision applicationFundingDecision = applicationFundingDecisions.get(app.getId()); ApplicationStatus status = statusFromDecision(applicationFundingDecision); app.setApplicationStatus(status); }); } private List<Application> findApplicationsByIds(List<Long> applicationIds) { return (List) applicationRepository.findAll(applicationIds); } private List<Application> findSubmittedApplicationsForCompetition(Long competitionId) { return applicationRepository.findByCompetitionIdAndApplicationStatusId(competitionId, ApplicationStatusConstants.SUBMITTED.getId()); } private ServiceResult<Void> saveFundingDecisionData(List<Application> applicationsForCompetition, Map<Long, FundingDecision> applicationDecisions) { applicationDecisions.forEach((applicationId, decisionValue) -> { Optional<Application> applicationForDecision = applicationsForCompetition.stream().filter(application -> applicationId.equals(application.getId())).findFirst(); if (applicationForDecision.isPresent()) { Application application = applicationForDecision.get(); FundingDecisionStatus fundingDecision = fundingDecisionMapper.mapToDomain(decisionValue); application.setFundingDecision(fundingDecision); } }); return serviceSuccess(); } private Notification createFundingDecisionNotification(NotificationResource notificationResource, List<Pair<Long, NotificationTarget>> notificationTargetsByApplicationId, Notifications notificationType) { Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("subject", notificationResource.getSubject()); globalArguments.put("message", notificationResource.getMessageBody()); List<NotificationTarget> notificationTargets = simpleMap(notificationTargetsByApplicationId, Pair::getValue); return new Notification(systemNotificationSource, notificationTargets, notificationType, globalArguments); } private List<ServiceResult<Pair<Long, NotificationTarget>>> getLeadApplicantNotificationTargets(List<Long> applicationIds) { return simpleMap(applicationIds, applicationId -> { ServiceResult<ProcessRole> leadApplicantResult = getProcessRoles(applicationId, LEADAPPLICANT).andOnSuccess(EntityLookupCallbacks::getOnlyElementOrFail); return leadApplicantResult.andOnSuccessReturn(leadApplicant -> Pair.of(applicationId, new UserNotificationTarget(leadApplicant.getUser()))); }); } private ApplicationStatus statusFromDecision(FundingDecision applicationFundingDecision) { if (FUNDED.equals(applicationFundingDecision)) { return applicationStatusRepository.findOne(APPROVED.getId()); } else if (UNFUNDED.equals(applicationFundingDecision)) { return applicationStatusRepository.findOne(REJECTED.getId()); } else { return applicationStatusRepository.findOne(SUBMITTED.getId()); } } }
package org.innovateuk.ifs.project.finance.transactional; import au.com.bytecode.opencsv.CSVWriter; import org.innovateuk.ifs.commons.error.CommonFailureKeys; import org.innovateuk.ifs.project.transactional.ProjectGrantOfferService; import com.google.common.collect.Lists; import org.innovateuk.ifs.commons.error.Error; import org.innovateuk.ifs.commons.rest.LocalDateResource; import org.innovateuk.ifs.commons.rest.ValidationMessages; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.finance.domain.ProjectFinance; import org.innovateuk.ifs.finance.repository.ProjectFinanceRepository; import org.innovateuk.ifs.finance.resource.ProjectFinanceResource; import org.innovateuk.ifs.finance.resource.cost.AcademicCostCategoryGenerator; import org.innovateuk.ifs.finance.transactional.FinanceRowService; import org.innovateuk.ifs.project.domain.Project; import org.innovateuk.ifs.project.finance.domain.*; import org.innovateuk.ifs.project.finance.repository.CostCategoryRepository; import org.innovateuk.ifs.project.finance.repository.CostCategoryTypeRepository; import org.innovateuk.ifs.project.finance.repository.FinanceCheckProcessRepository; import org.innovateuk.ifs.project.finance.repository.SpendProfileRepository; import org.innovateuk.ifs.project.finance.resource.*; import org.innovateuk.ifs.project.repository.ProjectRepository; import org.innovateuk.ifs.project.resource.*; import org.innovateuk.ifs.project.transactional.ProjectService; import org.innovateuk.ifs.transactional.BaseTransactionalService; import org.innovateuk.ifs.user.domain.Organisation; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.mapper.UserMapper; import org.innovateuk.ifs.user.repository.OrganisationRepository; import org.innovateuk.ifs.user.resource.OrganisationTypeEnum; import org.innovateuk.ifs.util.CollectionFunctions; import org.innovateuk.ifs.validator.util.ValidationUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.math.BigDecimal.ROUND_HALF_UP; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*; import static org.innovateuk.ifs.commons.error.Error.fieldError; import static org.innovateuk.ifs.commons.service.ServiceResult.*; import static org.innovateuk.ifs.project.finance.resource.TimeUnit.MONTH; import static org.innovateuk.ifs.util.CollectionFunctions.*; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; /** * Service dealing with Project finance operations */ @Service public class ProjectFinanceServiceImpl extends BaseTransactionalService implements ProjectFinanceService { private static final String CSV_MONTH = "Month"; private static final String CSV_TOTAL = "TOTAL"; private static final String CSV_ELIGIBLE_COST_TOTAL = "Eligible Costs Total"; private static final String CSV_FILE_NAME_FORMAT = "%s_Spend_Profile_%s.csv"; private static final String CSV_FILE_NAME_DATE_FORMAT = "yyyy-MM-dd_HH-mm-ss"; private static final List<String> RESEARCH_CAT_GROUP_ORDER = new LinkedList<>(); public static final String EMPTY_CELL = ""; @Autowired private ProjectService projectService; @Autowired private ProjectRepository projectRepository; @Autowired private OrganisationRepository organisationRepository; @Autowired private SpendProfileRepository spendProfileRepository; @Autowired private CostCategoryTypeRepository costCategoryTypeRepository; @Autowired private CostCategoryRepository costCategoryRepository; @Autowired private FinanceCheckProcessRepository financeCheckProcessRepository; @Autowired private ProjectFinanceRepository projectFinanceRepository; @Autowired private FinanceRowService financeRowService; @Autowired private UserMapper userMapper; @Autowired private ValidationUtil validationUtil; @Autowired private SpendProfileCostCategorySummaryStrategy spendProfileCostCategorySummaryStrategy; @Autowired private ProjectGrantOfferService projectGrantOfferLetterService; static { RESEARCH_CAT_GROUP_ORDER.add(AcademicCostCategoryGenerator.DIRECTLY_INCURRED_STAFF.getLabel()); RESEARCH_CAT_GROUP_ORDER.add(AcademicCostCategoryGenerator.DIRECTLY_ALLOCATED_INVESTIGATORS.getLabel()); RESEARCH_CAT_GROUP_ORDER.add(AcademicCostCategoryGenerator.INDIRECT_COSTS.getLabel()); RESEARCH_CAT_GROUP_ORDER.add(AcademicCostCategoryGenerator.INDIRECT_COSTS_STAFF.getLabel()); } @Override public ServiceResult<Void> generateSpendProfile(Long projectId) { return getProject(projectId).andOnSuccess(project -> validateSpendProfileCanBeGenerated(project).andOnSuccess(() -> projectService.getProjectUsers(projectId).andOnSuccess(projectUsers -> { List<Long> organisationIds = removeDuplicates(simpleMap(projectUsers, ProjectUserResource::getOrganisation)); return generateSpendProfileForPartnerOrganisations(project, organisationIds); })) ); } private ServiceResult<Void> validateSpendProfileCanBeGenerated(Project project) { List<FinanceCheckProcess> financeCheckProcesses = simpleMap(project.getPartnerOrganisations(), po -> financeCheckProcessRepository.findOneByTargetId(po.getId())); Optional<FinanceCheckProcess> existingNonApprovedFinanceCheck = simpleFindFirst(financeCheckProcesses, process -> !FinanceCheckState.APPROVED.equals(process.getActivityState())); if (!existingNonApprovedFinanceCheck.isPresent()) { return serviceSuccess(); } else { return serviceFailure(SPEND_PROFILE_CANNOT_BE_GENERATED_UNTIL_ALL_FINANCE_CHECKS_APPROVED); } } @Override public ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType) { updateApprovalOfSpendProfile(projectId, approvalType); return projectGrantOfferLetterService.generateGrantOfferLetterIfReady(projectId).andOnFailure(() -> serviceFailure(CommonFailureKeys.GRANT_OFFER_LETTER_GENERATION_FAILURE)); } @Override public ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId) { List<SpendProfile> spendProfiles = getSpendProfileByProjectId(projectId); if(spendProfiles.isEmpty()) { return serviceSuccess(ApprovalType.EMPTY); } else if(spendProfiles.stream().anyMatch(spendProfile -> spendProfile.getApproval().equals(ApprovalType.REJECTED))) { return serviceSuccess(ApprovalType.REJECTED); } else if (spendProfiles.stream().allMatch(spendProfile -> spendProfile.getApproval().equals(ApprovalType.APPROVED))) { return serviceSuccess(ApprovalType.APPROVED); } return serviceSuccess(ApprovalType.UNSET); } @Override public ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return find( spendProfile(projectOrganisationCompositeId.getProjectId(), projectOrganisationCompositeId.getOrganisationId()), project(projectOrganisationCompositeId.getProjectId())). andOnSuccess((spendProfile, project) -> { List<CostCategory> costCategories = spendProfile.getCostCategoryType().getCostCategories(); Organisation organisation = organisationRepository.findOne(projectOrganisationCompositeId.getOrganisationId()); CostGroup eligibleCosts = spendProfile.getEligibleCosts(); CostGroup spendProfileFigures = spendProfile.getSpendProfileFigures(); Map<Long, BigDecimal> eligibleCostsPerCategory = simpleToLinkedMap( costCategories, CostCategory::getId, category -> findSingleMatchingCostByCategory(eligibleCosts, category).getValue()); Map<Long, List<Cost>> spendProfileCostsPerCategory = simpleToLinkedMap( costCategories, CostCategory::getId, category -> findMultipleMatchingCostsByCategory(spendProfileFigures, category)); LocalDate startDate = spendProfile.getProject().getTargetStartDate(); int durationInMonths = spendProfile.getProject().getDurationInMonths().intValue(); List<LocalDate> months = IntStream.range(0, durationInMonths).mapToObj(startDate::plusMonths).collect(toList()); List<LocalDateResource> monthResources = simpleMap(months, LocalDateResource::new); Map<Long, List<BigDecimal>> spendFiguresPerCategoryOrderedByMonth = simpleLinkedMapValue(spendProfileCostsPerCategory, costs -> orderCostsByMonths(costs, months, project.getTargetStartDate())); SpendProfileTableResource table = new SpendProfileTableResource(); table.setCostCategoryResourceMap(buildCostCategoryIdMap(costCategories)); table.setMonths(monthResources); table.setEligibleCostPerCategoryMap(eligibleCostsPerCategory); table.setMonthlyCostsPerCategoryMap(spendFiguresPerCategoryOrderedByMonth); table.setMarkedAsComplete(spendProfile.isMarkedAsComplete()); checkTotalForMonthsAndAddToTable(table); boolean isResearch = OrganisationTypeEnum.isResearch(organisation.getOrganisationType().getId()); if (isResearch) { table.setCostCategoryGroupMap(groupCategories(table)); } return serviceSuccess(table); }); } private Map<Long, CostCategoryResource> buildCostCategoryIdMap(List<CostCategory> costCategories) { Map<Long, CostCategoryResource> returnMap = new HashMap<>(); costCategories.forEach(costCategory -> { CostCategoryResource cr = new CostCategoryResource(); cr.setId(costCategory.getId()); cr.setName(costCategory.getName()); cr.setLabel(costCategory.getLabel()); returnMap.put(costCategory.getId(), cr); }); return returnMap; } private Map<String, List<Map<Long, List<BigDecimal>>>> groupCategories(SpendProfileTableResource spendProfileTableResource) { Map<String, List<Map<Long, List<BigDecimal>>>> catGroupMap = new HashMap<>(); spendProfileTableResource.getMonthlyCostsPerCategoryMap().forEach((category, values)-> { CostCategory costCategory = costCategoryRepository.findOne(category); if (costCategory.getLabel() == null) { costCategory.setLabel("DEFAULT"); } if (catGroupMap.get(costCategory.getLabel()) != null) { Map<Long, List<BigDecimal>> tempRow = new HashMap<>(); tempRow.put(category, values); catGroupMap.get(costCategory.getLabel()).add(tempRow); } else { List<Map<Long, List<BigDecimal>>> newList = new ArrayList<>(); Map<Long, List<BigDecimal>> tempRow = new HashMap<>(); tempRow.put(category, values); newList.add(tempRow); catGroupMap.put(costCategory.getLabel(), newList); } }); return orderResearchCategoryMap(catGroupMap); } private Map<String, List<Map<Long, List<BigDecimal>>>> orderResearchCategoryMap(Map<String, List<Map<Long, List<BigDecimal>>>> catGroupMap) { Map<String, List<Map<Long, List<BigDecimal>>>> orderedCatGroupMap = new LinkedHashMap<>(); RESEARCH_CAT_GROUP_ORDER.forEach(groupName -> { orderedCatGroupMap.put(groupName, catGroupMap.get(groupName)); }); return orderedCatGroupMap; } @Override public ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId) { SpendProfileTableResource spendProfileTableResource = getSpendProfileTable(projectOrganisationCompositeId).getSuccessObject(); try { return serviceSuccess(generateSpendProfileCSVData(spendProfileTableResource, projectOrganisationCompositeId)); } catch (IOException ioe) { return serviceFailure(SPEND_PROFILE_CSV_GENERATION_FAILURE); } } @Override public ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getSpendProfileEntity(projectOrganisationCompositeId.getProjectId(), projectOrganisationCompositeId.getOrganisationId()) .andOnSuccessReturn(profile -> { SpendProfileResource resource = new SpendProfileResource(); resource.setId(profile.getId()); resource.setGeneratedBy(userMapper.mapToResource(profile.getGeneratedBy())); resource.setGeneratedDate(profile.getGeneratedDate()); resource.setMarkedAsComplete(profile.isMarkedAsComplete()); return resource; }); } @Override public ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table) { return validateSpendProfileCosts(table) .andOnSuccess(() -> saveSpendProfileData(projectOrganisationCompositeId, table, false)); // We have to save the data even if the totals don't match } @Override public ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { SpendProfileTableResource table = getSpendProfileTable(projectOrganisationCompositeId).getSuccessObject(); if(table.getValidationMessages().hasErrors()) { // validate before marking as complete return serviceFailure(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE); } else { return saveSpendProfileData(projectOrganisationCompositeId, table, true); } } @Override public ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { SpendProfileTableResource table = getSpendProfileTable(projectOrganisationCompositeId).getSuccessObject(); return saveSpendProfileData(projectOrganisationCompositeId, table, false); } @Override public ServiceResult<Void> completeSpendProfilesReview(Long projectId) { return getProject(projectId).andOnSuccess(project -> { if (project.getSpendProfileSubmittedDate() != null) { return serviceFailure(SPEND_PROFILES_HAVE_ALREADY_BEEN_SUBMITTED); } if (project.getSpendProfiles().stream().anyMatch(spendProfile -> !spendProfile.isMarkedAsComplete())) { return serviceFailure(SPEND_PROFILES_MUST_BE_COMPLETE_BEFORE_SUBMISSION); } project.setSpendProfileSubmittedDate(LocalDateTime.now()); return serviceSuccess(); }); } @Override public ServiceResult<Void> saveCreditReport(Long projectId, Long organisationId, boolean reportPresent) { return getProjectFinance(projectId, organisationId).andOnSuccess(projectFinance -> validateCreditReport(projectFinance).andOnSuccessReturnVoid(() -> { projectFinance.setCreditReportConfirmed(reportPresent); projectFinanceRepository.save(projectFinance); })); } private ServiceResult<Void> validateCreditReport(ProjectFinance projectFinance) { if (Viability.APPROVED == projectFinance.getViability()) { return serviceFailure(VIABILITY_HAS_ALREADY_BEEN_APPROVED); } else { return serviceSuccess(); } } @Override public ServiceResult<Boolean> getCreditReport(Long projectId, Long organisationId) { return getProjectFinance(projectId, organisationId).andOnSuccessReturn(ProjectFinance::getCreditReportConfirmed); } @Override public ServiceResult<List<ProjectFinanceResource>> getProjectFinances(Long projectId) { return financeRowService.financeChecksTotals(projectId); } @Override public ServiceResult<ViabilityResource> getViability(ProjectOrganisationCompositeId projectOrganisationCompositeId){ Long projectId = projectOrganisationCompositeId.getProjectId(); Long organisationId = projectOrganisationCompositeId.getOrganisationId(); return getProjectFinance(projectId, organisationId).andOnSuccessReturn(projectFinance -> new ViabilityResource(projectFinance.getViability(), projectFinance.getViabilityStatus())); } @Override public ServiceResult<Void> saveViability(ProjectOrganisationCompositeId projectOrganisationCompositeId, Viability viability, ViabilityStatus viabilityStatus){ Long projectId = projectOrganisationCompositeId.getProjectId(); Long organisationId = projectOrganisationCompositeId.getOrganisationId(); return getProjectFinance(projectId, organisationId).andOnSuccess(projectFinance -> validateViability(projectFinance, viability, viabilityStatus).andOnSuccess(() -> saveViability(projectFinance, viability, viabilityStatus))); } private ServiceResult<Void> validateViability(ProjectFinance projectFinanceInDB, Viability viability, ViabilityStatus viabilityStatus) { if (Viability.APPROVED == projectFinanceInDB.getViability()) { return serviceFailure(VIABILITY_HAS_ALREADY_BEEN_APPROVED); } if (Viability.APPROVED == viability && ViabilityStatus.UNSET == viabilityStatus) { return serviceFailure(VIABILITY_RAG_STATUS_MUST_BE_SET); } return serviceSuccess(); } private ServiceResult<Void> saveViability(ProjectFinance projectFinance, Viability viability, ViabilityStatus viabilityStatus) { projectFinance.setViability(viability); projectFinance.setViabilityStatus(viabilityStatus); projectFinanceRepository.save(projectFinance); return serviceSuccess(); } private ServiceResult<Void> validateSpendProfileCosts(SpendProfileTableResource table) { Optional<ValidationMessages> validationMessages = validationUtil.validateSpendProfileTableResource(table); final List<Error> incorrectCosts = Lists.newArrayList(); validationMessages.ifPresent(v -> incorrectCosts.addAll(v.getErrors())); if (incorrectCosts.isEmpty()) { return serviceSuccess(); } else { return serviceFailure(incorrectCosts); } } private ServiceResult<Void> saveSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table, boolean markAsComplete) { return getSpendProfileEntity(projectOrganisationCompositeId.getProjectId(), projectOrganisationCompositeId.getOrganisationId()). andOnSuccess ( spendProfile -> { if(spendProfile.getProject().getSpendProfileSubmittedDate() != null) { return serviceFailure(SPEND_PROFILE_HAS_BEEN_SUBMITTED_AND_CANNOT_BE_EDITED); } spendProfile.setMarkedAsComplete(markAsComplete); updateSpendProfileCosts(spendProfile, table); spendProfileRepository.save(spendProfile); return serviceSuccess(); } ); } private void updateSpendProfileCosts(SpendProfile spendProfile, SpendProfileTableResource table) { Map<Long, List<BigDecimal>> monthlyCostsPerCategoryMap = table.getMonthlyCostsPerCategoryMap(); for (Map.Entry<Long, List<BigDecimal>> entry : monthlyCostsPerCategoryMap.entrySet()) { Long category = entry.getKey(); List<BigDecimal> monthlyCosts = entry.getValue(); updateSpendProfileCostsForCategory(category, monthlyCosts, spendProfile); } } private void updateSpendProfileCostsForCategory(Long category, List<BigDecimal> monthlyCosts, SpendProfile spendProfile) { List<Cost> filteredAndSortedCostsToUpdate = spendProfile.getSpendProfileFigures().getCosts().stream() .filter(cost -> cost.getCostCategory().getId() == category) .sorted(Comparator.comparing(cost -> cost.getCostTimePeriod().getOffsetAmount())) .collect(Collectors.toList()); int index = 0; for (Cost costToUpdate : filteredAndSortedCostsToUpdate) { costToUpdate.setValue(monthlyCosts.get(index)); index++; } } private void updateApprovalOfSpendProfile(Long projectId, ApprovalType approvalType) { List<SpendProfile> spendProfiles = spendProfileRepository.findByProjectId(projectId); spendProfiles.forEach(spendProfile -> spendProfile.setApproval(approvalType)); spendProfileRepository.save(spendProfiles); } private void checkTotalForMonthsAndAddToTable(SpendProfileTableResource table) { Map<Long, List<BigDecimal>> monthlyCostsPerCategoryMap = table.getMonthlyCostsPerCategoryMap(); Map<Long, BigDecimal> eligibleCostPerCategoryMap = table.getEligibleCostPerCategoryMap(); List<Error> categoriesWithIncorrectTotal = new ArrayList<>(); for (Map.Entry<Long, List<BigDecimal>> entry : monthlyCostsPerCategoryMap.entrySet()) { Long category = entry.getKey(); List<BigDecimal> monthlyCosts = entry.getValue(); BigDecimal actualTotalCost = monthlyCosts.stream().reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal expectedTotalCost = eligibleCostPerCategoryMap.get(category); if (actualTotalCost.compareTo(expectedTotalCost) == 1) { categoriesWithIncorrectTotal.add(fieldError(String.valueOf(category), actualTotalCost, SPEND_PROFILE_TOTAL_FOR_ALL_MONTHS_DOES_NOT_MATCH_ELIGIBLE_TOTAL_FOR_SPECIFIED_CATEGORY.getErrorKey())); } } ValidationMessages validationMessages = new ValidationMessages(categoriesWithIncorrectTotal); validationMessages.setObjectName("SPEND_PROFILE"); table.setValidationMessages(validationMessages); } private List<BigDecimal> orderCostsByMonths(List<Cost> costs, List<LocalDate> months, LocalDate startDate) { return simpleMap(months, month -> findCostForMonth(costs, month, startDate)); } private BigDecimal findCostForMonth(List<Cost> costs, LocalDate month, LocalDate startDate) { Optional<Cost> matching = simpleFindFirst(costs, cost -> cost.getCostTimePeriod().getStartDate(startDate).equals(month)); return matching.map(Cost::getValue).orElse(BigDecimal.ZERO); } private Supplier<ServiceResult<SpendProfile>> spendProfile(Long projectId, Long organisationId) { return () -> getSpendProfileEntity(projectId, organisationId); } private ServiceResult<SpendProfile> getSpendProfileEntity(Long projectId, Long organisationId) { return find(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId), notFoundError(SpendProfile.class, projectId, organisationId)); } private ServiceResult<Void> generateSpendProfileForPartnerOrganisations(Project project, List<Long> organisationIds) { Calendar now = Calendar.getInstance(); List<ServiceResult<Void>> generationResults = simpleMap(organisationIds, organisationId -> getCurrentlyLoggedInUser().andOnSuccess(user -> spendProfileCostCategorySummaryStrategy.getCostCategorySummaries(project.getId(), organisationId). andOnSuccess(spendProfileCostCategorySummaries -> generateSpendProfileForOrganisation(project.getId(), organisationId, spendProfileCostCategorySummaries, user, now)))); return processAnyFailuresOrSucceed(generationResults); } private ServiceResult<Void> generateSpendProfileForOrganisation( Long projectId, Long organisationId, SpendProfileCostCategorySummaries spendProfileCostCategorySummaries, User generatedBy, Calendar generatedDate) { return find(project(projectId), organisation(organisationId)).andOnSuccess( (project, organisation) -> generateSpendProfileForOrganisation(spendProfileCostCategorySummaries , project, organisation, generatedBy, generatedDate)); } private ServiceResult<Void> generateSpendProfileForOrganisation(SpendProfileCostCategorySummaries spendProfileCostCategorySummaries, Project project, Organisation organisation, User generatedBy, Calendar generatedDate) { List<Cost> eligibleCosts = generateEligibleCosts(spendProfileCostCategorySummaries); List<Cost> spendProfileCosts = generateSpendProfileFigures(spendProfileCostCategorySummaries, project); CostCategoryType costCategoryType = costCategoryTypeRepository.findOne(spendProfileCostCategorySummaries.getCostCategoryType().getId()); SpendProfile spendProfile = new SpendProfile(organisation, project, costCategoryType, eligibleCosts, spendProfileCosts, generatedBy, generatedDate, false, ApprovalType.UNSET); spendProfileRepository.save(spendProfile); return serviceSuccess(); } private List<Cost> generateSpendProfileFigures(SpendProfileCostCategorySummaries summaryPerCategory, Project project) { List<List<Cost>> spendProfileCostsPerCategory = simpleMap(summaryPerCategory.getCosts(), summary -> { CostCategory cc = costCategoryRepository.findOne(summary.getCategory().getId()); return IntStream.range(0, project.getDurationInMonths().intValue()).mapToObj(i -> { BigDecimal costValueForThisMonth = i == 0 ? summary.getFirstMonthSpend() : summary.getOtherMonthsSpend(); return new Cost(costValueForThisMonth). withCategory(cc). withTimePeriod(i, MONTH, 1, MONTH); }).collect(toList()); }); return flattenLists(spendProfileCostsPerCategory); } private List<Cost> generateEligibleCosts(SpendProfileCostCategorySummaries spendProfileCostCategorySummaries) { return simpleMap(spendProfileCostCategorySummaries.getCosts(), cost -> { CostCategory cc = costCategoryRepository.findOne(cost.getCategory().getId()); return new Cost(cost.getTotal().setScale(0, ROUND_HALF_UP)).withCategory(cc); }); } private Supplier<ServiceResult<Project>> project(Long id) { return () -> getProject(id); } private ServiceResult<Project> getProject(Long id) { return find(projectRepository.findOne(id), notFoundError(Project.class, id)); } private List<SpendProfile> getSpendProfileByProjectId(Long projectId) { return spendProfileRepository.findByProjectId(projectId); } private SpendProfileCSVResource generateSpendProfileCSVData(SpendProfileTableResource spendProfileTableResource, ProjectOrganisationCompositeId projectOrganisationCompositeId) throws IOException { Map<Long, BigDecimal> categoryToActualTotal = buildSpendProfileActualTotalsForAllCategories(spendProfileTableResource); List<BigDecimal> totalForEachMonth = buildTotalForEachMonth(spendProfileTableResource); BigDecimal totalOfAllActualTotals = buildTotalOfTotals(categoryToActualTotal); BigDecimal totalOfAllEligibleTotals = buildTotalOfTotals(spendProfileTableResource.getEligibleCostPerCategoryMap()); Organisation organisation = organisationRepository.findOne(projectOrganisationCompositeId.getOrganisationId()); StringWriter stringWriter = new StringWriter(); CSVWriter csvWriter = new CSVWriter(stringWriter); ArrayList<String[]> rows = new ArrayList<>(); ArrayList<String> byCategory = new ArrayList<>(); ArrayList<String> monthsRow = new ArrayList<>(); monthsRow.add(CSV_MONTH); monthsRow.add(EMPTY_CELL); spendProfileTableResource.getMonths().forEach( value -> monthsRow.add(value.getLocalDate().toString())); monthsRow.add(CSV_TOTAL); monthsRow.add(CSV_ELIGIBLE_COST_TOTAL); final int[] columnSize = new int[1]; spendProfileTableResource.getMonthlyCostsPerCategoryMap().forEach((category, values)-> { CostCategory cc = costCategoryRepository.findOne(category); if ( cc.getLabel() != null ) { byCategory.add(cc.getLabel()); } byCategory.add(String.valueOf(cc.getName())); values.forEach(val -> { byCategory.add(val.toString()); }); byCategory.add(categoryToActualTotal.get(category).toString()); byCategory.add(spendProfileTableResource.getEligibleCostPerCategoryMap().get(category).toString()); if ( monthsRow.size() > byCategory.size() && monthsRow.contains(EMPTY_CELL)) { monthsRow.remove(EMPTY_CELL); rows.add(monthsRow.stream().toArray(String[]::new)); } else if (monthsRow.size() > 0 ){ rows.add(monthsRow.stream().toArray(String[]::new)); } monthsRow.clear(); rows.add(byCategory.stream().toArray(String[]::new)); columnSize[0] = byCategory.size(); byCategory.clear(); }); ArrayList<String> totals = new ArrayList<>(); totals.add(CSV_TOTAL); totals.add(EMPTY_CELL); totalForEachMonth.forEach(value -> totals.add(value.toString())); totals.add(totalOfAllActualTotals.toString()); totals.add(totalOfAllEligibleTotals.toString()); if ( totals.size() > columnSize[0] && totals.contains(EMPTY_CELL)) { totals.remove(EMPTY_CELL); } rows.add(totals.stream().toArray(String[]::new)); csvWriter.writeAll(rows); csvWriter.close(); SpendProfileCSVResource spendProfileCSVResource = new SpendProfileCSVResource(); spendProfileCSVResource.setCsvData(stringWriter.toString()); spendProfileCSVResource.setFileName(generateSpendProfileFileName(organisation.getName())); return spendProfileCSVResource; } private String generateSpendProfileFileName(String organisationName) { Date date = new Date() ; SimpleDateFormat dateFormat = new SimpleDateFormat(CSV_FILE_NAME_DATE_FORMAT); return String.format(CSV_FILE_NAME_FORMAT, organisationName, dateFormat.format(date)); } private Map<Long, BigDecimal> buildSpendProfileActualTotalsForAllCategories(SpendProfileTableResource table) { return CollectionFunctions.simpleLinkedMapValue(table.getMonthlyCostsPerCategoryMap(), (List<BigDecimal> monthlyCosts) -> monthlyCosts.stream().reduce(BigDecimal.ZERO, BigDecimal::add)); } private List<BigDecimal> buildTotalForEachMonth(SpendProfileTableResource table) { Map<Long, List<BigDecimal>> monthlyCostsPerCategoryMap = table.getMonthlyCostsPerCategoryMap(); List<BigDecimal> totalForEachMonth = Stream.generate(() -> BigDecimal.ZERO).limit(table.getMonths().size()).collect(Collectors.toList()); AtomicInteger atomicInteger = new AtomicInteger(0); totalForEachMonth.forEach(totalForThisMonth -> { int index = atomicInteger.getAndIncrement(); monthlyCostsPerCategoryMap.forEach((category, value) -> { BigDecimal costForThisMonthForCategory = value.get(index); if (totalForEachMonth.get(index) != null) { totalForEachMonth.set(index, totalForEachMonth.get(index).add(costForThisMonthForCategory)); } else { totalForEachMonth.set(index, costForThisMonthForCategory); } }); }); return totalForEachMonth; } private BigDecimal buildTotalOfTotals(Map<Long, BigDecimal> input) { return input.values().stream().reduce(BigDecimal.ZERO, (d1, d2) -> d1.add(d2)); } private List<Cost> findMultipleMatchingCostsByCategory(CostGroup spendProfileFigures, CostCategory category) { return simpleFilter(spendProfileFigures.getCosts(), f -> f.getCostCategory().equals(category)); } private Cost findSingleMatchingCostByCategory(CostGroup eligibleCosts, CostCategory category) { return simpleFindFirst(eligibleCosts.getCosts(), f -> f.getCostCategory().equals(category)).get(); } private ServiceResult<ProjectFinance> getProjectFinance(Long projectId, Long organisationId) { return find(projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisationId), notFoundError(ProjectFinance.class, projectId, organisationId)); } }
package com.vrg.rapid; import com.google.common.net.HostAndPort; import com.vrg.rapid.pb.MembershipServiceGrpc; import io.grpc.ClientInterceptor; import io.grpc.MethodDescriptor; import io.grpc.ServerInterceptor; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test public API */ public class ClusterTest { @SuppressWarnings("FieldCanBeLocal") @Nullable private static Logger grpcLogger = null; @Nullable private static Logger nettyLogger = null; private static final int RPC_TIMEOUT_SHORT_MS = 100; private final Map<HostAndPort, Cluster> instances = new ConcurrentHashMap<>(); private final Map<HostAndPort, StaticFailureDetector> staticFds = new ConcurrentHashMap<>(); private final Map<HostAndPort, List<ServerInterceptor>> serverInterceptors = new ConcurrentHashMap<>(); private final Map<HostAndPort, List<ClientInterceptor>> clientInterceptors = new ConcurrentHashMap<>(); private boolean useStaticFd = false; @Nullable private Random random = null; private long seed; private int basePort; @Nullable private AtomicInteger portCounter = null; @Rule public final TestWatcher testWatcher = new TestWatcher() { @Override protected void failed(final Throwable e, final Description description) { System.out.println("\u001B[31m [FAILED] [Seed: " + seed + "] " + description.getMethodName() + "\u001B[0m"); } }; @BeforeClass public static void beforeClass() { // gRPC INFO logs clutter the test output grpcLogger = Logger.getLogger("io.grpc"); grpcLogger.setLevel(Level.WARNING); nettyLogger = Logger.getLogger("io.grpc.netty.NettyServerHandler"); nettyLogger.setLevel(Level.OFF); } @Before public void beforeTest() { basePort = 1234; portCounter = new AtomicInteger(basePort); instances.clear(); seed = ThreadLocalRandom.current().nextLong(); random = new Random(seed); // Tests need to opt out of the in-process channel RpcServer.USE_IN_PROCESS_SERVER = true; RpcClient.USE_IN_PROCESS_CHANNEL = true; // Tests that depend on failure detection should set intervals by themselves MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100000; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 100000; RpcClient.Conf.RPC_JOIN_PHASE_2_TIMEOUT = RpcClient.Conf.RPC_TIMEOUT_MEDIUM_MS * 20; RpcClient.Conf.RPC_TIMEOUT_MS = RpcClient.Conf.RPC_TIMEOUT_MEDIUM_MS; RpcClient.Conf.RPC_PROBE_TIMEOUT = 5000; useStaticFd = false; staticFds.clear(); serverInterceptors.clear(); clientInterceptors.clear(); } @After public void afterTest() throws InterruptedException { for (final Cluster cluster: instances.values()) { cluster.shutdown(); } } /** * Test with a single node joining through a seed. */ @Test public void singleNodeJoinsThroughSeed() throws IOException, InterruptedException, ExecutionException { RpcServer.USE_IN_PROCESS_SERVER = false; RpcClient.USE_IN_PROCESS_CHANNEL = false; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(1, seedHost); verifyCluster(1, seedHost); extendCluster(1, seedHost); verifyCluster(2, seedHost); } /** * Test with K nodes joining the network through a single seed. */ @Test public void tenNodesJoinSequentially() throws IOException, InterruptedException { // Explicitly test netty RpcServer.USE_IN_PROCESS_SERVER = false; RpcClient.USE_IN_PROCESS_CHANNEL = false; final int numNodes = 10; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(1, seedHost); // Only bootstrap a seed. verifyCluster(1, seedHost); for (int i = 0; i < numNodes; i++) { extendCluster(1, seedHost); waitAndVerifyAgreement( i + 2, 5, 1000, seedHost); } } /** * Identical to the previous test, but with more than K nodes joining in serial. */ @Test public void twentyNodesJoinSequentially() throws IOException, InterruptedException { // Explicitly test netty RpcServer.USE_IN_PROCESS_SERVER = false; RpcClient.USE_IN_PROCESS_CHANNEL = false; final int numNodes = 20; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(1, seedHost); // Only bootstrap a seed. verifyCluster(1, seedHost); for (int i = 0; i < numNodes; i++) { extendCluster(1, seedHost); waitAndVerifyAgreement( i + 2, 5, 1000, seedHost); } } /** * Identical to the previous test, but with more than K nodes joining in parallel. * <p> * The test starts with a single seed and all N - 1 subsequent nodes initiate their join protocol at the same * time. This tests a single seed's ability to bootstrap a large cluster in one step. */ @Test(timeout=150000) public void threeHundredNodesJoinInParallel() throws IOException, InterruptedException { final int numNodes = 300; // Includes the size of the cluster final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodes, seedHost); verifyCluster(numNodes, seedHost); } /** * This test starts with a single seed, and a wave where 50 subsequent nodes initiate their join protocol * concurrently. Following this, a subsequent wave begins where 100 nodes then start together. */ @Test(timeout=150000) public void hundredNodesJoinFiftyNodeCluster() throws IOException, InterruptedException { RpcServer.USE_IN_PROCESS_SERVER = true; RpcClient.USE_IN_PROCESS_CHANNEL = true; final int numNodesPhase1 = 50; final int numNodesPhase2 = 100; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodesPhase1, seedHost); waitAndVerifyAgreement(numNodesPhase1, 10, 100, seedHost); extendCluster(numNodesPhase2, seedHost); waitAndVerifyAgreement(numNodesPhase1 + numNodesPhase2, 10, 1000, seedHost); } /** * This test starts with a 4 node cluster. We then fail a single node to see if the monitoring mechanism * identifies the failing node and arrives at a decision to remove it. */ @Test public void oneFailureOutOfFourNodes() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 1000; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 500; final int numNodes = 4; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodes, seedHost); verifyCluster(numNodes, seedHost); final HostAndPort nodeToFail = HostAndPort.fromParts("127.0.0.1", basePort + 2); failSomeNodes(Collections.singletonList(nodeToFail)); waitAndVerifyAgreement(numNodes - 1, 10, 1000, seedHost); verifyNumClusterInstances(numNodes - 1); } /** * This test starts with a 30 node cluster, then fails 5 nodes while an additional 10 join. */ @Test(timeout=30000) public void concurrentNodeJoinsAndFails() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 200; final int numNodes = 30; final int failingNodes = 5; final int phaseTwojoiners = 10; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodes, seedHost); verifyCluster(numNodes, seedHost); failSomeNodes(IntStream.range(basePort + 2, basePort + 2 + failingNodes) .mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i)) .collect(Collectors.toList())); extendCluster(phaseTwojoiners, seedHost); waitAndVerifyAgreement(numNodes - failingNodes + phaseTwojoiners, 20, 1000, seedHost); verifyNumClusterInstances(numNodes - failingNodes + phaseTwojoiners); } /** * This test starts with a 5 node cluster, then joins two waves of six nodes each. */ @Test(timeout=30000) public void concurrentNodeJoinsNetty() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100000; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 100000; RpcServer.USE_IN_PROCESS_SERVER = false; RpcClient.USE_IN_PROCESS_CHANNEL = false; final int numNodes = 5; final int phaseOneJoiners = 6; final int phaseTwojoiners = 6; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodes, seedHost); verifyCluster(numNodes, seedHost); final Random r = new Random(); for (int i = 0; i < phaseOneJoiners/2; i++) { final List<HostAndPort> keysAsArray = new ArrayList<>(instances.keySet()); extendCluster(2, keysAsArray.get(r.nextInt(instances.size()))); Thread.sleep(50); } Thread.sleep(100); for (int i = 0; i < phaseTwojoiners; i++) { extendCluster(1, seedHost); Thread.sleep(50); } waitAndVerifyAgreement(numNodes + phaseOneJoiners + phaseTwojoiners, 20, 1000, seedHost); verifyNumClusterInstances(numNodes + phaseOneJoiners + phaseTwojoiners); } /** * This test starts with a 50 node cluster. We then fail 16 nodes to see if the monitoring mechanism * identifies the crashed nodes, and arrives at a decision. * */ @Test public void twelveFailuresOutOfFiftyNodes() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 500; RpcClient.Conf.RPC_PROBE_TIMEOUT = 100; final int numNodes = 50; final int failingNodes = 12; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodes, seedHost); verifyCluster(numNodes, seedHost); failSomeNodes(IntStream.range(basePort + 2, basePort + 2 + failingNodes) .mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i)) .collect(Collectors.toList())); waitAndVerifyAgreement(numNodes - failingNodes, 30, 1000, seedHost); verifyNumClusterInstances(numNodes - failingNodes); } /** * This test starts with a 50 node cluster. We then use the static failure detector to fail * all edges to 3 nodes. */ @Test public void failTenRandomNodes() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 200; useStaticFd = true; final int numNodes = 50; final int numFailingNodes = 10; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); createCluster(numNodes, seedHost); verifyCluster(numNodes, seedHost); // Fail the first 3 nodes. final Set<HostAndPort> failingNodes = getRandomHosts(numFailingNodes); staticFds.values().forEach(e -> e.addFailedNodes(failingNodes)); waitAndVerifyAgreement(numNodes - failingNodes.size(), 20, 1000, seedHost); // Nodes do not actually shutdown(), but are detected faulty. The faulty nodes have active // cluster instances and identify themselves as kicked out. verifyNumClusterInstances(numNodes); } /** * This test starts with a 50 node cluster. We then randomly fail at most 10 randomly selected nodes. */ @Test public void injectAsymmetricDrops() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 100; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 200; RpcClient.Conf.RPC_PROBE_TIMEOUT = 200; final int numNodes = 50; final int numFailingNodes = 10; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); // These nodes will drop the first 100 probe requests they receive final Set<HostAndPort> failedNodes = getRandomHosts(basePort + 1, basePort + numNodes, numFailingNodes); // Since the random function returns a set of failed nodes, // we may have less than numFailedNodes entries in the set failedNodes.forEach(host -> dropFirstNAtServer(host, 100, MembershipServiceGrpc.METHOD_RECEIVE_PROBE)); createCluster(numNodes, seedHost); waitAndVerifyAgreement(numNodes - failedNodes.size(), 10, 1000, seedHost); verifyNumClusterInstances(numNodes); } /** * This test starts with a node joining a 1 node cluster. We drop phase 2 messages at the seed * such that RPC-level retries of the first join attempt eventually get through. */ @Test public void phase2MessageDropsRpcRetries() throws IOException, InterruptedException { RpcClient.Conf.RPC_JOIN_PHASE_2_TIMEOUT = RPC_TIMEOUT_SHORT_MS * 5; RpcClient.Conf.RPC_TIMEOUT_MS = RPC_TIMEOUT_SHORT_MS; // use short retry delays to run tests faster. final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); // Drop join-phase-2 attempts by nextNode, but only enough that the RPC retries make it past dropFirstNAtServer(seedHost, (RpcClient.Conf.RPC_DEFAULT_RETRIES) - 1, MembershipServiceGrpc.METHOD_RECEIVE_JOIN_PHASE2MESSAGE); createCluster(1, seedHost); extendCluster(1, seedHost); waitAndVerifyAgreement(2, 15, 1000, seedHost); verifyNumClusterInstances(2); } /** * This test starts with a node joining a 1 node cluster. We drop phase 2 messages at the seed * such that RPC-level retries of the first join attempt fail, and the client re-initiates a join. */ @Test public void phase2JoinAttemptRetry() throws IOException, InterruptedException { RpcClient.Conf.RPC_JOIN_PHASE_2_TIMEOUT = RPC_TIMEOUT_SHORT_MS * 5; RpcClient.Conf.RPC_TIMEOUT_MS = RPC_TIMEOUT_SHORT_MS; // use short retry delays to run tests faster. final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); // Drop join-phase-2 attempts by nextNode such that it re-attempts a join under a new configuration dropFirstNAtServer(seedHost, (RpcClient.Conf.RPC_DEFAULT_RETRIES) + 1, MembershipServiceGrpc.METHOD_RECEIVE_JOIN_PHASE2MESSAGE); createCluster(1, seedHost); extendCluster(1, seedHost); waitAndVerifyAgreement(2, 15, 1000, seedHost); verifyNumClusterInstances(2); } /** * By the time a joiner issues a join-phase2-message, we change the configuration. */ @Test public void phase2JoinAttemptRetryWithConfigChange() throws IOException, InterruptedException { RpcClient.Conf.RPC_JOIN_PHASE_2_TIMEOUT = RPC_TIMEOUT_SHORT_MS * 5; RpcClient.Conf.RPC_TIMEOUT_MS = RPC_TIMEOUT_SHORT_MS; // use short retry delays to run tests faster. final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); final HostAndPort joinerHost = HostAndPort.fromParts("127.0.0.1", basePort + 1); // Drop join-phase-2 attempts by nextNode such that it re-attempts a join under a new configuration createCluster(1, seedHost); // The next host to join will have its join-phase2-message blocked. final CountDownLatch latch = blockAtClient(joinerHost, MembershipServiceGrpc.METHOD_RECEIVE_JOIN_PHASE2MESSAGE); extendClusterNonBlocking(1, seedHost); // The following node is now free to join. This will render the configuration received by the previous // joiner node stale extendCluster(1, seedHost); latch.countDown(); waitAndVerifyAgreement(3, 15, 1000, seedHost); verifyNumClusterInstances(3); } /** * Shutdown a node and rejoin multiple times. */ @Test public void testRejoinSingleNode() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 200; RpcClient.Conf.RPC_PROBE_TIMEOUT = 100; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); final HostAndPort leavingHost = HostAndPort.fromParts("127.0.0.1", basePort + 1); createCluster(10, seedHost); // Shutdown and rejoin five times for (int i = 0; i < 5; i++) { final Cluster cluster = instances.remove(leavingHost); cluster.shutdown(); waitAndVerifyAgreement(9, 10, 500, seedHost); extendCluster(leavingHost, seedHost); waitAndVerifyAgreement(10, 10, 500, seedHost); } } /** * Shutdown a node and rejoin multiple times. */ @Test public void testRejoinMultipleNodes() throws IOException, InterruptedException { MembershipService.FAILURE_DETECTOR_INITIAL_DELAY_IN_MS = 0; MembershipService.FAILURE_DETECTOR_INTERVAL_IN_MS = 200; RpcClient.Conf.RPC_PROBE_TIMEOUT = 100; final HostAndPort seedHost = HostAndPort.fromParts("127.0.0.1", basePort); final int numNodes = 30; final int failNodes = 5; createCluster(numNodes, seedHost); final ExecutorService executor = Executors.newWorkStealingPool(failNodes); final CountDownLatch latch = new CountDownLatch(failNodes); for (int j = 0; j < failNodes; j++) { final int inc = j; executor.execute(() -> { // Shutdown and rejoin five times try { for (int i = 0; i < 5; i++) { final HostAndPort leavingHost = HostAndPort.fromParts("127.0.0.1", basePort + 1 + inc); final Cluster cluster = instances.remove(leavingHost); try { cluster.shutdown(); waitAndVerifyAgreement(numNodes - failNodes, 20, 500, seedHost); extendCluster(leavingHost, seedHost); waitAndVerifyAgreement(numNodes, 20, 500, seedHost); } catch (InterruptedException e) { fail(); } } } finally { latch.countDown(); } }); } latch.await(); waitAndVerifyAgreement(numNodes, 10, 250, seedHost); } /** * Creates a cluster of size {@code numNodes} with a seed {@code seedHost}. * * @param numNodes cluster size * @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point * for subsequent joiners. * @throws IOException Thrown if the Cluster.start() or join() methods throw an IOException when trying * to register an RpcServer. */ private void createCluster(final int numNodes, final HostAndPort seedHost) throws IOException { final Cluster seed = buildCluster(seedHost).start(); instances.put(seedHost, seed); assertEquals(seed.getMemberlist().size(), 1); if (numNodes >= 2) { extendCluster(numNodes - 1, seedHost); } } /** * Add {@code numNodes} instances to a cluster. * * @param numNodes cluster size * @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point * for subsequent joiners. */ private void extendCluster(final int numNodes, final HostAndPort seedHost) { final ExecutorService executor = Executors.newWorkStealingPool(numNodes); try { final CountDownLatch latch = new CountDownLatch(numNodes); for (int i = 0; i < numNodes; i++) { executor.submit(() -> { try { final HostAndPort joiningHost = HostAndPort.fromParts("127.0.0.1", portCounter.incrementAndGet()); final Cluster nonSeed = buildCluster(joiningHost).join(seedHost); instances.put(joiningHost, nonSeed); } catch (final Exception e) { e.printStackTrace(); fail(); } finally { latch.countDown(); } }); } latch.await(); } catch (final Exception e) { e.printStackTrace(); fail(); } finally { executor.shutdown(); } } /** * Add {@code numNodes} instances to a cluster. * * @param joiningNode HostAndPort that represents the node joining. * @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point * for subsequent joiners. */ private void extendCluster(final HostAndPort joiningNode, final HostAndPort seedHost) { final ExecutorService executor = Executors.newWorkStealingPool(1); try { final CountDownLatch latch = new CountDownLatch(1); executor.submit(() -> { try { final Cluster nonSeed = buildCluster(joiningNode).join(seedHost); instances.put(joiningNode, nonSeed); } catch (final Exception e) { e.printStackTrace(); fail(); } finally { latch.countDown(); } }); latch.await(); } catch (final Exception e) { e.printStackTrace(); fail(); } finally { executor.shutdown(); } } /** * Add {@code numNodes} instances to a cluster without waiting for their join methods to return * * @param numNodes cluster size * @param seedHost HostAndPort that represents the seed node to initialize and be used as the contact point * for subsequent joiners. */ private void extendClusterNonBlocking(final int numNodes, final HostAndPort seedHost) { final ExecutorService executor = Executors.newWorkStealingPool(numNodes); try { for (int i = 0; i < numNodes; i++) { executor.submit(() -> { try { final HostAndPort joiningHost = HostAndPort.fromParts("127.0.0.1", portCounter.incrementAndGet()); final Cluster nonSeed = buildCluster(joiningHost).join(seedHost); instances.put(joiningHost, nonSeed); } catch (final Exception e) { e.printStackTrace(); fail(); } }); } } catch (final Exception e) { e.printStackTrace(); fail(); } finally { executor.shutdown(); } } /** * Fail a set of nodes in a cluster by calling shutdown(). * * @param nodesToFail list of HostAndPort objects representing the nodes to fail */ private void failSomeNodes(final List<HostAndPort> nodesToFail) { final ExecutorService executor = Executors.newWorkStealingPool(nodesToFail.size()); try { final CountDownLatch latch = new CountDownLatch(nodesToFail.size()); for (final HostAndPort nodeToFail : nodesToFail) { executor.execute(() -> { try { assertTrue(nodeToFail + " not in instances", instances.containsKey(nodeToFail)); instances.get(nodeToFail).shutdown(); instances.remove(nodeToFail); } catch (final InterruptedException e) { fail(); } finally { latch.countDown(); } }); } latch.await(); } catch (final Exception e) { e.printStackTrace(); fail(); } finally { executor.shutdown(); } } /** * Verify that all nodes in the cluster are of size {@code expectedSize} and have an identical * list of members as the seed node. * * @param expectedSize expected size of each cluster * @param seedHost seed node to validate the cluster view against */ private void verifyCluster(final int expectedSize, final HostAndPort seedHost) { for (final Cluster cluster : instances.values()) { assertEquals(cluster.toString(), expectedSize, cluster.getMemberlist().size()); assertEquals(cluster.getMemberlist(), instances.get(seedHost).getMemberlist()); } } /** * Verify the number of Cluster instances that managed to start. * * @param expectedSize expected size of each cluster */ private void verifyNumClusterInstances(final int expectedSize) { assertEquals(expectedSize, instances.size()); } /** * Verify whether the cluster has converged {@code maxTries} times with a delay of @{code intervalInMs} * between attempts. This is used to give failure detector logic some time to kick in. * * @param expectedSize expected size of each cluster * @param maxTries number of tries to checkMonitoree if the cluster has stabilized. * @param intervalInMs the time duration between checks. * @param seedNode the seed node to validate the cluster membership against */ private void waitAndVerifyAgreement(final int expectedSize, final int maxTries, final int intervalInMs, final HostAndPort seedNode) throws InterruptedException { int tries = maxTries; while (--tries > 0) { boolean ready = true; for (final Cluster cluster : instances.values()) { if (!(cluster.getMemberlist().size() == expectedSize && cluster.getMemberlist().equals(instances.get(seedNode).getMemberlist()))) { ready = false; } } if (!ready) { Thread.sleep(intervalInMs); } else { break; } } verifyCluster(expectedSize, seedNode); } // Helper that provides a list of N random nodes that have already been added to the instances map private Set<HostAndPort> getRandomHosts(final int N) { assert random != null; final List<Map.Entry<HostAndPort, Cluster>> entries = new ArrayList<>(instances.entrySet()); Collections.shuffle(entries); return random.ints(instances.size(), 0, N) .mapToObj(i -> entries.get(i).getKey()) .collect(Collectors.toSet()); } // Helper that provides a list of N random nodes from portStart to portEnd private Set<HostAndPort> getRandomHosts(final int portStart, final int portEnd, final int N) { assert random != null; return random.ints(N, portStart, portEnd) .mapToObj(i -> HostAndPort.fromParts("127.0.0.1", i)) .collect(Collectors.toSet()); } // Helper to use static-failure-detectors and inject interceptors private Cluster.Builder buildCluster(final HostAndPort host) { Cluster.Builder builder = new Cluster.Builder(host); if (useStaticFd) { final StaticFailureDetector fd = new StaticFailureDetector(new HashSet<>()); builder = builder.setLinkFailureDetector(fd); staticFds.put(host, fd); } if (serverInterceptors.containsKey(host)) { builder = builder.setServerInterceptors(serverInterceptors.get(host)); } if (clientInterceptors.containsKey(host)) { builder = builder.setClientInterceptors(clientInterceptors.get(host)); } return builder; } // Helper that drops the first N requests at a server of a given type private <T, E> void dropFirstNAtServer(final HostAndPort host, final int N, final MethodDescriptor<T, E> messageType) { serverInterceptors.computeIfAbsent(host, (k) -> new ArrayList<>(1)) .add(new ServerDropInterceptors.FirstN<>(N, messageType, host)); } // Helper that delays requests of a given type at the client private <T, E> CountDownLatch blockAtClient(final HostAndPort host, final MethodDescriptor<T, E> messageType) { final CountDownLatch latch = new CountDownLatch(1); clientInterceptors.computeIfAbsent(host, (k) -> new ArrayList<>(1)) .add(new ClientInterceptors.Delayer<>(latch, messageType)); return latch; } }
package org.intermine.web; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import org.apache.struts.actions.DispatchAction; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; /** * Action to handle links on main tile * @author Mark Woodbridge */ public class MainChange extends DispatchAction { /** * Remove all nodes under a given path * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws */ public ActionForward removeNode(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE); PathQuery pathQuery = (PathQuery) session.getAttribute(Constants.QUERY); String path = request.getParameter("path"); removeNode(pathQuery, path); String prefix; if (path.indexOf(".") == -1) { prefix = path; } else { prefix = path.substring(0, path.lastIndexOf(".")); path = ((Node) pathQuery.getNodes().get(prefix)).getType(); } session.setAttribute("prefix", prefix); session.setAttribute("path", path); return mapping.findForward("query"); } protected static void removeNode(PathQuery pathQuery, String path) { // copy because we will be remove paths from the Map as we go Set keys = new HashSet(pathQuery.getNodes().keySet()); // remove the node and it's children for (Iterator i = keys.iterator(); i.hasNext();) { String testPath = (String) i.next(); if (testPath.startsWith(path)) { removeOneNode(pathQuery, testPath); } } } protected static void removeOneNode(PathQuery pathQuery, String path) { // ensure removal of any view nodes that depend on a type constraint // eg. Department.employees.salary where salary is only defined in a subclass of Employee // note that we first have to find out what type Department thinks the employees field is // and then check if any of the view nodes assume the field is constrained to a subclass String parentType = ((PathNode) pathQuery.getNodes().get(path)).getParentType(); Model model = pathQuery.getModel(); if (parentType != null) { ClassDescriptor parentCld = MainHelper.getClassDescriptor(parentType, model); String pathLastField = path.substring(path.lastIndexOf(".") + 1); FieldDescriptor fd = parentCld.getFieldDescriptorByName(pathLastField); if (fd instanceof ReferenceDescriptor) { ReferenceDescriptor rf = (ReferenceDescriptor) fd; ClassDescriptor realClassDescriptor = rf.getReferencedClassDescriptor(); Iterator viewPathIter = pathQuery.getView().iterator(); while (viewPathIter.hasNext()) { String viewPath = (String) viewPathIter.next(); if (viewPath.startsWith(path) && !viewPath.equals(path)) { String fieldName = viewPath.substring(path.length() + 1); if (fieldName.indexOf(".") != -1) { fieldName = fieldName.substring(0, fieldName.indexOf(".")); } if (realClassDescriptor.getFieldDescriptorByName(fieldName) == null) { // the field must be in a sub-class rather than the base class so remove // the viewPath viewPathIter.remove(); } } } } } pathQuery.getNodes().remove(path); } /** * Add a new constraint to this Node * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws */ public ActionForward addConstraint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); String path = request.getParameter("path"); session.setAttribute("editingNode", query.getNodes().get(path)); return mapping.findForward("query"); } /** * Remove a constraint (identified by index) from a Node * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws */ public ActionForward removeConstraint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); String path = request.getParameter("path"); int index = Integer.parseInt(request.getParameter("index")); ((PathNode) query.getNodes().get(path)).getConstraints().remove(index); return mapping.findForward("query"); } /** * Add a Node to the query * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws */ public ActionForward addPath(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); String prefix = (String) session.getAttribute("prefix"); String path = request.getParameter("path"); path = toPath(prefix, path); Node node = query.addNode(path); //automatically start editing node session.setAttribute("editingNode", node); //and change metadata view if relevant if (!node.isAttribute()) { session.setAttribute("prefix", path); session.setAttribute("path", node.getType()); } return mapping.findForward("query"); } /** * Change the currently active metadata Node * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws */ public ActionForward changePath(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); String path = request.getParameter("path"); String prefix = request.getParameter("prefix"); session.setAttribute("path", path); if (prefix != null) { session.setAttribute("prefix", prefix); } return new ForwardParameters(mapping.findForward("query")).addAnchor(path).forward(); } /** * Add a Node to the results view * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws */ public ActionForward addToView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); String prefix = (String) session.getAttribute("prefix"); String path = request.getParameter("path"); query.getView().add(toPath(prefix, path)); return mapping.findForward("query"); } /** * Convert a path and prefix to a path * @param prefix the prefix (eg null or Department.company) * @param path the path (eg Company, Company.departments) * @return the new path */ protected static String toPath(String prefix, String path) { if (prefix != null) { if (path.indexOf(".") == -1) { path = prefix; } else { path = prefix + "." + path.substring(path.indexOf(".") + 1); } } return path; } }
package io.realm; import android.content.Context; import android.view.LayoutInflater; import android.widget.BaseAdapter; public abstract class RealmBaseAdapter<T extends RealmObject> extends BaseAdapter { protected LayoutInflater inflater; protected RealmResults<T> realmResults; protected Context context; protected int resId; public RealmBaseAdapter(Context context, RealmResults<T> realmResults, boolean automaticUpdate) { if (context == null) { throw new IllegalArgumentException("Context cannot be null"); } if (realmResults == null) { throw new IllegalArgumentException("RealmResults cannot be null"); } this.context = context; this.realmResults = realmResults; this.inflater = LayoutInflater.from(context); if (automaticUpdate) { realmResults.getRealm().addChangeListener(new RealmChangeListener() { @Override public void onChange() { notifyDataSetChanged(); } }); } } @Override public int getCount() { return realmResults.size(); } @Override public T getItem(int i) { return realmResults.get(i); } @Override public long getItemId(int i) { return i; // TODO: find better solution once we have unique IDs } /** * Update the RealmResults associated to the Adapter. Useful when the query has been changed. * If the query does not change you might consider using the automaticUpdate feature * @param realmResults the new RealmResults coming from the new query. */ public void updateRealmResults(RealmResults<T> realmResults) { this.realmResults = realmResults; notifyDataSetChanged(); } }
package controllers; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.Duration; import org.spout.cereal.config.ConfigurationNode; import org.spout.cereal.config.yaml.YamlConfiguration; import play.Logger; import play.libs.Json; import play.mvc.Result; import play.mvc.Results; import com.afforess.assembly.util.DatabaseAccess; import com.afforess.assembly.util.Utils; import com.limewoodMedia.nsapi.NationStates; public class RegionController extends NationStatesController { private final String imgurClientKey; public RegionController(DatabaseAccess access, YamlConfiguration config, NationStates api) { super(access, config, api); ConfigurationNode imgurAuth = getConfig().getChild("imgur"); imgurClientKey = imgurAuth.getChild("client-key").getString(null); } public Result getUpdateTime(String region, int std) throws SQLException, ExecutionException { Connection conn = null; final int regionId = getDatabase().getRegionIdCache().get(Utils.sanitizeName(region)); if (regionId == -1) { return Results.badRequest(); } try { conn = getConnection(); PreparedStatement updateTime = conn.prepareStatement("SELECT normalized_start, major FROM assembly.region_update_calculations WHERE region = ? AND update_time < 200000 ORDER BY start DESC LIMIT 0, 60"); updateTime.setInt(1, regionId); ResultSet times = updateTime.executeQuery(); List<Long> majorData = new ArrayList<Long>(30); List<Long> minorData = new ArrayList<Long>(30); SummaryStatistics minor = new SummaryStatistics(); SummaryStatistics major = new SummaryStatistics(); while(times.next()) { if (times.getInt(2) == 1) { major.addValue(times.getLong(1)); majorData.add(times.getLong(1)); } else { minor.addValue(times.getLong(1)); minorData.add(times.getLong(1)); } } DbUtils.closeQuietly(times); DbUtils.closeQuietly(updateTime); if (std > 0) { //Check for major update outliers Set<Long> outliers = new HashSet<Long>(); for (Long time : majorData) { if (time.longValue() > (major.getMean() + major.getStandardDeviation() * std)) { outliers.add(time); } } if (outliers.size() > 0) { major.clear(); for (Long time : majorData) { if (!outliers.contains(time)) { major.addValue(time); } } } outliers.clear(); //Check for minor update outliers for (Long time : minorData) { if (time.longValue() > (minor.getMean() + minor.getStandardDeviation() * std)) { outliers.add(time); } } if (outliers.size() > 0) { minor.clear(); for (Long time : minorData) { if (!outliers.contains(time)) { minor.addValue(time); } } } } Map<String, Object> data = new HashMap<String, Object>(); Map<String, Long> majorUpdate = new HashMap<String, Long>(); majorUpdate.put("mean", Double.valueOf(major.getMean()).longValue()); majorUpdate.put("std", Double.valueOf(major.getStandardDeviation()).longValue()); majorUpdate.put("max", Double.valueOf(major.getMax()).longValue()); majorUpdate.put("min", Double.valueOf(major.getMin()).longValue()); majorUpdate.put("geomean", Double.valueOf(major.getGeometricMean()).longValue()); majorUpdate.put("variance", Double.valueOf(major.getVariance()).longValue()); data.put("major", majorUpdate); Map<String, Long> minorUpdate = new HashMap<String, Long>(); minorUpdate.put("mean", Double.valueOf(minor.getMean()).longValue()); minorUpdate.put("std", Double.valueOf(minor.getStandardDeviation()).longValue()); minorUpdate.put("max", Double.valueOf(minor.getMax()).longValue()); minorUpdate.put("min", Double.valueOf(minor.getMin()).longValue()); minorUpdate.put("geomean", Double.valueOf(minor.getGeometricMean()).longValue()); minorUpdate.put("variance", Double.valueOf(minor.getVariance()).longValue()); data.put("minor", minorUpdate); Result result = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(data.hashCode()), "60"); if (result != null) { return result; } return ok(Json.toJson(data)).as("application/json"); } finally { DbUtils.closeQuietly(conn); } } public Result getNations(String regions, boolean xml) throws SQLException, ExecutionException { Map<String, Object> regionData = new LinkedHashMap<String, Object>(); Connection conn = null; try { conn = getConnection(); String[] split = regions.split(","); for (int i = 0; i < split.length; i++) { List<String> nations = new ArrayList<String>(); PreparedStatement statement = conn.prepareStatement("SELECT name FROM assembly.nation WHERE alive = 1 AND region = ? ORDER BY update_order ASC"); statement.setInt(1, getDatabase().getRegionIdCache().get(Utils.sanitizeName(split[i]))); ResultSet result = statement.executeQuery(); while(result.next()) { nations.add(result.getString(1)); } Collections.reverse(nations); regionData.put(split[i], nations); DbUtils.closeQuietly(result); DbUtils.closeQuietly(statement); } } finally { DbUtils.closeQuietly(conn); } Utils.handleDefaultPostHeaders(request(), response()); if (xml) { String data = "<REGIONS>\n\t"; for (Entry<String, Object> e : regionData.entrySet()) { data += "<REGION id=\"" + e.getKey() + "\">\n\t\t<NATIONS>"; @SuppressWarnings("unchecked") List<String> nations = (List<String>) e.getValue(); StringBuilder b = new StringBuilder(); int chunk = 0; for (String nation : nations) { if (b.length() / 30000 != chunk) { chunk++; b.append("</NATIONS><NATIONS>"); } else if (b.length() > 0) { b.append(":"); } b.append(nation); } b.append("</NATIONS>\n\t</REGION>"); data += b.toString(); } data += "\n</REGIONS>"; return ok(data).as("application/xml"); } else { return ok(Json.toJson(regionData.size() == 1 ? regionData.get(regions.split(",")[0]) : regionData)).as("application/json"); } } public Result getPopulationTrends(String region) throws SQLException, ExecutionException { Map<String, Object> data = new HashMap<String, Object>(4); Connection conn = null; try { conn = getConnection(); PreparedStatement statement = conn.prepareStatement("SELECT population, timestamp FROM assembly.region_populations WHERE region = ? AND timestamp > ? ORDER BY TIMESTAMP DESC"); statement.setString(1, Utils.sanitizeName(region)); statement.setLong(2, System.currentTimeMillis() - Duration.standardDays(30).getMillis()); ResultSet result = statement.executeQuery(); List<Population> population = new ArrayList<Population>(); while(result.next()) { population.add(new Population(result.getInt(1), result.getLong(2))); } data.put("region", population); DbUtils.closeQuietly(result); DbUtils.closeQuietly(statement); PreparedStatement global = conn.prepareStatement("CALL assembly.first_seen_history(30)"); result = global.executeQuery(); population = new ArrayList<Population>(); while(result.next()) { population.add(new Population(result.getInt(1), result.getLong(2))); } data.put("global_growth", population); DbUtils.closeQuietly(result); DbUtils.closeQuietly(global); global = conn.prepareStatement("CALL assembly.cte_history(30)"); result = global.executeQuery(); population = new ArrayList<Population>(); while(result.next()) { population.add(new Population(result.getInt(1), result.getLong(2))); } data.put("global_cte", population); DbUtils.closeQuietly(result); DbUtils.closeQuietly(global); global = conn.prepareStatement("SELECT count(id) FROM assembly.nation WHERE alive = 1;"); result = global.executeQuery(); result.next(); data.put("global_alive", result.getInt(1)); DbUtils.closeQuietly(result); DbUtils.closeQuietly(global); } finally { DbUtils.closeQuietly(conn); } Result result = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(data.hashCode()), "21600"); if (result != null) { return result; } return ok(Json.toJson(data)).as("application/json"); } static class Population { @JsonProperty int population; @JsonProperty long timestamp; Population() { } Population(int population, long timestamp) { this.population = population; this.timestamp = timestamp; } } public Result setRegionalMap(String region, boolean disband) throws SQLException, ExecutionException { Result ret = Utils.validateRequest(request(), response(), getAPI(), getDatabase()); if (ret != null) { return ret; } String nation = Utils.sanitizeName(Utils.getPostValue(request(), "nation")); Utils.handleDefaultPostHeaders(request(), response()); Connection conn = null; try { conn = getConnection(); PreparedStatement select = conn.prepareStatement("SELECT delegate, founder FROM assembly.region WHERE name = ?"); select.setString(1, Utils.sanitizeName(region)); ResultSet result = select.executeQuery(); boolean regionAdministrator = true; if (result.next()) { Logger.info("Attempting to set map for " + region + ", nation: " + nation); Logger.info("Delegate: " + result.getString(1) + " | Founder: " + result.getString(2)); if (!nation.equals(result.getString(1)) && !nation.equals(result.getString(2))) { regionAdministrator = false; } } else { Logger.info("Attempting to set map for " + region + ", no region found!"); regionAdministrator = false; } DbUtils.closeQuietly(result); DbUtils.closeQuietly(select); if (!regionAdministrator) { return Results.unauthorized(); } if (disband) { PreparedStatement update = conn.prepareStatement("UPDATE assembly.region SET regional_map = NULL, regional_map_preview = NULL WHERE name = ?"); update.setString(1, Utils.sanitizeName(region)); update.executeUpdate(); DbUtils.closeQuietly(update); } else { String mapLink = Utils.getPostValue(request(), "regional_map"); String mapPreview = Utils.getPostValue(request(), "regional_map_preview"); if (mapPreview == null) { return Results.badRequest("missing map preview"); } if (mapLink == null) { return Results.badRequest("missing map link"); } String imgurPreview = null; try { imgurPreview = Utils.uploadToImgur(mapPreview, imgurClientKey); } catch (Exception e) { Logger.warn("Unable to upload image to imgur for regional map [" + mapPreview + "]", e); } if (imgurPreview == null) { return Results.badRequest("invalid map preview"); } PreparedStatement update = conn.prepareStatement("UPDATE assembly.region SET regional_map = ?, regional_map_preview = ? WHERE name = ?"); update.setString(1, mapLink); update.setString(2, imgurPreview); update.setString(3, Utils.sanitizeName(region)); update.executeUpdate(); DbUtils.closeQuietly(update); } } finally { DbUtils.closeQuietly(conn); } return Results.ok(); } public Result getRegionalMap(String region) throws SQLException, ExecutionException { Map<String, String> links = new HashMap<String, String>(3); Connection conn = null; try { conn = getConnection(); PreparedStatement update = conn.prepareStatement("SELECT regional_map, regional_map_preview FROM assembly.region WHERE name = ?"); update.setString(1, Utils.sanitizeName(region)); ResultSet set = update.executeQuery(); if (set.next()) { String mapLink = set.getString(1); if (!set.wasNull()) { links.put("regional_map", mapLink); } String mapPreview = set.getString(2); if (!set.wasNull()) { links.put("regional_map_preview", mapPreview); } } DbUtils.closeQuietly(set); DbUtils.closeQuietly(update); } finally { DbUtils.closeQuietly(conn); } Result result = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(links.hashCode()), "60"); if (result != null) { return result; } return Results.ok(Json.toJson(links)).as("application/json"); } public Result setRegionalTitle(String region, boolean disband) throws SQLException, ExecutionException { Result ret = Utils.validateRequest(request(), response(), getAPI(), getDatabase()); if (ret != null) { return ret; } String nation = Utils.sanitizeName(Utils.getPostValue(request(), "nation")); String delegateTitle = Utils.getPostValue(request(), "delegate_title"); String founderTitle = Utils.getPostValue(request(), "founder_title"); Utils.handleDefaultPostHeaders(request(), response()); //Must have valid title if (!disband) { if (delegateTitle == null || founderTitle == null || delegateTitle.isEmpty() || founderTitle.isEmpty()) { return Results.badRequest("Missing title"); } else if (delegateTitle.length() > 40 || founderTitle.length() > 40) { return Results.badRequest("Maximum title length is 40 characters"); } } Connection conn = null; try { conn = getConnection(); PreparedStatement select = conn.prepareStatement("SELECT id, delegate, founder FROM assembly.region WHERE name = ?"); select.setString(1, Utils.sanitizeName(region)); ResultSet result = select.executeQuery(); boolean regionAdministrator = true; int regionId = -1; if (result.next()) { regionId = result.getInt(1); final String delegate = result.getString(2); final String founder = result.getString(3); Logger.info("Attempting to set regional titles for " + region + ", nation: " + nation); Logger.info("Delegate: " + delegate + " | Founder: " + founder); if (!nation.equals(delegate) && !nation.equals(founder)) { regionAdministrator = false; } } else { Logger.info("Attempting to set regional titles for " + region + ", no region found!"); regionAdministrator = false; } if (regionAdministrator) { PreparedStatement update = conn.prepareStatement("UPDATE assembly.region SET delegate_title = ?, founder_title = ? WHERE id = ?"); if (!disband) { update.setString(1, delegateTitle); update.setString(2, founderTitle); } else { update.setNull(1, Types.VARCHAR); update.setNull(2, Types.VARCHAR); } update.setInt(3, regionId); update.executeUpdate(); return Results.ok(); } } finally { DbUtils.closeQuietly(conn); } return Results.unauthorized(); } public Result getRegionalTitles(String region) throws SQLException, ExecutionException { Connection conn = null; try { conn = getConnection(); PreparedStatement select = conn.prepareStatement("SELECT delegate_title, founder_title FROM assembly.region WHERE name = ?"); select.setString(1, Utils.sanitizeName(region)); ResultSet result = select.executeQuery(); if (result.next()) { Map<String, String> data = new HashMap<String, String>(2); String title = result.getString(1); if (!result.wasNull()) { data.put("delegate_title", title); } title = result.getString(2); if (!result.wasNull()) { data.put("founder_title", title); } Result r = Utils.handleDefaultGetHeaders(request(), response(), String.valueOf(data.hashCode()), "600"); if (r != null) { return r; } return Results.ok(Json.toJson(data)).as("application/json"); } } finally { DbUtils.closeQuietly(conn); } Result r = Utils.handleDefaultGetHeaders(request(), response(), "0", "60"); if (r != null) { return r; } return Results.ok("").as("application/json"); } }
package io.xchris6041x.devin; public final class AnsiColor { // Reset public static final String RESET = "\u001B[0m"; // Colors public static final String BLACK = "\u001B[30m"; public static final String RED = "\u001B[1;31m"; public static final String GREEN = "\u001B[1;32m"; public static final String YELLOW = "\u001B[1;33m"; public static final String BLUE = "\u001B[1;34m"; public static final String PURPLE = "\u001B[1;35m"; public static final String CYAN = "\u001B[1;36m"; public static final String WHITE = "\u001B[1;37m"; // Dark Colors public static final String DARK_RED = "\u001B[31m"; public static final String DARK_GREEN = "\u001B[32m"; public static final String DARK_YELLOW = "\u001B[33m"; public static final String DARK_BLUE = "\u001B[34m"; public static final String DARK_PURPLE = "\u001B[35m"; public static final String DARK_CYAN = "\u001B[36m"; public static final String GRAY = "\u001B[37m"; private AnsiColor(){ } }
package utils.parser; import java.util.ArrayList; import utils.exceptions.IllegalArgumentsException; public class Parser2 { public static void printHelp() { System.out.println(" ====== USAGE ======="); System.out.println(" "); System.out.println(" java DynamicAnalyzer path/to/main \t\t Compiles file at path/to/main and sets it as mainfile"); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static String[] getSootOptions(String[] args) { ArrayList<String> sootOptions = new ArrayList<String>(); sootOptions.add("-f"); sootOptions.add("c"); // one arg: use as both path and mainClass, output CLASS, to current folder if (args.length == 1) { checkIfStartsWithDash(args[0], "Must supply path to mainClass!"); if (args[0] == "help") { printHelp(); } String[] toAdd = new String[] {"-main-class", args[0], args[0], "-d", System.getProperty("user.dir")}; for (String string : toAdd) { sootOptions.add(string);} } else if (args.length > 1) { checkIfStartsWithDash(args[0], "First argument must be the mainClass!"); } return sootOptions.toArray(new String[0]); } private static void checkIfStartsWithDash(String s, String m) { if (s.startsWith("-")) { throw new IllegalArgumentsException(m); } } }
package eftemj; import ij.IJ; import ij.ImageJ; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class EFTEMj_Debug { /** * Set the plugins.dir property to make the EFTEMj appear in the Plugins menu. Finally start ImageJ. * * @param args * Not used */ public static void main(final String[] args) { EFTEMj.debugLevel = EFTEMj.DEBUG_SHOW_IMAGES; final Class<?> clazz = EFTEMj_Debug.class; final String url = clazz.getResource("/" + clazz.getName().replace('.', '/') + ".class").toString(); // this is the path were maven creates the jar-file final String pluginsDir = url.substring("file:".length(), url.length() - clazz.getName().length() - ".class".length() - "classes/".length()); System.setProperty("plugins.dir", pluginsDir); // start ImageJ new ImageJ(); } public static void log(final String logText, final boolean highPriority) { LogFileWriter logFileWriter = LogFileWriter.getInstance(); if (EFTEMj.debugLevel >= EFTEMj.DEBUG_LOGGING) { logFileWriter.write(logText); } else if (EFTEMj.debugLevel >= EFTEMj.DEBUG_LOGGING & highPriority) { logFileWriter.write(logText); } if (EFTEMj.debugLevel >= EFTEMj.DEBUG_IN_APP_LOGGING) { IJ.log(logText); } } private static class LogFileWriter { private static LogFileWriter instance = null; private File file; private LogFileWriter() { file = new File(EFTEMj_Prefs.getLogFile()); } public static LogFileWriter getInstance() { if (instance == null) { instance = new LogFileWriter(); } return instance; } public void write(final String text) { try { FileWriter fw = new FileWriter(file, true); fw.write(text); fw.write(String.format("%n")); fw.close(); } catch (final IOException exc) { IJ.showMessage("Can't write to the log file." + "\n" + exc); } } } }
package org.eddy; import org.eddy.dao.mapper.test.UserMapper; import org.eddy.model.User; import org.junit.Assert; 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.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = {ApplicationStart.class}) @ActiveProfiles(value="dev") public class UserTest { @Autowired UserMapper userMapper; @Test @Transactional public void test() { List<User> users = userMapper.selectById(1); Assert.assertEquals(1, users.size()); Assert.assertEquals(new Integer(1), users.get(0).getId()); } @Test @Transactional public void test2() { List<User> users = userMapper.selectById(1); Assert.assertEquals(1, users.size()); Assert.assertEquals(new Integer(1), users.get(0).getId()); System.out.println(2); } @Test @Transactional public void test3() { userMapper.insert("today"); } }
package com.couchbase.lite.replicator; import com.couchbase.lite.Document; import com.couchbase.lite.LiteTestCase; import com.couchbase.lite.mockserver.MockBulkDocs; import com.couchbase.lite.mockserver.MockCheckpointPut; import com.couchbase.lite.mockserver.MockDispatcher; import com.couchbase.lite.mockserver.MockHelper; import com.couchbase.lite.mockserver.MockRevsDiff; import com.couchbase.lite.util.Log; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class Replication2Test extends LiteTestCase { public void testExcessiveCheckpointingDuringPushReplication() throws Exception { List<Document> docs = new ArrayList<Document>(); // 1. Add 200 local documents for(int i = 0; i < 200; i++) { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("testExcessiveCheckpointingDuringPushReplication", String.valueOf(i)); Document doc = createDocumentWithProperties(database, properties); docs.add(doc); } // create mock server MockDispatcher dispatcher = new MockDispatcher(); MockWebServer server = new MockWebServer(); server.setDispatcher(dispatcher); server.play(); // checkpoint GET response -> error // _revs_diff response -- everything missing MockRevsDiff mockRevsDiff = new MockRevsDiff(); mockRevsDiff.setSticky(true); dispatcher.enqueueResponse(MockHelper.PATH_REGEX_REVS_DIFF, mockRevsDiff); // _bulk_docs response -- everything stored MockBulkDocs mockBulkDocs = new MockBulkDocs(); mockBulkDocs.setSticky(true); dispatcher.enqueueResponse(MockHelper.PATH_REGEX_BULK_DOCS, mockBulkDocs); // checkpoint PUT response (sticky) MockCheckpointPut mockCheckpointPut = new MockCheckpointPut(); mockCheckpointPut.setSticky(true); dispatcher.enqueueResponse(MockHelper.PATH_REGEX_CHECKPOINT, mockCheckpointPut); // 2. Kick off continuous push replication Replication replicator = database.createPushReplication(server.getUrl("/db")); replicator.setContinuous(true); CountDownLatch replicationIdleSignal = new CountDownLatch(1); ReplicationIdleObserver replicationIdleObserver = new ReplicationIdleObserver(replicationIdleSignal); replicator.addChangeListener(replicationIdleObserver); replicator.start(); // 3. Wait for document to be pushed // NOTE: (Not 100% reproducible) With CBL Java on Jenkins (Super slow environment), // Replicator becomes IDLE between batches for this case, after 100 push replicated. // TODO: Need to investigate // wait until replication goes idle boolean successful = replicationIdleSignal.await(60, TimeUnit.SECONDS); assertTrue(successful); // wait until mock server gets the checkpoint PUT request boolean foundCheckpointPut = false; String expectedLastSequence = "200"; while (!foundCheckpointPut) { RecordedRequest request = dispatcher.takeRequestBlocking(MockHelper.PATH_REGEX_CHECKPOINT); if (request.getMethod().equals("PUT")) { foundCheckpointPut = true; String body = request.getUtf8Body(); Log.e("testExcessiveCheckpointingDuringPushReplication", "body => " + body); // TODO: this is not valid if device can not handle all replication data at once //assertTrue(body.indexOf(expectedLastSequence) != -1); // wait until mock server responds to the checkpoint PUT request dispatcher.takeRecordedResponseBlocking(request); } } // make some assertions about the outgoing _bulk_docs requests RecordedRequest bulkDocsRequest1 = dispatcher.takeRequest(MockHelper.PATH_REGEX_BULK_DOCS); assertNotNull(bulkDocsRequest1); RecordedRequest bulkDocsRequest2 = dispatcher.takeRequest(MockHelper.PATH_REGEX_BULK_DOCS); assertNotNull(bulkDocsRequest2); // order may not be guaranteed // TODO: this is not valid if device can not handle all replication data at once //assertTrue(isBulkDocJsonContainsDoc(bulkDocsRequest1, docs.get(0)) || isBulkDocJsonContainsDoc(bulkDocsRequest2, docs.get(0))); //assertTrue(isBulkDocJsonContainsDoc(bulkDocsRequest1, docs.get(100)) || isBulkDocJsonContainsDoc(bulkDocsRequest2, docs.get(100))); // check if Android CBL client sent only one PUT /{db}/_local/xxxx request // previous check already consume this request, so queue size should be 0. BlockingQueue<RecordedRequest> queue = dispatcher.getRequestQueueSnapshot(MockHelper.PATH_REGEX_CHECKPOINT); assertEquals(0, queue.size()); // cleanup stopReplication(replicator); server.shutdown(); } }
package com.dmdirc.ui.swing.dialogs.channelsetting; import com.dmdirc.Channel; import com.dmdirc.config.IdentityManager; import com.dmdirc.interfaces.ConfigChangeListener; import com.dmdirc.parser.ChannelListModeItem; import com.dmdirc.util.MapList; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import net.miginfocom.swing.MigLayout; /** List modes panel. */ public final class ChannelListModesPane extends JPanel implements ActionListener, ListSelectionListener, ConfigChangeListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 5; /** Channel. */ private final Channel channel; /** Combox box used to switch between list modes. */ private final JComboBox listModesMenu; /** Arraylist of jpanels containing the listmodes. */ private final List<JList> listModesPanels; /** JPanel used to show listmodespanels in. */ private final JScrollPane listModesPanel; /** Add list mode button. */ private final JButton addListModeButton; /** Remove list mode button. */ private final JButton removeListModeButton; /** list modes available on this server. */ private final char[] listModesArray; /** Modes on creation. */ private final MapList<Character, ChannelListModeItem> existingListItems; /** Mode count label. */ private final JLabel modeCount; /** Cell renderer. */ private ListCellRenderer renderer; /** Extended info toggle. */ private JCheckBox toggle; /** * Creates a new instance of ChannelListModePane. * * @param channel Parent channel */ public ChannelListModesPane(final Channel channel) { super(); this.channel = channel; if (channel.getConfigManager().getOptionBool("general", "extendedListModes", false)) { renderer = new ExtendedListModeCellRenderer(); } else { renderer = new ListModeCellRenderer(); } listModesPanel = new JScrollPane(); listModesPanels = new ArrayList<JList>(); listModesArray = channel.getServer().getParser().getListChanModes().toCharArray(); existingListItems = new MapList<Character, ChannelListModeItem>(); listModesMenu = new JComboBox(new DefaultComboBoxModel()); addListModeButton = new JButton("Add"); removeListModeButton = new JButton("Remove"); removeListModeButton.setEnabled(false); modeCount = new JLabel(); toggle = new JCheckBox("Show extended information", channel.getConfigManager().getOptionBool("general", "extendedListModes", false)); toggle.setMargin(new Insets(0, 0, 0, 0)); toggle.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); initListModesPanel(); initListeners(); setVisible(true); } /** Updates the panel. */ public void update() { final boolean visible = listModesPanel.isVisible(); if (visible) { listModesPanel.setVisible(false); } existingListItems.clear(); for (int i = 0; i < listModesArray.length; i++) { final char mode = listModesArray[i]; existingListItems.add(mode, new ArrayList<ChannelListModeItem>(channel.getChannelInfo(). getListModeParam(mode))); final ArrayList<ChannelListModeItem> listItems = channel.getChannelInfo().getListModeParam(mode); final DefaultListModel model = (DefaultListModel) listModesPanels.get(i).getModel(); model.removeAllElements(); for (ChannelListModeItem listItem : listItems) { model.addElement(listItem); } } if (visible) { listModesPanel.setVisible(true); } } /** Updates the list mode menu. */ private void updateMenu() { if (listModesArray.length == 0) { listModesMenu.setEnabled(false); addListModeButton.setEnabled(false); return; } else { listModesMenu.setEnabled(true); addListModeButton.setEnabled(true); } final DefaultComboBoxModel model = (DefaultComboBoxModel) listModesMenu.getModel(); for (char mode : listModesArray) { String modeText = mode + " list"; if (channel.getConfigManager(). getOptionBool("server", "friendlymodes", false) && channel.getConfigManager().hasOption("server", "mode" + mode)) { modeText = channel.getConfigManager(). getOption("server", "mode" + mode) + " list"; } model.addElement(modeText); final JList list = new JList(new DefaultListModel()); list.setCellRenderer(renderer); list.setVisibleRowCount(8); list.addListSelectionListener(this); listModesPanels.add(list); } if (listModesPanels.isEmpty()) { listModesPanel.setViewportView(new JPanel()); } else { listModesPanel.setViewportView(listModesPanels.get(0)); } updateModeCount(); listModesPanel.setVisible(true); } /** Initialises the list modes panel. */ private void initListModesPanel() { updateMenu(); setLayout(new MigLayout("fill, wrap 1")); add(toggle, "alignx center"); add(listModesMenu, "growx"); add(listModesPanel, "grow"); add(modeCount, "growx, pushx"); add(addListModeButton, "split 2, growx"); add(removeListModeButton, "growx"); update(); updateModeCount(); } /** Initialises listeners for this dialog. */ private void initListeners() { addListModeButton.addActionListener(this); removeListModeButton.addActionListener(this); listModesMenu.addActionListener(this); toggle.addActionListener(this); channel.getConfigManager().addChangeListener("general", "extendedListModes", this); } /** Sends the list modes to the server. */ public void save() { final Map<ChannelListModeItem, Character> currentModes = new HashMap<ChannelListModeItem, Character>(); final Map<ChannelListModeItem, Character> newModes = new HashMap<ChannelListModeItem, Character>(); for (int i = 0; i < listModesArray.length; i++) { final char mode = listModesArray[i]; final Enumeration<?> values = ((DefaultListModel) listModesPanels.get(i).getModel()).elements(); final List<ChannelListModeItem> listItems = existingListItems.get(mode); for (ChannelListModeItem listItem : listItems) { currentModes.put(listItem, mode); } while (values.hasMoreElements()) { final ChannelListModeItem value = (ChannelListModeItem) values.nextElement(); newModes.put(value, mode); } } for (Entry<ChannelListModeItem, Character> entry : newModes.entrySet()) { if (currentModes.containsKey(entry.getKey())) { currentModes.remove(entry.getKey()); } else { channel.getChannelInfo(). alterMode(true, entry.getValue(), entry.getKey().getItem()); } } for (Entry<ChannelListModeItem, Character> entry : currentModes.entrySet()) { channel.getChannelInfo(). alterMode(false, entry.getValue(), entry.getKey().getItem()); } channel.getChannelInfo().sendModes(); } /** Adds a list mode. */ private void addListMode() { final int selectedIndex = listModesMenu.getSelectedIndex(); String modeText = "" + listModesArray[selectedIndex]; String modeMask; if (channel.getConfigManager(). hasOption("server", "mode" + listModesArray[selectedIndex])) { modeText = channel.getConfigManager(). getOption("server", "mode" + listModesArray[selectedIndex]); } modeMask = JOptionPane.showInputDialog(listModesPanel, "Please enter the hostmask for the new " + modeText); if (modeMask != null && (!modeMask.isEmpty() || !modeMask.isEmpty())) { final DefaultListModel model = (DefaultListModel) listModesPanels.get(selectedIndex). getModel(); model.addElement(new ChannelListModeItem(modeMask, "", System.currentTimeMillis() / 1000)); } updateModeCount(); } /** Removes a list mode. */ private void removeListMode() { final int selectedIndex = listModesMenu.getSelectedIndex(); final JList list = listModesPanels.get(selectedIndex); for (Object mode : list.getSelectedValues()) { ((DefaultListModel) list.getModel()).removeElement(mode); } updateModeCount(); } /** * {@inheritDoc} * * @param event Action event */ @Override public void actionPerformed(final ActionEvent event) { if (listModesMenu.equals(event.getSource())) { final int selectedIndex = listModesMenu.getSelectedIndex(); listModesPanel.setVisible(false); listModesPanel.setViewportView(listModesPanels.get(selectedIndex)); listModesPanel.setVisible(true); } else if (addListModeButton.equals(event.getSource())) { addListMode(); } else if (removeListModeButton.equals(event.getSource())) { removeListMode(); } else if (toggle.equals(event.getSource())) { IdentityManager.getChannelConfig(channel.getServer().getNetwork(), channel.toString()).setOption("general", "extendedListModes", !toggle.isSelected()); } } /** * {@inheritDoc} * * @param event List selection event */ @Override public void valueChanged(final ListSelectionEvent event) { if (!event.getValueIsAdjusting()) { final int selected = ((JList) event.getSource()).getSelectedIndex(); if (selected == -1) { removeListModeButton.setEnabled(false); } else { removeListModeButton.setEnabled(true); } } } /** Updates the mode count label. */ private void updateModeCount() { if (listModesPanels.isEmpty()) { modeCount.setText(null); return; } final int selected = listModesMenu.getSelectedIndex(); final int maxModes = channel.getServer().getParser(). getMaxListModes(listModesArray[selected]); if (maxModes == -1) { modeCount.setText("" + listModesPanels.get(selected).getModel(). getSize()); } else { modeCount.setText(listModesPanels.get(selected).getModel().getSize() + " of " + channel.getServer().getParser(). getMaxListModes(listModesArray[selected])); } } /** {@inheritDoc} */ @Override public void configChanged(final String domain, final String key) { if (channel.getConfigManager().getOptionBool("general", "extendedListModes", false)) { renderer = new ListModeCellRenderer(); } else { renderer = new ExtendedListModeCellRenderer(); } for (JList list : listModesPanels) { list.setCellRenderer(renderer); } } }
package com.dafrito.lua.script; import static org.junit.Assert.assertEquals; import lua.LuaLibrary; import lua.LuaLibrary.lua_State; import org.junit.Test; public class LuaTableTest { LuaLibrary lua = LuaLibrary.INSTANCE; @Test public void getAndPutAValueIntoATable() throws Exception { LuaScriptContext ctx = new LuaScriptContext(); LuaBindings b = ctx.getGlobals(); lua.lua_createtable(b.getState(), 0, 0); LuaTable t = new LuaTable(new LuaReference(b)); t.set(1, "No time"); assertEquals("No time", t.get(1)); } class LuaTable { private LuaBindings b; private LuaReference ref; private lua_State s; public LuaTable(LuaReference ref) { this.b = ref.getBindings(); this.ref = ref; this.s = b.getState(); } public Object get(Object k) { ref.get(); b.toLua(k); lua.lua_gettable(s, -2); Object v = b.fromLua(-1); lua.lua_settop(s, -2); return v; } public void set(Object k, Object v) { ref.get(); b.toLua(k); b.toLua(v); lua.lua_settable(s, -3); lua.lua_settop(s, -2); } } class LuaReference { private final LuaBindings b; private int ref; public LuaReference(LuaBindings b) { this.b = b; this.ref = lua.luaL_ref(b.getState(), LuaLibrary.LUA_REGISTRYINDEX); check(); } public LuaBindings getBindings() { return this.b; } public void get() { check(); lua.lua_rawgeti(b.getState(), LuaLibrary.LUA_REGISTRYINDEX, this.ref); } private void check() { if (this.isClosed()) { throw new RuntimeException(); } } public boolean isClosed() { return this.ref == LuaLibrary.LUA_REFNIL; } public void close() { if (this.isClosed()) { return; } lua.luaL_unref(b.getState(), LuaLibrary.LUA_REGISTRYINDEX, this.ref); this.ref = LuaLibrary.LUA_REFNIL; } } }
package eu.ydp.empiria.player.client.module.connection; import com.google.gwt.json.client.JSONArray; import com.google.inject.Inject; import com.google.inject.Provider; import eu.ydp.empiria.player.client.gin.factory.ConnectionModuleFactory; import eu.ydp.empiria.player.client.module.AbstractInteractionModule; import eu.ydp.empiria.player.client.module.ActivityPresenter; import eu.ydp.empiria.player.client.module.abstractmodule.structure.AbstractModuleStructure; import eu.ydp.empiria.player.client.module.connection.presenter.ConnectionModulePresenter; import eu.ydp.empiria.player.client.module.connection.structure.ConnectionModuleJAXBParser; import eu.ydp.empiria.player.client.module.connection.structure.ConnectionModuleStructure; import eu.ydp.empiria.player.client.module.connection.structure.MatchInteractionBean; public class ConnectionModule extends AbstractInteractionModule<ConnectionModule, ConnectionModuleModel, MatchInteractionBean> { @Inject private ConnectionModulePresenter presenter; @Inject private ConnectionModuleStructure connectionStructure; @Inject protected Provider<ConnectionModule> moduleFactory; @Inject private ConnectionModuleFactory connectionModuleFactory; private ConnectionModuleModel connectionModel; @Override protected void initalizeModule() { connectionModel = connectionModuleFactory.getConnectionModuleModel(getResponse(), this); connectionModel.setResponseSocket(getModuleSocket()); getResponse().setCountMode(getCountMode()); } @Override public ConnectionModule getNewInstance() { return moduleFactory.get(); } @Override protected ActivityPresenter<ConnectionModuleModel, MatchInteractionBean> getPresenter() { return presenter; } @Override protected ConnectionModuleModel getResponseModel() { return connectionModel; } @Override protected AbstractModuleStructure<MatchInteractionBean, ConnectionModuleJAXBParser> getStructure() { return connectionStructure; } @Override public void setState(JSONArray newState) { //TODO: Override and commented out for BETT //FIXME: Find out why connection is not correctly restoring it's state! } }
package eu.ydp.empiria.player.client.module.texteditor; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONString; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.xml.client.Element; import com.google.inject.Inject; import eu.ydp.empiria.player.client.module.*; import eu.ydp.empiria.player.client.module.texteditor.presenter.TextEditorPresenter; import eu.ydp.gwtutil.client.gin.scopes.module.ModuleScoped; public class TextEditorModule extends SimpleModuleBase implements IStateful, IUniqueModule, IActivity, ILifecycleModule { private final TextEditorPresenter presenter; @Inject public TextEditorModule(@ModuleScoped TextEditorPresenter presenter) { this.presenter = presenter; } @Override protected void initModule(Element element) { presenter.init(getModuleId()); } @Override public void lock(boolean lo) { presenter.lock(); } @Override public void reset() { } @Override public JSONArray getState() { JSONArray state = new JSONArray(); JSONString value = new JSONString(presenter.getContent()); state.set(0, value); return state; } @Override public void setState(JSONArray newState) { String value = newState.get(0).toString(); presenter.setContent(value); } @Override public void markAnswers(boolean mark) { lock(mark); } @Override public void showCorrectAnswers(boolean show) { lock(show); } @Override public String getIdentifier() { return "textEditorId"; } @Override public Widget getView() { return presenter.getView(); } @Override public void onBodyLoad() { presenter.convertEditor(); } @Override public void onBodyUnload() { } @Override public void onSetUp() { } @Override public void onStart() { } @Override public void onClose() { } }
package gov.nih.nci.cananolab.dto.particle.characterization; import gov.nih.nci.cananolab.domain.particle.characterization.physical.Surface; import gov.nih.nci.cananolab.domain.particle.characterization.physical.SurfaceChemistry; import gov.nih.nci.cananolab.util.CaNanoLabComparators; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SurfaceBean { private List<SurfaceChemistry> surfaceChemistryList = new ArrayList<SurfaceChemistry>(); private Surface domainSurface = new Surface(); public SurfaceBean() { } public SurfaceBean(Surface surface) { domainSurface = surface; for (SurfaceChemistry chem : surface.getSurfaceChemistryCollection()) { surfaceChemistryList.add(chem); } Collections.sort(surfaceChemistryList, new CaNanoLabComparators.SurfaceChemistryDateComparator()); } public Surface getDomainSurface() { return domainSurface; } public List<SurfaceChemistry> getSurfaceChemistryList() { return surfaceChemistryList; } public void addSurfaceChemistry() { surfaceChemistryList.add(new SurfaceChemistry()); } public void removeSurfaceChemistry(int ind) { surfaceChemistryList.remove(ind); } }
package org.rstudio.studio.client.common.reditor; /** * Models a language for CodeMirror. * * == HOW TO ADD A NEW LANGUAGE TO THE SOURCE EDITOR == * 1) Edit ./resources/colors.css, add all necessary CSS rules there * 2) Put your parser file in ./resources/ * 3) Add your parser to REditorResources, following the example of the other * parsers * 4) Add your parser to this class's ALL_PARSER_URLS * 5) In this class, add a static LANG_xyz field for your language * 6) In this class, edit the static getLanguageForExtension to return your * EditorLanguage for any applicable extensions */ public class EditorLanguage { // RStudio-maintained or extended modes public static final EditorLanguage LANG_R = new EditorLanguage( "mode/r", true); public static final EditorLanguage LANG_RDOC = new EditorLanguage( "mode/rdoc", false); public static final EditorLanguage LANG_TEX = new EditorLanguage( "mode/tex", false); public static final EditorLanguage LANG_SWEAVE = new EditorLanguage( "mode/sweave", true); public static final EditorLanguage LANG_RMARKDOWN = new EditorLanguage( "mode/rmarkdown", true); public static final EditorLanguage LANG_DCF = new EditorLanguage( "mode/dcf", false); public static final EditorLanguage LANG_RHTML = new EditorLanguage( "mode/rhtml", true); public static final EditorLanguage LANG_CPP = new EditorLanguage( "mode/c_cpp", true); // Modes borrowed from Ace public static final EditorLanguage LANG_PLAIN = new EditorLanguage( "ace/mode/text", false); public static final EditorLanguage LANG_MARKDOWN = new EditorLanguage( "ace/mode/markdown", false); public static final EditorLanguage LANG_HTML = new EditorLanguage( "ace/mode/html", false); public static final EditorLanguage LANG_CSS = new EditorLanguage( "ace/mode/css", true); public static final EditorLanguage LANG_JAVASCRIPT = new EditorLanguage( "ace/mode/javascript", true); public static final EditorLanguage LANG_PYTHON = new EditorLanguage( "ace/mode/python", true); public static final EditorLanguage LANG_SQL = new EditorLanguage( "ace/mode/sql", true); public static final EditorLanguage LANG_SH = new EditorLanguage( "ace/mode/sh", true); public static final EditorLanguage LANG_YAML = new EditorLanguage( "ace/mode/yaml", true); public static final EditorLanguage LANG_XML = new EditorLanguage( "ace/mode/xml", true); public static final EditorLanguage LANG_GROOVY = new EditorLanguage( "ace/mode/groovy", true); /** * * @param parserName The name of the parser--it's found at the top of the * parser .js file * e. This MUST match the value inside the .js file or else * dynamic language switching (Save As... with a different extension) * won't work. * @param useRCompletion If true, then Tab is intercepted for completion */ public EditorLanguage( String parserName, boolean useRCompletion) { parserName_ = parserName; useRCompletion_ = useRCompletion; } public String getParserName() { return parserName_; } public boolean useRCompletion() { return useRCompletion_; } private final String parserName_; private final boolean useRCompletion_; }
package org.rstudio.studio.client.workbench.views.source; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.events.*; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.js.JsObject; import org.rstudio.core.client.widget.Operation; import org.rstudio.core.client.widget.ProgressIndicator; import org.rstudio.core.client.widget.ProgressOperationWithInput; import org.rstudio.core.client.widget.Widgetable; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.FileDialogs; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.common.SimpleRequestCallback; import org.rstudio.studio.client.common.filetypes.EditableFileType; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileEvent; import org.rstudio.studio.client.common.filetypes.events.OpenSourceFileHandler; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.workbench.MRUList; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.RemoteFileSystemContext; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.helper.IntStateValue; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.views.data.events.ViewDataEvent; import org.rstudio.studio.client.workbench.views.data.events.ViewDataHandler; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource; import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FileTypeChangedHandler; import org.rstudio.studio.client.workbench.views.source.events.*; import org.rstudio.studio.client.workbench.views.source.model.ContentItem; import org.rstudio.studio.client.workbench.views.source.model.DataItem; import org.rstudio.studio.client.workbench.views.source.model.SourceDocument; import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations; import java.util.ArrayList; import java.util.HashSet; public class Source implements InsertSourceHandler, Widgetable, OpenSourceFileHandler, TabClosingHandler, SelectionHandler<Integer>, TabClosedHandler, FileEditHandler, ShowContentHandler, ShowDataHandler, BeforeShowHandler { public interface Display extends Widgetable, HasTabClosingHandlers, HasTabClosedHandlers, HasBeforeSelectionHandlers<Integer>, HasSelectionHandlers<Integer> { void addTab(Widget widget, ImageResource icon, String name, String tooltip, boolean switchToTab); void selectTab(int tabIndex); void selectTab(Widget widget); int getTabCount(); int getActiveTabIndex(); void closeTab(Widget widget, boolean interactive); void closeTab(int index, boolean interactive); void setDirty(Widget widget, boolean dirty); void manageChevronVisibility(); void showOverflowPopup(); void ensureVisible(); void renameTab(Widget child, ImageResource icon, String value, String tooltip); HandlerRegistration addBeforeShowHandler(BeforeShowHandler handler); } @Inject public Source(Commands commands, Display view, SourceServerOperations server, EditingTargetSource editingTargetSource, FileTypeRegistry fileTypeRegistry, GlobalDisplay globalDisplay, FileDialogs fileDialogs, RemoteFileSystemContext fileContext, EventBus events, Session session, WorkbenchContext workbenchContext, MRUList mruList, UIPrefs uiPrefs) { commands_ = commands; view_ = view; server_ = server; editingTargetSource_ = editingTargetSource; fileTypeRegistry_ = fileTypeRegistry; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileContext_ = fileContext; events_ = events; workbenchContext_ = workbenchContext; mruList_ = mruList; uiPrefs_ = uiPrefs; view_.addTabClosingHandler(this); view_.addTabClosedHandler(this); view_.addSelectionHandler(this); view_.addBeforeShowHandler(this); dynamicCommands_ = new HashSet<AppCommand>(); dynamicCommands_.add(commands.saveSourceDoc()); dynamicCommands_.add(commands.reopenSourceDocWithEncoding()); dynamicCommands_.add(commands.saveSourceDocAs()); dynamicCommands_.add(commands.saveSourceDocWithEncoding()); dynamicCommands_.add(commands.printSourceDoc()); dynamicCommands_.add(commands.executeCode()); dynamicCommands_.add(commands.executeAllCode()); dynamicCommands_.add(commands.executeToCurrentLine()); dynamicCommands_.add(commands.executeFromCurrentLine()); dynamicCommands_.add(commands.executeCurrentFunction()); dynamicCommands_.add(commands.sourceActiveDocument()); dynamicCommands_.add(commands.compilePDF()); dynamicCommands_.add(commands.publishPDF()); dynamicCommands_.add(commands.popoutDoc()); dynamicCommands_.add(commands.findReplace()); dynamicCommands_.add(commands.extractFunction()); dynamicCommands_.add(commands.commentUncomment()); dynamicCommands_.add(commands.jumpToFunction()); dynamicCommands_.add(commands.setWorkingDirToActiveDoc()); for (AppCommand command : dynamicCommands_) { command.setVisible(false); command.setEnabled(false); } // allow Ctrl+W to propagate to the browser if close doc is disabled if (!Desktop.isDesktop()) { AppCommand closeSourceDoc = commands_.closeSourceDoc(); closeSourceDoc.setPreventShortcutWhenDisabled(false); } events.addHandler(ShowContentEvent.TYPE, this); events.addHandler(ShowDataEvent.TYPE, this); events.addHandler(ViewDataEvent.TYPE, new ViewDataHandler() { public void onViewData(ViewDataEvent event) { server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), JsObject.createJsObject(), new SimpleRequestCallback<SourceDocument>("Edit Data Frame") { public void onResponseReceived(SourceDocument response) { addTab(response); } }); } }); events.addHandler(FileTypeChangedEvent.TYPE, new FileTypeChangedHandler() { public void onFileTypeChanged(FileTypeChangedEvent event) { manageCommands(); } }); events.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler() { public void onSwitchToDoc(SwitchToDocEvent event) { ensureVisible(false); view_.selectTab(event.getSelectedIndex()); } }); events.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler() { public void onSourceFileSaved(SourceFileSavedEvent event) { mruList_.add(event.getPath()); } }); restoreDocuments(session); new IntStateValue(MODULE_SOURCE, KEY_ACTIVETAB, true, session.getSessionInfo().getClientState()) { @Override protected void onInit(Integer value) { if (value == null) return; if (value >= 0 && view_.getTabCount() > value) view_.selectTab(value); if (view_.getTabCount() > 0 && view_.getActiveTabIndex() >= 0) { editors_.get(view_.getActiveTabIndex()).onInitiallyLoaded(); } } @Override protected Integer getValue() { return view_.getActiveTabIndex(); } }; initialized_ = true; // As tabs were added before, manageCommands() was suppressed due to // initialized_ being false, so we need to run it explicitly manageCommands(); // Same with this event fireDocTabsChanged(); } /** * @param isNewTabPending True if a new tab is about to be created. (If * false and there are no tabs already, then a new source doc might * be created to make sure we don't end up with a source pane showing * with no tabs in it.) */ private void ensureVisible(boolean isNewTabPending) { newTabPending_++; try { view_.ensureVisible(); } finally { newTabPending_ } } public Widget toWidget() { return view_.toWidget(); } private void restoreDocuments(final Session session) { final JsArray<SourceDocument> docs = session.getSessionInfo().getSourceDocuments(); for (int i = 0; i < docs.length(); i++) { addTab(docs.get(i)); } } public void onShowContent(ShowContentEvent event) { ensureVisible(true); ContentItem content = event.getContent(); server_.newDocument( FileTypeRegistry.URLCONTENT.getTypeId(), (JsObject) content.cast(), new SimpleRequestCallback<SourceDocument>("Show") { @Override public void onResponseReceived(SourceDocument response) { addTab(response); } }); } public void onShowData(ShowDataEvent event) { ensureVisible(true); DataItem data = event.getData(); for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(data.getURI())) { ((DataEditingTarget)editors_.get(i)).updateData(data); view_.selectTab(i); return; } } server_.newDocument( FileTypeRegistry.DATAFRAME.getTypeId(), (JsObject) data.cast(), new SimpleRequestCallback<SourceDocument>("Show Data Frame") { @Override public void onResponseReceived(SourceDocument response) { addTab(response); } }); } @Handler public void onNewSourceDoc() { newDoc(FileTypeRegistry.R, null); } private void newDoc(EditableFileType fileType, final CommandWithArg<EditingTarget> executeOnSuccess) { ensureVisible(true); server_.newDocument( fileType.getTypeId(), JsObject.createJsObject(), new SimpleRequestCallback<SourceDocument>( "Error Creating New Document") { @Override public void onResponseReceived(SourceDocument newDoc) { EditingTarget target = addTab(newDoc); if (executeOnSuccess != null) executeOnSuccess.execute(target); } }); } @Handler public void onActivateSource() { ensureVisible(false); if (activeEditor_ != null) activeEditor_.focus(); } @Handler public void onSwitchToTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); view_.showOverflowPopup(); } @Handler public void onFirstTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); if (view_.getTabCount() > 0) view_.selectTab(0); } @Handler public void onPreviousTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); int index = view_.getActiveTabIndex(); if (index >= 1) view_.selectTab(index - 1); } @Handler public void onNextTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); int index = view_.getActiveTabIndex(); if (index < view_.getTabCount() - 1) view_.selectTab(index + 1); } @Handler public void onLastTab() { if (view_.getTabCount() == 0) return; ensureVisible(false); if (view_.getTabCount() > 0) view_.selectTab(view_.getTabCount() - 1); } @Handler public void onCloseSourceDoc() { if (view_.getTabCount() == 0) return; view_.closeTab(view_.getActiveTabIndex(), true); } @Handler public void onCloseAllSourceDocs() { } @Handler public void onOpenSourceDoc() { fileDialogs_.openFile( "Open File", fileContext_, workbenchContext_.getDefaultFileDialogDir(), new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem input, ProgressIndicator indicator) { if (input == null) return; workbenchContext_.setDefaultFileDialogDir( input.getParentPath()); indicator.onCompleted(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { fileTypeRegistry_.openFile(input); } }); } }); } public void onOpenSourceFile(final OpenSourceFileEvent event) { final CommandWithArg<FileSystemItem> action = new CommandWithArg<FileSystemItem>() { @Override public void execute(FileSystemItem file) { openFile(file, event.getFileType()); } }; // Warning: event.getFile() can be null (e.g. new Sweave document) if (event.getFile() != null && event.getFile().getLength() < 0) { // If the file has no size info, stat the file from the server. This // is to prevent us from opening large files accidentally. server_.stat(event.getFile().getPath(), new ServerRequestCallback<FileSystemItem>() { @Override public void onResponseReceived(FileSystemItem response) { action.execute(response); } @Override public void onError(ServerError error) { // Couldn't stat the file? Proceed anyway. If the file doesn't // exist, we'll let the downstream code be the one to show the // error. action.execute(event.getFile()); } }); } else { action.execute(event.getFile()); } } // top-level wrapper for opening files. takes care of: // - making sure the view is visible // - checking whether it is already open and re-selecting its tab // - prohibit opening very large files (>500KB) // - confirmation of opening large files (>100KB) // - finally, actually opening the file from the server // via the call to the lower level openFile method private void openFile(final FileSystemItem file, final TextFileType fileType) { ensureVisible(true); if (file == null) { newDoc(fileType, null); return; } for (int i = 0; i < editors_.size(); i++) { EditingTarget target = editors_.get(i); String thisPath = target.getPath(); if (thisPath != null && thisPath.equalsIgnoreCase(file.getPath())) { view_.selectTab(i); mruList_.add(thisPath); return; } } EditingTarget target = editingTargetSource_.getEditingTarget(fileType); if (file.getLength() > target.getFileSizeLimit()) { showFileTooLargeWarning(file, target.getFileSizeLimit()); } else if (file.getLength() > target.getLargeFileSize()) { confirmOpenLargeFile(file, new Operation() { public void execute() { openFileFromServer(file, fileType); } }); } else { openFileFromServer(file, fileType); } } private void showFileTooLargeWarning(FileSystemItem file, long sizeLimit) { StringBuilder msg = new StringBuilder(); msg.append("The file '" + file.getName() + "' is too "); msg.append("large to open in the source editor (the file is "); msg.append(StringUtil.formatFileSize(file.getLength()) + " and the "); msg.append("maximum file size is "); msg.append(StringUtil.formatFileSize(sizeLimit) + ")"); globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING, "Selected File Too Large", msg.toString()); } private void confirmOpenLargeFile(FileSystemItem file, Operation openOperation) { StringBuilder msg = new StringBuilder(); msg.append("The source file '" + file.getName() + "' is large ("); msg.append(StringUtil.formatFileSize(file.getLength()) + ") "); msg.append("and may take some time to open. "); msg.append("Are you sure you want to continue opening it?"); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Confirm Open", msg.toString(), openOperation, false); // 'No' is default } private void openFileFromServer(final FileSystemItem file, final TextFileType fileType) { final Command dismissProgress = globalDisplay_.showProgress( "Opening file..."); server_.openDocument( file.getPath(), fileType.getTypeId(), uiPrefs_.defaultEncoding().getValue(), new ServerRequestCallback<SourceDocument>() { @Override public void onError(ServerError error) { dismissProgress.execute(); Debug.logError(error); globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR, "Error while opening file", error.getUserMessage()); } @Override public void onResponseReceived(SourceDocument document) { dismissProgress.execute(); mruList_.add(document.getPath()); addTab(document); } }); } private EditingTarget addTab(SourceDocument doc) { final EditingTarget target = editingTargetSource_.getEditingTarget( doc, fileContext_, new Provider<String>() { public String get() { return getNextDefaultName(); } }); final Widget widget = target.toWidget(); editors_.add(target); view_.addTab(widget, target.getIcon(), target.getName().getValue(), target.getTabTooltip(), // used as tooltip, if non-null true); fireDocTabsChanged(); target.getName().addValueChangeHandler(new ValueChangeHandler<String>() { public void onValueChange(ValueChangeEvent<String> event) { view_.renameTab(widget, target.getIcon(), event.getValue(), target.getPath()); fireDocTabsChanged(); } }); view_.setDirty(widget, target.dirtyState().getValue()); target.dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { view_.setDirty(widget, event.getValue()); } }); target.addEnsureVisibleHandler(new EnsureVisibleHandler() { public void onEnsureVisible(EnsureVisibleEvent event) { view_.selectTab(widget); } }); target.addCloseHandler(new CloseHandler<Void>() { public void onClose(CloseEvent<Void> voidCloseEvent) { view_.closeTab(widget, false); } }); return target; } private String getNextDefaultName() { int max = 0; for (EditingTarget target : editors_) { String name = target.getName().getValue(); max = Math.max(max, getUntitledNum(name)); } return "Untitled" + (max + 1); } private native final int getUntitledNum(String name) /*-{ var match = /^Untitled([0-9]{1,5})$/.exec(name); if (!match) return 0; return parseInt(match[1]); }-*/; public void onInsertSource(final InsertSourceEvent event) { if (activeEditor_ != null && activeEditor_ instanceof TextEditingTarget && commands_.executeCode().isEnabled()) { TextEditingTarget textEditor = (TextEditingTarget) activeEditor_; textEditor.insertCode(event.getCode(), event.isBlock()); } else { newDoc(FileTypeRegistry.R, new CommandWithArg<EditingTarget>() { public void execute(EditingTarget arg) { ((TextEditingTarget)arg).insertCode(event.getCode(), event.isBlock()); } }); } } public void onTabClosing(final TabClosingEvent event) { EditingTarget target = editors_.get(event.getTabIndex()); if (!target.onBeforeDismiss()) event.cancel(); } public void onTabClosed(TabClosedEvent event) { EditingTarget target = editors_.remove(event.getTabIndex()); target.onDismiss(); if (activeEditor_ == target) { activeEditor_.onDeactivate(); activeEditor_ = null; } server_.closeDocument(target.getId(), new VoidServerRequestCallback()); manageCommands(); fireDocTabsChanged(); if (view_.getTabCount() == 0) { events_.fireEvent(new LastSourceDocClosedEvent()); } } private void fireDocTabsChanged() { if (!initialized_) return; String[] ids = new String[editors_.size()]; ImageResource[] icons = new ImageResource[editors_.size()]; String[] names = new String[editors_.size()]; String[] paths = new String[editors_.size()]; for (int i = 0; i < ids.length; i++) { EditingTarget target = editors_.get(i); ids[i] = target.getId(); icons[i] = target.getIcon(); names[i] = target.getName().getValue(); paths[i] = target.getPath(); } events_.fireEvent(new DocTabsChangedEvent(ids, icons, names, paths)); view_.manageChevronVisibility(); } public void onSelection(SelectionEvent<Integer> event) { if (activeEditor_ != null) activeEditor_.onDeactivate(); activeEditor_ = null; if (event.getSelectedItem() >= 0) { activeEditor_ = editors_.get(event.getSelectedItem()); activeEditor_.onActivate(); if (initialized_) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { activeEditor_.focus(); } }); } } if (initialized_) manageCommands(); } private void manageCommands() { boolean hasDocs = editors_.size() > 0; commands_.closeSourceDoc().setEnabled(hasDocs); commands_.nextTab().setEnabled(hasDocs); commands_.previousTab().setEnabled(hasDocs); commands_.firstTab().setEnabled(hasDocs); commands_.lastTab().setEnabled(hasDocs); commands_.switchToTab().setEnabled(hasDocs); commands_.activateSource().setEnabled(hasDocs); commands_.setWorkingDirToActiveDoc().setEnabled(hasDocs); HashSet<AppCommand> newCommands = activeEditor_ != null ? activeEditor_.getSupportedCommands() : new HashSet<AppCommand>(); HashSet<AppCommand> commandsToEnable = new HashSet<AppCommand>(newCommands); commandsToEnable.removeAll(activeCommands_); HashSet<AppCommand> commandsToDisable = new HashSet<AppCommand>(activeCommands_); commandsToDisable.removeAll(newCommands); for (AppCommand command : commandsToEnable) { command.setEnabled(true); command.setVisible(true); } for (AppCommand command : commandsToDisable) { command.setEnabled(false); command.setVisible(false); } // Save/Save As should always stay visible commands_.saveSourceDoc().setVisible(true); commands_.saveSourceDocAs().setVisible(true); commands_.setWorkingDirToActiveDoc().setVisible(true); activeCommands_ = newCommands; assert verifyNoUnsupportedCommands(newCommands) : "Unsupported commands detected (please add to Source.dynamicCommands_)"; } private boolean verifyNoUnsupportedCommands(HashSet<AppCommand> commands) { HashSet<AppCommand> temp = new HashSet<AppCommand>(commands); temp.removeAll(dynamicCommands_); return temp.size() == 0; } public void onFileEdit(FileEditEvent event) { fileTypeRegistry_.editFile(event.getFile()); } public void onBeforeShow(BeforeShowEvent event) { if (view_.getTabCount() == 0 && newTabPending_ == 0) { // Avoid scenarios where the Source tab comes up but no tabs are // in it. (But also avoid creating an extra source tab when there // were already new tabs about to be created!) onNewSourceDoc(); } } ArrayList<EditingTarget> editors_ = new ArrayList<EditingTarget>(); private EditingTarget activeEditor_; private final Commands commands_; private final Display view_; private final SourceServerOperations server_; private final EditingTargetSource editingTargetSource_; private final FileTypeRegistry fileTypeRegistry_; private final GlobalDisplay globalDisplay_; private final WorkbenchContext workbenchContext_; private final FileDialogs fileDialogs_; private final RemoteFileSystemContext fileContext_; private final EventBus events_; private final MRUList mruList_; private final UIPrefs uiPrefs_; private HashSet<AppCommand> activeCommands_ = new HashSet<AppCommand>(); private final HashSet<AppCommand> dynamicCommands_; private static final String MODULE_SOURCE = "source"; private static final String KEY_ACTIVETAB = "activeTab"; private boolean initialized_; // If positive, a new tab is about to be created private int newTabPending_; }
package rover; import java.util.Random; public class TemplateRover extends Rover { public TemplateRover() { super(); //use your username for team name setTeam("template"); try { //set attributes for this rover //speed, scan range, max load //has to add up to <= 9 //Fourth attribute is the collector type setAttributes(4, 4, 1, 1); } catch (Exception e) { e.printStackTrace(); } } @Override void begin() { //called when the world is started getLog().info("BEGIN!"); try { //move somewhere initially move(5,5,2); } catch (Exception e) { e.printStackTrace(); } } @Override void end() { // called when the world is stopped // the agent is killed after this getLog().info("END!"); } @Override void poll(PollResult pr) { // This is called when one of the actions has completed getLog().info("Remaining Power: " + getEnergy()); if(pr.getResultStatus() == PollResult.FAILED) { getLog().info("Ran out of power..."); return; } switch(pr.getResultType()) { case PollResult.MOVE: //move finished getLog().info("Move complete."); //now scan try { getLog().info("Scanning..."); scan(4); } catch (Exception e) { e.printStackTrace(); } break; case PollResult.SCAN: getLog().info("Scan complete"); for(ScanItem item : pr.getScanItems()) { if(item.getItemType() == ScanItem.RESOURCE) { getLog().info("Resource found at: " + item.getxOffset() + ", " + item.getyOffset() + " Type: "+item.getResourceType()); if (item.getxOffset() < 0.1 && item.getyOffset() < 0.1) { try { getLog().info("Attempting a collect!"); collect(); } catch (Exception e) { e.printStackTrace(); } break; } else { try { getLog().info("Moving to resource."); move(item.getxOffset(), item.getyOffset(), 4); } catch (Exception e) { e.printStackTrace(); } break; } } else if(item.getItemType() == ScanItem.BASE) { getLog().info("Base found at: " + item.getxOffset() + ", " + item.getyOffset()); } else { getLog().info("Rover found at: " + item.getxOffset() + ", " + item.getyOffset()); } } // now move again Random rand = new Random(); try { getLog().info("Moving..."); move(5 * rand.nextDouble(), 5 * rand.nextDouble(), 4); } catch (Exception e) { e.printStackTrace(); } break; case PollResult.COLLECT: getLog().info("Collect complete."); try { getLog().info("Moving..."); move(1,1,4); } catch (Exception e) { e.printStackTrace(); } break; case PollResult.DEPOSIT: getLog().info("Deposit complete."); break; } } }
package com.exedio.cope; /** * Signals, that an attempt to find an item by it's ID has been failed, * because there is no item with such an ID. * * This exception will be thrown by {@link Model#findByID(String) Model.findByID}, * if there is no item with the given ID. * * @author Ralf Wiebicke */ public final class NoSuchIDException extends Exception { private final String id; private final boolean notAnID; private final String detail; NoSuchIDException(final String id, final boolean notAnID, final String detail) { super("no such id <"+id+">, "+detail); this.id = id; this.notAnID = notAnID; this.detail = detail; } NoSuchIDException(final String id, final NumberFormatException cause, final String numberString) { this(id, true, "wrong number format <"+numberString+">"); } public String getMessage() { return "no such id <" + id + ">, " + detail; } /** * Returns, whether the id is invalid on principle * within the currently deployed model, * this means, the will never be and has never been an * item for this id. */ public boolean notAnID() { return notAnID; } }
package de.codescape.bitvunit.rule.page; import com.gargoylesoftware.htmlunit.html.HtmlHtml; import de.codescape.bitvunit.model.Page; import de.codescape.bitvunit.rule.AbstractRule; import de.codescape.bitvunit.rule.Violations; import static de.codescape.bitvunit.util.html.HtmlElementUtil.hasNonEmptyAttribute; /** * LanguageForHtmlTagRule ensures that the given HTML document provides it's language information through the * <code>lang</code> attribute on the <code>&lt;html/&gt;</code> tag. * <p/> * A valid example of a document in German language would look like this: * <pre><code>&lt;html lang="de"&gt;...&lt;/html&gt;</code></pre> * * @author Stefan Glase * @since 0.2 */ public class LanguageForHtmlTagRule extends AbstractRule { private static final String RULE_NAME = "LanguageForHtmlTag"; private static final String RULE_MESSAGE = "Every <html /> tag should communicate the main language of that page with it's lang attribute."; private static final String LANG_ATTRIBUTE = "lang"; @Override public String getName() { return RULE_NAME; } @Override protected void applyTo(Page page, Violations violations) { for (HtmlHtml html : page.findAllHtmlTags()) { if (!hasNonEmptyAttribute(html, LANG_ATTRIBUTE)) { violations.add(createViolation(html, RULE_MESSAGE)); } } } }
public abstract class Command implements Cloneable, Comparable<Command>, ActionInterface { private String commandName; private String description; private String parameters; public Command() { // TODO what should the default be? this.commandName = "none"; this.description = "A none command"; this.parameters = ""; } public Command(String commandName, String description) { this.commandName = commandName; this.description = description; this.parameters = ""; } /** * Execute the command */ @Override public abstract void execute(); /** * Perform a shallow clone */ @Override public Object clone() { // Try cloning try { return super.clone(); } catch(CloneNotSupportedException cnse) { throw new RuntimeException("The command could not be cloned"); } } /** * Compares the command names of the commands. Usually used when the command is help * so that all available commands are printed in order */ @Override public int compareTo(Command other) { if(other == null) { throw new IllegalArgumentException("The command that you provided is null"); } // Order the commands in alphabetical order return this.commandName.compareToIgnoreCase(other.commandName); } /** * Compares the command name * @param text * @return */ public boolean equals(String text) { return this.commandName.equalsIgnoreCase(text); } /** * Check if the command objects are the same */ @Override public boolean equals(Object other) { // TODO is this right if(this == other) { return true; } if(other == null || (this.getClass() != other.getClass())) { return false; } // Cast and create a command object Command object = (Command) other; // Check if the instance variables do not match if(!this.commandName.equals(object.getCommandName())) { return false; } if(!this.description.equals(object.getDescription())) { return false; } if(!this.parameters.equals(object.getParameters())) { return false; } return true; } /** * Return the command name * @return */ public String getCommandName() { return this.commandName; } /** * Return the description * @return */ public String getDescription() { return this.description; } /** * Return the parameters * @return */ public String getParameters() { return this.parameters; } /** * Return an array of string with the parameters of the command * @param delimiters * @return */ public String[] getParameters(String delimiters) { if(delimiters == null) { throw new IllegalArgumentException("The delimiters that you provided are null"); } if(delimiters.isEmpty()) { throw new IllegalArgumentException("You did not provided any delimiters"); } // Split the string based on the delimiters return this.parameters.split(delimiters); } /** * Return the hash code of the object */ @Override public int hashCode() { // TODO correct? or this.toString.hashCode? String variables = this.commandName + this.description + this.parameters; return variables.hashCode(); } /** * Return if there are parameters * @return */ public boolean hasParameters() { return !this.parameters.isEmpty(); } /** * Print the message without a new line * @param message */ public void print(String message) { System.out.print(message); } /** * Print a new line * @param message */ public void println() { this.println(""); } /** * Print a message with a new line * @param message */ public void println(String message) { this.print(message + "\n"); } /** * Setting the parameters * @param parameters */ public void setParameters(String parameters) { if(parameters == null) { throw new IllegalArgumentException("The parameters that you provided are null"); } this.parameters = parameters; } /** * Print the variables from the command */ @Override public String toString() { return "Command name: " + this.commandName + " description: " + this.description + " parameters: " + this.parameters; } }
package de.tudresden.inf.lat.born.gui.processor; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Objects; import javax.swing.JFileChooser; import org.semanticweb.owlapi.model.OWLOntologyManager; import de.tudresden.inf.lat.born.gui.common.TextViewer; import de.tudresden.inf.lat.born.owlapi.example.ExampleConfiguration; import de.tudresden.inf.lat.born.owlapi.example.ExampleLoader; import de.tudresden.inf.lat.born.owlapi.processor.ProblogInputCreator; import de.tudresden.inf.lat.born.owlapi.processor.ProcessorConfiguration; import de.tudresden.inf.lat.born.owlapi.processor.ProcessorConfigurationImpl; import de.tudresden.inf.lat.born.owlapi.processor.ProcessorCore; import de.tudresden.inf.lat.born.owlapi.processor.ProcessorExecutionResult; import de.tudresden.inf.lat.born.owlapi.processor.ProcessorExecutionResultImpl; import de.tudresden.inf.lat.born.problog.type.ProblogProgram; /** * This class is a controller for the main panel. * * @author Julian Mendez */ public class ProcessorController implements ActionListener { /** * This class lets the processor run in a separate thread. * * @author Julian Mendez * */ class ProcessorRunner extends Thread { public void run() { long start = System.nanoTime(); ProcessorCore core = new ProcessorCore(); ProcessorExecutionResult executionResult = new ProcessorExecutionResultImpl(); core.run(getModel(), start, executionResult); String resultText = executionResult.getResult(); ProblogInputCreator problogInputCreator = new ProblogInputCreator(); String result = problogInputCreator.replaceByPrefixes(getModel().getOntology(), resultText); getView().setResult(result); getView().setComputing(false); getView().setButtonsEnabled(true); } } private static final String actionInputOntology = "open ontology file"; private static final String actionViewOntology = "view ontology file"; private static final String actionBayesianNetwork = "Bayesian network file"; private static final String actionViewBayesianNetwork = "view Bayesian network file"; private static final String actionResetCompletionRules = "reset completion rules"; private static final String actionGoToPreviousCompletionRules = "go to previous completion rules"; private static final String actionConsoleInput = "read console"; private static final String actionConsoleOutput = "console output"; private static final String actionComputeInference = "compute inference"; private static final String actionComboBoxExample = "choose example"; private final OWLOntologyManager owlOntologyManager; private final ProcessorView view; private ProcessorRunner processorRunner; private final ExampleLoader exampleLoader = new ExampleLoader(); private String lastUsedCompletionRules = ""; private String previousToLastUsedCompletionRules = ""; private File lastPath = null; /** * Constructs a new controller. * * @param view * panel to be controlled * @param ontologyManager * an OWL ontology manager */ public ProcessorController(ProcessorView view, OWLOntologyManager ontologyManager) { Objects.requireNonNull(view); Objects.requireNonNull(ontologyManager); this.view = view; this.owlOntologyManager = ontologyManager; init(); } @Override public void actionPerformed(ActionEvent e) { Objects.requireNonNull(e); String cmd = e.getActionCommand(); if (cmd.equals(actionInputOntology)) { executeActionInputOntology(); } else if (cmd.equals(actionViewOntology)) { executeActionViewOntology(); } else if (cmd.equals(actionBayesianNetwork)) { executeActionBayesianNetwork(); } else if (cmd.equals(actionViewBayesianNetwork)) { executeActionViewBayesianNetwork(); } else if (cmd.equals(actionResetCompletionRules)) { executeActionResetCompletionRules(); } else if (cmd.equals(actionGoToPreviousCompletionRules)) { executeActionGoToPreviousCompletionRules(); } else if (cmd.equals(actionConsoleInput)) { executeActionConsoleInput(); } else if (cmd.equals(actionConsoleOutput)) { executeActionConsoleOutput(); } else if (cmd.equals(actionComputeInference)) { executeActionComputeInference(); } else if (cmd.equals(actionComboBoxExample)) { executeActionComboBoxExample(); } else { throw new IllegalStateException(); } } void executeActionInputOntology() { JFileChooser fileChooser = new JFileChooser(this.lastPath); int returnVal = fileChooser.showOpenDialog(getView().getPanel()); File file = null; if (returnVal == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } if (Objects.nonNull(file)) { getView().setOntologyFile(file.getAbsolutePath()); getView().updateOntologyFile(); this.lastPath = file.getParentFile(); } } void executeActionViewOntology() { String text = ""; try { text = ProcessorConfigurationImpl.read(new FileReader(getView().getOntologyFile())); } catch (IOException e) { text = e.getMessage(); } TextViewer panel = new TextViewer(); panel.setBounds(new Rectangle(0, 0, 800, 600)); panel.setVisible(true); panel.getView().setModel(text); } void executeActionBayesianNetwork() { JFileChooser fileChooser = new JFileChooser(this.lastPath); int returnVal = fileChooser.showOpenDialog(getView().getPanel()); File file = null; if (returnVal == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } if (Objects.nonNull(file)) { getView().setBayesianNetworkFile(file.getAbsolutePath()); getView().updateBayesianNetworkFile(); this.lastPath = file.getParentFile(); } } void executeActionViewBayesianNetwork() { String text = ""; try { text = ProcessorConfigurationImpl.read(new FileReader(getView().getBayesianNetworkFile())); } catch (IOException e) { text = e.getMessage(); } TextViewer panel = new TextViewer(); panel.setBounds(new Rectangle(0, 0, 800, 600)); panel.setVisible(true); panel.getView().setModel(text); } void executeActionResetCompletionRules() { String defaultCompletionRules = (new ProblogProgram()) .asStringWithTabs((new ProblogInputCreator()).getDefaultCompletionRules()); getView().setCompletionRules(defaultCompletionRules); updatePreviousToLastUsedCompletionRules(defaultCompletionRules); updatePreviousToLastUsedCompletionRules(defaultCompletionRules); } void executeActionGoToPreviousCompletionRules() { this.lastUsedCompletionRules = this.previousToLastUsedCompletionRules; getView().setCompletionRules(this.previousToLastUsedCompletionRules); } void executeActionConsoleInput() { JFileChooser fileChooser = new JFileChooser(this.lastPath); int returnVal = fileChooser.showOpenDialog(getView().getPanel()); File file = null; if (returnVal == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } if (Objects.nonNull(file)) { getView().readConsoleInput(file.getAbsolutePath()); this.lastPath = file.getParentFile(); } } void executeActionConsoleOutput() { JFileChooser fileChooser = new JFileChooser(this.lastPath); int returnVal = fileChooser.showSaveDialog(getView().getPanel()); File file = null; if (returnVal == JFileChooser.APPROVE_OPTION) { file = fileChooser.getSelectedFile(); } if (Objects.nonNull(file)) { getView().writeConsoleOutput(file.getAbsolutePath()); this.lastPath = file.getParentFile(); } } void executeActionComputeInference() { getView().setButtonsEnabled(false); getView().setComputing(true); getView().updateQuery(); getView().updateCompletionRules(); updatePreviousToLastUsedCompletionRules(getModel().getAdditionalCompletionRules()); this.processorRunner = new ProcessorRunner(); this.processorRunner.start(); } void executeActionComboBoxExample() { int index = getView().getComboBoxExampleIndex(); ExampleConfiguration exampleConfiguration = this.exampleLoader.getExampleConfigurations().get(index); getView().setOntologyFile(exampleConfiguration.getOntologyFileName()); getModel().setOntology(exampleConfiguration.getOntology()); getView().setBayesianNetworkFile(exampleConfiguration.getBayesianNetworkFileName()); getModel().setBayesianNetwork(exampleConfiguration.getBayesianNetwork()); getView().setConsoleInput(exampleConfiguration.getQuery()); getModel().setQuery(exampleConfiguration.getQuery()); getView().setConsoleOutput(""); } /** * Returns the model. * * @return the model */ public ProcessorConfiguration getModel() { return getView().getModel(); } /** * Returns the OWL ontology manager. * * @return the OWL ontology manager */ public OWLOntologyManager getOWLOntologyManager() { return this.owlOntologyManager; } /** * Returns the view. * * @return the view */ public ProcessorView getView() { return this.view; } /** * Initializes the data and GUI. This method is called when the view is * initialized. */ void init() { getModel().setUseOfDefaultCompletionRules(false); getView().addButtonOntologyFileListener(this, actionInputOntology); getView().addButtonViewOntologyListener(this, actionViewOntology); getView().addButtonBayesianNetworkFileListener(this, actionBayesianNetwork); getView().addButtonViewBayesianNetworkListener(this, actionViewBayesianNetwork); getView().addButtonResetCompletionRulesListener(this, actionResetCompletionRules); getView().addButtonGoToPreviousCompletionRulesListener(this, actionGoToPreviousCompletionRules); getView().addButtonConsoleInputListener(this, actionConsoleInput); getView().addButtonConsoleOutputListener(this, actionConsoleOutput); getView().addButtonComputeInferenceListener(this, actionComputeInference); getView().addComboBoxExampleListener(this, actionComboBoxExample); getView().addExamples(this.exampleLoader.getExampleConfigurations()); executeActionResetCompletionRules(); } void updatePreviousToLastUsedCompletionRules(String current) { this.previousToLastUsedCompletionRules = this.lastUsedCompletionRules; this.lastUsedCompletionRules = current; } }
package org.dellroad.stuff.pobj; import java.util.HashMap; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import org.dellroad.stuff.java.ThreadLocalHolder; import org.dellroad.stuff.spring.AbstractBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.BeanNameAware; public class PersistentObjectTransactionManager<T> extends AbstractBean implements BeanNameAware { /** * Default transaction queue capacity ({@link Integer#MAX_VALUE}) when in Disruptor mode. */ public static final int DEFAULT_QUEUE_CAPACITY = Integer.MAX_VALUE; static final ThreadLocal<HashMap<String, PersistentObjectTransactionManager<?>>> ASPECT_MANAGER_MAP = new ThreadLocal<HashMap<String, PersistentObjectTransactionManager<?>>>(); private static final FutureTask<Void> TERMINATE_TASK = new FutureTask<Void>(new Runnable() { public void run() { } }, null); private static final AtomicInteger THREAD_COUNTER = new AtomicInteger(); private final ThreadLocalHolder<TxInfo> currentRoot = new ThreadLocalHolder<TxInfo>(); private final Object nonDisruptorLock = new Object(); private PersistentObject<T> persistentObject; private String name = "default"; private int queueCapacity = DEFAULT_QUEUE_CAPACITY; private boolean disruptorMode; private boolean started; private volatile LinkedBlockingQueue<FutureTask<?>> queue; private volatile WorkerThread workerThread; // Lifecycle /** * Set the name of this instance. * * <p> * The implementation in {@link PersistentObjectTransactionManager} invokes {@link #setName}, so that instances' * names are automatically inherited from their Spring bean names, unless the name is already set to something else. * </p> */ @Override public void setBeanName(String beanName) { if (this.getName() == null) this.setName(beanName); } @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); synchronized (this) { // Sanity check if (this.started) throw new IllegalStateException("already started"); // Check required properties if (this.persistentObject == null) throw new IllegalStateException("no PersistentObject configured"); if (this.name == null) throw new IllegalStateException("no name configured"); // Check mode if (this.disruptorMode) { // Initialize queue this.queue = new LinkedBlockingQueue<FutureTask<?>>(this.getQueueCapacity()); // Start worker thread this.workerThread = new WorkerThread(); this.workerThread.start(); } // Done this.started = true; } } @Override public void destroy() throws Exception { synchronized (this) { // Sanity check if (!this.started) throw new IllegalStateException("not started"); // Stop worker thread if (this.queue != null) this.queue.add(TERMINATE_TASK); // Wait for worker thread to finish if (this.workerThread != null) { this.workerThread.join(); this.workerThread = null; } // Reset queue this.queue = null; // Done this.started = false; } super.destroy(); } // Public API /** * Configure the {@link PersistentObject} database that this instance manages transactions for. * * <p> * Required property. * </p> */ public void setPersistentObject(PersistentObject<T> persistentObject) { this.persistentObject = persistentObject; } public synchronized void setDisruptorMode(boolean disruptorMode) { if (this.started && disruptorMode != this.disruptorMode) throw new IllegalStateException("can't change disruptorMode while running"); this.disruptorMode = disruptorMode; } /** * Get the configured name of this instance. Default is {@code "default"}. */ public String getName() { return this.name; } /** * Set the configured name of this instance. */ public void setName(String name) { this.name = name; } /** * Get the configured capacity of the transaction queue for Disruptor mode. Default is {@link Integer#MAX_VALUE}. */ public int getQueueCapacity() { return this.queueCapacity; } public void setQueueCapacity(int queueCapacity) { if (queueCapacity <= 0) throw new IllegalArgumentException("queueCapacity <= 0"); this.queueCapacity = queueCapacity; } public <V> Future<V> scheduleTransaction(Callable<V> action, boolean readOnly, boolean shared) { return this.scheduleTransactionTask(new FutureTask<V>(this.getTask(action, readOnly, shared))); } public Future<Void> scheduleTransaction(Runnable action, boolean readOnly, boolean shared) { return this.scheduleTransactionTask(new FutureTask<Void>(this.getTask(action, readOnly, shared))); } public <V> V performTransaction(Callable<V> action, boolean readOnly, boolean shared) throws Exception { // Check if reentrant if (this.checkReentrant(readOnly, shared)) return action.call(); // Handle non-disruptor mode if (!this.disruptorMode) { final Callable<V> task = this.getTask(action, readOnly, shared); synchronized (this.nonDisruptorLock) { return task.call(); } } // Handle disruptor mode return this.waitFormScheduledTransaction(this.scheduleTransaction(action, readOnly, shared)); } public void performTransaction(Runnable action, boolean readOnly, boolean shared) { // Check if reentrant if (this.checkReentrant(readOnly, shared)) { action.run(); return; } // Handle non-disruptor mode if (!this.disruptorMode) { final Callable<Void> task = this.getTask(action, readOnly, shared); try { synchronized (this.nonDisruptorLock) { task.call(); } } catch (Error e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw this.<RuntimeException>maskException(e); // should never happen } } // Handle disruptor mode this.waitFormScheduledTransaction(this.scheduleTransaction(action, readOnly, shared)); } @SuppressWarnings("unchecked") public static <T> PersistentObjectTransactionManager<T> getCurrent(String name) { if (name == null) throw new IllegalArgumentException("null name"); final HashMap<String, PersistentObjectTransactionManager<?>> managerMap = ASPECT_MANAGER_MAP.get(); final PersistentObjectTransactionManager<?> manager = managerMap != null ? managerMap.get(name) : null; if (manager == null) { throw new IllegalStateException("no PersistentObjectTransactionManager named `" + name + "' has an open transaction in the current thread"); } return (PersistentObjectTransactionManager<T>)manager; } @SuppressWarnings("unchecked") public static <T> PersistentObjectTransactionManager<T> getCurrent() { final HashMap<String, PersistentObjectTransactionManager<?>> managerMap = ASPECT_MANAGER_MAP.get(); if (managerMap == null || managerMap.isEmpty()) { throw new IllegalStateException("there are no PersistentObjectTransactionManager transactions open" + " in the current thread"); } if (managerMap.size() > 1) { throw new IllegalStateException("there is more than one PersistentObjectTransactionManager transaction open" + " in the current thread"); } return (PersistentObjectTransactionManager<T>)managerMap.values().iterator().next(); } public T getRoot() { return this.currentRoot.require().getSnapshot().getRoot(); } public long getVersion() { return this.currentRoot.require().getSnapshot().getVersion(); } /** * Determine if the current thread is running within a transaction. */ public boolean isTransaction() { return this.currentRoot.get() != null; } /** * Determine if the current thread is running within a transaction and that transaction is read-only. */ public boolean isReadOnlyTransaction() { final TxInfo txInfo = this.currentRoot.get(); return txInfo != null && txInfo.isReadOnly(); } /** * Determine if the current thread is running within a transaction and that transaction is a read-only shared root transaction. */ public boolean isReadOnlySharedRootTransaction() { final TxInfo txInfo = this.currentRoot.get(); return txInfo != null && txInfo.isReadOnly() && txInfo.isShared(); } // Internal methods private boolean checkReentrant(boolean readOnly, boolean shared) { // Are we already within a transaction? final TxInfo txInfo = this.currentRoot.get(); if (txInfo == null) return false; // Check for incompatibilities if (txInfo.isReadOnly()) { if (!readOnly) { throw new IllegalStateException("illegal read-write transaction created reentrantly" + " within a read-only transaction"); } if (txInfo.isShared() && !shared) { throw new IllegalStateException("illegal non-shared read-only transaction created reentrantly" + " within a shared read-only transaction"); } } return true; } private <V> FutureTask<V> scheduleTransactionTask(FutureTask<V> task) { // Sanity check if (task == null) throw new IllegalArgumentException("null task"); if (!this.started) throw new IllegalStateException("instance not started"); if (this.queue == null) throw new IllegalStateException("instance is not running in Disruptor mode"); // Enqueue transaction this.queue.add(task); // Done return task; } private <V> V waitFormScheduledTransaction(Future<V> future) { boolean interrupted = false; try { while (true) { try { return future.get(); } catch (InterruptedException e) { interrupted = true; } } } catch (ExecutionException e) { final Throwable cause = e.getCause(); this.prependCurrentStackTrace(cause, "Synchronous PersistentObjectTransactionManager Transaction"); throw this.<RuntimeException>maskException(cause); // re-throw original exception } catch (CancellationException e) { throw new RuntimeException("transaction method execution was canceled", e); // should never happen } finally { if (interrupted) Thread.currentThread().interrupt(); } } private <V> Callable<V> getTask(final Callable<V> action, final boolean readOnly, final boolean shared) { return new Callable<V>() { @Override public V call() throws Exception { final PersistentObject<T>.Snapshot snapshot = readOnly && shared ? PersistentObjectTransactionManager.this.persistentObject.getSharedRootSnapshot() : PersistentObjectTransactionManager.this.persistentObject.getRootSnapshot(); final TxInfo txInfo = new TxInfo(snapshot, readOnly, shared); return PersistentObjectTransactionManager.this.currentRoot.invoke(txInfo, new Callable<V>() { @Override public V call() throws Exception { return PersistentObjectTransactionManager.this.executeTransaction(action, txInfo); } }); } }; } private Callable<Void> getTask(final Runnable action, boolean readOnly, boolean shared) { return this.getTask(new Callable<Void>() { @Override public Void call() { action.run(); return null; } }, readOnly, shared); } private <V> V executeTransaction(Callable<V> action, TxInfo txInfo) throws Exception { // Associate this instance with the current thread HashMap<String, PersistentObjectTransactionManager<?>> managerMap = ASPECT_MANAGER_MAP.get(); final boolean emptyMap = managerMap == null; if (emptyMap) { managerMap = new HashMap<String, PersistentObjectTransactionManager<?>>(); ASPECT_MANAGER_MAP.set(managerMap); } if (managerMap.containsKey(this.name)) { throw new IllegalStateException("A PersistentObjectTransactionManager named `" + this.name + "' already has an open transaction in the current thread; all names must be distinct"); } managerMap.put(this.name, this); // Perform transaction V result; try { // Invoke callback try { result = action.call(); } catch (Exception e) { throw e; } // Update database (read-write transactions only) if (!txInfo.isReadOnly()) this.persistentObject.setRoot(txInfo.getSnapshot().getRoot(), txInfo.getSnapshot().getVersion()); } finally { if (emptyMap) ASPECT_MANAGER_MAP.remove(); else managerMap.remove(this.name); } // Done return result; } // Checked exception masker @SuppressWarnings("unchecked") <T extends Throwable> T maskException(Throwable t) throws T { throw (T)t; } // Prepend stack frames from the current thread onto the given exception's stack frames void prependCurrentStackTrace(Throwable t, String description) { this.prependStackFrames(t, new Throwable(), description, 1); } // Prepend the second exception's stack frames onto the first exception's stack frames void prependStackFrames(Throwable t, Throwable p, String description, int skip) { final StackTraceElement[] innerFrames = t.getStackTrace(); final StackTraceElement[] outerFrames = p.getStackTrace(); final StackTraceElement[] frames = new StackTraceElement[innerFrames.length + 1 + Math.max(outerFrames.length - skip, 0)]; System.arraycopy(innerFrames, 0, frames, 0, innerFrames.length); frames[innerFrames.length] = new StackTraceElement(this.getClass().getName(), "<" + this.name + ">", description, -1); for (int i = 0; i < outerFrames.length - skip; i++) frames[innerFrames.length + 1 + i] = outerFrames[i + skip]; t.setStackTrace(frames); } // Worker thread private class WorkerThread extends Thread { private final Logger log = LoggerFactory.getLogger(this.getClass()); public WorkerThread() { super("PersistentObjectTransactionManager-" + PersistentObjectTransactionManager.THREAD_COUNTER.incrementAndGet()); } @Override public void run() { this.log.debug(this + " transaction thread starting"); int count = 0; try { while (true) { // Get next in queue final FutureTask<?> task = PersistentObjectTransactionManager.this.queue.take(); if (task == TERMINATE_TASK) break; // Execute task task.run(); count++; } } catch (Throwable t) { this.log.error(this + " transaction thread caught unexpected exception", t); } finally { this.log.debug(this + " transaction thread stopping after " + count + " transactions"); } } } // Transaction Info private class TxInfo { private final PersistentObject<T>.Snapshot snapshot; private final boolean readOnly; private final boolean shared; TxInfo(PersistentObject<T>.Snapshot snapshot, boolean readOnly, boolean shared) { this.snapshot = snapshot; this.readOnly = readOnly; this.shared = shared; } public PersistentObject<T>.Snapshot getSnapshot() { return this.snapshot; } public boolean isReadOnly() { return this.readOnly; } public boolean isShared() { return this.shared; } } }
package com.box.androidsdk.content.requests; import com.box.androidsdk.content.models.BoxIteratorBoxEntity; import com.box.androidsdk.content.models.BoxSession; import com.box.androidsdk.content.BoxException; import com.box.androidsdk.content.listeners.ProgressListener; import com.box.androidsdk.content.models.BoxJsonObject; import com.box.androidsdk.content.models.BoxIterator; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; import java.util.Locale; /** * Abstract class representing a request to upload a file. * * @param <E> type of BoxJsonObject to be returned in the response. * @param <R> type of BoxRequest being created. */ public abstract class BoxRequestUpload<E extends BoxJsonObject, R extends BoxRequest<E,R>> extends BoxRequestItem<E,R> { InputStream mStream; long mUploadSize; Date mCreatedDate; Date mModifiedDate; String mFileName; String mSha1; File mFile; /** * Creates an upload request from an InputStream with the default parameters. * * @param clazz class of the object returned in the response. * @param fileInputStream file input stream to upload. * @param requestUrl URL for the upload endpoint. * @param session the authenticated session that will be used to make the request with. */ public BoxRequestUpload(Class<E> clazz, InputStream fileInputStream, String requestUrl, BoxSession session) { super(clazz,null,requestUrl, session); mRequestMethod = Methods.POST; mStream = fileInputStream; mFileName = ""; } @Override protected void setHeaders(BoxHttpRequest request) { super.setHeaders(request); if (mSha1 != null) { request.addHeader("Content-MD5", mSha1); } } /** * * @return a stream in which to get the contents to upload from. This may have been directly set or will create * a stream from the file specified. * @throws FileNotFoundException thrown if a file was specified, but is not found. */ protected InputStream getInputStream() throws FileNotFoundException{ if (mStream != null){ return mStream; } return new FileInputStream(mFile); } protected BoxRequestMultipart createMultipartRequest() throws IOException, BoxException{ URL requestUrl = buildUrl(); BoxRequestMultipart httpRequest = new BoxRequestMultipart(requestUrl, mRequestMethod, mListener); setHeaders(httpRequest); httpRequest.setFile(getInputStream(),mFileName,mUploadSize); if (mCreatedDate != null) { httpRequest.putField("content_created_at", mCreatedDate); } if (mModifiedDate != null) { httpRequest.putField("content_modified_at", mModifiedDate); } return httpRequest; } @Override protected BoxHttpRequest createHttpRequest() throws IOException, BoxException { BoxRequestMultipart httpRequest = createMultipartRequest(); httpRequest.writeBody(httpRequest.mUrlConnection, mListener); return httpRequest; } @Override public E onSend() throws BoxException { BoxRequest.BoxRequestHandler requestHandler = getRequestHandler(); BoxHttpResponse response = null; try { // Create the HTTP request and send it BoxHttpRequest request = createHttpRequest(); response = new BoxHttpResponse(request.getUrlConnection()); response.open(); logDebug(response); // Process the response through the provided handler if (requestHandler.isResponseSuccess(response)) { BoxIterator list = (BoxIterator) requestHandler.onResponse(BoxIteratorBoxEntity.class, response); return (E)list.get(0); } // All non successes will throw int code = response.getResponseCode(); throw new BoxException(String.format(Locale.ENGLISH, "An error occurred while sending the request (%s)", code), response); } catch (IOException e) { throw handleSendException(requestHandler, response, e); } catch (InstantiationException e) { throw handleSendException(requestHandler, response, e); } catch (IllegalAccessException e) { throw handleSendException(requestHandler, response, e); } catch (BoxException e) { throw handleSendException(requestHandler, response, e); } } private BoxException handleSendException(BoxRequestHandler requestHandler, BoxHttpResponse response, Exception ex) throws BoxException { BoxException e = ex instanceof BoxException ? (BoxException) ex : new BoxException("Couldn't connect to the Box API due to a network error.", ex); requestHandler.onException(this, response, e); return e; } /** * Sets the progress listener for the upload request. * * @param listener progress listener for the request. * @return request with the updated progress listener. */ public R setProgressListener(ProgressListener listener){ mListener = listener; return (R)this; } /** * Returns the size of the upload. * * @return the size of the upload in bytes. */ public long getUploadSize() { return mUploadSize; } /** * Sets the upload size in the request. * * @param mUploadSize size of the upload in bytes. * @return request with the updated size. */ public R setUploadSize(long mUploadSize) { this.mUploadSize = mUploadSize; return (R)this; } /** * Returns the content modified date currently set in the request. * * @return the content modified date currently set in the request, or null if not set. */ public Date getModifiedDate() { return mModifiedDate; } /** * Sets the content modified date in the request. * * @param mModifiedDate date to set as the content modified date. * @return request with the updated content modified date. */ public R setModifiedDate(Date mModifiedDate) { this.mModifiedDate = mModifiedDate; return (R)this; } /** * Returns the content created date currently set in the request. * * @return the content created date currently set in the request, or null if not set. */ public Date getCreatedDate() { return mCreatedDate; } /** * Sets the content created date in the request. * * @param mCreatedDate date to set as the content created date in the request. * @return request with the updated content created date. */ public R setCreatedDate(Date mCreatedDate) { this.mCreatedDate = mCreatedDate; return (R)this; } /** * Returns the sha1 currently set in the request. * * @return sha1 currently set in the request, or null if not set. */ public String getSha1() { return mSha1; } /** * Sets the sha1 in the request. * * @param sha1 sha1 to set in the request. */ public void setSha1(String sha1) { mSha1 = sha1; } /** * Returns the file to upload. * * @return file to upload. */ public File getFile(){ return mFile; } }
package org.tuckey.web.filters.urlrewrite.sample; import org.tuckey.web.filters.urlrewrite.extend.RewriteRule; import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A sample of how you might write a custom rule. */ public class SampleRewriteRule extends RewriteRule { public RewriteMatch matches(HttpServletRequest request, HttpServletResponse response) { // return null if we don't want the request if (!request.getRequestURI().startsWith("/staff/")) return null; Integer id = null; try { // grab the things out of the url we need id = Integer.valueOf(request.getRequestURI().replaceFirst( "/staff/([0-9]+)/", "$1")); } catch (NumberFormatException e) { // if we don't get a good id then return null return null; } // match required with clean parameters return new SampleRewriteMatch(id.intValue()); } }
package gov.nih.nci.cagrid.gridgrouper.service; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.internet2.middleware.grouper.AccessPrivilege; import edu.internet2.middleware.grouper.CompositeType; import edu.internet2.middleware.grouper.GrantPrivilegeException; import edu.internet2.middleware.grouper.Group; import edu.internet2.middleware.grouper.GroupDeleteException; import edu.internet2.middleware.grouper.GroupFinder; import edu.internet2.middleware.grouper.GroupModifyException; import edu.internet2.middleware.grouper.GroupNotFoundException; import edu.internet2.middleware.grouper.GrouperSession; import edu.internet2.middleware.grouper.GrouperSourceAdapter; import edu.internet2.middleware.grouper.InsufficientPrivilegeException; import edu.internet2.middleware.grouper.Member; import edu.internet2.middleware.grouper.MemberAddException; import edu.internet2.middleware.grouper.MemberDeleteException; import edu.internet2.middleware.grouper.MemberFinder; import edu.internet2.middleware.grouper.Membership; import edu.internet2.middleware.grouper.NamingPrivilege; import edu.internet2.middleware.grouper.Privilege; import edu.internet2.middleware.grouper.RevokePrivilegeException; import edu.internet2.middleware.grouper.SchemaException; import edu.internet2.middleware.grouper.Stem; import edu.internet2.middleware.grouper.StemAddException; import edu.internet2.middleware.grouper.StemDeleteException; import edu.internet2.middleware.grouper.StemFinder; import edu.internet2.middleware.grouper.StemModifyException; import edu.internet2.middleware.grouper.StemNotFoundException; import edu.internet2.middleware.grouper.SubjectFinder; import edu.internet2.middleware.subject.Subject; import edu.internet2.middleware.subject.SubjectNotFoundException; import edu.internet2.middleware.subject.provider.SubjectTypeEnum; import gov.nih.nci.cagrid.common.FaultHelper; import gov.nih.nci.cagrid.gridgrouper.bean.GroupCompositeType; import gov.nih.nci.cagrid.gridgrouper.bean.GroupDescriptor; import gov.nih.nci.cagrid.gridgrouper.bean.GroupIdentifier; import gov.nih.nci.cagrid.gridgrouper.bean.GroupPrivilege; import gov.nih.nci.cagrid.gridgrouper.bean.GroupPrivilegeType; import gov.nih.nci.cagrid.gridgrouper.bean.GroupUpdate; import gov.nih.nci.cagrid.gridgrouper.bean.LogicalOperator; import gov.nih.nci.cagrid.gridgrouper.bean.MemberDescriptor; import gov.nih.nci.cagrid.gridgrouper.bean.MemberFilter; import gov.nih.nci.cagrid.gridgrouper.bean.MemberType; import gov.nih.nci.cagrid.gridgrouper.bean.MembershipDescriptor; import gov.nih.nci.cagrid.gridgrouper.bean.MembershipExpression; import gov.nih.nci.cagrid.gridgrouper.bean.MembershipQuery; import gov.nih.nci.cagrid.gridgrouper.bean.MembershipStatus; import gov.nih.nci.cagrid.gridgrouper.bean.MembershipType; import gov.nih.nci.cagrid.gridgrouper.bean.StemDescriptor; import gov.nih.nci.cagrid.gridgrouper.bean.StemIdentifier; import gov.nih.nci.cagrid.gridgrouper.bean.StemPrivilege; import gov.nih.nci.cagrid.gridgrouper.bean.StemPrivilegeType; import gov.nih.nci.cagrid.gridgrouper.bean.StemUpdate; import gov.nih.nci.cagrid.gridgrouper.common.SubjectUtils; import gov.nih.nci.cagrid.gridgrouper.stubs.types.GrantPrivilegeFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.GridGrouperRuntimeFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.GroupAddFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.GroupDeleteFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.GroupModifyFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.GroupNotFoundFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.InsufficientPrivilegeFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.MemberAddFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.MemberDeleteFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.RevokePrivilegeFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.SchemaFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.StemAddFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.StemDeleteFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.StemModifyFault; import gov.nih.nci.cagrid.gridgrouper.stubs.types.StemNotFoundFault; import gov.nih.nci.cagrid.gridgrouper.subject.GridSourceAdapter; /** * @author <A HREF="MAILTO:[email protected]">Stephen Langella</A> * @author <A HREF="MAILTO:[email protected]">Scott Oster</A> * @author <A HREF="MAILTO:[email protected]">Shannon Hastings</A> * @author <A HREF="MAILTO:[email protected]">David W. Ervin</A> * @version $Id: GridGrouperBaseTreeNode.java,v 1.1 2006/08/04 03:49:26 langella * Exp $ */ public class GridGrouper { public static final String GROUPER_SUPER_USER = "GrouperSystem"; public static final String GROUPER_ADMIN_STEM_NAME = "grouperadministration"; public static final String GROUPER_ADMIN_STEM_DISPLAY_NAME = "Grouper Administration"; public static final String GROUPER_ADMIN_GROUP_NAME_EXTENTION = "gridgrouperadministrators"; public static final String GROUPER_ADMIN_GROUP_DISPLAY_NAME_EXTENTION = "Grid Grouper Administrators"; public static final String GROUPER_ADMIN_GROUP_NAME = "grouperadministration:gridgrouperadministrators"; public static final String UNKNOWN_SUBJECT = "Unknown"; private Group adminGroup; private Log log; public GridGrouper() throws GridGrouperRuntimeFault { try { this.log = LogFactory.getLog(this.getClass().getName()); GrouperSession session = GrouperSession.start(SubjectFinder.findById(GROUPER_SUPER_USER)); Stem adminStem = null; try { adminStem = StemFinder.findByName(session, GROUPER_ADMIN_STEM_NAME); } catch (StemNotFoundException e) { Stem root = StemFinder.findRootStem(session); adminStem = root.addChildStem(GROUPER_ADMIN_STEM_NAME, GROUPER_ADMIN_STEM_DISPLAY_NAME); } try { this.adminGroup = GroupFinder.findByName(session, GROUPER_ADMIN_GROUP_NAME); } catch (GroupNotFoundException gne) { this.adminGroup = adminStem.addChildGroup(GROUPER_ADMIN_GROUP_NAME_EXTENTION, GROUPER_ADMIN_GROUP_DISPLAY_NAME_EXTENTION); } } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred initializing Grid Grouper: " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } } public StemDescriptor getStem(String gridIdentity, StemIdentifier stemId) throws GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); StemDescriptor des = null; Stem stem = StemFinder.findByName(session, stemId.getStemName()); des = stemtoStemDescriptor(stem); return des; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem, " + stemId.getStemName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the stem " + stemId.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public StemDescriptor[] getChildStems(String gridIdentity, StemIdentifier parentStemId) throws RemoteException, GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); StemDescriptor[] children = null; Stem parent = StemFinder.findByName(session, parentStemId.getStemName()); Set set = parent.getChildStems(); children = new StemDescriptor[set.size()]; Iterator itr = set.iterator(); int count = 0; while (itr.hasNext()) { children[count] = stemtoStemDescriptor((Stem) itr.next()); count++; } return children; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The parent stem, " + parentStemId.getStemName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the child stems for the parent stem, " + parentStemId.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public StemDescriptor getParentStem(String gridIdentity, StemIdentifier childStemId) throws RemoteException, GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); StemDescriptor parent = null; Stem child = StemFinder.findByName(session, childStemId.getStemName()); Stem s = child.getParentStem(); parent = stemtoStemDescriptor(s); return parent; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The parent stem for the child " + childStemId.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the parent stem for the child stem, " + childStemId.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public StemDescriptor updateStem(String gridIdentity, StemIdentifier stem, StemUpdate update) throws GridGrouperRuntimeFault, InsufficientPrivilegeFault, StemModifyFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); StemDescriptor des = null; Stem target = StemFinder.findByName(session, stem.getStemName()); if ((update.getDescription() != null) && (!update.getDescription().equals(target.getDescription()))) { target.setDescription(update.getDescription()); } if ((update.getDisplayExtension() != null) && (!update.getDisplayExtension().equals(target.getDisplayExtension()))) { target.setDisplayExtension(update.getDisplayExtension()); } des = stemtoStemDescriptor(target); return des; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (StemModifyException e) { StemModifyFault fault = new StemModifyFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemModifyFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public String[] getSubjectsWithStemPrivilege(String gridIdentity, StemIdentifier stem, StemPrivilegeType privilege) throws RemoteException, GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); Stem target = StemFinder.findByName(session, stem.getStemName()); Set subs = null; if (privilege.equals(StemPrivilegeType.create)) { subs = target.getCreators(); } else if (privilege.equals(StemPrivilegeType.stem)) { subs = target.getStemmers(); } else { throw new Exception(privilege.getValue() + " is not a valid stem privilege!!!"); } int size = 0; if (subs != null) { size = subs.size(); } String[] subjects = new String[size]; if (subs != null) { Iterator itr = subs.iterator(); int count = 0; while (itr.hasNext()) { Subject s = (Subject) itr.next(); subjects[count] = s.getId(); count++; } } return subjects; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the subjects with the privilege " + privilege.getValue() + " on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public StemPrivilege[] getStemPrivileges(String gridIdentity, StemIdentifier stem, String subject) throws RemoteException, GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); Set privs = target.getPrivs(SubjectFinder.findById(subject)); int size = 0; if (privs != null) { size = privs.size(); } StemPrivilege[] rights = new StemPrivilege[size]; if (privs != null) { Iterator itr = privs.iterator(); int count = 0; while (itr.hasNext()) { NamingPrivilege p = (NamingPrivilege) itr.next(); rights[count] = new StemPrivilege(); rights[count].setStemName(p.getStem().getName()); rights[count].setImplementationClass(p.getImplementationName()); rights[count].setIsRevokable(p.isRevokable()); rights[count].setOwner(p.getOwner().getId()); rights[count].setPrivilegeType(StemPrivilegeType.fromValue(p.getName())); rights[count].setSubject(p.getSubject().getId()); count++; } } return rights; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the privileges for the subject " + subject + " on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public boolean hasStemPrivilege(String gridIdentity, StemIdentifier stem, String subject, StemPrivilegeType privilege) throws GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); if (privilege == null) { return false; } else if (privilege.equals(StemPrivilegeType.create)) { return target.hasCreate(SubjectFinder.findById(subject)); } else if (privilege.equals(StemPrivilegeType.stem)) { return target.hasStem(SubjectFinder.findById(subject)); } else { return false; } } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error determing if the subject " + subject + " has the privilege " + privilege.getValue() + " on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void grantStemPrivilege(String gridIdentity, StemIdentifier stem, String subject, StemPrivilegeType privilege) throws GridGrouperRuntimeFault, StemNotFoundFault, GrantPrivilegeFault, InsufficientPrivilegeFault, SchemaFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); target.grantPriv(SubjectFinder.findById(subject), Privilege.getInstance(privilege.getValue())); } catch (GrantPrivilegeException e) { GrantPrivilegeFault fault = new GrantPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GrantPrivilegeFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to manages privileges on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (SchemaException e) { SchemaFault fault = new SchemaFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (SchemaFault) helper.getFault(); throw fault; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred granting a privilege for the subject " + subject + " on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void revokeStemPrivilege(String gridIdentity, StemIdentifier stem, String subject, StemPrivilegeType privilege) throws GridGrouperRuntimeFault, StemNotFoundFault, InsufficientPrivilegeFault, RevokePrivilegeFault, SchemaFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); target.revokePriv(SubjectFinder.findById(subject), Privilege.getInstance(privilege.getValue())); } catch (RevokePrivilegeException e) { RevokePrivilegeFault fault = new RevokePrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (RevokePrivilegeFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to manages privileges on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (SchemaException e) { SchemaFault fault = new SchemaFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (SchemaFault) helper.getFault(); throw fault; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the privileges for the subject " + subject + " on the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public StemDescriptor addChildStem(String gridIdentity, StemIdentifier stem, String extension, String displayExtension) throws GridGrouperRuntimeFault, InsufficientPrivilegeFault, StemAddFault, StemNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); Stem child = target.addChildStem(extension, displayExtension); return stemtoStemDescriptor(child); } catch (StemAddException e) { StemAddFault fault = new StemAddFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemAddFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to add children to the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred adding the child " + extension + " to the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void deleteStem(String gridIdentity, StemIdentifier stem) throws GridGrouperRuntimeFault, InsufficientPrivilegeFault, StemDeleteFault, StemNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); target.delete(); } catch (StemDeleteException e) { StemDeleteFault fault = new StemDeleteFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemDeleteFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to add children to the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault .setFaultString("An error occurred in deleting the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupDescriptor[] getChildGroups(String gridIdentity, StemIdentifier stem) throws GridGrouperRuntimeFault, StemNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); GroupDescriptor[] children = null; Set set = target.getChildGroups(); children = new GroupDescriptor[set.size()]; Iterator itr = set.iterator(); int count = 0; while (itr.hasNext()) { children[count] = grouptoGroupDescriptor((Group) itr.next()); count++; } return children; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("An error occurred in getting the child groups for the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public gov.nih.nci.cagrid.gridgrouper.bean.GroupDescriptor addChildGroup(String gridIdentity, StemIdentifier stem, String extension, String displayExtension) throws RemoteException, GridGrouperRuntimeFault, GroupAddFault, InsufficientPrivilegeFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Stem target = StemFinder.findByName(session, stem.getStemName()); Group child = target.addChildGroup(extension, displayExtension); return grouptoGroupDescriptor(child); } catch (GroupAddFault e) { GroupAddFault fault = new GroupAddFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupAddFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to add groups to the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (StemNotFoundException e) { StemNotFoundFault fault = new StemNotFoundFault(); fault.setFaultString("The stem " + stem.getStemName() + " could not be found!!!"); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (StemNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred adding the group " + extension + " to the stem " + stem.getStemName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupDescriptor getGroup(String gridIdentity, GroupIdentifier group) throws GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); Group grp = GroupFinder.findByName(session, group.getGroupName()); return grouptoGroupDescriptor(grp); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void deleteGroup(String gridIdentity, GroupIdentifier group) throws GridGrouperRuntimeFault, GroupNotFoundFault, GroupDeleteFault, InsufficientPrivilegeFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); Group grp = GroupFinder.findByName(session, group.getGroupName()); grp.delete(); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (GroupDeleteException e) { GroupDeleteFault fault = new GroupDeleteFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupDeleteFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred deleting the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupDescriptor updateGroup(String gridIdentity, GroupIdentifier group, GroupUpdate update) throws GridGrouperRuntimeFault, GroupNotFoundFault, GroupModifyFault, InsufficientPrivilegeFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); Group grp = GroupFinder.findByName(session, group.getGroupName()); if ((update.getDescription() != null) && (!update.getDescription().equals(grp.getDescription()))) { grp.setDescription(update.getDescription()); } if ((update.getExtension() != null) && (!update.getExtension().equals(grp.getExtension()))) { grp.setExtension(update.getExtension()); } if ((update.getDisplayExtension() != null) && (!update.getDisplayExtension().equals(grp.getDisplayExtension()))) { grp.setDisplayExtension(update.getDisplayExtension()); } return grouptoGroupDescriptor(grp); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (GroupModifyException e) { GroupModifyFault fault = new GroupModifyFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupModifyFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred updating the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void addMember(String gridIdentity, GroupIdentifier group, String subject) throws GridGrouperRuntimeFault, GroupNotFoundFault, InsufficientPrivilegeFault, MemberAddFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); Group grp = GroupFinder.findByName(session, group.getGroupName()); grp.addMember(SubjectFinder.findById(subject)); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (MemberAddException e) { MemberAddFault fault = new MemberAddFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (MemberAddFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred adding a member to the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public MemberDescriptor[] getMembers(String gridIdentity, GroupIdentifier group, MemberFilter filter) throws RemoteException, GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); Group target = GroupFinder.findByName(session, group.getGroupName()); Set set = null; if (filter.equals(MemberFilter.All)) { set = target.getMembers(); } else if (filter.equals(MemberFilter.EffectiveMembers)) { set = target.getEffectiveMembers(); } else if (filter.equals(MemberFilter.ImmediateMembers)) { set = target.getImmediateMembers(); } else if (filter.equals(MemberFilter.CompositeMembers)) { set = target.getCompositeMembers(); } else { throw new Exception("Unsuppoted member filter type!!!"); } MemberDescriptor[] members = new MemberDescriptor[set.size()]; Iterator itr = set.iterator(); int count = 0; while (itr.hasNext()) { Member m = (Member) itr.next(); members[count] = memberToMemberDescriptor(m); count++; } return members; } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + " was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the members of the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public boolean isMemberOf(GrouperSession session, GroupIdentifier group, String member, MemberFilter filter) throws GridGrouperRuntimeFault, GroupNotFoundFault { try { Group target = GroupFinder.findByName(session, group.getGroupName()); if (filter.equals(MemberFilter.All)) { return target.hasMember(SubjectFinder.findById(member)); } else if (filter.equals(MemberFilter.EffectiveMembers)) { return target.hasEffectiveMember(SubjectFinder.findById(member)); } else if (filter.equals(MemberFilter.ImmediateMembers)) { return target.hasImmediateMember(SubjectFinder.findById(member)); } else { throw new Exception("Unsuppoted member filter type!!!"); } } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred determining if " + member + " is a member of the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } } public boolean isMemberOf(String gridIdentity, GroupIdentifier group, String member, MemberFilter filter) throws GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); return isMemberOf(session, group, member, filter); } catch (GridGrouperRuntimeFault e) { throw e; } catch (GroupNotFoundFault e) { throw e; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred determining if " + member + " is a member of the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public MembershipDescriptor[] getMemberships(String gridIdentity, GroupIdentifier group, MemberFilter filter) throws RemoteException, GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); Group target = GroupFinder.findByName(session, group.getGroupName()); Set set = null; if (filter.equals(MemberFilter.All)) { set = target.getMemberships(); } else if (filter.equals(MemberFilter.EffectiveMembers)) { set = target.getEffectiveMemberships(); } else if (filter.equals(MemberFilter.ImmediateMembers)) { set = target.getImmediateMemberships(); } else if (filter.equals(MemberFilter.CompositeMembers)) { set = target.getCompositeMemberships(); } else { throw new Exception("Unsuppoted member filter type!!!"); } MembershipDescriptor[] members = new MembershipDescriptor[set.size()]; Iterator itr = set.iterator(); int count = 0; while (itr.hasNext()) { Membership m = (Membership) itr.next(); members[count] = new MembershipDescriptor(); members[count].setMember(memberToMemberDescriptor(m.getMember())); members[count].setGroup(grouptoGroupDescriptor(m.getGroup())); try { members[count].setViaGroup(grouptoGroupDescriptor(m.getViaGroup())); } catch (GroupNotFoundException gnfe) { } members[count].setDepth(m.getDepth()); count++; } return members; } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the members of the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public Group getAdminGroup() { return this.adminGroup; } private MemberDescriptor memberToMemberDescriptor(Member m) throws Exception { MemberDescriptor member = new MemberDescriptor(); member.setUUID(m.getUuid()); member.setSubjectId(m.getSubjectId()); member.setSubjectName(m.getSubject().getName()); if (m.getSubject().getSource().getClass().getName().equals(GridSourceAdapter.class.getName())) { member.setMemberType(MemberType.Grid); } else if ((m.getSubjectType().equals(SubjectTypeEnum.GROUP)) && (m.getSubject().getSource().getClass().getName().equals(GrouperSourceAdapter.class.getName()))) { member.setMemberType(MemberType.GrouperGroup); } else { member.setMemberType(MemberType.Other); } return member; } private GroupDescriptor grouptoGroupDescriptor(Group group) throws Exception { GroupDescriptor des = new GroupDescriptor(); des.setCreateSource(group.getCreateSource()); des.setParentStem(group.getParentStem().getName()); des.setCreateSubject(group.getCreateSubject().getId()); des.setCreateTime(group.getCreateTime().getTime()); des.setDescription(group.getDescription()); des.setDisplayExtension(group.getDisplayExtension()); des.setDisplayName(group.getDisplayName()); des.setExtension(group.getExtension()); des.setModifySource(group.getModifySource()); try { des.setModifySubject(group.getModifySubject().getId()); } catch (Exception ex) { if (ex.getMessage().indexOf("has not been modified") != -1) { des.setModifySubject(""); } else { throw ex; } } des.setModifyTime(group.getModifyTime().getTime()); des.setName(group.getName()); des.setUUID(group.getUuid()); des.setHasComposite(group.hasComposite()); des.setIsComposite(group.isComposite()); return des; } private StemDescriptor stemtoStemDescriptor(Stem stem) throws Exception { StemDescriptor des = new StemDescriptor(); des.setCreateSource(stem.getCreateSource()); des.setCreateSubject(stem.getCreateSubject().getId()); des.setCreateTime(stem.getCreateTime().getTime()); des.setDescription(stem.getDescription()); des.setDisplayExtension(stem.getDisplayExtension()); des.setDisplayName(stem.getDisplayName()); des.setExtension(stem.getExtension()); des.setModifySource(stem.getModifySource()); try { des.setModifySubject(stem.getModifySubject().getId()); } catch (Exception ex) { if (ex.getMessage().indexOf("has not been modified") != -1) { des.setModifySubject(""); } else { throw ex; } } des.setModifyTime(stem.getModifyTime().getTime()); des.setName(stem.getName()); des.setUUID(stem.getUuid()); return des; } public void deleteMember(String gridIdentity, GroupIdentifier group, String member) throws RemoteException, GridGrouperRuntimeFault, InsufficientPrivilegeFault, GroupNotFoundFault, MemberDeleteFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); Group grp = GroupFinder.findByName(session, group.getGroupName()); grp.deleteMember(SubjectFinder.findById(member)); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (MemberDeleteException e) { MemberDeleteFault fault = new MemberDeleteFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (MemberDeleteFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred deleting the member " + member + " from the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupDescriptor addCompositeMember(String gridIdentity, GroupCompositeType type, GroupIdentifier composite, GroupIdentifier left, GroupIdentifier right) throws GridGrouperRuntimeFault, GroupNotFoundFault, MemberAddFault, InsufficientPrivilegeFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); Group grp = GroupFinder.findByName(session, composite.getGroupName()); Group leftgrp = GroupFinder.findByName(session, left.getGroupName()); Group rightgrp = GroupFinder.findByName(session, right.getGroupName()); CompositeType ct = null; if (type.equals(GroupCompositeType.Union)) { ct = CompositeType.UNION; } else if (type.equals(GroupCompositeType.Intersection)) { ct = CompositeType.INTERSECTION; } else if (type.equals(GroupCompositeType.Complement)) { ct = CompositeType.COMPLEMENT; } else { throw new Exception("The composite type " + type.getValue() + " is not supported!!!"); } grp.addCompositeMember(ct, leftgrp, rightgrp); return grouptoGroupDescriptor(grp); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (MemberAddException e) { MemberAddFault fault = new MemberAddFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (MemberAddFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred adding a composite member to the group " + composite.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupDescriptor deleteCompositeMember(String gridIdentity, GroupIdentifier group) throws GridGrouperRuntimeFault, GroupNotFoundFault, InsufficientPrivilegeFault, MemberDeleteFault { GrouperSession session = null; try { Subject caller = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(caller); Group grp = GroupFinder.findByName(session, group.getGroupName()); grp.deleteCompositeMember(); return grouptoGroupDescriptor(grp); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (MemberDeleteException e) { MemberDeleteFault fault = new MemberDeleteFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (MemberDeleteFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred deleting the composite member from the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void grantGroupPrivilege(String gridIdentity, GroupIdentifier group, String subject, GroupPrivilegeType privilege) throws GridGrouperRuntimeFault, GroupNotFoundFault, GrantPrivilegeFault, InsufficientPrivilegeFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Group grp = GroupFinder.findByName(session, group.getGroupName()); grp.grantPriv(SubjectFinder.findById(subject), Privilege.getInstance(privilege.getValue())); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (GrantPrivilegeException e) { GrantPrivilegeFault fault = new GrantPrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GrantPrivilegeFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to manages privileges on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred granting a privilege for the subject " + subject + " on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public void revokeGroupPrivilege(String gridIdentity, GroupIdentifier group, String subject, GroupPrivilegeType privilege) throws RemoteException, GridGrouperRuntimeFault, GroupNotFoundFault, RevokePrivilegeFault, InsufficientPrivilegeFault, SchemaFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Group grp = GroupFinder.findByName(session, group.getGroupName()); grp.revokePriv(SubjectFinder.findById(subject), Privilege.getInstance(privilege.getValue())); } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (RevokePrivilegeException e) { RevokePrivilegeFault fault = new RevokePrivilegeFault(); fault.setFaultString(e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (RevokePrivilegeFault) helper.getFault(); throw fault; } catch (InsufficientPrivilegeException e) { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have the right to manages privileges on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (InsufficientPrivilegeFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred revoking a privilege for the subject " + subject + " on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public String[] getSubjectsWithGroupPrivilege(String gridIdentity, GroupIdentifier group, GroupPrivilegeType privilege) throws RemoteException, GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject subject = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subject); Group grp = GroupFinder.findByName(session, group.getGroupName()); Set subs = null; if (privilege.equals(GroupPrivilegeType.admin)) { subs = grp.getAdmins(); } else if (privilege.equals(GroupPrivilegeType.optin)) { subs = grp.getOptins(); } else if (privilege.equals(GroupPrivilegeType.optout)) { subs = grp.getOptouts(); } else if (privilege.equals(GroupPrivilegeType.read)) { subs = grp.getReaders(); } else if (privilege.equals(GroupPrivilegeType.update)) { subs = grp.getUpdaters(); } else if (privilege.equals(GroupPrivilegeType.view)) { subs = grp.getViewers(); } else { throw new Exception(privilege.getValue() + " is not a valid group privilege!!!"); } int size = 0; if (subs != null) { size = subs.size(); } String[] subjects = new String[size]; if (subs != null) { Iterator itr = subs.iterator(); int count = 0; while (itr.hasNext()) { Subject s = (Subject) itr.next(); subjects[count] = s.getId(); count++; } } return subjects; } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the subjects with the privilege " + privilege.getValue() + " on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupPrivilege[] getGroupPrivileges(String gridIdentity, GroupIdentifier group, String subject) throws GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Group grp = GroupFinder.findByName(session, group.getGroupName()); Set privs = grp.getPrivs(SubjectFinder.findById(subject)); int size = 0; if (privs != null) { size = privs.size(); } GroupPrivilege[] rights = new GroupPrivilege[size]; if (privs != null) { Iterator itr = privs.iterator(); int count = 0; while (itr.hasNext()) { AccessPrivilege p = (AccessPrivilege) itr.next(); rights[count] = new GroupPrivilege(); rights[count].setGroupName(p.getGroup().getName()); rights[count].setImplementationClass(p.getImplementationName()); rights[count].setIsRevokable(p.isRevokable()); rights[count].setOwner(p.getOwner().getId()); rights[count].setPrivilegeType(GroupPrivilegeType.fromValue(p.getName())); rights[count].setSubject(p.getSubject().getId()); count++; } } return rights; } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error occurred getting the privileges for the subject " + subject + " on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public boolean hasGroupPrivilege(String gridIdentity, GroupIdentifier group, String subject, GroupPrivilegeType privilege) throws GridGrouperRuntimeFault, GroupNotFoundFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Group target = GroupFinder.findByName(session, group.getGroupName()); if (privilege == null) { return false; } else if (privilege.equals(GroupPrivilegeType.admin)) { return target.hasAdmin(SubjectFinder.findById(subject)); } else if (privilege.equals(GroupPrivilegeType.optin)) { return target.hasOptin(SubjectFinder.findById(subject)); } else if (privilege.equals(GroupPrivilegeType.optout)) { return target.hasOptout(SubjectFinder.findById(subject)); } else if (privilege.equals(GroupPrivilegeType.read)) { return target.hasRead(SubjectFinder.findById(subject)); } else if (privilege.equals(GroupPrivilegeType.update)) { return target.hasUpdate(SubjectFinder.findById(subject)); } else if (privilege.equals(GroupPrivilegeType.view)) { return target.hasView(SubjectFinder.findById(subject)); } else { return false; } } catch (GroupNotFoundException e) { GroupNotFoundFault fault = new GroupNotFoundFault(); fault.setFaultString("The group, " + group.getGroupName() + "was not found."); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GroupNotFoundFault) helper.getFault(); throw fault; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error determing if the subject " + subject + " has the privilege " + privilege.getValue() + " on the group " + group.getGroupName() + ": " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } private void validateMemberAccess(String caller, String member) throws SubjectNotFoundException, InsufficientPrivilegeFault { if ((caller.equals(member)) || (getAdminGroup().hasMember(SubjectUtils.getSubject(caller)))) { return; } else { InsufficientPrivilegeFault fault = new InsufficientPrivilegeFault(); fault.setFaultString("You do not have access to the member " + member + "."); throw fault; } } public MemberDescriptor getMember(String gridIdentity, String memberIdentity) throws GridGrouperRuntimeFault, InsufficientPrivilegeFault { GrouperSession session = null; try { validateMemberAccess(gridIdentity, memberIdentity); Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Member m = MemberFinder.findBySubject(session, SubjectUtils.getSubject(memberIdentity)); return memberToMemberDescriptor(m); // TODO: We may need to also throw a member not found fault } catch (InsufficientPrivilegeFault e) { throw e; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error finding the member " + memberIdentity + ":\n" + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public GroupDescriptor[] getMembersGroups(String gridIdentity, String memberIdentity, MembershipType type) throws GridGrouperRuntimeFault, InsufficientPrivilegeFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); Member m = MemberFinder.findBySubject(session, SubjectUtils.getSubject(memberIdentity)); Set<?> set = null; if ((type != null) && (type.equals(MembershipType.EffectiveMembers))) { set = m.getEffectiveGroups(); } else if ((type != null) && (type.equals(MembershipType.ImmediateMembers))) { set = m.getImmediateGroups(); } else { set = m.getGroups(); } Iterator<?> itr = set.iterator(); ArrayList<GroupDescriptor> groups = new ArrayList<GroupDescriptor>(); while (itr.hasNext()) { Group group = (Group) itr.next(); if (group.hasRead(subj) || gridIdentity.equals(memberIdentity) || (getAdminGroup().hasMember(subj))) { groups.add(grouptoGroupDescriptor(group)); } } GroupDescriptor[] grps = groups.toArray(new GroupDescriptor[groups.size()]); return grps; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error finding the member " + memberIdentity + ":\n" + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } public boolean isMember(String gridIdentity, String member, MembershipExpression exp) throws GridGrouperRuntimeFault { GrouperSession session = null; try { Subject subj = SubjectFinder.findById(gridIdentity); session = GrouperSession.start(subj); return isMember(session, member, exp); } catch (GridGrouperRuntimeFault f) { throw f; } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error determing if the subject " + member + " is a member: " + e.getMessage()); FaultHelper helper = new FaultHelper(fault); helper.addFaultCause(e); fault = (GridGrouperRuntimeFault) helper.getFault(); throw fault; } finally { if (session != null) { try { session.stop(); } catch (Exception e) { this.log.error(e.getMessage(), e); } } } } private boolean isMember(GrouperSession session, String member, MembershipExpression exp) throws GridGrouperRuntimeFault { if (exp.getLogicRelation().equals(LogicalOperator.AND)) { return evaluateAndExpression(session, member, exp); } else { return evaluateOrExpression(session, member, exp); } } private boolean evaluateAndExpression(GrouperSession session, String member, MembershipExpression exp) throws GridGrouperRuntimeFault { MembershipExpression[] exps = exp.getMembershipExpression(); MembershipQuery[] queries = exp.getMembershipQuery(); if ((exps == null) && (queries == null)) { GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Invalid Expression"); throw fault; } if (exps != null) { for (int i = 0; i < exps.length; i++) { if (!isMember(session, member, exps[i])) { return false; } } } if (queries != null) { for (int i = 0; i < queries.length; i++) { String grpName = queries[i].getGroupIdentifier().getGroupName(); try { Group grp = GroupFinder.findByName(session, grpName); boolean isMember = grp.hasMember(SubjectFinder.findById(member)); if (queries[i].getMembershipStatus().equals(MembershipStatus.NOT_MEMBER_OF)) { if (isMember) { return false; } } else { if (!isMember) { return false; } } } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error in determining if the subject " + member + " is a member of the group " + grpName + ": " + e.getMessage()); throw fault; } } } return true; } private boolean evaluateOrExpression(GrouperSession session, String member, MembershipExpression exp) throws GridGrouperRuntimeFault { MembershipExpression[] exps = exp.getMembershipExpression(); MembershipQuery[] queries = exp.getMembershipQuery(); if ((exps == null) && (queries == null)) { GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Invalid Expression"); throw fault; } if (exps != null) { for (int i = 0; i < exps.length; i++) { if (isMember(session, member, exps[i])) { return true; } } } if (queries != null) { for (int i = 0; i < queries.length; i++) { String grpName = queries[i].getGroupIdentifier().getGroupName(); try { Group grp = GroupFinder.findByName(session, grpName); boolean isMember = grp.hasMember(SubjectFinder.findById(member)); if (queries[i].getMembershipStatus().equals(MembershipStatus.NOT_MEMBER_OF)) { if (!isMember) { return true; } } else { if (isMember) { return true; } } } catch (Exception e) { this.log.error(e.getMessage(), e); GridGrouperRuntimeFault fault = new GridGrouperRuntimeFault(); fault.setFaultString("Error in determining if the subject " + member + " is a member of the group " + grpName + ": " + e.getMessage()); throw fault; } } } return false; } }
package cane.brothers.e4.commander.handlers; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.core.di.extensions.Preference; import org.eclipse.e4.ui.model.application.MApplication; import org.eclipse.e4.ui.model.application.ui.MUIElement; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.e4.ui.model.application.ui.basic.MPartStack; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.e4.ui.workbench.modeling.EModelService; import org.eclipse.e4.ui.workbench.modeling.EPartService; import org.eclipse.e4.ui.workbench.modeling.EPartService.PartState; import cane.brothers.e4.commander.IdStorage; import cane.brothers.e4.commander.preferences.PreferenceConstants; import cane.brothers.e4.commander.utils.PartUtils; import cane.brothers.e4.commander.utils.PathUtils; /** * Copy tab to other panel using PartDescriptor. * * @see PartDescriptor */ public class CopyPartHandler { @Inject EModelService modelService; @Inject MApplication application; @Inject EPartService partService; @SuppressWarnings("restriction") @Inject @Preference(PreferenceConstants.PB_STAY_ACTIVE_TAB) boolean stayActiveTab; @Execute public void execute(@Named(IServiceConstants.ACTIVE_PART) MPart activePart) { System.out.println((this.getClass().getSimpleName() + " called")); //$NON-NLS-1$ MPart newPart = partService .createPart(IdStorage.DYNAMIC_PART_DESCRIPTOR_ID); newPart = copyPart(newPart, activePart); String oppositePanelId = PartUtils.getPanelId(activePart, true); MUIElement oppositePanel = modelService.find(oppositePanelId, application); if (oppositePanel instanceof MPartStack) { MPartStack stack = (MPartStack) oppositePanel; stack.getChildren().add(newPart); } partService.showPart(newPart, PartState.VISIBLE); // The current tab will stay active partService.showPart(stayActiveTab ? activePart : newPart, PartState.ACTIVATE); } private MPart copyPart(MPart newPart, MPart part) { if (part != null) { Map<String, String> state = part.getPersistedState(); Path rootPath = Paths.get(state.get("rootPath")); newPart.setLabel(PathUtils.getFileName(rootPath)); newPart.setElementId(PartUtils.createElementId()); // NB! copy also "active" tag newPart.getTags().addAll(part.getTags()); } return newPart; } }
package com.intellij.ui; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.NotNullProducer; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.StartupUiUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; import java.util.HashMap; import java.util.Map; import static com.intellij.util.ObjectUtils.notNull; /** * @author Konstantin Bulenkov */ @SuppressWarnings("UseJBColor") public class JBColor extends Color { public static final Color PanelBackground = namedColor("Panel.background", 0xffffff); private static final class Lazy { private static volatile boolean DARK = StartupUiUtil.isUnderDarcula(); } private final Color darkColor; private final NotNullProducer<? extends Color> func; public JBColor(int rgb, int darkRGB) { this(new Color(rgb), new Color(darkRGB)); } public JBColor(@NotNull Color regular, @NotNull Color dark) { super(regular.getRGB(), regular.getAlpha() != 255); darkColor = dark; func = null; } public JBColor(@NotNull NotNullProducer<? extends Color> function) { super(0); darkColor = null; func = function; } @NotNull public static JBColor namedColor(@NonNls @NotNull String propertyName, int defaultValueRGB) { return namedColor(propertyName, new Color(defaultValueRGB)); } @NotNull public static JBColor namedColor(@NonNls @NotNull String propertyName, int defaultValueRGB, int darkValueRGB) { return namedColor(propertyName, new JBColor(defaultValueRGB, darkValueRGB)); } @NotNull public static JBColor namedColor(@NonNls @NotNull final String propertyName, @NotNull final Color defaultColor) { return new JBColor(() -> { Color color = notNull(UIManager.getColor(propertyName), () -> notNull(findPatternMatch(propertyName), defaultColor)); if (UIManager.get(propertyName) == null) { if (Registry.is("ide.save.missing.jb.colors", false)) { return _saveAndReturnColor(propertyName, color); } } return color; }); } // Let's find if namedColor can be overridden by *.propertyName rule in ui theme and apply it // We need to cache calculated results. Cache and rules will be reset after LaF change private static Color findPatternMatch(@NotNull String name) { Object value = UIManager.get("*"); if (value instanceof Map) { Map<?, ?> map = (Map<?, ?>)value; Object o = UIManager.get("*cache"); if (!(o instanceof Map)) { o = new HashMap<String, Color>(); UIManager.put("*cache", o); } @SuppressWarnings("unchecked") Map<String, Color> cache = (Map)o; if (cache.containsKey(name)) { return cache.get(name); } Color color = null; for (Map.Entry<?, ?> entry : map.entrySet()) { if (entry.getKey() instanceof String && name.endsWith((String)entry.getKey())) { Object result = map.get(entry.getKey()); if (result instanceof Color) { color = (Color)result; break; } } } cache.put(name, color); return color; } return null; } /** * @deprecated use {@link JBUI.CurrentTheme.Link.Foreground#ENABLED} */ @NotNull @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") public static Color link() { //noinspection UnnecessaryFullyQualifiedName return com.intellij.util.ui.JBUI.CurrentTheme.Link.Foreground.ENABLED; } public static void setDark(boolean dark) { Lazy.DARK = dark; } public static boolean isBright() { return !Lazy.DARK; } @ApiStatus.Internal //For CodeWithMe only public Color getDarkVariant() { return darkColor; } @NotNull Color getColor() { return func != null ? func.produce() : Lazy.DARK ? getDarkVariant() : this; } @Override public int getRed() { final Color c = getColor(); return c == this ? super.getRed() : c.getRed(); } @Override public int getGreen() { final Color c = getColor(); return c == this ? super.getGreen() : c.getGreen(); } @Override public int getBlue() { final Color c = getColor(); return c == this ? super.getBlue() : c.getBlue(); } @Override public int getAlpha() { final Color c = getColor(); return c == this ? super.getAlpha() : c.getAlpha(); } @Override public int getRGB() { final Color c = getColor(); return c == this ? super.getRGB() : c.getRGB(); } @Override @NotNull public Color brighter() { if (func != null) { return new JBColor(() -> func.produce().brighter()); } return new JBColor(super.brighter(), getDarkVariant().brighter()); } @Override @NotNull public Color darker() { if (func != null) { return new JBColor(() -> func.produce().darker()); } return new JBColor(super.darker(), getDarkVariant().darker()); } @Override public int hashCode() { final Color c = getColor(); return c == this ? super.hashCode() : c.hashCode(); } @Override public boolean equals(Object obj) { final Color c = getColor(); return c == this ? super.equals(obj) : c.equals(obj); } @Override public String toString() { final Color c = getColor(); return c == this ? super.toString() : c.toString(); } @Override public float @NotNull [] getRGBComponents(float[] compArray) { final Color c = getColor(); return c == this ? super.getRGBComponents(compArray) : c.getRGBComponents(compArray); } @Override public float @NotNull [] getRGBColorComponents(float[] compArray) { final Color c = getColor(); return c == this ? super.getRGBComponents(compArray) : c.getRGBColorComponents(compArray); } @Override public float @NotNull [] getComponents(float[] compArray) { final Color c = getColor(); return c == this ? super.getComponents(compArray) : c.getComponents(compArray); } @Override public float @NotNull [] getColorComponents(float[] compArray) { final Color c = getColor(); return c == this ? super.getColorComponents(compArray) : c.getColorComponents(compArray); } @Override public float @NotNull [] getComponents(@NotNull ColorSpace colorSpace, float[] compArray) { final Color c = getColor(); return c == this ? super.getComponents(colorSpace, compArray) : c.getComponents(colorSpace, compArray); } @Override public float @NotNull [] getColorComponents(@NotNull ColorSpace colorSpace, float[] compArray) { final Color c = getColor(); return c == this ? super.getColorComponents(colorSpace, compArray) : c.getColorComponents(colorSpace, compArray); } @Override @NotNull public ColorSpace getColorSpace() { final Color c = getColor(); return c == this ? super.getColorSpace() : c.getColorSpace(); } @Override @NotNull public synchronized PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform affineTransform, RenderingHints hints) { final Color c = getColor(); return c == this ? super.createContext(cm, r, r2d, affineTransform, hints) : c.createContext(cm, r, r2d, affineTransform, hints); } @Override public int getTransparency() { final Color c = getColor(); return c == this ? super.getTransparency() : c.getTransparency(); } public static final JBColor red = new JBColor(Color.red, DarculaColors.RED); public static final JBColor RED = red; public static final JBColor blue = new JBColor(Color.blue, DarculaColors.BLUE); public static final JBColor BLUE = blue; public static final JBColor white = new JBColor(Color.white, background()); public static final JBColor WHITE = white; public static final JBColor black = new JBColor(Color.black, foreground()); public static final JBColor BLACK = black; public static final JBColor gray = new JBColor(Gray._128, Gray._128); public static final JBColor GRAY = gray; public static final JBColor lightGray = new JBColor(Gray._192, Gray._64); public static final JBColor LIGHT_GRAY = lightGray; public static final JBColor darkGray = new JBColor(Gray._64, Gray._192); public static final JBColor DARK_GRAY = darkGray; public static final JBColor pink = new JBColor(Color.pink, Color.pink); public static final JBColor PINK = pink; public static final JBColor orange = new JBColor(Color.orange, new Color(159, 107, 0)); public static final JBColor ORANGE = orange; public static final JBColor yellow = new JBColor(Color.yellow, new Color(138, 138, 0)); public static final JBColor YELLOW = yellow; public static final JBColor green = new JBColor(Color.green, new Color(98, 150, 85)); public static final JBColor GREEN = green; public static final Color magenta = new JBColor(Color.magenta, new Color(151, 118, 169)); public static final Color MAGENTA = magenta; public static final Color cyan = new JBColor(Color.cyan, new Color(0, 137, 137)); public static final Color CYAN = cyan; @NotNull public static Color foreground() { return new JBColor(UIUtil::getLabelForeground); } @NotNull public static Color background() { return new JBColor(UIUtil::getListBackground); } @NotNull public static Color border() { return namedColor("Borders.color", new JBColor(Gray._192, Gray._50)); } private static final Map<String, Color> defaultThemeColors = new HashMap<>(); @NotNull public static Color get(@NotNull final String colorId, @NotNull final Color defaultColor) { return new JBColor(() -> { Color color = defaultThemeColors.get(colorId); if (color != null) { return color; } defaultThemeColors.put(colorId, defaultColor); return defaultColor; }); } private static void saveMissingColorInUIDefaults(String propertyName, Color color) { if (Registry.is("ide.save.missing.jb.colors", false)) { String key = propertyName + "!!!"; if (UIManager.get(key) == null) { UIManager.put(key, color); } } } @ApiStatus.Internal private static Color _saveAndReturnColor(@NonNls @NotNull String propertyName, Color color) { String key = propertyName + "!!!"; Object saved = UIManager.get(key); if (saved instanceof Color) { //in case a designer changed the key return (Color)saved; } UIManager.put(key, color); return color; } }
package com.dianping.cat.report.task.alert.heartbeat; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.unidal.helper.Threads.Task; import org.unidal.lookup.annotation.Inject; import org.unidal.tuple.Pair; import com.dianping.cat.Cat; import com.dianping.cat.Constants; import com.dianping.cat.consumer.heartbeat.HeartbeatAnalyzer; import com.dianping.cat.consumer.heartbeat.model.entity.HeartbeatReport; import com.dianping.cat.consumer.heartbeat.model.entity.Machine; import com.dianping.cat.consumer.heartbeat.model.entity.Period; import com.dianping.cat.consumer.transaction.TransactionAnalyzer; import com.dianping.cat.consumer.transaction.model.entity.TransactionReport; import com.dianping.cat.helper.TimeHelper; import com.dianping.cat.home.rule.entity.Condition; import com.dianping.cat.home.rule.entity.Config; import com.dianping.cat.message.Transaction; import com.dianping.cat.report.page.model.spi.ModelService; import com.dianping.cat.report.task.alert.AlertResultEntity; import com.dianping.cat.report.task.alert.AlertType; import com.dianping.cat.report.task.alert.BaseAlert; import com.dianping.cat.report.task.alert.sender.AlertEntity; import com.dianping.cat.service.ModelRequest; import com.dianping.cat.service.ModelResponse; public class HeartbeatAlert extends BaseAlert implements Task { @Inject(type = ModelService.class, value = HeartbeatAnalyzer.ID) private ModelService<HeartbeatReport> m_service; @Inject(type = ModelService.class, value = TransactionAnalyzer.ID) private ModelService<TransactionReport> m_transactionService; private static final String[] m_metrics = { "ThreadCount", "DaemonCount", "TotalStartedCount", "CatThreadCount", "PiegonThreadCount", "HttpThreadCount", "NewGcCount", "OldGcCount", "MemoryFree", "HeapUsage", "NoneHeapUsage", "SystemLoadAverage", "CatMessageOverflow", "CatMessageSize" }; private void buildArray(Map<String, double[]> map, int index, String name, double value) { double[] array = map.get(name); if (array == null) { array = new double[60]; map.put(name, array); } array[index] = value; } private void convertToDeltaArray(Map<String, double[]> map, String name) { double[] sources = map.get(name); double[] targets = new double[60]; for (int i = 1; i < 60; i++) { if (sources[i - 1] > 0) { double delta = sources[i] - sources[i - 1]; if (delta >= 0) { targets[i] = delta; } } } map.put(name, targets); } private double[] extract(double[] lastHourValues, double[] currentHourValues, int maxMinute, int alreadyMinute) { int lastLength = maxMinute - alreadyMinute - 1; double[] result = new double[maxMinute]; for (int i = 0; i < lastLength; i++) { result[i] = lastHourValues[60 - lastLength + i]; } for (int i = lastLength; i < maxMinute; i++) { result[i] = currentHourValues[i - lastLength]; } return result; } private double[] extract(double[] values, int maxMinute, int alreadyMinute) { double[] result = new double[maxMinute]; for (int i = 0; i < maxMinute; i++) { result[i] = values[alreadyMinute + 1 - maxMinute + i]; } return result; } private Map<String, double[]> generateArgumentMap(Machine machine) { Map<String, double[]> map = new HashMap<String, double[]>(); List<Period> periods = machine.getPeriods(); for (int index = 0; index < periods.size(); index++) { Period period = periods.get(index); buildArray(map, index, "ThreadCount", period.getThreadCount()); buildArray(map, index, "DaemonCount", period.getDaemonCount()); buildArray(map, index, "TotalStartedCount", period.getTotalStartedCount()); buildArray(map, index, "CatThreadCount", period.getCatThreadCount()); buildArray(map, index, "PiegonThreadCount", period.getPigeonThreadCount()); buildArray(map, index, "HttpThreadCount", period.getHttpThreadCount()); buildArray(map, index, "NewGcCount", period.getNewGcCount()); buildArray(map, index, "OldGcCount", period.getOldGcCount()); buildArray(map, index, "MemoryFree", period.getMemoryFree()); buildArray(map, index, "HeapUsage", period.getHeapUsage()); buildArray(map, index, "NoneHeapUsage", period.getNoneHeapUsage()); buildArray(map, index, "SystemLoadAverage", period.getSystemLoadAverage()); buildArray(map, index, "CatMessageOverflow", period.getCatMessageOverflow()); buildArray(map, index, "CatMessageSize", period.getCatMessageSize()); } convertToDeltaArray(map, "TotalStartedCount"); convertToDeltaArray(map, "NewGcCount"); convertToDeltaArray(map, "OldGcCount"); convertToDeltaArray(map, "CatMessageSize"); convertToDeltaArray(map, "CatMessageOverflow"); return map; } private HeartbeatReport generateReport(String domain, long date) { ModelRequest request = new ModelRequest(domain, date) .setProperty("ip", Constants.ALL); if (m_service.isEligable(request)) { ModelResponse<HeartbeatReport> response = m_service.invoke(request); return response.getModel(); } else { throw new RuntimeException("Internal error: no eligable ip service registered for " + request + "!"); } } @Override public String getName() { return AlertType.HeartBeat.getName(); } private void processDomain(String domain) { List<Config> configs = m_ruleConfigManager.queryConfigsByGroup(domain); int minute = getAlreadyMinute(); int maxMinute = queryCheckMinuteAndConditions(configs).getKey(); if (minute >= maxMinute - 1) { long currentMill = System.currentTimeMillis(); long currentHourMill = currentMill - currentMill % TimeHelper.ONE_HOUR; HeartbeatReport currentReport = generateReport(domain, currentHourMill); for (Machine machine : currentReport.getMachines().values()) { String ip = machine.getIp(); Map<String, double[]> arguments = generateArgumentMap(machine); for (String metric : m_metrics) { double[] values = extract(arguments.get(metric), maxMinute, minute); processMeitrc(domain, ip, metric, values); } } } else if (minute < 0) { long currentMill = System.currentTimeMillis(); long lastHourMill = currentMill - currentMill % TimeHelper.ONE_HOUR - TimeHelper.ONE_HOUR; HeartbeatReport lastReport = generateReport(domain, lastHourMill); for (Machine machine : lastReport.getMachines().values()) { String ip = machine.getIp(); Map<String, double[]> arguments = generateArgumentMap(machine); for (String metric : m_metrics) { double[] values = extract(arguments.get(metric), maxMinute, 59); processMeitrc(domain, ip, metric, values); } } } else { long currentMill = System.currentTimeMillis(); long currentHourMill = currentMill - currentMill % TimeHelper.ONE_HOUR; long lastHourMill = currentHourMill - TimeHelper.ONE_HOUR; HeartbeatReport currentReport = generateReport(domain, currentHourMill); HeartbeatReport lastReport = generateReport(domain, lastHourMill); for (Machine lastMachine : lastReport.getMachines().values()) { String ip = lastMachine.getIp(); Machine currentMachine = currentReport.getMachines().get(ip); if (currentMachine != null) { Map<String, double[]> lastHourArguments = generateArgumentMap(lastMachine); Map<String, double[]> currentHourArguments = generateArgumentMap(currentMachine); for (String metric : m_metrics) { double[] values = extract(lastHourArguments.get(metric), currentHourArguments.get(metric), maxMinute, minute); processMeitrc(domain, ip, metric, values); } } } } } private void processMeitrc(String domain, String ip, String metric, double[] values) { try { List<Config> configs = m_ruleConfigManager.queryConfigs(domain, metric); Pair<Integer, List<Condition>> resultPair = queryCheckMinuteAndConditions(configs); int maxMinute = resultPair.getKey(); List<Condition> conditions = resultPair.getValue(); double[] baseline = new double[maxMinute]; List<AlertResultEntity> alerts = m_dataChecker.checkData(values, baseline, conditions); for (AlertResultEntity alertResult : alerts) { AlertEntity entity = new AlertEntity(); entity.setDate(alertResult.getAlertTime()).setContent(alertResult.getContent()) .setLevel(alertResult.getAlertLevel()); entity.setMetric(metric).setType(getName()).setGroup(domain); entity.getParas().put("ip", ip); m_sendManager.addAlert(entity); } } catch (Exception e) { Cat.logError(e); } } private Set<String> queryDomains() { Set<String> domains = new HashSet<String>(); ModelRequest request = new ModelRequest("cat", System.currentTimeMillis()); if (m_transactionService.isEligable(request)) { ModelResponse<TransactionReport> response = m_transactionService.invoke(request); domains.addAll(response.getModel().getDomainNames()); } return domains; } @Override public void run() { boolean active = true; try { Thread.sleep(5000); } catch (InterruptedException e) { active = false; } while (active) { Transaction t = Cat.newTransaction("AlertHeartbeat", TimeHelper.getMinuteStr()); long current = System.currentTimeMillis(); try { Set<String> domains = queryDomains(); for (String domain : domains) { try { processDomain(domain); } catch (Exception e) { Cat.logError(e); } } t.setStatus(Transaction.SUCCESS); } catch (Exception e) { t.setStatus(e); } finally { t.complete(); } long duration = System.currentTimeMillis() - current; try { if (duration < DURATION) { Thread.sleep(DURATION - duration); } } catch (InterruptedException e) { active = false; } } } @Override public void shutdown() { } }
package fr.unice.polytech.al.trafficlight.central.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; public class WebRequester { /** * URLs files configurations location. */ public static final Path URLS_FILE_DIR = Paths.get("./resources/urls/"); /** * JSON serializer/deserializer. */ private static Gson gson = new GsonBuilder().create(); /** * URLs configuration. */ private Properties urlsConfig = new Properties(); /** * URL base path. */ private String urlPath; /** * Instantiates a new web requester. */ public WebRequester(String urlType, String urlPath) { try { // Load the configuration file with URLs this.loadUrls(URLS_FILE_DIR.resolve(urlType)); } catch (IOException e) { e.printStackTrace(); } this.urlPath = urlPath; } /** * Loads URLs configuration from specified configuration path. * * @param urlsConfigPath path to configuration file * @throws IOException if IO error occurs */ public void loadUrls(Path urlsConfigPath) throws IOException { try (InputStream fis = getClass().getClassLoader() .getResourceAsStream(urlsConfigPath.toString())) { // Load properties urlsConfig.load(fis); } } /** * Creates a web target for the specified crossroad. * * @param crossroad the crossroad * @param path the path * @return the web target */ public WebTarget target(String crossroad, String path) { // Get URLs of the crossroad String url = this.urlsConfig.getProperty(crossroad); if (url == null) { throw new RuntimeException("Specified crossroad doesn't exists in configuration file."); } // Create target return ClientBuilder.newClient() .target(this.urlsConfig.getProperty(crossroad)) .path(this.urlPath + path); } /** * Puts a request for the specified crossroad, at the specified path. * * @param crossroad the crossroad * @param path the path * @param entity the entity * @return the response */ public Response put(String crossroad, String path, Object entity) { // Convert entity to JSON Entity requestEntity = Entity.entity(gson.toJson(entity), MediaType.APPLICATION_JSON); // Call the target path return target(crossroad, path) .request(MediaType.APPLICATION_JSON) .put(requestEntity, Response.class); } // @TODO GET/POST/DELETE if needed }
package org.eclipse.birt.chart.render; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Enumeration; import java.util.Map; import org.eclipse.birt.chart.computation.BoundingBox; import org.eclipse.birt.chart.computation.DataSetIterator; import org.eclipse.birt.chart.computation.Engine3D; import org.eclipse.birt.chart.computation.IConstants; import org.eclipse.birt.chart.computation.Methods; import org.eclipse.birt.chart.computation.ValueFormatter; import org.eclipse.birt.chart.computation.withaxes.AllAxes; import org.eclipse.birt.chart.computation.withaxes.AutoScale; import org.eclipse.birt.chart.computation.withaxes.Grid; import org.eclipse.birt.chart.computation.withaxes.IntersectionValue; import org.eclipse.birt.chart.computation.withaxes.OneAxis; import org.eclipse.birt.chart.computation.withaxes.PlotWith2DAxes; import org.eclipse.birt.chart.computation.withaxes.PlotWith3DAxes; import org.eclipse.birt.chart.computation.withaxes.PlotWithAxes; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IDisplayServer; import org.eclipse.birt.chart.device.IPrimitiveRenderer; import org.eclipse.birt.chart.device.IStructureDefinitionListener; import org.eclipse.birt.chart.device.ITextMetrics; import org.eclipse.birt.chart.engine.i18n.Messages; import org.eclipse.birt.chart.event.BlockGenerationEvent; import org.eclipse.birt.chart.event.EventObjectCache; import org.eclipse.birt.chart.event.InteractionEvent; import org.eclipse.birt.chart.event.Line3DRenderEvent; import org.eclipse.birt.chart.event.LineRenderEvent; import org.eclipse.birt.chart.event.Polygon3DRenderEvent; import org.eclipse.birt.chart.event.PolygonRenderEvent; import org.eclipse.birt.chart.event.PrimitiveRenderEvent; import org.eclipse.birt.chart.event.RectangleRenderEvent; import org.eclipse.birt.chart.event.StructureSource; import org.eclipse.birt.chart.event.Text3DRenderEvent; import org.eclipse.birt.chart.event.TextRenderEvent; import org.eclipse.birt.chart.event.TransformationEvent; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.factory.RunTimeContext; import org.eclipse.birt.chart.internal.factory.DateFormatWrapperFactory; import org.eclipse.birt.chart.internal.factory.IDateFormatWrapper; import org.eclipse.birt.chart.internal.model.FittingCalculator; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.attribute.Anchor; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.ChartDimension; import org.eclipse.birt.chart.model.attribute.ColorDefinition; import org.eclipse.birt.chart.model.attribute.FormatSpecifier; import org.eclipse.birt.chart.model.attribute.HorizontalAlignment; import org.eclipse.birt.chart.model.attribute.Insets; import org.eclipse.birt.chart.model.attribute.LineAttributes; import org.eclipse.birt.chart.model.attribute.Location; import org.eclipse.birt.chart.model.attribute.Location3D; import org.eclipse.birt.chart.model.attribute.Orientation; import org.eclipse.birt.chart.model.attribute.Position; import org.eclipse.birt.chart.model.attribute.TextAlignment; import org.eclipse.birt.chart.model.attribute.VerticalAlignment; import org.eclipse.birt.chart.model.attribute.impl.BoundsImpl; import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl; import org.eclipse.birt.chart.model.attribute.impl.Location3DImpl; import org.eclipse.birt.chart.model.attribute.impl.LocationImpl; import org.eclipse.birt.chart.model.attribute.impl.TextAlignmentImpl; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.CurveFitting; import org.eclipse.birt.chart.model.component.Label; import org.eclipse.birt.chart.model.component.MarkerLine; import org.eclipse.birt.chart.model.component.MarkerRange; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.component.impl.LabelImpl; import org.eclipse.birt.chart.model.data.DataElement; import org.eclipse.birt.chart.model.data.DateTimeDataElement; import org.eclipse.birt.chart.model.data.NumberDataElement; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.TextDataElement; import org.eclipse.birt.chart.model.data.Trigger; import org.eclipse.birt.chart.model.data.impl.NumberDataElementImpl; import org.eclipse.birt.chart.model.data.impl.TriggerImpl; import org.eclipse.birt.chart.model.layout.Block; import org.eclipse.birt.chart.model.layout.ClientArea; import org.eclipse.birt.chart.model.layout.LabelBlock; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.model.layout.Plot; import org.eclipse.birt.chart.model.layout.TitleBlock; import org.eclipse.birt.chart.plugin.ChartEnginePlugin; import org.eclipse.birt.chart.script.ScriptHandler; import org.eclipse.birt.chart.util.CDateTime; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.emf.common.util.EList; import com.ibm.icu.text.DecimalFormat; /** * Provides a base framework for custom series rendering extensions that are * interested in being rendered in a pre-computed plot containing axes. Series * type extensions could subclass this class to participate in the axes * rendering framework. */ public abstract class AxesRenderer extends BaseRenderer { private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.engine/render" ); //$NON-NLS-1$ private Axis ax; private boolean leftWallFill = false; private boolean rightWallFill = false; private boolean floorFill = false; /** * The constructor. */ public AxesRenderer( ) { super( ); } /** * Overridden behavior for graphic element series that are plotted along * axes * * @param bo */ public final void render( Map htRenderers, Bounds bo ) throws ChartException { final boolean bFirstInSequence = ( iSeriesIndex == 0 ); final boolean bLastInSequence = ( iSeriesIndex == iSeriesCount - 1 ); long lTimer = System.currentTimeMillis( ); final Chart cm = getModel( ); final IDeviceRenderer idr = getDevice( ); final ScriptHandler sh = getRunTimeContext( ).getScriptHandler( ); if ( bFirstInSequence ) // SEQUENCE OF MULTIPLE SERIES RENDERERS // (POSSIBLY PARTICIPATING IN A COMBINATION CHART) { // SETUP A TIMER lTimer = System.currentTimeMillis( ); htRenderers.put( TIMER, new Long( lTimer ) ); // RENDER THE CHART BY WALKING THROUGH THE RECURSIVE BLOCK STRUCTURE Block bl = cm.getBlock( ); final Enumeration e = bl.children( true ); final BlockGenerationEvent bge = new BlockGenerationEvent( bl ); // ALWAYS RENDER THE OUTERMOST BLOCK FIRST ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); bge.updateBlock( bl ); renderChartBlock( idr, bl, StructureSource.createChartBlock( bl ) ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); while ( e.hasMoreElements( ) ) { bl = (Block) e.nextElement( ); bge.updateBlock( bl ); if ( bl instanceof Plot ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderPlot( idr, (Plot) bl ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); if ( !bLastInSequence ) { // STOP AT THE PLOT IF NOT ALSO THE LAST IN THE // SEQUENCE break; } } else if ( bl instanceof TitleBlock ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderTitle( idr, (TitleBlock) bl ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else if ( bl instanceof LabelBlock ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderLabel( idr, bl, StructureSource.createUnknown( bl ) ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else if ( bl instanceof Legend ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderLegend( idr, (Legend) bl, htRenderers ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderBlock( idr, bl, StructureSource.createUnknown( bl ) ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } } } else if ( bLastInSequence ) { Block bl = cm.getBlock( ); final Enumeration e = bl.children( true ); final BlockGenerationEvent bge = new BlockGenerationEvent( this ); boolean bStarted = false; while ( e.hasMoreElements( ) ) { bl = (Block) e.nextElement( ); if ( !bStarted && !bl.isPlot( ) ) { continue; // IGNORE ALL BLOCKS UNTIL PLOT IS ENCOUNTERED } bStarted = true; bge.updateBlock( bl ); if ( bl instanceof Plot ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderPlot( idr, (Plot) bl ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else if ( bl instanceof TitleBlock ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderTitle( idr, (TitleBlock) bl ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else if ( bl instanceof LabelBlock ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderLabel( idr, bl, StructureSource.createUnknown( bl ) ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else if ( bl instanceof Legend ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderLegend( idr, (Legend) bl, htRenderers ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } else { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, bl ); renderBlock( idr, bl, StructureSource.createUnknown( bl ) ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, bl, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, bl ); } } } else { // FOR ALL SERIES IN-BETWEEN, ONLY RENDER THE PLOT final BlockGenerationEvent bge = new BlockGenerationEvent( this ); Plot p = cm.getPlot( ); bge.updateBlock( p ); ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_BLOCK, p, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_BLOCK, p ); renderPlot( idr, p ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_BLOCK, p, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_BLOCK, p ); } lTimer = System.currentTimeMillis( ) - lTimer; if ( htRenderers.containsKey( TIMER ) ) { final Long l = (Long) htRenderers.get( TIMER ); htRenderers.put( TIMER, new Long( l.longValue( ) + lTimer ) ); } else { htRenderers.put( TIMER, new Long( lTimer ) ); } if ( bLastInSequence ) { Object obj = getComputations( ); if ( obj instanceof PlotWith2DAxes ) { final PlotWith2DAxes pw2da = (PlotWith2DAxes) getComputations( ); pw2da.getStackedSeriesLookup( ).resetSubUnits( ); } logger.log( ILogger.INFORMATION, Messages.getString( "info.elapsed.render.time", //$NON-NLS-1$ new Object[]{ new Long( lTimer ) }, getRunTimeContext( ).getULocale( ) ) ); htRenderers.remove( TIMER ); } } private final int compare( DataElement de1, DataElement de2 ) throws ChartException { if ( de1 == null && de2 == null ) return IConstants.EQUAL; if ( de1 == null || de2 == null ) return IConstants.SOME_NULL; final Class c1 = de1.getClass( ); final Class c2 = de2.getClass( ); if ( c1.equals( c2 ) ) { if ( de1 instanceof NumberDataElement ) { return Double.compare( ( (NumberDataElement) de1 ).getValue( ), ( (NumberDataElement) de2 ).getValue( ) ); } else if ( de1 instanceof DateTimeDataElement ) { final long l1 = ( (DateTimeDataElement) de1 ).getValue( ); final long l2 = ( (DateTimeDataElement) de1 ).getValue( ); return ( l1 < l1 ? IConstants.LESS : ( l1 == l2 ? IConstants.EQUAL : IConstants.MORE ) ); } else if ( de1 instanceof TextDataElement ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.DATA_FORMAT, "exception.unsupported.compare.text", //$NON-NLS-1$ Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); } else { throw new ChartException( ChartEnginePlugin.ID, ChartException.DATA_FORMAT, "exception.unsupported.compare.unknown.objects", //$NON-NLS-1$ new Object[]{ de1, de2 }, Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); // i18n_CONCATENATIONS_REMOVED } } throw new ChartException( ChartEnginePlugin.ID, ChartException.DATA_FORMAT, "exception.unsupported.compare.different.objects", //$NON-NLS-1$ new Object[]{ de1, de2 }, Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); // i18n_CONCATENATIONS_REMOVED } private static final TextAlignment anchorToAlignment( Anchor anc ) { final TextAlignment ta = TextAlignmentImpl.create( ); // SET AS // CENTERED // HORZ/VERT if ( anc == null ) { return ta; } // SETUP VERTICAL ALIGNMENT switch ( anc.getValue( ) ) { case Anchor.NORTH : case Anchor.NORTH_EAST : case Anchor.NORTH_WEST : ta.setVerticalAlignment( VerticalAlignment.TOP_LITERAL ); break; case Anchor.SOUTH : case Anchor.SOUTH_EAST : case Anchor.SOUTH_WEST : ta.setVerticalAlignment( VerticalAlignment.BOTTOM_LITERAL ); break; default : ta.setVerticalAlignment( VerticalAlignment.CENTER_LITERAL ); } // SETUP HORIZONTAL ALIGNMENT switch ( anc.getValue( ) ) { case Anchor.EAST : case Anchor.NORTH_EAST : case Anchor.SOUTH_EAST : ta.setHorizontalAlignment( HorizontalAlignment.RIGHT_LITERAL ); break; case Anchor.WEST : case Anchor.NORTH_WEST : case Anchor.SOUTH_WEST : ta.setHorizontalAlignment( HorizontalAlignment.LEFT_LITERAL ); break; default : ta.setHorizontalAlignment( HorizontalAlignment.CENTER_LITERAL ); } return ta; } private void sort( double[] a, double[] b, final boolean sortFirstArray ) { double[][] sa = new double[a.length][2]; for ( int i = 0; i < a.length; i++ ) { double[] ca = new double[2]; ca[0] = a[i]; ca[1] = b[i]; sa[i] = ca; } Arrays.sort( sa, new Comparator( ) { public int compare( Object o1, Object o2 ) { double[] l1 = (double[]) o1; double[] l2 = (double[]) o2; if ( sortFirstArray ) { if ( l1[0] == l2[0] ) { return 0; } if ( l1[0] < l2[0] ) { return -1; } } else { if ( l1[1] == l2[1] ) { return 0; } if ( l1[1] < l2[1] ) { return -1; } } return 1; } } ); for ( int i = 0; i < a.length; i++ ) { a[i] = sa[i][0]; b[i] = sa[i][1]; } } /** * Renders the FittingCurve if defined for supported series. * * @param ipr * @param points * @param curve * @param bDeferred * @throws ChartException */ protected final void renderFittingCurve( IPrimitiveRenderer ipr, Location[] points, CurveFitting curve, boolean bShowAsTape, boolean bDeferred ) throws ChartException { if ( !curve.getLineAttributes( ).isSetVisible( ) ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, "exception.curve.line.visibility.not.defined", //$NON-NLS-1$ Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); } boolean isTransposed = ( (ChartWithAxes) getModel( ) ).isTransposed( ); if ( curve.getLineAttributes( ).isVisible( ) ) { ScriptHandler.callFunction( getRunTimeContext( ).getScriptHandler( ), ScriptHandler.BEFORE_DRAW_FITTING_CURVE, curve, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_FITTING_CURVE, curve ); // Render curve. double[] xArray = new double[points.length]; double[] yArray = new double[points.length]; for ( int i = 0; i < xArray.length; i++ ) { xArray[i] = points[i].getX( ); yArray[i] = points[i].getY( ); } sort( xArray, yArray, !isTransposed ); double[] baseArray = xArray, orthogonalArray = yArray; if ( isTransposed ) { baseArray = yArray; orthogonalArray = xArray; } FittingCalculator fc = new FittingCalculator( baseArray, orthogonalArray, 0.33 ); double[] fitYarray = fc.getFittedValue( ); orthogonalArray = fitYarray; if ( isTransposed ) { baseArray = fitYarray; orthogonalArray = yArray; sort( baseArray, orthogonalArray, false ); } if ( curve.getLineAttributes( ).getColor( ) != null ) { CurveRenderer crdr = new CurveRenderer( (ChartWithAxes) getModel( ), this, curve.getLineAttributes( ), LocationImpl.create( baseArray, orthogonalArray ), bShowAsTape, -1, bDeferred, false, null, false, true ); crdr.draw( ipr ); } // Render curve label. if ( curve.getLabel( ).isSetVisible( ) && curve.getLabel( ).isVisible( ) ) { Label lb = LabelImpl.copyInstance( curve.getLabel( ) ); // handle external resource string final String sPreviousValue = lb.getCaption( ).getValue( ); lb.getCaption( ) .setValue( getRunTimeContext( ).externalizedMessage( sPreviousValue ) ); BoundingBox bb = Methods.computeBox( getXServer( ), IConstants.LEFT/* DONT-CARE */, lb, 0, 0 ); Anchor lbAnchor = curve.getLabelAnchor( ); if ( lbAnchor == null ) { lbAnchor = Anchor.NORTH_LITERAL; } int horizontal = IConstants.CENTER; int vertical = IConstants.ABOVE; // convert anchor to position. switch ( lbAnchor.getValue( ) ) { case Anchor.WEST : case Anchor.NORTH_WEST : case Anchor.SOUTH_WEST : horizontal = IConstants.LEFT; break; case Anchor.NORTH : case Anchor.SOUTH : horizontal = IConstants.CENTER; break; case Anchor.EAST : case Anchor.NORTH_EAST : case Anchor.SOUTH_EAST : horizontal = IConstants.RIGHT; break; } switch ( lbAnchor.getValue( ) ) { case Anchor.NORTH : case Anchor.NORTH_WEST : case Anchor.NORTH_EAST : case Anchor.WEST : case Anchor.EAST : vertical = IConstants.ABOVE; break; case Anchor.SOUTH : case Anchor.SOUTH_WEST : case Anchor.SOUTH_EAST : vertical = IConstants.BELOW; break; } double xs, ys; if ( isTransposed ) { if ( horizontal == IConstants.LEFT ) { ys = orthogonalArray[orthogonalArray.length - 1] - bb.getHeight( ); // switch left/right horizontal = IConstants.RIGHT; } else if ( horizontal == IConstants.RIGHT ) { ys = orthogonalArray[0]; // switch left/right horizontal = IConstants.LEFT; } else { ys = orthogonalArray[0] + ( orthogonalArray[orthogonalArray.length - 1] - orthogonalArray[0] ) / 2d - bb.getHeight( ) / 2d; } xs = getFitYPosition( orthogonalArray, baseArray, horizontal, bb.getHeight( ), bb.getWidth( ), vertical == IConstants.BELOW ); } else { if ( horizontal == IConstants.LEFT ) { xs = xArray[0]; } else if ( horizontal == IConstants.RIGHT ) { xs = xArray[xArray.length - 1] - bb.getWidth( ); } else { xs = xArray[0] + ( xArray[xArray.length - 1] - xArray[0] ) / 2d - bb.getWidth( ) / 2d; } ys = getFitYPosition( xArray, fitYarray, horizontal, bb.getWidth( ), bb.getHeight( ), vertical == IConstants.ABOVE ); } bb.setLeft( xs ); bb.setTop( ys ); if ( ChartUtil.isShadowDefined( lb ) ) { renderLabel( StructureSource.createSeries( getSeries( ) ), TextRenderEvent.RENDER_SHADOW_AT_LOCATION, lb, Position.RIGHT_LITERAL, LocationImpl.create( bb.getLeft( ), bb.getTop( ) ), BoundsImpl.create( bb.getLeft( ), bb.getTop( ), bb.getWidth( ), bb.getHeight( ) ) ); } renderLabel( StructureSource.createSeries( getSeries( ) ), TextRenderEvent.RENDER_TEXT_IN_BLOCK, lb, Position.RIGHT_LITERAL, LocationImpl.create( bb.getLeft( ), bb.getTop( ) ), BoundsImpl.create( bb.getLeft( ), bb.getTop( ), bb.getWidth( ), bb.getHeight( ) ) ); } ScriptHandler.callFunction( getRunTimeContext( ).getScriptHandler( ), ScriptHandler.AFTER_DRAW_FITTING_CURVE, curve, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_FITTING_CURVE, curve ); } } /** * * @param xa * xa must be sorted from smallest to largest. * @param ya * @param center * @param width * @param height */ private double getFitYPosition( double[] xa, double[] ya, int align, double width, double height, boolean above ) { int gap = 10; double rt = 0; if ( align == IConstants.LEFT ) { rt = ya[0]; } else if ( align == IConstants.RIGHT ) { rt = ya[ya.length - 1]; } else { if ( ya.length % 2 == 1 ) { rt = ya[ya.length / 2]; } else { int x = ya.length / 2; rt = ( ya[x] + ya[x - 1] ) / 2; } } return above ? ( rt - height - gap ) : ( rt + gap ); } /** * Renders all marker ranges associated with all axes (base and orthogonal) * in the plot Marker ranges are drawn immediately (not rendered as * deferred) at an appropriate Z-order immediately after the plot background * is drawn. * * @param oaxa * An array containing all axes * @param boPlotClientArea * The bounds of the actual client area * * @throws RenderingException */ private final void renderMarkerRanges( OneAxis[] oaxa, Bounds boPlotClientArea ) throws ChartException { Axis ax; EList el; int iRangeCount, iAxisCount = oaxa.length; MarkerRange mr; RectangleRenderEvent rre; DataElement deStart, deEnd; AutoScale asc; double dMin = 0, dMax = 0; int iOrientation, iCompare = IConstants.EQUAL; final Bounds bo = BoundsImpl.create( 0, 0, 0, 0 ); final IDeviceRenderer idr = getDevice( ); final ScriptHandler sh = getRunTimeContext( ).getScriptHandler( ); final boolean bTransposed = ( (ChartWithAxes) getModel( ) ).isTransposed( ); final PlotWithAxes pwa = (PlotWithAxes) getComputations( ); final StringBuffer sb = new StringBuffer( ); Bounds boText = BoundsImpl.create( 0, 0, 0, 0 ); Anchor anc = null; Label la = null; TextRenderEvent tre; Orientation or; double dOriginalAngle = 0; for ( int i = 0; i < iAxisCount; i++ ) { ax = oaxa[i].getModelAxis( ); iOrientation = ax.getOrientation( ).getValue( ); if ( bTransposed ) // TOGGLE ORIENTATION { iOrientation = ( iOrientation == Orientation.HORIZONTAL ) ? Orientation.VERTICAL : Orientation.HORIZONTAL; } asc = oaxa[i].getScale( ); el = ax.getMarkerRanges( ); iRangeCount = el.size( ); for ( int j = 0; j < iRangeCount; j++ ) { mr = (MarkerRange) el.get( j ); ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_MARKER_RANGE, ax, mr, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_MARKER_RANGE, mr ); deStart = mr.getStartValue( ); deEnd = mr.getEndValue( ); try { iCompare = compare( deStart, deEnd ); } catch ( ChartException dfex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, dfex ); } // IF OUT OF ORDER, SWAP if ( iCompare == IConstants.MORE ) { final DataElement deTemp = deStart; deStart = deEnd; deEnd = deTemp; } if ( isDimension3D( ) ) { // TODO render 3D marker range return; } // COMPUTE THE START BOUND try { dMin = ( deStart == null ) ? ( ( iOrientation == Orientation.HORIZONTAL ) ? boPlotClientArea.getLeft( ) : boPlotClientArea.getTop( ) + boPlotClientArea.getHeight( ) ) : PlotWith2DAxes.getLocation( asc, deStart ); } catch ( Exception ex ) { logger.log( ILogger.WARNING, Messages.getString( "exception.cannot.locate.start.marker.range", //$NON-NLS-1$ new Object[]{ deStart, mr }, getRunTimeContext( ).getULocale( ) ) ); continue; // TRY NEXT MARKER RANGE } // COMPUTE THE END BOUND try { dMax = ( deEnd == null ) ? ( ( iOrientation == Orientation.HORIZONTAL ) ? boPlotClientArea.getLeft( ) + boPlotClientArea.getWidth( ) : boPlotClientArea.getTop( ) ) : PlotWith2DAxes.getLocation( asc, deEnd ); } catch ( Exception ex ) { logger.log( ILogger.WARNING, Messages.getString( "exception.cannot.locate.end.marker.range", //$NON-NLS-1$ new Object[]{ deEnd, mr }, getRunTimeContext( ).getULocale( ) ) ); continue; // TRY NEXT MARKER RANGE } rre = (RectangleRenderEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerRange( mr ), RectangleRenderEvent.class ); if ( iOrientation == Orientation.HORIZONTAL ) { // RESTRICT RIGHT EDGE if ( dMax > boPlotClientArea.getLeft( ) + boPlotClientArea.getWidth( ) ) { dMax = boPlotClientArea.getLeft( ) + boPlotClientArea.getWidth( ); } // RESTRICT LEFT EDGE if ( dMin < boPlotClientArea.getLeft( ) ) { dMax = boPlotClientArea.getLeft( ); } bo.set( dMin, boPlotClientArea.getTop( ), dMax - dMin, boPlotClientArea.getHeight( ) ); } else { // RESTRICT TOP EDGE if ( dMax < boPlotClientArea.getTop( ) ) { dMax = boPlotClientArea.getTop( ); } // RESTRICT BOTTOM EDGE if ( dMin > boPlotClientArea.getTop( ) + boPlotClientArea.getHeight( ) ) { dMin = boPlotClientArea.getTop( ) + boPlotClientArea.getHeight( ); } bo.set( boPlotClientArea.getLeft( ), dMax, boPlotClientArea.getWidth( ), dMin - dMax ); } if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { if ( iOrientation == Orientation.HORIZONTAL ) { bo.translate( pwa.getSeriesThickness( ), 0 ); } else { bo.translate( 0, -pwa.getSeriesThickness( ) ); } } // DRAW THE MARKER RANGE (RECTANGULAR AREA) rre.setBounds( bo ); rre.setOutline( mr.getOutline( ) ); rre.setBackground( mr.getFill( ) ); idr.fillRectangle( rre ); idr.drawRectangle( rre ); la = LabelImpl.copyInstance( mr.getLabel( ) ); if ( la.isVisible( ) ) { if ( la.getCaption( ).getValue( ) != null && !IConstants.UNDEFINED_STRING.equals( la.getCaption( ) .getValue( ) ) && la.getCaption( ).getValue( ).length( ) > 0 ) { la.getCaption( ).setValue( oaxa[i].getRunTimeContext( ) .externalizedMessage( la.getCaption( ) .getValue( ) ) ); } else { try { sb.delete( 0, sb.length( ) ); sb.append( Messages.getString( "prefix.marker.range.caption", //$NON-NLS-1$ getRunTimeContext( ).getULocale( ) ) ); sb.append( ValueFormatter.format( deStart, mr.getFormatSpecifier( ), oaxa[i].getRunTimeContext( ).getULocale( ), null ) ); sb.append( Messages.getString( "separator.marker.range.caption", //$NON-NLS-1$ getRunTimeContext( ).getULocale( ) ) ); sb.append( ValueFormatter.format( deEnd, mr.getFormatSpecifier( ), oaxa[i].getRunTimeContext( ).getULocale( ), null ) ); sb.append( Messages.getString( "suffix.marker.range.caption", //$NON-NLS-1$ getRunTimeContext( ).getULocale( ) ) ); la.getCaption( ).setValue( sb.toString( ) ); } catch ( ChartException dfex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, dfex ); } } // DETERMINE THE LABEL ANCHOR (TRANSPOSE IF NEEDED) anc = switchAnchor( mr.getLabelAnchor( ) ); if ( bTransposed ) { or = ax.getOrientation( ) == Orientation.HORIZONTAL_LITERAL ? Orientation.VERTICAL_LITERAL : Orientation.HORIZONTAL_LITERAL; dOriginalAngle = la.getCaption( ) .getFont( ) .getRotation( ); try { la.getCaption( ) .getFont( ) .setRotation( pwa.getTransposedAngle( dOriginalAngle ) ); anc = pwa.transposedAnchor( or, anc ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, uiex ); } } BoundingBox bb = null; try { bb = Methods.computeBox( idr.getDisplayServer( ), IConstants.LEFT, la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, uiex ); } boText.set( 0, 0, bb.getWidth( ), bb.getHeight( ) ); // NOW THAT WE COMPUTED THE BOUNDS, RENDER THE ACTUAL TEXT tre = (TextRenderEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerRange( mr ), TextRenderEvent.class ); tre.setBlockBounds( bo ); tre.setBlockAlignment( anchorToAlignment( anc ) ); tre.setLabel( la ); tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK ); idr.drawText( tre ); } if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = mr.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerRange( mr ), InteractionEvent.class ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createMarkerRange( mr ) ); iev.addTrigger( tg ); } iev.setHotSpot( rre ); idr.enableInteraction( iev ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_MARKER_RANGE, ax, mr, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_MARKER_RANGE, mr ); } } } /** * Ths background is the first component rendered within the plot block. * This is rendered with Z-order=0 */ protected void renderBackground( IPrimitiveRenderer ipr, Plot p ) throws ChartException { // PLOT BLOCK STUFF super.renderBackground( ipr, p ); final ChartWithAxes cwa = (ChartWithAxes) getModel( ); final PlotWithAxes pwa = (PlotWithAxes) getComputations( ); // PLOT CLIENT AREA final ClientArea ca = p.getClientArea( ); Bounds bo = pwa.getPlotBounds( ); final RectangleRenderEvent rre = (RectangleRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), RectangleRenderEvent.class ); if ( !isDimension3D( ) ) { // render client area shadow if ( ca.getShadowColor( ) != null ) { rre.setBounds( bo.translateInstance( 3, 3 ) ); rre.setBackground( ca.getShadowColor( ) ); ipr.fillRectangle( rre ); } // render client area rre.setBounds( bo ); rre.setOutline( ca.getOutline( ) ); rre.setBackground( ca.getBackground( ) ); ipr.fillRectangle( rre ); } // NOW THAT THE AXES HAVE BEEN COMPUTED, FILL THE INTERNAL PLOT AREA double dSeriesThickness = pwa.getSeriesThickness( ); double[] daX = { bo.getLeft( ) - dSeriesThickness, bo.getLeft( ) + bo.getWidth( ) - dSeriesThickness }; double[] daY = { bo.getTop( ) + bo.getHeight( ) + dSeriesThickness, bo.getTop( ) + dSeriesThickness }; final AllAxes aax = pwa.getAxes( ); AutoScale scPrimaryBase = null; AutoScale scPrimaryOrthogonal = null; AutoScale scAncillaryBase = null; double dXStart = 0; double dYStart = 0; double dZStart = 0; double dXEnd = 0; double dYEnd = 0; double dZEnd = 0; int baseTickCount = 0; int ancillaryTickCount = 0; int orthogonalTickCount = 0; double xStep = 0; double yStep = 0; double zStep = 0; Location panningOffset = null; if ( isDimension3D( ) ) { scPrimaryBase = aax.getPrimaryBase( ).getScale( ); scPrimaryOrthogonal = aax.getPrimaryOrthogonal( ).getScale( ); scAncillaryBase = aax.getAncillaryBase( ).getScale( ); dXStart = scPrimaryBase.getStart( ); dYStart = scPrimaryOrthogonal.getStart( ); dZStart = scAncillaryBase.getStart( ); dXEnd = scPrimaryBase.getEnd( ); dYEnd = scPrimaryOrthogonal.getEnd( ); dZEnd = scAncillaryBase.getEnd( ); baseTickCount = scPrimaryBase.getTickCordinates( ).length; ancillaryTickCount = scAncillaryBase.getTickCordinates( ).length; orthogonalTickCount = scPrimaryOrthogonal.getTickCordinates( ).length; xStep = scPrimaryBase.getUnitSize( ); yStep = scPrimaryOrthogonal.getUnitSize( ); zStep = scAncillaryBase.getUnitSize( ); panningOffset = getPanningOffset( ); } if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { Location[] loa = null; // DRAW THE LEFT WALL if ( cwa.getWallFill( ) == null ) { renderPlane( ipr, StructureSource.createPlot( p ), new Location[]{ LocationImpl.create( daX[0], daY[0] ), LocationImpl.create( daX[0], daY[1] ) }, ca.getBackground( ), ca.getOutline( ), cwa.getDimension( ), dSeriesThickness, false ); } else { loa = new Location[4]; loa[0] = LocationImpl.create( daX[0], daY[0] ); loa[1] = LocationImpl.create( daX[0], daY[1] ); loa[2] = LocationImpl.create( daX[0] + dSeriesThickness, daY[1] - dSeriesThickness ); loa[3] = LocationImpl.create( daX[0] + dSeriesThickness, daY[0] - dSeriesThickness ); final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), PolygonRenderEvent.class ); pre.setPoints( loa ); pre.setBackground( cwa.getWallFill( ) ); pre.setOutline( ca.getOutline( ) ); ipr.fillPolygon( pre ); ipr.drawPolygon( pre ); } // DRAW THE FLOOR if ( cwa.getFloorFill( ) == null ) { renderPlane( ipr, StructureSource.createPlot( p ), new Location[]{ LocationImpl.create( daX[0], daY[0] ), LocationImpl.create( daX[1], daY[0] ) }, ca.getBackground( ), ca.getOutline( ), cwa.getDimension( ), dSeriesThickness, false ); } else { if ( loa == null ) { loa = new Location[4]; } loa[0] = LocationImpl.create( daX[0], daY[0] ); loa[1] = LocationImpl.create( daX[1], daY[0] ); loa[2] = LocationImpl.create( daX[1] + dSeriesThickness, daY[0] - dSeriesThickness ); loa[3] = LocationImpl.create( daX[0] + dSeriesThickness, daY[0] - dSeriesThickness ); final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), PolygonRenderEvent.class ); pre.setPoints( loa ); pre.setBackground( cwa.getFloorFill( ) ); pre.setOutline( ca.getOutline( ) ); ipr.fillPolygon( pre ); ipr.drawPolygon( pre ); } } else if ( pwa.getDimension( ) == IConstants.THREE_D ) { Location3D[] loa = null; final Polygon3DRenderEvent pre = (Polygon3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), Polygon3DRenderEvent.class ); pre.setDoubleSided( true ); // DRAW THE WALL if ( ( cwa.getWallFill( ) instanceof ColorDefinition && ( (ColorDefinition) cwa.getWallFill( ) ).getTransparency( ) > 0 ) || ( !( cwa.getWallFill( ) instanceof ColorDefinition ) && cwa.getWallFill( ) != null ) ) { loa = new Location3D[4]; // Left Wall loa[0] = Location3DImpl.create( dXStart, dYStart, dZStart ); loa[1] = Location3DImpl.create( dXStart, dYEnd, dZStart ); loa[2] = Location3DImpl.create( dXStart, dYEnd, dZEnd ); loa[3] = Location3DImpl.create( dXStart, dYStart, dZEnd ); pre.setPoints3D( loa ); pre.setBackground( cwa.getWallFill( ) ); pre.setDoubleSided( true ); pre.setOutline( ca.getOutline( ) ); getDeferredCache( ).addPlane( pre, PrimitiveRenderEvent.DRAW | PrimitiveRenderEvent.FILL ); // // split to small planes to render. // for ( int i = 0; i < orthogonalTickCount - 1; i++ ) // for ( int j = 0; j < ancillaryTickCount - 1; j++ ) // loa[0] = Location3DImpl.create( dXStart, dYStart // + yStep // * i, dZStart + zStep * j ); // loa[1] = Location3DImpl.create( dXStart, dYStart // + ( i + 1 ) // * yStep, dZStart + j * zStep ); // loa[2] = Location3DImpl.create( dXStart, dYStart // + ( i + 1 ) // * yStep, dZStart + ( j + 1 ) * zStep ); // loa[3] = Location3DImpl.create( dXStart, dYStart // * yStep, dZStart + ( j + 1 ) * zStep ); // pre.setPoints3D( loa ); // pre.setBackground( cwa.getWallFill( ) ); // pre.setOutline( ca.getOutline( ) ); // getDeferredCache( ).addPlane( pre, // PrimitiveRenderEvent.DRAW // | PrimitiveRenderEvent.FILL ); leftWallFill = true; // Right Wall loa[0] = Location3DImpl.create( dXStart, dYStart, dZStart ); loa[1] = Location3DImpl.create( dXEnd, dYStart, dZStart ); loa[2] = Location3DImpl.create( dXEnd, dYEnd, dZStart ); loa[3] = Location3DImpl.create( dXStart, dYEnd, dZStart ); pre.setPoints3D( loa ); pre.setBackground( cwa.getWallFill( ) ); pre.setDoubleSided( true ); pre.setOutline( ca.getOutline( ) ); getDeferredCache( ).addPlane( pre, PrimitiveRenderEvent.DRAW | PrimitiveRenderEvent.FILL ); // // split to small planes to render. // for ( int i = 0; i < orthogonalTickCount - 1; i++ ) // for ( int j = 0; j < baseTickCount - 1; j++ ) // loa[0] = Location3DImpl.create( dXStart + j * xStep, // dYStart + i * yStep, // dZStart ); // loa[1] = Location3DImpl.create( dXStart // + ( j + 1 ) // * xStep, dYStart + i * yStep, dZStart ); // loa[2] = Location3DImpl.create( dXStart // + ( j + 1 ) // * xStep, dYStart + ( i + 1 ) * yStep, dZStart ); // loa[3] = Location3DImpl.create( dXStart + j * xStep, // dYStart + ( i + 1 ) * yStep, // dZStart ); // pre.setPoints3D( loa ); // pre.setBackground( cwa.getWallFill( ) ); // pre.setOutline( ca.getOutline( ) ); // getDeferredCache( ).addPlane( pre, // PrimitiveRenderEvent.DRAW // | PrimitiveRenderEvent.FILL ); rightWallFill = true; } // DRAW THE FLOOR if ( ( cwa.getFloorFill( ) instanceof ColorDefinition && ( (ColorDefinition) cwa.getFloorFill( ) ).getTransparency( ) > 0 ) || ( !( cwa.getFloorFill( ) instanceof ColorDefinition ) && cwa.getFloorFill( ) != null ) ) { if ( loa == null ) { loa = new Location3D[4]; } loa[0] = Location3DImpl.create( dXStart, dYStart, dZStart ); loa[1] = Location3DImpl.create( dXStart, dYStart, dZEnd ); loa[2] = Location3DImpl.create( dXEnd, dYStart, dZEnd ); loa[3] = Location3DImpl.create( dXEnd, dYStart, dZStart ); pre.setPoints3D( loa ); pre.setBackground( cwa.getFloorFill( ) ); pre.setDoubleSided( true ); pre.setOutline( ca.getOutline( ) ); getDeferredCache( ).addPlane( pre, PrimitiveRenderEvent.DRAW | PrimitiveRenderEvent.FILL ); // // split to small planes to render. // for ( int i = 0; i < baseTickCount - 1; i++ ) // for ( int j = 0; j < ancillaryTickCount - 1; j++ ) // loa[0] = Location3DImpl.create( dXStart + i * xStep, // dYStart, // dZStart + j * zStep ); // loa[1] = Location3DImpl.create( dXStart + i * xStep, // dYStart, // dZStart + ( j + 1 ) * zStep ); // loa[2] = Location3DImpl.create( dXStart // + ( i + 1 ) // * xStep, dYStart, dZStart + ( j + 1 ) * zStep ); // loa[3] = Location3DImpl.create( dXStart // + ( i + 1 ) // * xStep, dYStart, dZStart + j * zStep ); // pre.setPoints3D( loa ); // pre.setBackground( cwa.getFloorFill( ) ); // pre.setOutline( ca.getOutline( ) ); // getDeferredCache( ).addPlane( pre, // PrimitiveRenderEvent.DRAW // | PrimitiveRenderEvent.FILL ); floorFill = true; } } // SETUP AXIS ARRAY final OneAxis[] oaxa = new OneAxis[2 + aax.getOverlayCount( ) + ( aax.getAncillaryBase( ) != null ? 1 : 0 )]; oaxa[0] = aax.getPrimaryBase( ); oaxa[1] = aax.getPrimaryOrthogonal( ); for ( int i = 0; i < aax.getOverlayCount( ); i++ ) { oaxa[2 + i] = aax.getOverlay( i ); } if ( aax.getAncillaryBase( ) != null ) { oaxa[2 + aax.getOverlayCount( )] = aax.getAncillaryBase( ); } // RENDER MARKER RANGES (MARKER LINES ARE DRAWN LATER) renderMarkerRanges( oaxa, bo ); // RENDER GRID LINES (MAJOR=DONE; MINOR=DONE) double x = 0, y = 0, vnext = 0; LineAttributes lia; LineRenderEvent lre; final Insets insCA = aax.getInsets( ); // RENDER MINOR GRID LINES FIRST int iCount; Grid g; double[] doaMinor = null; for ( int i = 0; i < oaxa.length; i++ ) { g = oaxa[i].getGrid( ); iCount = g.getMinorCountPerMajor( ); lia = oaxa[i].getGrid( ).getLineAttributes( IConstants.MINOR ); if ( lia == null || !lia.isSetStyle( ) || !lia.isVisible( ) ) { continue; } if ( iCount <= 0 ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, "exception.cannot.split.major", //$NON-NLS-1$ new Object[]{ new Integer( iCount ) }, Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); } AutoScale sc = oaxa[i].getScale( ); doaMinor = sc.getMinorCoordinates( iCount ); if ( isDimension3D( ) ) { Line3DRenderEvent lre3d = (Line3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), Line3DRenderEvent.class ); lre3d.setLineAttributes( lia ); switch ( oaxa[i].getAxisType( ) ) { case IConstants.BASE_AXIS : double[] xa = scPrimaryBase.getTickCordinates( ); if ( floorFill ) { for ( int k = 0; k < xa.length - 1; k++ ) { for ( int j = 0; j < doaMinor.length - 1; j++ ) { for ( int n = 0; n < ancillaryTickCount - 1; n++ ) { if ( ChartUtil.mathGE( xa[k] + doaMinor[j], xa[k + 1] ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre3d.setStart3D( Location3DImpl.create( xa[k] + doaMinor[j], dYStart, dZStart + n * zStep ) ); lre3d.setEnd3D( Location3DImpl.create( xa[k] + doaMinor[j], dYStart, dZStart + ( n + 1 ) * zStep ) ); getDeferredCache( ).addLine( lre3d ); } } } } if ( rightWallFill ) { for ( int k = 0; k < xa.length - 1; k++ ) { for ( int j = 0; j < doaMinor.length - 1; j++ ) { for ( int n = 0; n < orthogonalTickCount - 1; n++ ) { if ( ChartUtil.mathGE( xa[k] + doaMinor[j], xa[k + 1] ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre3d.setStart3D( Location3DImpl.create( xa[k] + doaMinor[j], dYStart + n * yStep, dZStart ) ); lre3d.setEnd3D( Location3DImpl.create( xa[k] + doaMinor[j], dYStart + ( n + 1 ) * yStep, dZStart ) ); getDeferredCache( ).addLine( lre3d ); } } } } break; case IConstants.ORTHOGONAL_AXIS : double[] ya = scPrimaryOrthogonal.getTickCordinates( ); if ( leftWallFill ) { for ( int k = 0; k < ya.length - 1; k++ ) { for ( int j = 0; j < doaMinor.length - 1; j++ ) { for ( int n = 0; n < ancillaryTickCount - 1; n++ ) { if ( ChartUtil.mathGE( ya[k] + doaMinor[j], ya[k + 1] ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre3d.setStart3D( Location3DImpl.create( dXStart, ya[k] + doaMinor[j], dZStart + n * zStep ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart, ya[k] + doaMinor[j], dZStart + ( n + 1 ) * zStep ) ); getDeferredCache( ).addLine( lre3d ); } } } } if ( rightWallFill ) { for ( int k = 0; k < ya.length - 1; k++ ) { for ( int j = 0; j < doaMinor.length - 1; j++ ) { for ( int n = 0; n < baseTickCount - 1; n++ ) { if ( ChartUtil.mathGE( ya[k] + doaMinor[j], ya[k + 1] ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre3d.setStart3D( Location3DImpl.create( dXStart + n * xStep, ya[k] + doaMinor[j], dZStart ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart + ( n + 1 ) * xStep, ya[k] + doaMinor[j], dZStart ) ); getDeferredCache( ).addLine( lre3d ); } } } } break; case IConstants.ANCILLARY_AXIS : double[] za = scAncillaryBase.getTickCordinates( ); if ( leftWallFill ) { for ( int k = 0; k < za.length - 1; k++ ) { for ( int j = 0; j < doaMinor.length - 1; j++ ) { for ( int n = 0; n < orthogonalTickCount - 1; n++ ) { if ( ChartUtil.mathGE( za[k] + doaMinor[j], za[k + 1] ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre3d.setStart3D( Location3DImpl.create( dXStart, dYStart + n * yStep, za[k] + doaMinor[j] ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart, dYStart + ( n + 1 ) * yStep, za[k] + doaMinor[j] ) ); getDeferredCache( ).addLine( lre3d ); } } } } if ( floorFill ) { for ( int k = 0; k < za.length - 1; k++ ) { for ( int j = 0; j < doaMinor.length - 1; j++ ) { for ( int n = 0; n < baseTickCount - 1; n++ ) { if ( ChartUtil.mathGE( za[k] + doaMinor[j], za[k + 1] ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre3d.setStart3D( Location3DImpl.create( dXStart + n * xStep, dYStart, za[k] + doaMinor[j] ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart + ( n + 1 ) * xStep, dYStart, za[k] + doaMinor[j] ) ); getDeferredCache( ).addLine( lre3d ); } } } } break; default : break; } } else if ( oaxa[i].getOrientation( ) == IConstants.HORIZONTAL ) { int iDirection = sc.getDirection( ) == IConstants.BACKWARD ? -1 : 1; double[] da = sc.getTickCordinates( ); double dY2 = bo.getTop( ) + 1, dY1 = bo.getTop( ) + bo.getHeight( ) - 2; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { for ( int j = 0; j < da.length - 1; j++ ) { x = da[j]; for ( int k = 0; k < doaMinor.length; k++ ) { if ( ( iDirection == 1 && ChartUtil.mathGE( x + doaMinor[k], da[j + 1] ) ) || ( iDirection == -1 && ChartUtil.mathLE( x - doaMinor[k], da[j + 1] ) ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( x + iDirection * doaMinor[k], dY1 + pwa.getSeriesThickness( ) ) ); lre.setEnd( LocationImpl.create( x + iDirection * doaMinor[k] + pwa.getSeriesThickness( ), dY1 ) ); ipr.drawLine( lre ); } } } for ( int j = 0; j < da.length - 1; j++ ) { x = da[j]; vnext = da[j + 1]; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { x += pwa.getSeriesThickness( ); vnext += pwa.getSeriesThickness( ); } for ( int k = 0; k < doaMinor.length; k++ ) { if ( ( iDirection == 1 && ChartUtil.mathGE( x + doaMinor[k], vnext ) ) || ( iDirection == -1 && ChartUtil.mathLE( x - doaMinor[k], vnext ) ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( x + iDirection * doaMinor[k], dY1 ) ); lre.setEnd( LocationImpl.create( x + iDirection * doaMinor[k], dY2 ) ); ipr.drawLine( lre ); } } } else if ( oaxa[i].getOrientation( ) == IConstants.VERTICAL ) { int iDirection = sc.getDirection( ) != IConstants.FORWARD ? -1 : 1; double[] da = sc.getTickCordinates( ); double dX1 = bo.getLeft( ) + 1, dX2 = bo.getLeft( ) + bo.getWidth( ) - 2; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { for ( int j = 0; j < da.length - 1; j++ ) { y = da[j] - pwa.getSeriesThickness( ); vnext = da[j + 1] - pwa.getSeriesThickness( ); for ( int k = 0; k < doaMinor.length; k++ ) { if ( ( iDirection == 1 && ChartUtil.mathGE( y + doaMinor[k], vnext ) ) || ( iDirection == -1 && ChartUtil.mathLE( y - doaMinor[k], vnext ) ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( dX1, y + iDirection * doaMinor[k] ) ); lre.setEnd( LocationImpl.create( dX1 - pwa.getSeriesThickness( ), y + iDirection * doaMinor[k] + pwa.getSeriesThickness( ) ) ); ipr.drawLine( lre ); } } } for ( int j = 0; j < da.length - 1; j++ ) { y = da[j]; vnext = da[j + 1]; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { y -= pwa.getSeriesThickness( ); vnext -= pwa.getSeriesThickness( ); } for ( int k = 0; k < doaMinor.length; k++ ) { if ( ( iDirection == 1 && ChartUtil.mathGE( y + doaMinor[k], vnext ) ) || ( iDirection == -1 && ChartUtil.mathLE( y - doaMinor[k], vnext ) ) ) { // if current minor tick exceeds the // range of current unit, skip continue; } lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( dX1, y + iDirection * doaMinor[k] ) ); lre.setEnd( LocationImpl.create( dX2, y + iDirection * doaMinor[k] ) ); ipr.drawLine( lre ); } } } } // RENDER MAJOR GRID LINES NEXT for ( int i = 0; i < oaxa.length; i++ ) { lia = oaxa[i].getGrid( ).getLineAttributes( IConstants.MAJOR ); if ( lia == null || !lia.isSetStyle( ) || !lia.isVisible( ) ) // GRID // LINE // UNDEFINED { continue; } AutoScale sc = oaxa[i].getScale( ); if ( isDimension3D( ) ) { Line3DRenderEvent lre3d = (Line3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), Line3DRenderEvent.class ); lre3d.setLineAttributes( lia ); switch ( oaxa[i].getAxisType( ) ) { case IConstants.BASE_AXIS : double[] xa = scPrimaryBase.getTickCordinates( ); if ( floorFill ) { for ( int k = 0; k < xa.length; k++ ) { for ( int j = 0; j < ancillaryTickCount - 1; j++ ) { lre3d.setStart3D( Location3DImpl.create( xa[k], dYStart, dZStart + j * zStep ) ); lre3d.setEnd3D( Location3DImpl.create( xa[k], dYStart, dZStart + ( j + 1 ) * zStep ) ); getDeferredCache( ).addLine( lre3d ); } } } if ( rightWallFill ) { for ( int k = 0; k < xa.length; k++ ) { for ( int j = 0; j < orthogonalTickCount - 1; j++ ) { lre3d.setStart3D( Location3DImpl.create( xa[k], dYStart + j * yStep, dZStart ) ); lre3d.setEnd3D( Location3DImpl.create( xa[k], dYStart + ( j + 1 ) * yStep, dZStart ) ); getDeferredCache( ).addLine( lre3d ); } } } break; case IConstants.ORTHOGONAL_AXIS : double[] ya = scPrimaryOrthogonal.getTickCordinates( ); if ( leftWallFill ) { for ( int k = 0; k < ya.length; k++ ) { for ( int j = 0; j < ancillaryTickCount - 1; j++ ) { lre3d.setStart3D( Location3DImpl.create( dXStart, ya[k], dZStart + j * zStep ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart, ya[k], dZStart + ( j + 1 ) * zStep ) ); getDeferredCache( ).addLine( lre3d ); } } } if ( rightWallFill ) { for ( int k = 0; k < ya.length; k++ ) { for ( int j = 0; j < baseTickCount - 1; j++ ) { lre3d.setStart3D( Location3DImpl.create( dXStart + j * xStep, ya[k], dZStart ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart + ( j + 1 ) * xStep, ya[k], dZStart ) ); getDeferredCache( ).addLine( lre3d ); } } } break; case IConstants.ANCILLARY_AXIS : double[] za = scAncillaryBase.getTickCordinates( ); if ( leftWallFill ) { for ( int k = 0; k < za.length; k++ ) { for ( int j = 0; j < orthogonalTickCount - 1; j++ ) { lre3d.setStart3D( Location3DImpl.create( dXStart, dYStart + j * yStep, za[k] ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart, dYStart + ( j + 1 ) * yStep, za[k] ) ); getDeferredCache( ).addLine( lre3d ); } } } if ( floorFill ) { for ( int k = 0; k < za.length; k++ ) { for ( int j = 0; j < baseTickCount - 1; j++ ) { lre3d.setStart3D( Location3DImpl.create( dXStart + j * xStep, dYStart, za[k] ) ); lre3d.setEnd3D( Location3DImpl.create( dXStart + ( j + 1 ) * xStep, dYStart, za[k] ) ); getDeferredCache( ).addLine( lre3d ); } } } break; default : break; } } else if ( oaxa[i].getOrientation( ) == IConstants.HORIZONTAL ) { double[] da = sc.getTickCordinates( ); double dY2 = bo.getTop( ) + 1, dY1 = bo.getTop( ) + bo.getHeight( ) - 2; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { for ( int j = 0; j < da.length; j++ ) { if ( j == 0 && insCA.getBottom( ) < lia.getThickness( ) ) continue; if ( j == da.length - 1 && insCA.getTop( ) < lia.getThickness( ) ) continue; x = da[j]; lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( x, dY1 + pwa.getSeriesThickness( ) ) ); lre.setEnd( LocationImpl.create( x + pwa.getSeriesThickness( ), dY1 ) ); ipr.drawLine( lre ); } } for ( int j = 0; j < da.length; j++ ) { if ( j == 0 && insCA.getBottom( ) < lia.getThickness( ) ) continue; if ( j == da.length - 1 && insCA.getTop( ) < lia.getThickness( ) ) continue; x = da[j]; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { x += pwa.getSeriesThickness( ); } lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( x, dY1 ) ); lre.setEnd( LocationImpl.create( x, dY2 ) ); ipr.drawLine( lre ); } } else if ( oaxa[i].getOrientation( ) == IConstants.VERTICAL ) { double[] da = sc.getTickCordinates( ); double dX1 = bo.getLeft( ) + 1, dX2 = bo.getLeft( ) + bo.getWidth( ) - 2; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { for ( int j = 0; j < da.length; j++ ) { if ( j == 0 && insCA.getLeft( ) < lia.getThickness( ) ) continue; if ( j == da.length - 1 && insCA.getRight( ) < lia.getThickness( ) ) continue; y = ( da[j] - pwa.getSeriesThickness( ) ); lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( dX1, y ) ); lre.setEnd( LocationImpl.create( dX1 - pwa.getSeriesThickness( ), y + pwa.getSeriesThickness( ) ) ); ipr.drawLine( lre ); } } for ( int j = 0; j < da.length; j++ ) { if ( j == 0 && insCA.getLeft( ) < lia.getThickness( ) ) continue; if ( j == da.length - 1 && insCA.getRight( ) < lia.getThickness( ) ) continue; y = da[j]; if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { y -= pwa.getSeriesThickness( ); } lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createPlot( p ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( dX1, y ) ); lre.setEnd( LocationImpl.create( dX2, y ) ); ipr.drawLine( lre ); } } } if ( !isDimension3D( ) && p.getClientArea( ).getOutline( ).isVisible( ) ) { rre.setBounds( bo ); ipr.drawRectangle( rre ); } } /** * The axes correspond to the lines/planes being rendered within the plot * block. This is rendered with Z-order=2 */ private final void renderAxesStructure( IPrimitiveRenderer ipr, Plot p ) throws ChartException { final PlotWithAxes pwa = (PlotWithAxes) getComputations( ); final AllAxes aax = pwa.getAxes( ); if ( pwa.getDimension( ) == IConstants.THREE_D ) { renderEachAxis( ipr, p, aax.getPrimaryBase( ), IConstants.BASE_AXIS ); renderEachAxis( ipr, p, aax.getAncillaryBase( ), IConstants.ANCILLARY_AXIS ); renderEachAxis( ipr, p, aax.getPrimaryOrthogonal( ), IConstants.ORTHOGONAL_AXIS ); } else { final int iCount = aax.getOverlayCount( ) + 2; final OneAxis[] oaxa = new OneAxis[iCount]; oaxa[0] = aax.getPrimaryBase( ); oaxa[1] = aax.getPrimaryOrthogonal( ); for ( int i = 0; i < iCount - 2; i++ ) { oaxa[i + 2] = aax.getOverlay( i ); } // RENDER THE AXIS LINES FOR EACH AXIS IN THE PLOT for ( int i = 0; i < iCount; i++ ) { renderEachAxis( ipr, p, oaxa[i], IConstants.AXIS ); } } } /** * The axes correspond to the lines/planes being rendered within the plot * block. This is rendered with Z-order=2 */ private final void renderAxesLabels( IPrimitiveRenderer ipr, Plot p, OneAxis[] oaxa ) throws ChartException { // RENDER THE AXIS LINES FOR EACH AXIS IN THE PLOT for ( int i = 0; i < oaxa.length; i++ ) { renderEachAxis( ipr, p, oaxa[i], IConstants.LABELS ); } } /** * This method renders the bar graphic elements superimposed over the plot * background and any previously rendered series' graphic elements. */ public final void renderPlot( IPrimitiveRenderer ipr, Plot p ) throws ChartException { if ( !p.isVisible( ) ) // CHECK VISIBILITY { return; } // final ClipRenderEvent cre = (ClipRenderEvent) ( (EventObjectCache) // getDevice( ) ).getEventObject( StructureSource.createPlot( p ), // ClipRenderEvent.class ); final boolean bFirstInSequence = ( iSeriesIndex == 0 ); final boolean bLastInSequence = ( iSeriesIndex == iSeriesCount - 1 ); final PlotWithAxes pwa = (PlotWithAxes) getComputations( ); if ( bFirstInSequence ) { renderBackground( ipr, p ); renderAxesStructure( ipr, p ); } if ( getSeries( ) != null ) { ISeriesRenderingHints srh = null; try { srh = ( (PlotWithAxes) getComputations( ) ).getSeriesRenderingHints( getSeriesDefinition( ), getSeries( ) ); } catch ( Exception ex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, ex ); } // try // Bounds boClipping = p.getBounds( ) // .scaledInstance( getDevice( ).getDisplayServer( ) // .getDpiResolution( ) / 72d ); // Location[] loaClipping = new Location[4]; // loaClipping[0] = LocationImpl.create( boClipping.getLeft( ), // boClipping.getTop( ) ); // loaClipping[1] = LocationImpl.create( boClipping.getLeft( ) // + boClipping.getWidth( ), boClipping.getTop( ) ); // loaClipping[2] = LocationImpl.create( boClipping.getLeft( ) // + boClipping.getWidth( ), boClipping.getTop( ) // + boClipping.getHeight( ) ); // loaClipping[3] = LocationImpl.create( boClipping.getLeft( ), // boClipping.getTop( ) + boClipping.getHeight( ) ); // cre.setVertices( loaClipping ); // getDevice( ).setClip( cre ); ScriptHandler.callFunction( getRunTimeContext( ).getScriptHandler( ), ScriptHandler.BEFORE_DRAW_SERIES, getSeries( ), this, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_SERIES, getSeries( ) ); // CALLS THE APPROPRIATE SUBCLASS FOR GRAPHIC ELEMENT RENDERING renderSeries( ipr, p, srh ); ScriptHandler.callFunction( getRunTimeContext( ).getScriptHandler( ), ScriptHandler.AFTER_DRAW_SERIES, getSeries( ), this, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_SERIES, getSeries( ) ); } if ( bLastInSequence ) { final Location panningOffset = getPanningOffset( ); try { if ( isDimension3D( ) ) { getDeferredCache( ).process3DEvent( get3DEngine( ), panningOffset.getX( ), panningOffset.getY( ) ); } getDeferredCache( ).flush( ); // FLUSH DEFERRED CACHE } catch ( ChartException ex ) { // NOTE: RENDERING EXCEPTION ALREADY BEING THROWN throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, ex ); } // SETUP AXIS ARRAY final AllAxes aax = pwa.getAxes( ); final OneAxis[] oaxa = new OneAxis[2 + aax.getOverlayCount( ) + ( aax.getAncillaryBase( ) != null ? 1 : 0 )]; oaxa[0] = aax.getPrimaryBase( ); oaxa[1] = aax.getPrimaryOrthogonal( ); for ( int i = 0; i < aax.getOverlayCount( ); i++ ) { oaxa[2 + i] = aax.getOverlay( i ); } if ( aax.getAncillaryBase( ) != null ) { oaxa[2 + aax.getOverlayCount( )] = aax.getAncillaryBase( ); } Bounds bo = pwa.getPlotBounds( ); // RENDER MARKER LINES renderMarkerLines( oaxa, bo ); // // restore clipping. // cre.setVertices( null ); // getDevice( ).setClip( cre ); // RENDER AXIS LABELS LAST renderAxesLabels( ipr, p, oaxa ); try { if ( isDimension3D( ) ) { getDeferredCache( ).process3DEvent( get3DEngine( ), panningOffset.getX( ), panningOffset.getY( ) ); } getDeferredCache( ).flush( ); // FLUSH DEFERRED CACHE } catch ( ChartException ex ) { // NOTE: RENDERING EXCEPTION ALREADY BEING THROWN throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, ex ); } } // finally // // restore clipping. // cre.setVertices( null ); // getDevice( ).setClip( cre ); } /** * Renders all marker lines (and labels at requested positions) associated * with every axis in the plot Note that marker lines are drawn immediately * (not rendered as deferred) at the appropriate Z-order * * @param oaxa * @param boPlotClientArea * * @throws RenderingException */ private final void renderMarkerLines( OneAxis[] oaxa, Bounds boPlotClientArea ) throws ChartException { Axis ax; EList el; int iLineCount, iAxisCount = oaxa.length; MarkerLine ml; LineRenderEvent lre; DataElement deValue; AutoScale asc; double dCoordinate = 0; int iOrientation; final IDeviceRenderer idr = getDevice( ); final ScriptHandler sh = getRunTimeContext( ).getScriptHandler( ); final Location loStart = LocationImpl.create( 0, 0 ); final Location loEnd = LocationImpl.create( 0, 0 ); Anchor anc; Orientation or; TextRenderEvent tre = null; Label la = null; double dOriginalAngle = 0; final boolean bTransposed = ( (ChartWithAxes) getModel( ) ).isTransposed( ); final PlotWithAxes pwa = (PlotWithAxes) getComputations( ); final Bounds boText = BoundsImpl.create( 0, 0, 0, 0 ); for ( int i = 0; i < iAxisCount; i++ ) { ax = oaxa[i].getModelAxis( ); iOrientation = ax.getOrientation( ).getValue( ); if ( bTransposed ) // TOGGLE ORIENTATION { iOrientation = ( iOrientation == Orientation.HORIZONTAL ) ? Orientation.VERTICAL : Orientation.HORIZONTAL; } asc = oaxa[i].getScale( ); el = ax.getMarkerLines( ); iLineCount = el.size( ); for ( int j = 0; j < iLineCount; j++ ) { ml = (MarkerLine) el.get( j ); ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_MARKER_LINE, ax, ml, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_MARKER_LINE, ml ); deValue = ml.getValue( ); if ( deValue == null ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, "exception.marker.line.null.value", //$NON-NLS-1$ new Object[]{ ml }, Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); } // UPDATE THE LABEL CONTENT ASSOCIATED WITH THE MARKER LINE la = LabelImpl.copyInstance( ml.getLabel( ) ); if ( la.getCaption( ).getValue( ) != null && !IConstants.UNDEFINED_STRING.equals( la.getCaption( ) .getValue( ) ) && la.getCaption( ).getValue( ).length( ) > 0 ) { la.getCaption( ) .setValue( oaxa[i].getRunTimeContext( ) .externalizedMessage( la.getCaption( ) .getValue( ) ) ); } else { try { la.getCaption( ) .setValue( ValueFormatter.format( deValue, ml.getFormatSpecifier( ), oaxa[i].getRunTimeContext( ) .getULocale( ), null ) ); } catch ( ChartException dfex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, dfex ); } } if ( isDimension3D( ) ) { // TODO render 3D marker line return; } // COMPUTE THE LOCATION try { dCoordinate = PlotWith2DAxes.getLocation( asc, deValue ); } catch ( Exception ex ) { logger.log( ILogger.WARNING, Messages.getString( "exception.cannot.locate.value.marker.line", //$NON-NLS-1$ new Object[]{ deValue, ml }, getRunTimeContext( ).getULocale( ) ) ); continue; // TRY NEXT MARKER RANGE } lre = (LineRenderEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerLine( ml ), LineRenderEvent.class ); if ( iOrientation == Orientation.HORIZONTAL ) { // RESTRICT RIGHT EDGE if ( dCoordinate > boPlotClientArea.getLeft( ) + boPlotClientArea.getWidth( ) ) { dCoordinate = boPlotClientArea.getLeft( ) + boPlotClientArea.getWidth( ); } // RESTRICT LEFT EDGE if ( dCoordinate < boPlotClientArea.getLeft( ) ) { dCoordinate = boPlotClientArea.getLeft( ); } // SETUP THE TWO POINTS loStart.set( dCoordinate, boPlotClientArea.getTop( ) ); loEnd.set( dCoordinate, boPlotClientArea.getTop( ) + boPlotClientArea.getHeight( ) ); } else { // RESTRICT TOP EDGE if ( dCoordinate < boPlotClientArea.getTop( ) ) { dCoordinate = boPlotClientArea.getTop( ); } // RESTRICT BOTTOM EDGE if ( dCoordinate > boPlotClientArea.getTop( ) + boPlotClientArea.getHeight( ) ) { dCoordinate = boPlotClientArea.getTop( ) + boPlotClientArea.getHeight( ); } // SETUP THE TWO POINTS loStart.set( boPlotClientArea.getLeft( ), dCoordinate ); loEnd.set( boPlotClientArea.getLeft( ) + boPlotClientArea.getWidth( ), dCoordinate ); } // ADJUST FOR 2D PLOTS AS NEEDED if ( pwa.getDimension( ) == IConstants.TWO_5_D ) { if ( iOrientation == Orientation.HORIZONTAL ) { loStart.translate( 0, pwa.getSeriesThickness( ) ); loEnd.translate( 0, pwa.getSeriesThickness( ) ); } else { loStart.translate( -pwa.getSeriesThickness( ), 0 ); loEnd.translate( -pwa.getSeriesThickness( ), 0 ); } } // DRAW THE MARKER LINE lre.setStart( loStart ); lre.setEnd( loEnd ); lre.setLineAttributes( ml.getLineAttributes( ) ); idr.drawLine( lre ); // DRAW THE MARKER LINE LABEL AT THE APPROPRIATE LOCATION if ( la.isVisible( ) ) { // DETERMINE THE LABEL ANCHOR (TRANSPOSE IF NEEDED) anc = switchAnchor( ml.getLabelAnchor( ) ); if ( bTransposed ) { or = ax.getOrientation( ) == Orientation.HORIZONTAL_LITERAL ? Orientation.VERTICAL_LITERAL : Orientation.HORIZONTAL_LITERAL; // la = ml.getLabel( ); dOriginalAngle = la.getCaption( ) .getFont( ) .getRotation( ); try { la.getCaption( ) .getFont( ) .setRotation( pwa.getTransposedAngle( dOriginalAngle ) ); anc = pwa.transposedAnchor( or, anc ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, uiex ); } } BoundingBox bb = null; try { bb = Methods.computeBox( idr.getDisplayServer( ), IConstants.LEFT, la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, uiex ); } boText.set( 0, 0, bb.getWidth( ), bb.getHeight( ) ); if ( iOrientation == Orientation.VERTICAL ) { if ( anc != null ) { switch ( anc.getValue( ) ) { case Anchor.NORTH : case Anchor.NORTH_EAST : case Anchor.NORTH_WEST : boText.setTop( loStart.getY( ) - boText.getHeight( ) ); break; case Anchor.SOUTH : case Anchor.SOUTH_EAST : case Anchor.SOUTH_WEST : boText.setTop( loStart.getY( ) ); break; default : boText.setTop( loStart.getY( ) + ( loEnd.getY( ) - loStart.getY( ) - boText.getHeight( ) ) / 2 ); break; } switch ( anc.getValue( ) ) { case Anchor.NORTH_EAST : case Anchor.SOUTH_EAST : case Anchor.EAST : boText.setLeft( loEnd.getX( ) - boText.getWidth( ) ); break; case Anchor.NORTH_WEST : case Anchor.SOUTH_WEST : case Anchor.WEST : boText.setLeft( loStart.getX( ) ); break; default : boText.setLeft( loStart.getX( ) + ( loEnd.getX( ) - loStart.getX( ) - boText.getWidth( ) ) / 2 ); break; } } else // CENTER ANCHORED { boText.setLeft( loStart.getX( ) + ( loEnd.getX( ) - loStart.getX( ) - boText.getWidth( ) ) / 2 ); boText.setTop( loStart.getY( ) + ( loEnd.getY( ) - loStart.getY( ) - boText.getHeight( ) ) / 2 ); } } else { if ( anc != null ) { switch ( anc.getValue( ) ) { case Anchor.NORTH : case Anchor.NORTH_EAST : case Anchor.NORTH_WEST : boText.setTop( loStart.getY( ) ); break; case Anchor.SOUTH : case Anchor.SOUTH_EAST : case Anchor.SOUTH_WEST : boText.setTop( loEnd.getY( ) - boText.getHeight( ) ); break; default : boText.setTop( loStart.getY( ) + ( loEnd.getY( ) - loStart.getY( ) - boText.getHeight( ) ) / 2 ); break; } switch ( anc.getValue( ) ) { case Anchor.NORTH_EAST : case Anchor.SOUTH_EAST : case Anchor.EAST : boText.setLeft( loStart.getX( ) ); break; case Anchor.NORTH_WEST : case Anchor.SOUTH_WEST : case Anchor.WEST : boText.setLeft( loEnd.getX( ) - boText.getWidth( ) ); break; default : boText.setLeft( loStart.getX( ) + ( loEnd.getX( ) - loStart.getX( ) - boText.getWidth( ) ) / 2 ); break; } } else // CENTER ANCHORED { boText.setLeft( loStart.getX( ) + ( loEnd.getX( ) - loStart.getX( ) - boText.getWidth( ) ) / 2 ); boText.setTop( loStart.getY( ) + ( loEnd.getY( ) - loStart.getY( ) - boText.getHeight( ) ) / 2 ); } } // NOW THAT WE COMPUTED THE BOUNDS, RENDER THE ACTUAL TEXT tre = (TextRenderEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerLine( ml ), TextRenderEvent.class ); tre.setBlockBounds( boText ); tre.setBlockAlignment( null ); tre.setLabel( la ); tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK ); idr.drawText( tre ); } if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = ml.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerLine( ml ), InteractionEvent.class ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createMarkerLine( ml ) ); iev.addTrigger( tg ); } Location[] loaHotspot = new Location[4]; if ( iOrientation == Orientation.HORIZONTAL ) { loaHotspot[0] = LocationImpl.create( loStart.getX( ) - IConstants.LINE_EXPAND_SIZE, loStart.getY( ) ); loaHotspot[1] = LocationImpl.create( loStart.getX( ) + IConstants.LINE_EXPAND_SIZE, loStart.getY( ) ); loaHotspot[2] = LocationImpl.create( loEnd.getX( ) + IConstants.LINE_EXPAND_SIZE, loEnd.getY( ) ); loaHotspot[3] = LocationImpl.create( loEnd.getX( ) - IConstants.LINE_EXPAND_SIZE, loEnd.getY( ) ); } else { loaHotspot[0] = LocationImpl.create( loStart.getX( ), loStart.getY( ) - IConstants.LINE_EXPAND_SIZE ); loaHotspot[1] = LocationImpl.create( loEnd.getX( ), loEnd.getY( ) - IConstants.LINE_EXPAND_SIZE ); loaHotspot[2] = LocationImpl.create( loEnd.getX( ), loEnd.getY( ) + IConstants.LINE_EXPAND_SIZE ); loaHotspot[3] = LocationImpl.create( loStart.getX( ), loStart.getY( ) + IConstants.LINE_EXPAND_SIZE ); } final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) idr ).getEventObject( StructureSource.createMarkerLine( ml ), PolygonRenderEvent.class ); pre.setPoints( loaHotspot ); iev.setHotSpot( pre ); idr.enableInteraction( iev ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_MARKER_LINE, ax, ml, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_MARKER_LINE, ml ); } } } /** * Renders the axis. * * @param ipr * @param pl * @param ax * @param iWhatToDraw * * @throws RenderingException */ public final void renderEachAxis( IPrimitiveRenderer ipr, Plot pl, OneAxis ax, int iWhatToDraw ) throws ChartException { final RunTimeContext rtc = getRunTimeContext( ); final Axis axModel = ax.getModelAxis( ); final PlotWithAxes pwa = (PlotWithAxes) getComputations( ); final Insets insCA = pwa.getAxes( ).getInsets( ); final ScriptHandler sh = getRunTimeContext( ).getScriptHandler( ); final double dLocation = ax.getAxisCoordinate( ); final AutoScale sc = ax.getScale( ); final IntersectionValue iv = ax.getIntersectionValue( ); final int iMajorTickStyle = ax.getGrid( ) .getTickStyle( IConstants.MAJOR ); final int iMinorTickStyle = ax.getGrid( ) .getTickStyle( IConstants.MINOR ); final int iLabelLocation = ax.getLabelPosition( ); final int iOrientation = ax.getOrientation( ); final IDisplayServer xs = this.getDevice( ).getDisplayServer( ); Label la = LabelImpl.copyInstance( ax.getLabel( ) ); final double[] daEndPoints = sc.getEndPoints( ); final double[] da = sc.getTickCordinates( ); final double[] daMinor = sc.getMinorCoordinates( ax.getGrid( ) .getMinorCountPerMajor( ) ); String sText = null; final int iDimension = pwa.getDimension( ); final double dSeriesThickness = pwa.getSeriesThickness( ); final NumberDataElement nde = NumberDataElementImpl.create( 0 ); final FormatSpecifier fs = ax.getModelAxis( ).getFormatSpecifier( ); final double dStaggeredLabelOffset = sc.computeStaggeredAxisLabelOffset( xs, la, iOrientation ); final boolean bAxisLabelStaggered = sc.isAxisLabelStaggered( ); DecimalFormat df = null; final LineAttributes lia = ax.getLineAttributes( ); final LineAttributes liaMajorTick = ax.getGrid( ) .getTickAttributes( IConstants.MAJOR ); final LineAttributes liaMinorTick = ax.getGrid( ) .getTickAttributes( IConstants.MINOR ); if ( !lia.isSetVisible( ) ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, "exception.unset.axis.visibility", //$NON-NLS-1$ Messages.getResourceBundle( getRunTimeContext( ).getULocale( ) ) ); } final boolean bRenderAxisLabels = ( ( iWhatToDraw & IConstants.LABELS ) == IConstants.LABELS && la.isVisible( ) ); final boolean bRenderAxisTitle = ( ( iWhatToDraw & IConstants.LABELS ) == IConstants.LABELS ); Location lo = LocationImpl.create( 0, 0 ); final TransformationEvent trae = (TransformationEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), TransformationEvent.class ); final TextRenderEvent tre = (TextRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), TextRenderEvent.class ); tre.setLabel( la ); tre.setTextPosition( iLabelLocation ); tre.setLocation( lo ); final LineRenderEvent lre = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( 0, 0 ) ); lre.setEnd( LocationImpl.create( 0, 0 ) ); // Prepare 3D rendering variables. final boolean bRendering3D = iDimension == IConstants.THREE_D; final boolean bRenderOrthogonal3DAxis = ( iWhatToDraw & IConstants.ORTHOGONAL_AXIS ) == IConstants.ORTHOGONAL_AXIS && bRendering3D; final boolean bRenderBase3DAxis = ( iWhatToDraw & IConstants.BASE_AXIS ) == IConstants.BASE_AXIS && bRendering3D; final boolean bRenderAncillary3DAxis = ( iWhatToDraw & IConstants.ANCILLARY_AXIS ) == IConstants.ANCILLARY_AXIS && bRendering3D; final DeferredCache dc = getDeferredCache( ); final int axisType = ax.getAxisType( ); final Location panningOffset = getPanningOffset( ); final boolean bTransposed = ( (ChartWithAxes) getModel( ) ).isTransposed( ); double[] daEndPoints3D = null; double[] da3D = null; Location3D lo3d = null; Text3DRenderEvent t3dre = null; Line3DRenderEvent l3dre = null; double dXStart = 0; double dXEnd = 0; double dZStart = 0; double dZEnd = 0; if ( iDimension == IConstants.THREE_D ) { AllAxes aax = pwa.getAxes( ); dXEnd = aax.getPrimaryBase( ).getScale( ).getEnd( ); dZEnd = aax.getAncillaryBase( ).getScale( ).getEnd( ); dXStart = aax.getPrimaryBase( ).getScale( ).getStart( ); dZStart = aax.getAncillaryBase( ).getScale( ).getStart( ); daEndPoints3D = sc.getEndPoints( ); da3D = sc.getTickCordinates( ); lo3d = Location3DImpl.create( 0, 0, 0 ); t3dre = (Text3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Text3DRenderEvent.class ); t3dre.setLabel( la ); t3dre.setAction( Text3DRenderEvent.RENDER_TEXT_AT_LOCATION ); t3dre.setTextPosition( iLabelLocation ); t3dre.setLocation3D( lo3d ); l3dre = (Line3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Line3DRenderEvent.class ); l3dre.setLineAttributes( lia ); l3dre.setStart3D( Location3DImpl.create( 0, 0, 0 ) ); l3dre.setEnd3D( Location3DImpl.create( 0, 0, 0 ) ); } if ( iOrientation == IConstants.VERTICAL ) { int y; int y3d = 0; double dX = dLocation; double dZ = 0; if ( bRendering3D ) { Location3D l3d = ax.getAxisCoordinate3D( ); dX = l3d.getX( ); dZ = l3d.getZ( ); } if ( iv != null && iv.getType( ) == IntersectionValue.MAX && iDimension == IConstants.TWO_5_D ) { trae.setTransform( TransformationEvent.TRANSLATE ); trae.setTranslation( dSeriesThickness, -dSeriesThickness ); ipr.applyTransformation( trae ); } double dXTick1 = ( ( iMajorTickStyle & IConstants.TICK_LEFT ) == IConstants.TICK_LEFT ) ? ( dX - IConstants.TICK_SIZE ) : dX; double dXTick2 = ( ( iMajorTickStyle & IConstants.TICK_RIGHT ) == IConstants.TICK_RIGHT ) ? dX + IConstants.TICK_SIZE : dX; if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS && lia.isVisible( ) ) { if ( bRenderOrthogonal3DAxis ) { final double dStart = daEndPoints3D[0]; final double dEnd = daEndPoints3D[1]; l3dre.setLineAttributes( lia ); // center l3dre.setStart3D( dX, dStart, dZ ); l3dre.setEnd3D( dX, dEnd, dZ ); dc.addLine( l3dre ); // left l3dre.setStart3D( dX, dStart, dZEnd ); l3dre.setEnd3D( dX, dEnd, dZEnd ); dc.addLine( l3dre ); // right l3dre.setStart3D( dXEnd, dStart, dZ ); l3dre.setEnd3D( dXEnd, dEnd, dZ ); dc.addLine( l3dre ); if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = axModel.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { ArrayList cachedTriggers = null; Location3D[] loaHotspot = new Location3D[4]; Polygon3DRenderEvent pre3d = (Polygon3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Polygon3DRenderEvent.class ); // process center y-axis. loaHotspot[0] = Location3DImpl.create( dX - IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart, dZ + IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[1] = Location3DImpl.create( dX + IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart, dZ - IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[2] = Location3DImpl.create( dX + IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd, dZ - IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[3] = Location3DImpl.create( dX - IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd, dZ + IConstants.LINE_EXPAND_DOUBLE_SIZE ); pre3d.setPoints3D( loaHotspot ); pre3d.setDoubleSided( true ); if ( get3DEngine( ).processEvent( pre3d, panningOffset.getX( ), panningOffset.getY( ) ) != null ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); cachedTriggers = new ArrayList( ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); cachedTriggers.add( tg ); iev.addTrigger( TriggerImpl.copyInstance( tg ) ); } iev.setHotSpot( pre3d ); ipr.enableInteraction( iev ); } // process left y-axis. pre3d = (Polygon3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Polygon3DRenderEvent.class ); loaHotspot = new Location3D[4]; loaHotspot[0] = Location3DImpl.create( dXStart - IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart, dZEnd + IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[1] = Location3DImpl.create( dXStart + IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart, dZEnd - IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[2] = Location3DImpl.create( dXStart + IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd, dZEnd - IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[3] = Location3DImpl.create( dXStart - IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd, dZEnd + IConstants.LINE_EXPAND_DOUBLE_SIZE ); pre3d.setPoints3D( loaHotspot ); pre3d.setDoubleSided( true ); if ( get3DEngine( ).processEvent( pre3d, panningOffset.getX( ), panningOffset.getY( ) ) != null ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); if ( cachedTriggers == null ) { cachedTriggers = new ArrayList( ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); cachedTriggers.add( tg ); iev.addTrigger( TriggerImpl.copyInstance( tg ) ); } } else { for ( int t = 0; t < cachedTriggers.size( ); t++ ) { iev.addTrigger( TriggerImpl.copyInstance( (Trigger) cachedTriggers.get( t ) ) ); } } iev.setHotSpot( pre3d ); ipr.enableInteraction( iev ); } // process right y-axis. pre3d = (Polygon3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Polygon3DRenderEvent.class ); loaHotspot = new Location3D[4]; loaHotspot[0] = Location3DImpl.create( dXEnd - IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart, dZStart + IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[1] = Location3DImpl.create( dXEnd + IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart, dZStart - IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[2] = Location3DImpl.create( dXEnd + IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd, dZStart - IConstants.LINE_EXPAND_DOUBLE_SIZE ); loaHotspot[3] = Location3DImpl.create( dXEnd - IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd, dZStart + IConstants.LINE_EXPAND_DOUBLE_SIZE ); pre3d.setPoints3D( loaHotspot ); pre3d.setDoubleSided( true ); if ( get3DEngine( ).processEvent( pre3d, panningOffset.getX( ), panningOffset.getY( ) ) != null ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); if ( cachedTriggers == null ) { for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); iev.addTrigger( tg ); } } else { for ( int t = 0; t < cachedTriggers.size( ); t++ ) { iev.addTrigger( (Trigger) cachedTriggers.get( t ) ); } } iev.setHotSpot( pre3d ); ipr.enableInteraction( iev ); } } } } else { double dStart = daEndPoints[0] + insCA.getBottom( ), dEnd = daEndPoints[1] - insCA.getTop( ); if ( sc.getDirection( ) == IConstants.FORWARD ) { dStart = daEndPoints[1] + insCA.getBottom( ); dEnd = daEndPoints[0] - insCA.getTop( ); } if ( iv != null && iv.getType( ) == IntersectionValue.VALUE && iDimension == IConstants.TWO_5_D ) { final Location[] loa = new Location[4]; loa[0] = LocationImpl.create( dX, dStart ); loa[1] = LocationImpl.create( dX + dSeriesThickness, dStart - dSeriesThickness ); loa[2] = LocationImpl.create( dX + dSeriesThickness, dEnd - dSeriesThickness ); loa[3] = LocationImpl.create( dX, dEnd ); final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), PolygonRenderEvent.class ); pre.setPoints( loa ); pre.setBackground( ColorDefinitionImpl.create( 255, 255, 255, 127 ) ); pre.setOutline( lia ); ipr.fillPolygon( pre ); } lre.setLineAttributes( lia ); lre.getStart( ).set( dX, dStart ); lre.getEnd( ).set( dX, dEnd ); ipr.drawLine( lre ); if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = axModel.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); iev.addTrigger( tg ); } Location[] loaHotspot = new Location[4]; loaHotspot[0] = LocationImpl.create( dX - IConstants.LINE_EXPAND_SIZE, dStart ); loaHotspot[1] = LocationImpl.create( dX + IConstants.LINE_EXPAND_SIZE, dStart ); loaHotspot[2] = LocationImpl.create( dX + IConstants.LINE_EXPAND_SIZE, dEnd ); loaHotspot[3] = LocationImpl.create( dX - IConstants.LINE_EXPAND_SIZE, dEnd ); final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), PolygonRenderEvent.class ); pre.setPoints( loaHotspot ); iev.setHotSpot( pre ); ipr.enableInteraction( iev ); } } } } // The vertical axis directon, -1 means bottom->top, 1 means // top->bottom. final int iDirection = sc.getDirection( ) != IConstants.FORWARD ? -1 : 1; if ( ( sc.getType( ) & IConstants.TEXT ) == IConstants.TEXT || sc.isCategoryScale( ) ) { final double dUnitSize = iDirection * sc.getUnitSize( ); final double dOffset = dUnitSize / 2; DataSetIterator dsi = sc.getData( ); final int iDateTimeUnit = ( sc.getType( ) == IConstants.DATE_TIME ) ? CDateTime.computeUnit( dsi ) : IConstants.UNDEFINED; final ITextMetrics itmText = xs.getTextMetrics( la ); double x = ( iLabelLocation == IConstants.LEFT ) ? dXTick1 - 1 : dXTick2 + 1; dsi.reset( ); for ( int i = 0; i < da.length - 1; i++ ) { if ( bRenderAxisLabels ) { la.getCaption( ) .setValue( sc.formatCategoryValue( sc.getType( ), dsi.next( ), iDateTimeUnit ) ); if ( sc.isTickLabelVisible( i ) ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); itmText.reuse( la ); // RECYCLED } } y = (int) da[i]; if ( bRendering3D ) { y3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dXMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_LEFT ) == IConstants.TICK_LEFT ) ? ( dX - IConstants.TICK_SIZE ) : dX; double dXMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_RIGHT ) == IConstants.TICK_RIGHT ) ? dX + IConstants.TICK_SIZE : dX; if ( dXMinorTick1 != dXMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dXMinorTick1, // y3d + daMinor[k], // l3dreMinor.setEnd3D( // Location3DImpl.create( dXMinorTick2, // y3d + daMinor[k], // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( dXMinorTick1, y + iDirection * daMinor[k] ) ); lreMinor.setEnd( LocationImpl.create( dXMinorTick2, y + iDirection * daMinor[k] ) ); ipr.drawLine( lreMinor ); } } } } if ( dXTick1 != dXTick2 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dXTick1, y3d, dZ ); // l3dre.setEnd3D( dXTick2, y3d, dZ ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( dXTick1, y ); lre.getEnd( ).set( dXTick2, y ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.setStart( LocationImpl.create( dX, y ) ); lre.setEnd( LocationImpl.create( dX + dSeriesThickness, y - dSeriesThickness ) ); ipr.drawLine( lre ); } } } if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { double sx = x; double sx2 = dXEnd; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.LEFT ) { sx -= dStaggeredLabelOffset; sx2 += dStaggeredLabelOffset; } else { sx += dStaggeredLabelOffset; sx2 -= dStaggeredLabelOffset; } } if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { // Left wall lo3d.set( sx - pwa.getHorizontalSpacingInPixels( ), y3d + dOffset, dZEnd + pwa.getHorizontalSpacingInPixels( ) ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.LEFT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); // Right wall lo3d.set( sx2 + pwa.getHorizontalSpacingInPixels( ), y3d + dOffset, dZ - pwa.getHorizontalSpacingInPixels( ) ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.RIGHT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( sx, y + dOffset ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } } y = (int) da[da.length - 1]; if ( bRendering3D ) { y3d = (int) da3D[da3D.length - 1]; } if ( dXTick1 != dXTick2 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dXTick1, y3d, dZ ); // l3dre.setEnd3D( dXTick2, y3d, dZ ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( dXTick1, y ); lre.getEnd( ).set( dXTick2, y ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.setStart( LocationImpl.create( dX, y ) ); lre.setEnd( LocationImpl.create( dX + dSeriesThickness, y - dSeriesThickness ) ); ipr.drawLine( lre ); } } itmText.dispose( );// DISPOSED } else if ( ( sc.getType( ) & IConstants.LINEAR ) == IConstants.LINEAR ) { double dAxisValue = Methods.asDouble( sc.getMinimum( ) ) .doubleValue( ); final double dAxisStep = Methods.asDouble( sc.getStep( ) ) .doubleValue( ); if ( fs == null ) { df = new DecimalFormat( sc.getNumericPattern( ) ); } dAxisValue = Methods.asDouble( sc.getMinimum( ) ).doubleValue( ); // RESET double x = ( iLabelLocation == IConstants.LEFT ) ? dXTick1 - 1 : dXTick2 + 1; for ( int i = 0; i < da.length; i++ ) { nde.setValue( dAxisValue ); try { sText = ValueFormatter.format( nde, fs, ax.getRunTimeContext( ).getULocale( ), df ); } catch ( ChartException dfex ) { logger.log( dfex ); sText = IConstants.NULL_STRING; } y = (int) da[i]; if ( bRendering3D ) { y3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dXMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_LEFT ) == IConstants.TICK_LEFT ) ? ( dX - IConstants.TICK_SIZE ) : dX, dXMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_RIGHT ) == IConstants.TICK_RIGHT ) ? dX + IConstants.TICK_SIZE : dX; if ( dXMinorTick1 != dXMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // if ( y3d + daMinor[k] >= da3D[i + 1] ) // // if current minor tick exceed the // // range of current unit, skip // continue; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dXMinorTick1, // y3d + daMinor[k], // l3dreMinor.setEnd3D( // Location3DImpl.create( dXMinorTick2, // y3d + daMinor[k], // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { if ( ( iDirection == -1 && y - daMinor[k] <= da[i + 1] ) || ( iDirection == 1 && y + daMinor[k] >= da[i + 1] ) ) { // if current minor tick exceed the // range of current unit, skip continue; } lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( dXMinorTick1, y + iDirection * daMinor[k] ) ); lreMinor.setEnd( LocationImpl.create( dXMinorTick2, y + iDirection * daMinor[k] ) ); ipr.drawLine( lreMinor ); } } } } if ( dXTick1 != dXTick2 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dXTick1, y3d, dZ ); // l3dre.setEnd3D( dXTick2, y3d, dZ ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( dXTick1, y ); lre.getEnd( ).set( dXTick2, y ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( dX, y ) ); lre.setEnd( LocationImpl.create( dX + dSeriesThickness, y - dSeriesThickness ) ); ipr.drawLine( lre ); } } } if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { double sx = x; double sx2 = dXEnd; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.LEFT ) { sx -= dStaggeredLabelOffset; sx2 += dStaggeredLabelOffset; } else { sx += dStaggeredLabelOffset; sx2 -= dStaggeredLabelOffset; } } ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { // Left wall lo3d.set( sx - pwa.getHorizontalSpacingInPixels( ), y3d, dZEnd + pwa.getHorizontalSpacingInPixels( ) ); la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.LEFT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); // Right wall lo3d.set( sx2 + pwa.getHorizontalSpacingInPixels( ), y3d, dZ - pwa.getHorizontalSpacingInPixels( ) ); la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.RIGHT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( sx, y ); la.getCaption( ).setValue( sText ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } if ( i == da.length - 2 ) { // This is the last tick, use pre-computed value to // handle // non-equal scale unit case. dAxisValue = Methods.asDouble( sc.getMaximum( ) ) .doubleValue( ); } else { dAxisValue += dAxisStep; } } } else if ( ( sc.getType( ) & IConstants.LOGARITHMIC ) == IConstants.LOGARITHMIC ) { double dAxisValue = Methods.asDouble( sc.getMinimum( ) ) .doubleValue( ); final double dAxisStep = Methods.asDouble( sc.getStep( ) ) .doubleValue( ); dAxisValue = Methods.asDouble( sc.getMinimum( ) ).doubleValue( ); // RESET double x = ( iLabelLocation == IConstants.LEFT ) ? dXTick1 - 1 : dXTick2 + 1; for ( int i = 0; i < da.length; i++ ) { if ( bRenderAxisLabels ) // PERFORM COMPUTATIONS ONLY IF // AXIS LABEL IS VISIBLE { if ( fs == null ) { df = new DecimalFormat( sc.getNumericPattern( dAxisValue ) ); } nde.setValue( dAxisValue ); try { sText = ValueFormatter.format( nde, fs, ax.getRunTimeContext( ).getULocale( ), df ); } catch ( ChartException dfex ) { logger.log( dfex ); sText = IConstants.NULL_STRING; } } y = (int) da[i]; if ( bRendering3D ) { y3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dXMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_LEFT ) == IConstants.TICK_LEFT ) ? ( dX - IConstants.TICK_SIZE ) : dX; double dXMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_RIGHT ) == IConstants.TICK_RIGHT ) ? dX + IConstants.TICK_SIZE : dX; if ( dXMinorTick1 != dXMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dXMinorTick1, // y3d + daMinor[k], // l3dreMinor.setEnd3D( // Location3DImpl.create( dXMinorTick2, // y3d + daMinor[k], // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( dXMinorTick1, y + iDirection * daMinor[k] ) ); lreMinor.setEnd( LocationImpl.create( dXMinorTick2, y + iDirection * daMinor[k] ) ); ipr.drawLine( lreMinor ); } } } } if ( dXTick1 != dXTick2 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dXTick1, y3d, dZ ); // l3dre.setEnd3D( dXTick2, y3d, dZ ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( dXTick1, y ); lre.getEnd( ).set( dXTick2, y ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.setLineAttributes( lia ); lre.setStart( LocationImpl.create( dX, y ) ); lre.setEnd( LocationImpl.create( dX + dSeriesThickness, y - dSeriesThickness ) ); ipr.drawLine( lre ); } } } // RENDER LABELS ONLY IF REQUESTED if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { double sx = x; double sx2 = dXEnd; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.LEFT ) { sx -= dStaggeredLabelOffset; sx2 += dStaggeredLabelOffset; } else { sx += dStaggeredLabelOffset; sx2 -= dStaggeredLabelOffset; } } ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { // Left wall lo3d.set( sx - pwa.getHorizontalSpacingInPixels( ), y3d, dZEnd + pwa.getHorizontalSpacingInPixels( ) ); la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.LEFT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); // Right wall lo3d.set( sx2 + pwa.getHorizontalSpacingInPixels( ), y3d, dZ - pwa.getHorizontalSpacingInPixels( ) ); la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.RIGHT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( sx, y ); la.getCaption( ).setValue( sText ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } dAxisValue *= dAxisStep; } } else if ( ( sc.getType( ) & IConstants.DATE_TIME ) == IConstants.DATE_TIME ) { CDateTime cdt, cdtAxisValue = Methods.asDateTime( sc.getMinimum( ) ); final int iUnit = Methods.asInteger( sc.getUnit( ) ); final int iStep = Methods.asInteger( sc.getStep( ) ); IDateFormatWrapper sdf = null; if ( fs == null ) { sdf = DateFormatWrapperFactory.getPreferredDateFormat( iUnit, rtc.getULocale( ) ); } cdt = cdtAxisValue; double x = ( iLabelLocation == IConstants.LEFT ) ? dXTick1 - 1 : dXTick2 + 1; for ( int i = 0; i < da.length; i++ ) { try { sText = ValueFormatter.format( cdt, ax.getFormatSpecifier( ), ax.getRunTimeContext( ).getULocale( ), sdf ); } catch ( ChartException dfex ) { logger.log( dfex ); sText = IConstants.NULL_STRING; } y = (int) da[i]; if ( bRendering3D ) { y3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dXMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_LEFT ) == IConstants.TICK_LEFT ) ? ( dX - IConstants.TICK_SIZE ) : dX, dXMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_RIGHT ) == IConstants.TICK_RIGHT ) ? dX + IConstants.TICK_SIZE : dX; if ( dXMinorTick1 != dXMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dXMinorTick1, // y3d + daMinor[k], // l3dreMinor.setEnd3D( // Location3DImpl.create( dXMinorTick2, // y3d + daMinor[k], // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( dXMinorTick1, y + iDirection * daMinor[k] ) ); lreMinor.setEnd( LocationImpl.create( dXMinorTick2, y + iDirection * daMinor[k] ) ); ipr.drawLine( lreMinor ); } } } } if ( dXTick1 != dXTick2 ) { if ( bRenderOrthogonal3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dXTick1, y3d, dZ ); // l3dre.setEnd3D( dXTick2, y3d, dZ ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( dXTick1, y ); lre.getEnd( ).set( dXTick2, y ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.setStart( LocationImpl.create( dX, y ) ); lre.setEnd( LocationImpl.create( dX + dSeriesThickness, y - dSeriesThickness ) ); ipr.drawLine( lre ); } } } if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { double sx = x; double sx2 = dXEnd; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.LEFT ) { sx -= dStaggeredLabelOffset; sx2 += dStaggeredLabelOffset; } else { sx += dStaggeredLabelOffset; sx2 -= dStaggeredLabelOffset; } } ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { // Left wall lo3d.set( sx - pwa.getHorizontalSpacingInPixels( ), y3d, dZEnd + pwa.getHorizontalSpacingInPixels( ) ); la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.LEFT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); // Right wall lo3d.set( sx2 + pwa.getHorizontalSpacingInPixels( ), y3d, dZ - pwa.getHorizontalSpacingInPixels( ) ); la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setTextPosition( TextRenderEvent.RIGHT ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( sx, y ); la.getCaption( ).setValue( sText ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } // ALWAYS W.R.T START VALUE cdt = cdtAxisValue.forward( iUnit, iStep * ( i + 1 ) ); } } la = LabelImpl.copyInstance( ax.getTitle( ) ); // TEMPORARILY USE // FOR AXIS TITLE if ( la.isVisible( ) && bRenderAxisTitle ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_TITLE, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_TITLE, la ); final String sRestoreValue = la.getCaption( ).getValue( ); la.getCaption( ) .setValue( rtc.externalizedMessage( sRestoreValue ) ); BoundingBox bb = null; try { bb = Methods.computeBox( xs, ax.getTitlePosition( ), la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, uiex ); } if ( ax.getTitle( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { Bounds cbo = getPlotBounds( ); tre.setBlockBounds( BoundsImpl.create( cbo.getLeft( ) + ( cbo.getWidth( ) / 3d - bb.getWidth( ) ) / 2d, cbo.getTop( ) + 30, bb.getWidth( ), bb.getHeight( ) ) ); tre.setLabel( la ); tre.setBlockAlignment( la.getCaption( ) .getFont( ) .getAlignment( ) ); tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK ); ipr.drawText( tre ); tre.setBlockBounds( BoundsImpl.create( cbo.getLeft( ) + cbo.getWidth( ) - bb.getWidth( ), cbo.getTop( ) + 30 * 2, bb.getWidth( ), bb.getHeight( ) ) ); ipr.drawText( tre ); } else { final Bounds bo = BoundsImpl.create( ax.getTitleCoordinate( ), daEndPoints[1], bb.getWidth( ), daEndPoints[0] - daEndPoints[1] ); tre.setBlockBounds( bo ); tre.setLabel( la ); tre.setBlockAlignment( la.getCaption( ) .getFont( ) .getAlignment( ) ); tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK ); if ( ax.getTitle( ).isVisible( ) ) { ipr.drawText( tre ); } } } la.getCaption( ).setValue( sRestoreValue ); ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_TITLE, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_TITLE, la ); } la = LabelImpl.copyInstance( ax.getLabel( ) ); if ( iv != null && iv.getType( ) == IntersectionValue.MAX && iDimension == IConstants.TWO_5_D ) { trae.setTranslation( -dSeriesThickness, dSeriesThickness ); ipr.applyTransformation( trae ); } } else if ( iOrientation == IConstants.HORIZONTAL ) { int x; int x3d = 0; int z3d = 0; double dY = dLocation; double dX = 0; double dZ = 0; if ( bRendering3D ) { Location3D l3d = ax.getAxisCoordinate3D( ); dX = l3d.getX( ); dY = l3d.getY( ); dZ = l3d.getZ( ); } double dYTick1 = ( ( iMajorTickStyle & IConstants.TICK_ABOVE ) == IConstants.TICK_ABOVE ) ? ( bRendering3D ? dY + IConstants.TICK_SIZE : dY - IConstants.TICK_SIZE ) : dY; double dYTick2 = ( ( iMajorTickStyle & IConstants.TICK_BELOW ) == IConstants.TICK_BELOW ) ? ( bRendering3D ? dY - IConstants.TICK_SIZE : dY + IConstants.TICK_SIZE ) : dY; if ( iv != null && iDimension == IConstants.TWO_5_D && ( ( bTransposed && isRightToLeft( ) && iv.getType( ) == IntersectionValue.MIN ) || ( !isRightToLeft( ) && iv.getType( ) == IntersectionValue.MAX ) ) ) { trae.setTransform( TransformationEvent.TRANSLATE ); trae.setTranslation( dSeriesThickness, -dSeriesThickness ); ipr.applyTransformation( trae ); } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS && lia.isVisible( ) ) { if ( bRenderBase3DAxis ) { final double dStart = daEndPoints3D[0]; final double dEnd = daEndPoints3D[1]; l3dre.setLineAttributes( lia ); l3dre.setStart3D( dStart, dY, dZ ); l3dre.setEnd3D( dEnd, dY, dZ ); dc.addLine( l3dre ); if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = axModel.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { final Polygon3DRenderEvent pre3d = (Polygon3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Polygon3DRenderEvent.class ); Location3D[] loaHotspot = new Location3D[4]; loaHotspot[0] = Location3DImpl.create( dStart, dY - IConstants.LINE_EXPAND_DOUBLE_SIZE, dZ ); loaHotspot[1] = Location3DImpl.create( dStart, dY + IConstants.LINE_EXPAND_DOUBLE_SIZE, dZ ); loaHotspot[2] = Location3DImpl.create( dEnd, dY + IConstants.LINE_EXPAND_DOUBLE_SIZE, dZ ); loaHotspot[3] = Location3DImpl.create( dEnd, dY - IConstants.LINE_EXPAND_DOUBLE_SIZE, dZ ); pre3d.setPoints3D( loaHotspot ); pre3d.setDoubleSided( true ); if ( get3DEngine( ).processEvent( pre3d, panningOffset.getX( ), panningOffset.getY( ) ) != null ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); iev.addTrigger( tg ); } iev.setHotSpot( pre3d ); ipr.enableInteraction( iev ); } } } } else if ( bRenderAncillary3DAxis ) { final double dStart = daEndPoints3D[0]; final double dEnd = daEndPoints3D[1]; l3dre.setLineAttributes( lia ); l3dre.setStart3D( dX, dY, dStart ); l3dre.setEnd3D( dX, dY, dEnd ); dc.addLine( l3dre ); if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = axModel.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { final Polygon3DRenderEvent pre3d = (Polygon3DRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), Polygon3DRenderEvent.class ); Location3D[] loaHotspot = new Location3D[4]; loaHotspot[0] = Location3DImpl.create( dX, dY - IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart ); loaHotspot[1] = Location3DImpl.create( dX, dY + IConstants.LINE_EXPAND_DOUBLE_SIZE, dStart ); loaHotspot[2] = Location3DImpl.create( dX, dY + IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd ); loaHotspot[3] = Location3DImpl.create( dX, dY - IConstants.LINE_EXPAND_DOUBLE_SIZE, dEnd ); pre3d.setPoints3D( loaHotspot ); pre3d.setDoubleSided( true ); if ( get3DEngine( ).processEvent( pre3d, panningOffset.getX( ), panningOffset.getY( ) ) != null ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); iev.addTrigger( tg ); } iev.setHotSpot( pre3d ); ipr.enableInteraction( iev ); } } } } else { double dStart = daEndPoints[0] - insCA.getLeft( ), dEnd = daEndPoints[1] + insCA.getRight( ); if ( sc.getDirection( ) == IConstants.BACKWARD ) { dStart = daEndPoints[1] - insCA.getLeft( ); dEnd = daEndPoints[0] + insCA.getRight( ); } if ( iv != null && iv.getType( ) == IntersectionValue.VALUE && iDimension == IConstants.TWO_5_D ) { // Zero plane. final Location[] loa = new Location[4]; loa[0] = LocationImpl.create( dStart, dY ); loa[1] = LocationImpl.create( dStart + dSeriesThickness, dY - dSeriesThickness ); loa[2] = LocationImpl.create( dEnd + dSeriesThickness, dY - dSeriesThickness ); loa[3] = LocationImpl.create( dEnd, dY ); final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), PolygonRenderEvent.class ); pre.setPoints( loa ); pre.setBackground( ColorDefinitionImpl.create( 255, 255, 255, 127 ) ); pre.setOutline( lia ); ipr.fillPolygon( pre ); } lre.setLineAttributes( lia ); lre.getStart( ).set( dStart, dY ); lre.getEnd( ).set( dEnd, dY ); ipr.drawLine( lre ); if ( isInteractivityEnabled( ) ) { Trigger tg; EList elTriggers = axModel.getTriggers( ); if ( !elTriggers.isEmpty( ) ) { final InteractionEvent iev = (InteractionEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), InteractionEvent.class ); for ( int t = 0; t < elTriggers.size( ); t++ ) { tg = TriggerImpl.copyInstance( (Trigger) elTriggers.get( t ) ); processTrigger( tg, StructureSource.createAxis( axModel ) ); iev.addTrigger( tg ); } Location[] loaHotspot = new Location[4]; loaHotspot[0] = LocationImpl.create( dStart, dY - IConstants.LINE_EXPAND_SIZE ); loaHotspot[1] = LocationImpl.create( dEnd, dY - IConstants.LINE_EXPAND_SIZE ); loaHotspot[2] = LocationImpl.create( dEnd, dY + IConstants.LINE_EXPAND_SIZE ); loaHotspot[3] = LocationImpl.create( dStart, dY + IConstants.LINE_EXPAND_SIZE ); final PolygonRenderEvent pre = (PolygonRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), PolygonRenderEvent.class ); pre.setPoints( loaHotspot ); iev.setHotSpot( pre ); ipr.enableInteraction( iev ); } } } } // The horizontal axis direction. -1 means right->left, 1 means // left->right. final int iDirection = sc.getDirection( ) == IConstants.BACKWARD ? -1 : 1; if ( ( sc.getType( ) & IConstants.TEXT ) == IConstants.TEXT || sc.isCategoryScale( ) ) { final double dUnitSize = iDirection * sc.getUnitSize( ); final double dOffset = dUnitSize / 2; DataSetIterator dsi = sc.getData( ); final int iDateTimeUnit = ( sc.getType( ) == IConstants.DATE_TIME ) ? CDateTime.computeUnit( dsi ) : IConstants.UNDEFINED; final ITextMetrics itmText = xs.getTextMetrics( la ); double y = ( iLabelLocation == IConstants.ABOVE ) ? ( bRendering3D ? dYTick1 + 1 : dYTick1 - 1 ) : ( bRendering3D ? dYTick2 - 1 : dYTick2 + 1 ); dsi.reset( ); for ( int i = 0; i < da.length - 1; i++ ) { x = (int) da[i]; if ( bRendering3D ) { x3d = (int) da3D[i]; z3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dYMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_ABOVE ) == IConstants.TICK_ABOVE ) ? ( bRendering3D ? dY + IConstants.TICK_SIZE : dY - IConstants.TICK_SIZE ) : dY; double dYMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_BELOW ) == IConstants.TICK_BELOW ) ? ( bRendering3D ? dY - IConstants.TICK_SIZE : dY + IConstants.TICK_SIZE ) : dY; if ( dYMinorTick1 != -dYMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick1, // l3dreMinor.setEnd3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick2, // dc.addLine( l3dreMinor ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dX, // dYMinorTick1, // z3d + daMinor[k] ) ); // l3dreMinor.setEnd3D( // Location3DImpl.create( dX, // dYMinorTick2, // z3d + daMinor[k] ) ); // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick1 ) ); lreMinor.setEnd( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick2 ) ); ipr.drawLine( lreMinor ); } } } } if ( dYTick1 != dYTick2 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( x3d, dYTick1, dZ ); // l3dre.setEnd3D( x3d, dYTick2, dZ ); // dc.addLine( l3dre ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dX, dYTick1, z3d ); // l3dre.setEnd3D( dX, dYTick2, z3d ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( x, dYTick1 ); lre.getEnd( ).set( x, dYTick2 ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.getStart( ).set( x, dY ); lre.getEnd( ).set( x + dSeriesThickness, dY - dSeriesThickness ); ipr.drawLine( lre ); } } } if ( bRenderAxisLabels ) { la.getCaption( ) .setValue( sc.formatCategoryValue( sc.getType( ), dsi.next( ), // step to next value. iDateTimeUnit ) ); if ( sc.isTickLabelVisible( i ) ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); itmText.reuse( la );// RECYCLED double sy = y; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.ABOVE ) { sy -= dStaggeredLabelOffset; } else { sy += dStaggeredLabelOffset; } } if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { if ( axisType == IConstants.BASE_AXIS ) { lo3d.set( x3d + dOffset, sy - pwa.getVerticalSpacingInPixels( ), dZEnd + pwa.getVerticalSpacingInPixels( ) ); } else { lo3d.set( dXEnd + pwa.getVerticalSpacingInPixels( ), sy - pwa.getVerticalSpacingInPixels( ), z3d + dOffset ); } t3dre.setLocation3D( lo3d ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( x + dOffset, sy ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } } } // ONE LAST TICK x = (int) da[da.length - 1]; if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { if ( dYTick1 != dYTick2 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( x3d, dYTick1, dZ ); // l3dre.setEnd3D( x3d, dYTick2, dZ ); // dc.addLine( l3dre ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dX, dYTick1, z3d ); // l3dre.setEnd3D( dX, dYTick2, z3d ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( x, dYTick1 ); lre.getEnd( ).set( x, dYTick2 ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.getStart( ).set( x, dY ); lre.getEnd( ).set( x + dSeriesThickness, dY - dSeriesThickness ); ipr.drawLine( lre ); } } } itmText.dispose( ); // DISPOSED } else if ( ( sc.getType( ) & IConstants.LINEAR ) == IConstants.LINEAR ) { double dAxisValue = Methods.asDouble( sc.getMinimum( ) ) .doubleValue( ); final double dAxisStep = Methods.asDouble( sc.getStep( ) ) .doubleValue( ); if ( fs == null ) { df = new DecimalFormat( sc.getNumericPattern( ) ); } dAxisValue = Methods.asDouble( sc.getMinimum( ) ).doubleValue( ); // RESET double y = ( iLabelLocation == IConstants.ABOVE ) ? ( bRendering3D ? dYTick1 + 1 : dYTick1 - 1 ) : ( bRendering3D ? dYTick2 - 1 : dYTick2 + 1 ); for ( int i = 0; i < da.length; i++ ) { x = (int) da[i]; if ( bRendering3D ) { x3d = (int) da3D[i]; z3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dYMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_ABOVE ) == IConstants.TICK_ABOVE ) ? ( bRendering3D ? dY + IConstants.TICK_SIZE : dY - IConstants.TICK_SIZE ) : dY; double dYMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_BELOW ) == IConstants.TICK_BELOW ) ? ( bRendering3D ? dY - IConstants.TICK_SIZE : dY + IConstants.TICK_SIZE ) : dY; if ( dYMinorTick1 != -dYMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // if ( x3d + daMinor[k] >= da3D[i + 1] ) // // if current minor tick exceed the // // range of current unit, skip // continue; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick1, // l3dreMinor.setEnd3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick2, // dc.addLine( l3dreMinor ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // if ( z3d + daMinor[k] >= da3D[i + 1] ) // // if current minor tick exceed the // // range of current unit, skip // continue; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dX, // dYMinorTick1, // z3d + daMinor[k] ) ); // l3dreMinor.setEnd3D( // Location3DImpl.create( dX, // dYMinorTick2, // z3d + daMinor[k] ) ); // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { if ( ( iDirection == 1 && x + daMinor[k] >= da[i + 1] ) || ( iDirection == -1 && x - daMinor[k] <= da[i + 1] ) ) { // if current minor tick exceed the // range of current unit, skip continue; } lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick1 ) ); lreMinor.setEnd( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick2 ) ); ipr.drawLine( lreMinor ); } } } } if ( dYTick1 != dYTick2 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( x3d, dYTick1, dZ ); // l3dre.setEnd3D( x3d, dYTick2, dZ ); // dc.addLine( l3dre ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dX, dYTick1, z3d ); // l3dre.setEnd3D( dX, dYTick2, z3d ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( x, dYTick1 ); lre.getEnd( ).set( x, dYTick2 ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.getStart( ).set( x, dY ); lre.getEnd( ).set( x + dSeriesThickness, dY - dSeriesThickness ); ipr.drawLine( lre ); } } } // OPTIMIZED: ONLY PROCESS IF AXES LABELS ARE VISIBLE OR // REQUESTED FOR if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { nde.setValue( dAxisValue ); try { sText = ValueFormatter.format( nde, ax.getFormatSpecifier( ), ax.getRunTimeContext( ).getULocale( ), df ); } catch ( ChartException dfex ) { logger.log( dfex ); sText = IConstants.NULL_STRING; } ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); double sy = y; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.ABOVE ) { sy -= dStaggeredLabelOffset; } else { sy += dStaggeredLabelOffset; } } if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { if ( axisType == IConstants.BASE_AXIS ) { lo3d.set( x3d, sy - pwa.getVerticalSpacingInPixels( ), dZEnd + pwa.getVerticalSpacingInPixels( ) ); } else { lo3d.set( dXEnd + pwa.getVerticalSpacingInPixels( ), sy - pwa.getVerticalSpacingInPixels( ), z3d ); } la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( x, sy ); la.getCaption( ).setValue( sText ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } if ( i == da.length - 2 ) { // This is the last tick, use pre-computed value to // handle // non-equal scale unit case. dAxisValue = Methods.asDouble( sc.getMaximum( ) ) .doubleValue( ); } else { dAxisValue += dAxisStep; } } } else if ( ( sc.getType( ) & IConstants.LOGARITHMIC ) == IConstants.LOGARITHMIC ) { double dAxisValue = Methods.asDouble( sc.getMinimum( ) ) .doubleValue( ); final double dAxisStep = Methods.asDouble( sc.getStep( ) ) .doubleValue( ); dAxisValue = Methods.asDouble( sc.getMinimum( ) ).doubleValue( ); // RESET double y = ( iLabelLocation == IConstants.ABOVE ) ? ( bRendering3D ? dYTick1 + 1 : dYTick1 - 1 ) : ( bRendering3D ? dYTick2 - 1 : dYTick2 + 1 ); for ( int i = 0; i < da.length; i++ ) { x = (int) da[i]; if ( bRendering3D ) { x3d = (int) da3D[i]; z3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dYMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_ABOVE ) == IConstants.TICK_ABOVE ) ? ( bRendering3D ? dY + IConstants.TICK_SIZE : dY - IConstants.TICK_SIZE ) : dY; double dYMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_BELOW ) == IConstants.TICK_BELOW ) ? ( bRendering3D ? dY - IConstants.TICK_SIZE : dY + IConstants.TICK_SIZE ) : dY; if ( dYMinorTick1 != -dYMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick1, // l3dreMinor.setEnd3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick2, // dc.addLine( l3dreMinor ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dX, // dYMinorTick1, // z3d + daMinor[k] ) ); // l3dreMinor.setEnd3D( // Location3DImpl.create( dX, // dYMinorTick2, // z3d + daMinor[k] ) ); // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick1 ) ); lreMinor.setEnd( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick2 ) ); ipr.drawLine( lreMinor ); } } } } if ( dYTick1 != dYTick2 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( x3d, dYTick1, dZ ); // l3dre.setEnd3D( x3d, dYTick2, dZ ); // dc.addLine( l3dre ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dX, dYTick1, z3d ); // l3dre.setEnd3D( dX, dYTick2, z3d ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( lia ); lre.getStart( ).set( x, dYTick1 ); lre.getEnd( ).set( x, dYTick2 ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.getStart( ).set( x, dY ); lre.getEnd( ).set( x + dSeriesThickness, dY - dSeriesThickness ); ipr.drawLine( lre ); } } } // OPTIMIZED: ONLY PROCESS IF AXES LABELS ARE VISIBLE OR // REQUESTED FOR if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { if ( fs == null ) { df = new DecimalFormat( sc.getNumericPattern( dAxisValue ) ); } nde.setValue( dAxisValue ); try { sText = ValueFormatter.format( nde, ax.getFormatSpecifier( ), ax.getRunTimeContext( ).getULocale( ), df ); } catch ( ChartException dfex ) { logger.log( dfex ); sText = IConstants.NULL_STRING; } ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); double sy = y; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.ABOVE ) { sy -= dStaggeredLabelOffset; } else { sy += dStaggeredLabelOffset; } } if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { if ( axisType == IConstants.BASE_AXIS ) { lo3d.set( x3d, sy - pwa.getVerticalSpacingInPixels( ), dZEnd + pwa.getVerticalSpacingInPixels( ) ); } else { lo3d.set( dXEnd + pwa.getVerticalSpacingInPixels( ), sy - pwa.getVerticalSpacingInPixels( ), z3d ); } la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( x, sy ); la.getCaption( ).setValue( sText ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } dAxisValue *= dAxisStep; } } else if ( ( sc.getType( ) & IConstants.DATE_TIME ) == IConstants.DATE_TIME ) { CDateTime cdt, cdtAxisValue = Methods.asDateTime( sc.getMinimum( ) ); final int iUnit = Methods.asInteger( sc.getUnit( ) ); final int iStep = Methods.asInteger( sc.getStep( ) ); IDateFormatWrapper sdf = null; if ( fs == null ) { sdf = DateFormatWrapperFactory.getPreferredDateFormat( iUnit, rtc.getULocale( ) ); } cdt = cdtAxisValue; double y = ( iLabelLocation == IConstants.ABOVE ) ? ( bRendering3D ? dYTick1 + 1 : dYTick1 - 1 ) : ( bRendering3D ? dYTick2 - 1 : dYTick2 + 1 ); for ( int i = 0; i < da.length; i++ ) { x = (int) da[i]; if ( bRendering3D ) { x3d = (int) da3D[i]; z3d = (int) da3D[i]; } if ( ( iWhatToDraw & IConstants.AXIS ) == IConstants.AXIS ) { double dYMinorTick1 = ( ( iMinorTickStyle & IConstants.TICK_ABOVE ) == IConstants.TICK_ABOVE ) ? ( bRendering3D ? dY + IConstants.TICK_SIZE : dY - IConstants.TICK_SIZE ) : dY; double dYMinorTick2 = ( ( iMinorTickStyle & IConstants.TICK_BELOW ) == IConstants.TICK_BELOW ) ? ( bRendering3D ? dY - IConstants.TICK_SIZE : dY + IConstants.TICK_SIZE ) : dY; if ( dYMinorTick1 != -dYMinorTick2 ) { // RENDER THE MINOR TICKS FIRST (For ALL but the // last Major tick) if ( i != da.length - 1 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick1, // l3dreMinor.setEnd3D( // Location3DImpl.create( x3d // + daMinor[k], // dYMinorTick2, // dc.addLine( l3dreMinor ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // Line3DRenderEvent l3dreMinor = null; // for ( int k = 0; k < daMinor.length - 1; // l3dreMinor = (Line3DRenderEvent) ( // (EventObjectCache) ipr ).getEventObject( // StructureSource.createAxis( axModel ), // Line3DRenderEvent.class ); // l3dreMinor.setLineAttributes( // liaMinorTick ); // l3dreMinor.setStart3D( // Location3DImpl.create( dX, // dYMinorTick1, // z3d + daMinor[k] ) ); // l3dreMinor.setEnd3D( // Location3DImpl.create( dX, // dYMinorTick2, // z3d + daMinor[k] ) ); // dc.addLine( l3dreMinor ); } else { LineRenderEvent lreMinor = null; for ( int k = 0; k < daMinor.length - 1; k++ ) { lreMinor = (LineRenderEvent) ( (EventObjectCache) ipr ).getEventObject( StructureSource.createAxis( axModel ), LineRenderEvent.class ); lreMinor.setLineAttributes( liaMinorTick ); lreMinor.setStart( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick1 ) ); lreMinor.setEnd( LocationImpl.create( x + iDirection * daMinor[k], dYMinorTick2 ) ); ipr.drawLine( lreMinor ); } } } } if ( dYTick1 != dYTick2 ) { if ( bRenderBase3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( x3d, dYTick1, dZ ); // l3dre.setEnd3D( x3d, dYTick2, dZ ); // dc.addLine( l3dre ); } else if ( bRenderAncillary3DAxis ) { // !NOT RENDER TICKS FOR 3D AXES // l3dre.setLineAttributes( liaMajorTick ); // l3dre.setStart3D( dX, dYTick1, z3d ); // l3dre.setEnd3D( dX, dYTick2, z3d ); // dc.addLine( l3dre ); } else { lre.setLineAttributes( liaMajorTick ); lre.getStart( ).set( x, dYTick1 ); lre.getEnd( ).set( x, dYTick2 ); ipr.drawLine( lre ); } if ( iv != null && iDimension == IConstants.TWO_5_D && iv.getType( ) == IntersectionValue.VALUE ) { lre.getStart( ).set( x, dY ); lre.getEnd( ).set( x + dSeriesThickness, dY - dSeriesThickness ); ipr.drawLine( lre ); } } } // OPTIMIZED: ONLY PROCESS IF AXES LABELS ARE VISIBLE OR // REQUESTED FOR if ( bRenderAxisLabels && sc.isTickLabelVisible( i ) ) { try { sText = ValueFormatter.format( cdt, ax.getFormatSpecifier( ), ax.getRunTimeContext( ).getULocale( ), sdf ); } catch ( ChartException dfex ) { logger.log( dfex ); sText = IConstants.NULL_STRING; } ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_LABEL, la ); double sy = y; if ( bAxisLabelStaggered && sc.isTickLabelStaggered( i ) ) { if ( iLabelLocation == IConstants.ABOVE ) { sy -= dStaggeredLabelOffset; } else { sy += dStaggeredLabelOffset; } } if ( ax.getLabel( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { if ( axisType == IConstants.BASE_AXIS ) { lo3d.set( x3d, sy - pwa.getVerticalSpacingInPixels( ), dZEnd + pwa.getVerticalSpacingInPixels( ) ); } else { lo3d.set( dXEnd + pwa.getVerticalSpacingInPixels( ), sy - pwa.getVerticalSpacingInPixels( ), z3d ); } la.getCaption( ).setValue( sText ); t3dre.setLocation3D( lo3d ); t3dre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); dc.addLabel( t3dre ); } else { lo.set( x, sy ); la.getCaption( ).setValue( sText ); tre.setAction( TextRenderEvent.RENDER_TEXT_AT_LOCATION ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_LABEL, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_LABEL, la ); } // ALWAYS W.R.T START VALUE cdt = cdtAxisValue.forward( iUnit, iStep * ( i + 1 ) ); } } // RENDER THE AXIS TITLE la = LabelImpl.copyInstance( ax.getTitle( ) ); // TEMPORARILY USE // FOR AXIS TITLE if ( la.isVisible( ) && bRenderAxisTitle ) { ScriptHandler.callFunction( sh, ScriptHandler.BEFORE_DRAW_AXIS_TITLE, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_AXIS_TITLE, la ); final String sRestoreValue = la.getCaption( ).getValue( ); la.getCaption( ) .setValue( rtc.externalizedMessage( sRestoreValue ) ); // EXTERNALIZE la.getCaption( ) .getFont( ) .setAlignment( switchTextAlignment( la.getCaption( ) .getFont( ) .getAlignment( ) ) ); BoundingBox bb = null; try { bb = Methods.computeBox( xs, ax.getTitlePosition( ), la, 0, 0 ); } catch ( IllegalArgumentException uiex ) { throw new ChartException( ChartEnginePlugin.ID, ChartException.RENDERING, uiex ); } if ( ax.getTitle( ).isVisible( ) && la.isVisible( ) ) { if ( bRendering3D ) { Bounds cbo = getPlotBounds( ); if ( axisType == IConstants.BASE_AXIS ) { tre.setBlockBounds( BoundsImpl.create( cbo.getLeft( ) + ( cbo.getWidth( ) / 3d - bb.getWidth( ) ), cbo.getTop( ) + cbo.getHeight( ) - Math.min( bb.getHeight( ), bb.getWidth( ) ) - 30, bb.getWidth( ), bb.getHeight( ) ) ); } else { tre.setBlockBounds( BoundsImpl.create( cbo.getLeft( ) + cbo.getWidth( ) * 2 / 3d + ( cbo.getWidth( ) / 3d - bb.getWidth( ) ) / 2d, cbo.getTop( ) + cbo.getHeight( ) - Math.min( bb.getHeight( ), bb.getWidth( ) ) - 30 * 2, bb.getWidth( ), bb.getHeight( ) ) ); } tre.setLabel( la ); tre.setBlockAlignment( la.getCaption( ) .getFont( ) .getAlignment( ) ); tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK ); ipr.drawText( tre ); } else { final Bounds bo = BoundsImpl.create( daEndPoints[0], ax.getTitleCoordinate( ), daEndPoints[1] - daEndPoints[0], bb.getHeight( ) ); tre.setBlockBounds( bo ); tre.setLabel( la ); tre.setBlockAlignment( la.getCaption( ) .getFont( ) .getAlignment( ) ); tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK ); ipr.drawText( tre ); } } ScriptHandler.callFunction( sh, ScriptHandler.AFTER_DRAW_AXIS_TITLE, axModel, la, getRunTimeContext( ).getScriptContext( ) ); getRunTimeContext( ).notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_AXIS_TITLE, la ); } la = LabelImpl.copyInstance( ax.getLabel( ) ); // RESTORE BACK TO // AXIS LABEL if ( iv != null && iDimension == IConstants.TWO_5_D && ( ( bTransposed && isRightToLeft( ) && iv.getType( ) == IntersectionValue.MIN ) || ( !isRightToLeft( ) && iv.getType( ) == IntersectionValue.MAX ) ) ) { trae.setTranslation( -dSeriesThickness, dSeriesThickness ); ipr.applyTransformation( trae ); } } } /* * (non-Javadoc) * * @see org.eclipse.birt.chart.render.BaseRenderer#set(org.eclipse.birt.chart.model.Chart, * java.lang.Object, org.eclipse.birt.chart.model.component.Series, * org.eclipse.birt.chart.model.component.Axis, * org.eclipse.birt.chart.model.data.SeriesDefinition) */ public final void set( Chart _cm, Object _o, Series _se, Axis _ax, SeriesDefinition _sd ) { super.set( _cm, _o, _se, _sd ); ax = _ax; // HOLD AXIS HERE } /** * Returns if its a 3D rendering. * */ public final boolean isDimension3D( ) { return ( getModel( ).getDimension( ) == ChartDimension.THREE_DIMENSIONAL_LITERAL ); } /** * Returns previous visible series index by given index. * * @param currentIndex * @return */ protected int getPrevVisibleSiblingSeriesIndex( int currentIndex ) { SeriesDefinition sd = null; Series se = getSeries( ); if ( se.eContainer( ) instanceof SeriesDefinition ) { sd = (SeriesDefinition) se.eContainer( ); } if ( sd != null ) { int count = 0; int idx = sd.getRunTimeSeries( ).indexOf( se ); if ( idx > 0 ) { for ( int i = idx - 1; i >= 0; i { count++; if ( ( (Series) sd.getRunTimeSeries( ).get( i ) ).isVisible( ) ) { return currentIndex - count; } } } Axis cax = getAxis( ); int iDefintionIndex = cax.getSeriesDefinitions( ).indexOf( sd ); int iDefinitionCount = cax.getSeriesDefinitions( ).size( ); if ( iDefinitionCount > 0 ) { for ( int i = iDefintionIndex - 1; i >= 0; i { sd = (SeriesDefinition) cax.getSeriesDefinitions( ).get( i ); int runtimeSeriesCount = sd.getRunTimeSeries( ).size( ); for ( int j = runtimeSeriesCount - 1; j >= 0; j { count++; if ( ( (Series) sd.getRunTimeSeries( ).get( j ) ).isVisible( ) ) { return currentIndex - count; } } } } } return -1; } /** * @return Returns if current rendering is the last series in associated * axis. */ public final boolean isLastRuntimeSeriesInAxis( ) { SeriesDefinition sd = null; Series se = getSeries( ); if ( se.eContainer( ) instanceof SeriesDefinition ) { sd = (SeriesDefinition) se.eContainer( ); } if ( sd != null ) { Axis cax = getAxis( ); int iDefintionIndex = cax.getSeriesDefinitions( ).indexOf( sd ); int iDefinitionCount = cax.getSeriesDefinitions( ).size( ); if ( iDefinitionCount > 0 && iDefintionIndex == iDefinitionCount - 1 ) { int iThisSeriesIndex = sd.getRunTimeSeries( ).indexOf( se ); int iSeriesCount = sd.getRunTimeSeries( ).size( ); if ( iSeriesCount > 0 && iThisSeriesIndex == iSeriesCount - 1 ) { return true; } } } return false; } /** * Returns the 3D engine for this render. */ protected Engine3D get3DEngine( ) { if ( isDimension3D( ) ) { // delegate to 3d compuations. return ( (PlotWith3DAxes) oComputations ).get3DEngine( ); } return null; } /** * Returns the panning offset for 3D engine. */ protected Location getPanningOffset( ) { if ( isDimension3D( ) ) { // delegate to 3d compuations. return ( (PlotWith3DAxes) oComputations ).getPanningOffset( ); } return null; } /** * @return Returns the axis associated with current renderer. */ public final Axis getAxis( ) { return ax; } }
/** * This topological sort implementation takes an adjacency list of an acyclic graph and returns * an array with the indexes of the nodes in a (non unique) topological order * which tells you how to process the nodes in the graph. More precisely from wiki: * A topological ordering is a linear ordering of its vertices such that for * every directed edge uv from vertex u to vertex v, u comes before v in the ordering. * * Time Complexity: O(V + E) * * @author William Fiset, [email protected] **/ import java.util.*; // Helper Edge class to describe edges in the graph class Edge { int from, to, weight; public Edge (int f, int t, int w) { from = f; to = t; weight = w; } } public class TopologicalSortAdjacencyList { // Helper method that performs a depth first search on the graph to give // us the topological ordering we want. Instead of maintaining a stack // of the nodes we see we simply place them inside the ordering array // in reverse order for simplicity. private static int dfs(int i, int at, boolean[] visited, int[] ordering, Map<Integer, List<Edge>> graph) { visited[at] = true; List<Edge> edges = graph.get(at); if (edges != null) for (Edge edge : edges) if (!visited[edge.to]) i = dfs(i, edge.to, visited, ordering, graph); ordering[i] = at; return i-1; } // Finds a topological ordering of the nodes in a Directed Acyclic Graph (DAG) // The input to this function is an adjacency list for a graph and the number // of nodes in the graph. // NOTE: 'numNodes' is not necessarily the number of nodes currently present // in the adjacency list since you can have singleton nodes with no edges which // wouldn't be present in the adjacency list but are still part of the graph! public static int[] topologicalSort(Map<Integer, List<Edge>> graph, int numNodes) { int[] ordering = new int[numNodes]; boolean[] visited = new boolean[numNodes]; int i = numNodes - 1; for (int at = 0; at < numNodes; at++) if (!visited[at]) i = dfs(i, at, visited, ordering, graph); return ordering; } // A useful application of the topological sort is to find the shortest path // between two nodes in a Directed Acyclic Graph (DAG). Given an adjacency list // this method finds the shortest path to all nodes starting at 'start' // NOTE: 'numNodes' is not necessarily the number of nodes currently present // in the adjacency list since you can have singleton nodes with no edges which // wouldn't be present in the adjacency list but are still part of the graph! public static Integer[] dagShortestPath(Map<Integer, List<Edge>> graph, int start, int numNodes) { int[] topsort = topologicalSort(graph, numNodes); Integer[] dist = new Integer[numNodes]; dist[start] = 0; for(int i = 0; i < numNodes; i++) { int nodeIndex = topsort[i]; if (dist[nodeIndex] != null) { List<Edge> adjacentEdges = graph.get(nodeIndex); if (adjacentEdges != null) { for (Edge edge : adjacentEdges) { int newDist = dist[nodeIndex] + edge.weight; if (dist[edge.to] == null) dist[edge.to] = newDist; else dist[edge.to] = Math.min(dist[edge.to], newDist); } } } } return dist; } // Example usage of topological sort public static void main(String[] args) { // Graph setup final int N = 7; Map<Integer, List<Edge>> graph = new HashMap<>(); for (int i = 0; i < N; i++) graph.put(i, new ArrayList<>()); graph.get(0).add(new Edge(0,1,3)); graph.get(0).add(new Edge(0,2,2)); graph.get(0).add(new Edge(0,5,3)); graph.get(1).add(new Edge(1,3,1)); graph.get(1).add(new Edge(1,2,6)); graph.get(2).add(new Edge(2,3,1)); graph.get(2).add(new Edge(2,4,10)); graph.get(3).add(new Edge(3,4,5)); graph.get(5).add(new Edge(5,4,7)); int[] ordering = topologicalSort(graph, N); // // Prints: [6, 0, 5, 1, 2, 3, 4] System.out.println(java.util.Arrays.toString(ordering)); // Finds all the shortest paths starting at node 0 Integer[] dists = dagShortestPath(graph, 0, N); // Find the shortest path from 0 to 4 which is 8.0 System.out.println(dists[4]); // Find the shortest path from 0 to 6 which // is null since 6 is not reachable! System.out.println(dists[6]); } }
package org.timepedia.chronoscope.java2d; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.TimeZone; import org.timepedia.chronoscope.client.util.DateFormatter; import org.timepedia.chronoscope.client.util.date.ChronoDate; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; public class JDKDateFormatter implements DateFormatter { private static Date d = new Date(); private SimpleDateFormat fmt; public JDKDateFormatter(String format) { fmt = new SimpleDateFormat(format); } public String format(double timestamp) { d.setTime((long) timestamp); return fmt.format(d); } public String format(double timestamp, TimeZone timezone) { d.setTime((long)timestamp); return fmt.format(d); //FIXME // FIXME return fmt.format(new Date((long) timestamp), timeZoneOffset); } public double parse(String date) { try { return fmt.parse(date).getTime(); } catch (ParseException e) { e.printStackTrace(); return 0; } } }
package de.adito.jloadr.gui; import de.adito.jloadr.api.*; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.*; /** * @author j.boesl, 17.11.17 */ public class Splash extends JFrame implements ILoader.IStateCallback { private int absoluteProgress; private double relativeProgress; private JLabel splashLabel; private JLabel mbLoadedLabel; public Splash(String pIconPath, String pStartName) throws HeadlessException { if (pIconPath != null) { Path path = Paths.get(pIconPath); if (Files.exists(path)) setIconImage(new ImageIcon(path.toString()).getImage()); } if (pStartName != null) setTitle(pStartName); setUndecorated(true); splashLabel = new JLabel(); splashLabel.setHorizontalAlignment(SwingConstants.CENTER); getContentPane().add(splashLabel); mbLoadedLabel = new JLabel(); mbLoadedLabel.setForeground(Color.GRAY); splashLabel.add(mbLoadedLabel); } @Override public void setSplashResource(IResource pSplashResource) { SwingUtilities.invokeLater(() -> { if (pSplashResource == null) { splashLabel.setIcon(null); splashLabel.setText("loading ..."); } if (pSplashResource != null) { try { BufferedImage image = ImageIO.read(pSplashResource.getInputStream()); splashLabel.setIcon(new ImageIcon(image)); splashLabel.setText(""); } catch (IOException pE) { // no image } } pack(); setLocationRelativeTo(null); if (!isVisible()) setVisible(true); }); _update(); } @Override public void setProgress(int pAbsolute, double pRelative) { absoluteProgress = pAbsolute; relativeProgress = pRelative; _update(); } @Override public void finished() { relativeProgress = 1; _update(); } private void _update() { SwingUtilities.invokeLater(() -> { revalidate(); repaint(); }); } @Override public void paint(Graphics g) { int w = getContentPane().getWidth(); int h = getContentPane().getHeight(); String text = absoluteProgress == 0 ? "" : absoluteProgress / 1024 + " Mb"; mbLoadedLabel.setText(text); mbLoadedLabel.setSize(mbLoadedLabel.getPreferredSize()); mbLoadedLabel.setLocation(w - 4 - mbLoadedLabel.getWidth(), getHeight() - 12 - mbLoadedLabel.getHeight()); super.paint(g); g.setColor(SystemColor.GRAY); g.fillRect(4, h - 8, (int) Math.round((w - 8) * relativeProgress), 4); } }
package com.jme3.input; import static com.jme3.input.KeyInput.*; /** * Translate key codes (from {@link KeyInput}) to descriptive names. * * This class has only static methods, yet it can be instantiated. Here's why: * * It used to be that there was no static getName() method, so the only way to * get names was to instantiate a KeyNames. As a consequence, we have * applications and libraries that rely on being able to instantiate this class. */ public class KeyNames { private static final String[] KEY_NAMES = new String[0xFF]; static { KEY_NAMES[KEY_UNKNOWN] = "Unknown"; KEY_NAMES[KEY_0] = "0"; KEY_NAMES[KEY_1] = "1"; KEY_NAMES[KEY_2] = "2"; KEY_NAMES[KEY_3] = "3"; KEY_NAMES[KEY_4] = "4"; KEY_NAMES[KEY_5] = "5"; KEY_NAMES[KEY_6] = "6"; KEY_NAMES[KEY_7] = "7"; KEY_NAMES[KEY_8] = "8"; KEY_NAMES[KEY_9] = "9"; KEY_NAMES[KEY_Q] = "Q"; KEY_NAMES[KEY_W] = "W"; KEY_NAMES[KEY_E] = "E"; KEY_NAMES[KEY_R] = "R"; KEY_NAMES[KEY_T] = "T"; KEY_NAMES[KEY_Y] = "Y"; KEY_NAMES[KEY_U] = "U"; KEY_NAMES[KEY_I] = "I"; KEY_NAMES[KEY_O] = "O"; KEY_NAMES[KEY_P] = "P"; KEY_NAMES[KEY_A] = "A"; KEY_NAMES[KEY_S] = "S"; KEY_NAMES[KEY_D] = "D"; KEY_NAMES[KEY_F] = "F"; KEY_NAMES[KEY_G] = "G"; KEY_NAMES[KEY_H] = "H"; KEY_NAMES[KEY_J] = "J"; KEY_NAMES[KEY_K] = "K"; KEY_NAMES[KEY_L] = "L"; KEY_NAMES[KEY_Z] = "Z"; KEY_NAMES[KEY_X] = "X"; KEY_NAMES[KEY_C] = "C"; KEY_NAMES[KEY_V] = "V"; KEY_NAMES[KEY_B] = "B"; KEY_NAMES[KEY_N] = "N"; KEY_NAMES[KEY_M] = "M"; KEY_NAMES[KEY_F1] = "F1"; KEY_NAMES[KEY_F2] = "F2"; KEY_NAMES[KEY_F3] = "F3"; KEY_NAMES[KEY_F4] = "F4"; KEY_NAMES[KEY_F5] = "F5"; KEY_NAMES[KEY_F6] = "F6"; KEY_NAMES[KEY_F7] = "F7"; KEY_NAMES[KEY_F8] = "F8"; KEY_NAMES[KEY_F9] = "F9"; KEY_NAMES[KEY_F10] = "F10"; KEY_NAMES[KEY_F11] = "F11"; KEY_NAMES[KEY_F12] = "F12"; KEY_NAMES[KEY_F13] = "F13"; KEY_NAMES[KEY_F14] = "F14"; KEY_NAMES[KEY_F15] = "F15"; KEY_NAMES[KEY_NUMPAD0] = "Numpad 0"; KEY_NAMES[KEY_NUMPAD1] = "Numpad 1"; KEY_NAMES[KEY_NUMPAD2] = "Numpad 2"; KEY_NAMES[KEY_NUMPAD3] = "Numpad 3"; KEY_NAMES[KEY_NUMPAD4] = "Numpad 4"; KEY_NAMES[KEY_NUMPAD5] = "Numpad 5"; KEY_NAMES[KEY_NUMPAD6] = "Numpad 6"; KEY_NAMES[KEY_NUMPAD7] = "Numpad 7"; KEY_NAMES[KEY_NUMPAD8] = "Numpad 8"; KEY_NAMES[KEY_NUMPAD9] = "Numpad 9"; KEY_NAMES[KEY_NUMPADEQUALS] = "Numpad ="; KEY_NAMES[KEY_NUMPADENTER] = "Numpad Enter"; KEY_NAMES[KEY_NUMPADCOMMA] = "Numpad ,"; KEY_NAMES[KEY_DIVIDE] = "Numpad /"; KEY_NAMES[KEY_SUBTRACT] = "Numpad -"; KEY_NAMES[KEY_DECIMAL] = "Numpad ."; KEY_NAMES[KEY_LMENU] = "Left Alt"; KEY_NAMES[KEY_RMENU] = "Right Alt"; KEY_NAMES[KEY_LCONTROL] = "Left Ctrl"; KEY_NAMES[KEY_RCONTROL] = "Right Ctrl"; KEY_NAMES[KEY_LSHIFT] = "Left Shift"; KEY_NAMES[KEY_RSHIFT] = "Right Shift"; KEY_NAMES[KEY_LMETA] = "Left Option"; KEY_NAMES[KEY_RMETA] = "Right Option"; KEY_NAMES[KEY_MINUS] = "-"; KEY_NAMES[KEY_EQUALS] = "="; KEY_NAMES[KEY_LBRACKET] = "["; KEY_NAMES[KEY_RBRACKET] = "]"; KEY_NAMES[KEY_SEMICOLON] = ";"; KEY_NAMES[KEY_APOSTROPHE] = "'"; KEY_NAMES[KEY_GRAVE] = "`"; KEY_NAMES[KEY_BACKSLASH] = "\\"; KEY_NAMES[KEY_COMMA] = ","; KEY_NAMES[KEY_PERIOD] = "."; KEY_NAMES[KEY_SLASH] = "/"; KEY_NAMES[KEY_MULTIPLY] = "*"; KEY_NAMES[KEY_ADD] = "+"; KEY_NAMES[KEY_COLON] = ":"; KEY_NAMES[KEY_UNDERLINE] = "_"; KEY_NAMES[KEY_AT] = "@"; KEY_NAMES[KEY_APPS] = "Apps"; KEY_NAMES[KEY_POWER] = "Power"; KEY_NAMES[KEY_SLEEP] = "Sleep"; KEY_NAMES[KEY_STOP] = "Stop"; KEY_NAMES[KEY_ESCAPE] = "Esc"; KEY_NAMES[KEY_RETURN] = "Enter"; KEY_NAMES[KEY_SPACE] = "Space"; KEY_NAMES[KEY_BACK] = "Backspace"; KEY_NAMES[KEY_TAB] = "Tab"; KEY_NAMES[KEY_SYSRQ] = "SysRq"; KEY_NAMES[KEY_PAUSE] = "Pause"; KEY_NAMES[KEY_HOME] = "Home"; KEY_NAMES[KEY_PGUP] = "Page Up"; KEY_NAMES[KEY_PGDN] = "Page Down"; KEY_NAMES[KEY_END] = "End"; KEY_NAMES[KEY_INSERT] = "Insert"; KEY_NAMES[KEY_DELETE] = "Delete"; KEY_NAMES[KEY_UP] = "Up"; KEY_NAMES[KEY_LEFT] = "Left"; KEY_NAMES[KEY_RIGHT] = "Right"; KEY_NAMES[KEY_DOWN] = "Down"; KEY_NAMES[KEY_NUMLOCK] = "Num Lock"; KEY_NAMES[KEY_CAPITAL] = "Caps Lock"; KEY_NAMES[KEY_SCROLL] = "Scroll Lock"; KEY_NAMES[KEY_KANA] = "Kana"; KEY_NAMES[KEY_CONVERT] = "Convert"; KEY_NAMES[KEY_NOCONVERT] = "No Convert"; KEY_NAMES[KEY_YEN] = "Yen"; KEY_NAMES[KEY_CIRCUMFLEX] = "Circumflex"; KEY_NAMES[KEY_KANJI] = "Kanji"; KEY_NAMES[KEY_AX] = "Ax"; KEY_NAMES[KEY_UNLABELED] = "Unlabeled"; } /** * Obtain a descriptive name for the specified key code. Key codes are * defined in {@link KeyInput}. * * @param keyId a key code (&ge;0, &le;255) * @return the corresponding name, or null if not named */ public static String getName(int keyId) { return KEY_NAMES[keyId]; } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.util; import jodd.test.DisabledOnJava; import jodd.util.fixtures.subclass.IBase; import jodd.util.fixtures.subclass.IExtra; import jodd.util.fixtures.subclass.IOne; import jodd.util.fixtures.subclass.ITwo; import jodd.util.fixtures.subclass.SBase; import jodd.util.fixtures.subclass.SOne; import jodd.util.fixtures.subclass.STwo; import jodd.util.fixtures.testdata.A; import jodd.util.fixtures.testdata.B; import jodd.util.fixtures.testdata.C; import jodd.util.fixtures.testdata.JavaBean; import jodd.util.fixtures.testdata2.D; import jodd.util.fixtures.testdata2.E; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.io.File; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.AbstractMap; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class ClassUtilTest { @Test void testMethod() { TFooBean bean = new TFooBean(); Method m; m = ClassUtil.findMethod(TFooBean.class, "getMore"); assertNotNull(m); m = ClassUtil.findMethod(bean.getClass(), "getMore"); assertNotNull(m); m = ClassUtil.findMethod(bean.getClass(), "getXXX"); assertNull(m); } @Test void testMatchClasses() { TFooBean a = new TFooBean(); TFooBean b = new TFooBean(); TFooBean2 c = new TFooBean2(); assertTrue(TFooBean.class.isInstance(a)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, a.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean.class, b.getClass())); assertTrue(ClassUtil.isTypeOf(a.getClass(), b.getClass())); assertTrue(ClassUtil.isTypeOf(b.getClass(), a.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, c.getClass())); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, TFooBean.class)); assertFalse(ClassUtil.isTypeOf(TFooBean.class, TFooBean2.class)); assertTrue(ClassUtil.isTypeOf(c.getClass(), TFooBean.class)); assertFalse(ClassUtil.isTypeOf(a.getClass(), TFooBean2.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, Serializable.class)); assertTrue(Serializable.class.isInstance(c)); //noinspection ConstantConditions assertTrue(c instanceof Serializable); assertTrue(ClassUtil.isInstanceOf(c, Serializable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, Comparable.class)); assertFalse(ClassUtil.isTypeOf(TFooBean.class, Comparable.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, TFooIndyEx.class)); assertTrue(ClassUtil.isTypeOf(TFooBean2.class, TFooIndyEx.class)); assertTrue(ClassUtil.isTypeOf(TFooBean.class, TFooIndy.class)); } @Test void testMatchInterfaces() { assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); assertTrue(ClassUtil.isInstanceOf(new HashMap(), Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(AbstractMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(HashMap.class, Map.class)); assertTrue(ClassUtil.isTypeOf(Map.class, Map.class)); } @Test void testAccessibleA() { Method[] ms = ClassUtil.getAccessibleMethods(A.class, null); assertEquals(4 + 11, ms.length); // there are 11 accessible Object methods (9 public + 2 protected) ms = ClassUtil.getAccessibleMethods(A.class); assertEquals(4, ms.length); ms = A.class.getMethods(); assertEquals(1 + 9, ms.length); // there are 9 public Object methods ms = A.class.getDeclaredMethods(); assertEquals(4, ms.length); ms = ClassUtil.getSupportedMethods(A.class, null); assertEquals(4 + 12, ms.length); // there are 12 total Object methods (9 public + 2 protected + 1 private) ms = ClassUtil.getSupportedMethods(A.class); assertEquals(4, ms.length); Field[] fs = ClassUtil.getAccessibleFields(A.class); assertEquals(4, fs.length); fs = A.class.getFields(); assertEquals(1, fs.length); fs = A.class.getDeclaredFields(); assertEquals(4, fs.length); fs = ClassUtil.getSupportedFields(A.class); assertEquals(4, fs.length); } @Test void testAccessibleB() { Method[] ms = ClassUtil.getAccessibleMethods(B.class, null); assertEquals(3 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(B.class); assertEquals(3, ms.length); ms = B.class.getMethods(); assertEquals(1 + 9, ms.length); ms = B.class.getDeclaredMethods(); assertEquals(0, ms.length); ms = ClassUtil.getSupportedMethods(B.class, null); assertEquals(4 + 12, ms.length); ms = ClassUtil.getSupportedMethods(B.class); assertEquals(4, ms.length); Field[] fs = ClassUtil.getAccessibleFields(B.class); assertEquals(3, fs.length); fs = B.class.getFields(); assertEquals(1, fs.length); fs = B.class.getDeclaredFields(); assertEquals(0, fs.length); fs = ClassUtil.getSupportedFields(B.class); assertEquals(4, fs.length); } @Test void testAccessibleC() { Method[] ms = ClassUtil.getAccessibleMethods(C.class, null); assertEquals(5 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(C.class); assertEquals(5, ms.length); ms = C.class.getMethods(); assertEquals(2 + 9, ms.length); ms = C.class.getDeclaredMethods(); assertEquals(5, ms.length); ms = ClassUtil.getSupportedMethods(C.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(C.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(C.class); assertEquals(5, fs.length); fs = C.class.getFields(); assertEquals(3, fs.length); fs = C.class.getDeclaredFields(); assertEquals(5, fs.length); fs = ClassUtil.getSupportedFields(C.class); assertEquals(5, fs.length); } @Test void testAccessibleD() { Method[] ms = ClassUtil.getAccessibleMethods(D.class, null); assertEquals(3 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(D.class); assertEquals(3, ms.length); ms = D.class.getMethods(); assertEquals(2 + 9, ms.length); ms = D.class.getDeclaredMethods(); assertEquals(0, ms.length); ms = ClassUtil.getSupportedMethods(D.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(D.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(D.class); assertEquals(3, fs.length); fs = D.class.getFields(); assertEquals(3, fs.length); fs = D.class.getDeclaredFields(); assertEquals(0, fs.length); fs = ClassUtil.getSupportedFields(D.class); assertEquals(5, fs.length); } @Test void testAccessibleE() { Method[] ms = ClassUtil.getAccessibleMethods(E.class, null); assertEquals(5 + 11, ms.length); ms = ClassUtil.getAccessibleMethods(E.class); assertEquals(5, ms.length); ms = E.class.getMethods(); assertEquals(2 + 9, ms.length); ms = E.class.getDeclaredMethods(); assertEquals(4, ms.length); ms = ClassUtil.getSupportedMethods(E.class, null); assertEquals(5 + 12, ms.length); ms = ClassUtil.getSupportedMethods(E.class); assertEquals(5, ms.length); Field[] fs = ClassUtil.getAccessibleFields(E.class); assertEquals(5, fs.length); fs = E.class.getFields(); assertEquals(4, fs.length); fs = E.class.getDeclaredFields(); assertEquals(4, fs.length); fs = ClassUtil.getSupportedFields(E.class); assertEquals(5, fs.length); } @Test void testIsSubclassAndInterface() { assertTrue(ClassUtil.isTypeOf(SBase.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(SOne.class, SOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, SBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IOne.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, Serializable.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, ITwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, ITwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IBase.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IExtra.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, IExtra.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, STwo.class)); assertTrue(ClassUtil.isTypeOf(STwo.class, STwo.class)); } @Test void testBeanPropertyNames() { String name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getOne")); assertEquals("one", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setOne")); assertEquals("one", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "isTwo")); assertEquals("two", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setTwo")); assertEquals("two", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getThree")); assertEquals("three", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setThree")); assertEquals("three", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getF")); assertEquals("f", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setF")); assertEquals("f", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getG")); assertEquals("g", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setG")); assertEquals("g", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getURL")); assertEquals("URL", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setURL")); assertEquals("URL", name); name = ClassUtil.getBeanPropertyGetterName(ClassUtil.findMethod(JavaBean.class, "getBIGsmall")); assertEquals("BIGsmall", name); name = ClassUtil.getBeanPropertySetterName(ClassUtil.findMethod(JavaBean.class, "setBIGsmall")); assertEquals("BIGsmall", name); } @Test void testIsSubClassForCommonTypes() { assertTrue(ClassUtil.isTypeOf(Long.class, Long.class)); assertFalse(ClassUtil.isTypeOf(Long.class, long.class)); } public static class BaseClass<A, B> { public A f1; public B f2; public String f3; public A[] array1; } public static class ConcreteClass extends BaseClass<String, Integer> { public Long f4; public List<Long> f5; } public static class BaseClass2<X> extends BaseClass<X, Integer> { } public static class ConcreteClass2 extends BaseClass2<String> { } @Test void testGetFieldConcreteType() throws NoSuchFieldException { Field f1 = BaseClass.class.getField("f1"); Field f2 = BaseClass.class.getField("f2"); Field f3 = BaseClass.class.getField("f3"); Field f4 = ConcreteClass.class.getField("f4"); Field f5 = ConcreteClass.class.getField("f5"); Field array1 = BaseClass.class.getField("array1"); Class[] genericSupertypes = ClassUtil.getGenericSupertypes(ConcreteClass.class); assertEquals(String.class, genericSupertypes[0]); assertEquals(Integer.class, genericSupertypes[1]); assertEquals(String.class, ClassUtil.getRawType(f1.getGenericType(), ConcreteClass.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), ConcreteClass.class)); assertEquals(String.class, ClassUtil.getRawType(f3.getGenericType(), ConcreteClass.class)); assertEquals(Long.class, ClassUtil.getRawType(f4.getGenericType(), ConcreteClass.class)); assertEquals(List.class, ClassUtil.getRawType(f5.getGenericType(), ConcreteClass.class)); assertEquals(String[].class, ClassUtil.getRawType(array1.getGenericType(), ConcreteClass.class)); assertEquals(Object.class, ClassUtil.getRawType(f1.getGenericType())); assertNull(ClassUtil.getComponentType(f1.getGenericType(), -1)); assertEquals(Long.class, ClassUtil.getComponentType(f5.getGenericType(), 0)); } @Test void testGetFieldConcreteType2() throws Exception { Field array1 = BaseClass.class.getField("array1"); Field f2 = ConcreteClass2.class.getField("f2"); assertEquals(String[].class, ClassUtil.getRawType(array1.getGenericType(), ConcreteClass2.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), ConcreteClass2.class)); assertEquals(Integer.class, ClassUtil.getRawType(f2.getGenericType(), BaseClass2.class)); } public static class Soo { public List<String> stringList; public String[] strings; public String string; public List<Integer> getIntegerList() {return null;} public Integer[] getIntegers() {return null;} public Integer getInteger() {return null;} public <T> T getTemplate(T foo) {return null;} public Collection<? extends Number> getCollection() {return null;} public Collection<?> getCollection2() {return null;} } @Test void testGetRawAndComponentType() throws NoSuchFieldException { Class<Soo> sooClass = Soo.class; Field stringList = sooClass.getField("stringList"); assertEquals(List.class, ClassUtil.getRawType(stringList.getType())); assertEquals(String.class, ClassUtil.getComponentType(stringList.getGenericType(), 0)); Field strings = sooClass.getField("strings"); assertEquals(String[].class, ClassUtil.getRawType(strings.getType())); assertEquals(String.class, ClassUtil.getComponentType(strings.getGenericType(), -1)); Field string = sooClass.getField("string"); assertEquals(String.class, ClassUtil.getRawType(string.getType())); assertNull(ClassUtil.getComponentType(string.getGenericType(), 0)); Method integerList = ClassUtil.findMethod(sooClass, "getIntegerList"); assertEquals(List.class, ClassUtil.getRawType(integerList.getReturnType())); assertEquals(Integer.class, ClassUtil.getComponentType(integerList.getGenericReturnType(), -1)); Method integers = ClassUtil.findMethod(sooClass, "getIntegers"); assertEquals(Integer[].class, ClassUtil.getRawType(integers.getReturnType())); assertEquals(Integer.class, ClassUtil.getComponentType(integers.getGenericReturnType(), 0)); Method integer = ClassUtil.findMethod(sooClass, "getInteger"); assertEquals(Integer.class, ClassUtil.getRawType(integer.getReturnType())); assertNull(ClassUtil.getComponentType(integer.getGenericReturnType(), -1)); Method template = ClassUtil.findMethod(sooClass, "getTemplate"); assertEquals(Object.class, ClassUtil.getRawType(template.getReturnType())); assertNull(ClassUtil.getComponentType(template.getGenericReturnType(), 0)); Method collection = ClassUtil.findMethod(sooClass, "getCollection"); assertEquals(Collection.class, ClassUtil.getRawType(collection.getReturnType())); assertEquals(Number.class, ClassUtil.getComponentType(collection.getGenericReturnType(), -1)); Method collection2 = ClassUtil.findMethod(sooClass, "getCollection2"); assertEquals(Collection.class, ClassUtil.getRawType(collection2.getReturnType())); assertEquals(Object.class, ClassUtil.getComponentType(collection2.getGenericReturnType(), 0)); } public static class Base2<N extends Number, K> { public N getNumber() {return null;} public K getKiko() {return null;} } public static class Impl1<N extends Number> extends Base2<N, Long> {} public static class Impl2 extends Impl1<Integer> {} public static class Impl3 extends Impl2 {} @Test void testGetRawWithImplClass() throws NoSuchFieldException { Method number = ClassUtil.findMethod(Base2.class, "getNumber"); Method kiko = ClassUtil.findMethod(Base2.class, "getKiko"); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType())); assertEquals(Number.class, ClassUtil.getRawType(number.getGenericReturnType())); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType())); assertEquals(Object.class, ClassUtil.getRawType(kiko.getGenericReturnType())); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl1.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl1.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl1.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl1.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl2.class)); assertEquals(Integer.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl2.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl2.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl2.class)); assertEquals(Number.class, ClassUtil.getRawType(number.getReturnType(), Impl3.class)); assertEquals(Integer.class, ClassUtil.getRawType(number.getGenericReturnType(), Impl3.class)); assertEquals(Object.class, ClassUtil.getRawType(kiko.getReturnType(), Impl3.class)); assertEquals(Long.class, ClassUtil.getRawType(kiko.getGenericReturnType(), Impl3.class)); } public static class Base22<K, N extends Number> {} public static class Impl11<N extends Number> extends Base22<Long, N> {} public static class Impl22 extends Impl11<Integer> {} public static class Impl33 extends Impl22 {} @Test void testClassGenerics1() { Class[] componentTypes = ClassUtil.getGenericSupertypes(Base2.class); assertNull(componentTypes); Type[] types = Base2.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl1.class); assertEquals(2, componentTypes.length); assertEquals(Number.class, componentTypes[0]); assertEquals(Long.class, componentTypes[1]); types = Impl1.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl2.class); assertEquals(1, componentTypes.length); assertEquals(Integer.class, componentTypes[0]); types = Impl2.class.getGenericInterfaces(); assertEquals(0, types.length); componentTypes = ClassUtil.getGenericSupertypes(Impl3.class); assertNull(componentTypes); } @Test void testClassGenerics2() { Class[] componentTypes = ClassUtil.getGenericSupertypes(Base22.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(Impl11.class); assertEquals(2, componentTypes.length); assertEquals(Long.class, componentTypes[0]); assertEquals(Number.class, componentTypes[1]); componentTypes = ClassUtil.getGenericSupertypes(Impl22.class); assertEquals(1, componentTypes.length); assertEquals(Integer.class, componentTypes[0]); componentTypes = ClassUtil.getGenericSupertypes(Impl33.class); assertNull(componentTypes); } public static interface BaseAna<K, N extends Number> {} public static interface ImplAna<N extends Number> extends BaseAna<Long, N> {} public static interface ImplAna2 extends ImplAna<Integer> {} public static class ImplAna3 implements ImplAna2 {} public static class ImplAna4 extends ImplAna3 {} @Test void testClassGenerics3() { Class[] componentTypes = ClassUtil.getGenericSupertypes(BaseAna.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna2.class); assertNull(componentTypes); componentTypes = ClassUtil.getGenericSupertypes(ImplAna3.class); assertNull(componentTypes); // scan generic interfacase Type[] types = ImplAna3.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(ImplAna2.class, types[0]); assertNull(ClassUtil.getComponentType(types[0], 0)); types = ImplAna2.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(Integer.class, ClassUtil.getComponentType(types[0], 0)); types = ImplAna.class.getGenericInterfaces(); assertEquals(1, types.length); assertEquals(Long.class, ClassUtil.getComponentType(types[0], 0)); types = BaseAna.class.getGenericInterfaces(); assertEquals(0, types.length); types = ImplAna4.class.getGenericInterfaces(); assertEquals(0, types.length); } public static class FieldType<K extends Number, V extends List<String> & Collection<String>> { List fRaw; List<Object> fTypeObject; List<String> fTypeString; List<?> fWildcard; List<? super List<String>> fBoundedWildcard; Map<String, List<Set<Long>>> fTypeNested; Map<K, V> fTypeLiteral; K[] fGenericArray; } @Test void testFieldTypeToString() { Field[] fields = FieldType.class.getDeclaredFields(); Arrays.sort(fields, new Comparator<Field>() { @Override public int compare(Field o1, Field o2) { return o1.getName().compareTo(o2.getName()); } }); String result = ""; for (Field field : fields) { Type type = field.getGenericType(); result += field.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } assertEquals( "fBoundedWildcard - java.util.List<? super java.util.List<java.lang.String>>\n" + "fGenericArray - K[]\n" + "fRaw - java.util.List\n" + "fTypeLiteral - java.util.Map<K extends java.lang.Number>, <V extends java.util.List<java.lang.String> & java.util.Collection<java.lang.String>>\n" + "fTypeNested - java.util.Map<java.lang.String>, <java.util.List<java.util.Set<java.lang.Long>>>\n" + "fTypeObject - java.util.List<java.lang.Object>\n" + "fTypeString - java.util.List<java.lang.String>\n" + "fWildcard - java.util.List<? extends java.lang.Object>\n", result); } public static class MethodReturnType { List mRaw() {return null;} List<String> mTypeString() {return null;} List<?> mWildcard() {return null;} List<? extends Number> mBoundedWildcard() {return null;} <T extends List<String>> List<T> mTypeLiteral() {return null;} } @Test void testMethodTypeToString() { Method[] methods = MethodReturnType.class.getDeclaredMethods(); Arrays.sort(methods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); String result = ""; for (Method method : methods) { Type type = method.getGenericReturnType(); result += method.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } assertEquals( "mBoundedWildcard - java.util.List<? extends java.lang.Number>\n" + "mRaw - java.util.List\n" + "mTypeLiteral - java.util.List<T extends java.util.List<java.lang.String>>\n" + "mTypeString - java.util.List<java.lang.String>\n" + "mWildcard - java.util.List<? extends java.lang.Object>\n", result); } public static class MethodParameterType<A> { <T extends List<T>> void m(A a, String p1, T p2, List<?> p3, List<T> p4) { } } public static class Mimple extends MethodParameterType<Long>{} @Test void testMethodParameterTypeToString() { String result = ""; Method method = null; for (Method m : MethodParameterType.class.getDeclaredMethods()) { for (Type type : m.getGenericParameterTypes()) { result += m.getName() + " - " + ClassUtil.typeToString(type) + '\n'; } method = m; } assertEquals( "m - A extends java.lang.Object\n" + "m - java.lang.String\n" + "m - T extends java.util.List<T>\n" + "m - java.util.List<? extends java.lang.Object>\n" + "m - java.util.List<T extends java.util.List<T>>\n", result); Type[] types = method.getGenericParameterTypes(); assertEquals(Object.class, ClassUtil.getRawType(types[0], MethodParameterType.class)); assertEquals(String.class, ClassUtil.getRawType(types[1], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[2], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[3], MethodParameterType.class)); assertEquals(List.class, ClassUtil.getRawType(types[4], MethodParameterType.class)); // same methods, using different impl class assertEquals(Long.class, ClassUtil.getRawType(types[0], Mimple.class)); // change! assertEquals(String.class, ClassUtil.getRawType(types[1], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[2], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[3], Mimple.class)); assertEquals(List.class, ClassUtil.getRawType(types[4], Mimple.class)); } public interface SomeGuy {} public interface Cool extends SomeGuy {} public interface Vigilante {} public interface Flying extends Vigilante {} public interface SuperMario extends Flying, Cool {} class User implements SomeGuy {} class SuperUser extends User implements Cool {} class SuperMan extends SuperUser implements Flying {} @Test void testResolveAllInterfaces() { Class[] interfaces = ClassUtil.resolveAllInterfaces(HashMap.class); assertTrue(interfaces.length >= 3); assertTrue(ArraysUtil.contains(interfaces, Map.class)); assertTrue(ArraysUtil.contains(interfaces, Serializable.class)); assertTrue(ArraysUtil.contains(interfaces, Cloneable.class)); interfaces = ClassUtil.resolveAllInterfaces(SuperMan.class); assertEquals(4, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); assertTrue(ArraysUtil.contains(interfaces, Cool.class)); assertTrue(ArraysUtil.contains(interfaces, Flying.class)); assertTrue(ArraysUtil.contains(interfaces, Vigilante.class)); assertTrue(ArraysUtil.indexOf(interfaces, Flying.class) < ArraysUtil.indexOf(interfaces, SomeGuy.class)); interfaces = ClassUtil.resolveAllInterfaces(SuperUser.class); assertEquals(2, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); assertTrue(ArraysUtil.contains(interfaces, Cool.class)); interfaces = ClassUtil.resolveAllInterfaces(User.class); assertEquals(1, interfaces.length); assertTrue(ArraysUtil.contains(interfaces, SomeGuy.class)); interfaces = ClassUtil.resolveAllInterfaces(SomeGuy.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Cool.class); assertEquals(1, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Vigilante.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Flying.class); assertEquals(1, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(SuperMario.class); assertEquals(4, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(Object.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(int.class); assertEquals(0, interfaces.length); interfaces = ClassUtil.resolveAllInterfaces(int[].class); assertEquals(2, interfaces.length); // cloneable, serializable interfaces = ClassUtil.resolveAllInterfaces(Integer[].class); assertEquals(2, interfaces.length); } @Test void testResolveAllSuperclsses() { Class[] subclasses = ClassUtil.resolveAllSuperclasses(User.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(SuperUser.class); assertEquals(1, subclasses.length); assertEquals(User.class, subclasses[0]); subclasses = ClassUtil.resolveAllSuperclasses(SuperMan.class); assertEquals(2, subclasses.length); assertEquals(SuperUser.class, subclasses[0]); assertEquals(User.class, subclasses[1]); subclasses = ClassUtil.resolveAllSuperclasses(Cool.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Flying.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(SuperMario.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Object.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(int.class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(int[].class); assertEquals(0, subclasses.length); subclasses = ClassUtil.resolveAllSuperclasses(Integer[].class); assertEquals(0, subclasses.length); } @Nested @DisplayName("tests for ClassUtil#isUserDefinedMethod") class IsUserDefinedMethod { @Test void notUserDefinedMethod() throws Exception { final Method method = Object.class.getMethod("hashCode"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(false, actual); } @Test void userDefinedMethod() throws Exception { final Method method = StringBand.class.getMethod("toString"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(true, actual); } @Test void customObjectButMethodFromObject() throws Exception { final Method method = StringBand.class.getMethod("hashCode"); final boolean actual = ClassUtil.isUserDefinedMethod(method); // asserts assertEquals(false, actual); } } @Nested @DisplayName("ClassUtil#getClasses") class GetClasses { @Test void emptyArgument() { final Class[] actual = ClassUtil.getClasses(new Object[0]); // asserts assertNotNull(actual); assertEquals(0, actual.length); } @Test void noNullValueIncluded() { final Class[] actual = ClassUtil.getClasses(new Object(), new Base32(), File.class, 3, 23L, 44.55F, 11.11D); // asserts assertNotNull(actual); assertEquals(7, actual.length); assertEquals(Object.class, actual[0]); assertEquals(Base32.class, actual[1]); assertEquals(Class.class, actual[2]); assertEquals(Integer.class, actual[3]); assertEquals(Long.class, actual[4]); assertEquals(Float.class, actual[5]); assertEquals(Double.class, actual[6]); } @Test void onlyNullValuesIncluded() { final Class[] actual = ClassUtil.getClasses(null, null, null, null); // asserts assertNotNull(actual); assertEquals(4, actual.length); } } @Nested @DisplayName("tests for ClassUtil#isObjectMethod") class IsObjectMethod { @Test void methodFromObject() throws Exception { final Method method = Object.class.getMethod("hashCode"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(true, actual); } @Test void userDefinedMethod() throws Exception { final Method method = StringBand.class.getMethod("toString"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(false, actual); } @Test void customObjectButMethodFromObject() throws Exception { final Method method = StringBand.class.getMethod("hashCode"); final boolean actual = ClassUtil.isObjectMethod(method); // asserts assertEquals(true, actual); } } @Nested @DisplayName("tests for method jarFileOf") class JarFileOf { @Test void checkClassFromExternalJar() { final JarFile actual = ClassUtil.jarFileOf(StringUtils.class); // asserts assertNotNull(actual); assertTrue(actual.getName().contains("commons-lang3")); } @Test void checkWithClassFromThisModule() { final JarFile actual = ClassUtil.jarFileOf(Chalk.class); // asserts assertNull(actual); } @Test @DisabledOnJava(value = 9, description = "rt.jar does not exists in Java 9 anymore") void checkWithClassFromJRE() { final JarFile actual = ClassUtil.jarFileOf(Object.class); // asserts assertNotNull(actual); assertTrue(actual.getName().contains("rt.jar")); } } }
package jodd.joy.core; import jodd.io.findfile.ClassFinder; import jodd.typeconverter.Convert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <code>AppScanner</code> defines entries that will be included/excluded in * scanning process, when configuring Jodd frameworks. * By default, scanning entries includes all classes that belongs * to the project and to the Jodd. */ public class AppScanner { private static final Logger log = LoggerFactory.getLogger(AppScanner.class); protected final DefaultAppCore appCore; public AppScanner(DefaultAppCore appCore) { this.appCore = appCore; } /** * Scanning entries that will be examined by various * Jodd auto-magic tools. */ protected String[] includedEntries; /** * Scanning jars. */ protected String[] includedJars; /** * Should scanning ignore the exception. */ protected boolean ignoreExceptions; public String[] getIncludedEntries() { return includedEntries; } public void setIncludedEntries(String... includedEntries) { this.includedEntries = includedEntries; } public String[] getIncludedJars() { return includedJars; } public void setIncludedJars(String... includedJars) { this.includedJars = includedJars; } public boolean isIgnoreExceptions() { return ignoreExceptions; } public void setIgnoreExceptions(boolean ignoreExceptions) { this.ignoreExceptions = ignoreExceptions; } /** * Configures scanner class finder. Works for all three scanners: * Petite, DbOom and Madvoc. */ public void configure(ClassFinder classFinder) { if (includedEntries == null) { includedEntries = new String[] { appCore.getClass().getPackage().getName() + ".*", "jodd.*" }; } if (log.isDebugEnabled()) { log.debug("Scan entries: " + Convert.toString(includedEntries)); log.debug("Scan jars: " + Convert.toString(includedJars)); log.debug("Scan ignore exception: " + ignoreExceptions); } if (includedEntries != null) { classFinder.setIncludedEntries(includedEntries); } if (includedJars != null) { classFinder.setIncludedJars(includedJars); } classFinder.setIgnoreException(ignoreExceptions); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.mail; import jodd.util.StringPool; import java.util.Properties; /** * Secure SMTP server (STARTTLS) for sending emails. */ public class SmtpSslServer extends SmtpServer<SmtpSslServer> { public static final String MAIL_SMTP_STARTTLS_REQUIRED = "mail.smtp.starttls.required"; public static final String MAIL_SMTP_STARTTLS_ENABLE = "mail.smtp.starttls.enable"; public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "mail.smtp.socketFactory.port"; public static final String MAIL_SMTP_SOCKET_FACTORY_CLASS = "mail.smtp.socketFactory.class"; public static final String MAIL_SMTP_SOCKET_FACTORY_FALLBACK = "mail.smtp.socketFactory.fallback"; protected static final int DEFAULT_SSL_PORT = 465; public static SmtpSslServer create(String host) { return new SmtpSslServer(host, DEFAULT_SSL_PORT); } public static SmtpSslServer create(String host, int port) { return new SmtpSslServer(host, port); } public SmtpSslServer(String host) { super(host, DEFAULT_SSL_PORT); } public SmtpSslServer(String host, int port) { super(host, port); } protected boolean startTlsRequired = false; protected boolean plaintextOverTLS = true; /** * Sets <code>mail.smtp.starttls.required</code> which according to * Java Mail API means: If true, requires the use of the STARTTLS command. * If the server doesn't support the STARTTLS command, or the command fails, * the connect method will fail. Defaults to <code>false</code>. */ public SmtpSslServer startTlsRequired(boolean startTlsRequired) { this.startTlsRequired = startTlsRequired; return this; } /** * When enabled, SMTP socket factory class will be not set, * and Plaintext Authentication over TLS will be enabled. */ public SmtpSslServer plaintextOverTLS(boolean plaintextOverTLS) { this.plaintextOverTLS = plaintextOverTLS; return this; } @Override protected Properties createSessionProperties() { Properties props = super.createSessionProperties(); props.setProperty(MAIL_SMTP_STARTTLS_REQUIRED, startTlsRequired ? StringPool.TRUE : StringPool.FALSE); props.setProperty(MAIL_SMTP_STARTTLS_ENABLE, StringPool.TRUE); props.setProperty(MAIL_SMTP_SOCKET_FACTORY_PORT, String.valueOf(port)); props.setProperty(MAIL_SMTP_PORT, String.valueOf(port)); if (!plaintextOverTLS) { props.setProperty(MAIL_SMTP_SOCKET_FACTORY_CLASS, "javax.net.ssl.SSLSocketFactory"); } props.setProperty(MAIL_SMTP_SOCKET_FACTORY_FALLBACK, StringPool.FALSE); props.setProperty(MAIL_HOST, host); return props; } }
package com.microsoft.adal; import android.content.Context; /** * Error codes to help developer * * @author omercan */ public class ErrorCodes { public static enum ADALError { /** * Authority url is not valid */ DEVELOPER_AUTHORITY_IS_NOT_VALID_URL, /** * Authority is empty */ DEVELOPER_AUTHORITY_IS_EMPTY, /** * Async tasks can only be executed one time. They are not supposed to * be reused. */ DEVELOPER_ASYNC_TASK_REUSED, /** * Resource is empty */ DEVELOPER_RESOURCE_IS_EMPTY, /** * Invalid request to server */ SERVER_INVALID_REQUEST, /** * Authorization Failed */ AUTH_FAILED, /** * Authorization Failed: %d */ AUTH_FAILED_ERROR_CODE, /** * The Authorization Server returned an unrecognized response */ AUTH_FAILED_SERVER_ERROR, /** * The Application does not have a current ViewController */ AUTH_FAILED_NO_CONTROLLER, /** * The required resource bundle could not be loaded */ AUTH_FAILED_NO_RESOURCES, /** * The authorization server response has incorrectly encoded state */ AUTH_FAILED_NO_STATE, /** * The authorization server response has no encoded state */ AUTH_FAILED_BAD_STATE, /** * The requested access token could not be found */ AUTH_FAILED_NO_TOKEN, /** * The user cancelled the authorization request */ AUTH_FAILED_CANCELLED, /** * Invalid parameters for authorization operation */ AUTH_FAILED_INTERNAL_ERROR, DEVICE_INTERNET_IS_NOT_AVAILABLE } /** * Get error message from resource file. It will get the translated text. * Strings.xml inside the resource folder can be customized for your users. * * @param context required to get message. * @param enumId * @return Translated text */ public String getMessage(Context appContext, ADALError enumId) { if (appContext != null) { int id = appContext.getResources().getIdentifier(enumId.name(), "string", appContext.getPackageName()); return appContext.getString(id); } throw new IllegalArgumentException("appContext is null"); } }
// RMG - Reaction Mechanism Generator // RMG Team ([email protected]) // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. package jing.rxnSys; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.ListIterator; import jing.chem.Species; import jing.chem.SpeciesDictionary; import jing.param.Global; import jing.param.ParameterInfor; import jing.param.Pressure; import jing.param.Temperature; import jing.rxn.LindemannReaction; import jing.rxn.NegativeRateException; import jing.rxn.PDepNetwork; import jing.rxn.PDepReaction; import jing.rxn.Reaction; import jing.rxn.TROEReaction; import jing.rxn.TemplateReaction; import jing.rxn.ThirdBodyReaction; /** * Common base class for the DASSL and DASPK solvers, which share a lot of * code. */ public abstract class JDAS implements DAESolver { protected LinkedHashMap IDTranslator = new LinkedHashMap(); //## attribute IDTranslator protected double atol; //## attribute atol protected int parameterInfor;//svp protected ParameterInfor [] parameterInforArray = null; //## attribute parameterInfor protected double rtol; //## attribute rtol protected InitialStatus initialStatus;//svp protected int nState = 3 ; protected int neq = 3; protected int nParameter =0; protected double [] y; protected double [] yprime; protected int [] info = new int[30]; protected LinkedList rList ; protected LinkedList duplicates ; protected LinkedList thirdBodyList ; protected LinkedList troeList ; protected LinkedList lindemannList; protected StringBuilder outputString ; protected StringBuilder rString ; protected StringBuilder tbrString; protected StringBuilder troeString; protected StringBuilder lindemannString; protected int index; protected ValidityTester validityTester; //5/5/08 gmagoon: adding validityTester and autoflag as attributes needed for "automatic" time stepping protected boolean autoflag; protected double [] reactionFlux; protected double [] conversionSet; protected double endTime; protected StringBuilder thermoString = new StringBuilder(); protected JDAS() { } public JDAS(double p_rtol, double p_atol, int p_parameterInfor, InitialStatus p_initialStatus, int p_index, ValidityTester p_vt, boolean p_autoflag) { rtol = p_rtol; atol = p_atol; index = p_index; validityTester = p_vt; autoflag = p_autoflag; parameterInfor = p_parameterInfor; initialStatus = p_initialStatus; } public void addSA(){ if (parameterInfor == 0) { parameterInfor = 1; } } public void addConversion(double [] p_conversions, int numConversion) { conversionSet = new double[numConversion]; for (int i=0; i< numConversion; i++) conversionSet[i] = p_conversions[i]; } public double[] getConversion(){ return conversionSet; } public StringBuilder generatePDepODEReactionList(ReactionModel p_reactionModel, SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) { StringBuilder rString = new StringBuilder(); StringBuilder arrayString = new StringBuilder(); StringBuilder rateString = new StringBuilder(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)p_reactionModel; rList = new LinkedList(); duplicates = new LinkedList(); LinkedList nonPDepList = new LinkedList(); LinkedList pDepList = new LinkedList(); generatePDepReactionList(p_reactionModel, p_beginStatus, p_temperature, p_pressure, nonPDepList, pDepList); int size = nonPDepList.size() + pDepList.size() + duplicates.size(); for (Iterator iter = nonPDepList.iterator(); iter.hasNext(); ) { Reaction r = (Reaction)iter.next(); if (!(r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)){ rList.add(r); ODEReaction or = transferReaction(r, p_beginStatus, p_temperature, p_pressure); arrayString.append(or.rNum+" "+or.pNum+" "); for (int i=0;i<3;i++){ if (i<or.rNum) arrayString.append(or.rID[i]+" "); else arrayString.append(0+" "); } for (int i=0;i<3;i++){ if (i<or.pNum) arrayString.append(or.pID[i]+" "); else arrayString.append(0+" "); } // Original DASSL has these lines uncommented, while DASPK is as given (should they be different?) if (r.hasReverseReaction()) arrayString.append(1 + " "); else arrayString.append(0 + " "); rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " "); } } for (Iterator iter = pDepList.iterator(); iter.hasNext(); ) { Reaction r = (Reaction)iter.next(); if (r instanceof PDepReaction) { rList.add(r); ODEReaction or = transferReaction(r, p_beginStatus, p_temperature, p_pressure); arrayString.append(or.rNum+" "+or.pNum+" "); for (int i=0;i<3;i++){ if (i<or.rNum) arrayString.append(or.rID[i]+" "); else arrayString.append(0+" "); } for (int i=0;i<3;i++){ if (i<or.pNum) arrayString.append(or.pID[i]+" "); else arrayString.append(0+" "); } arrayString.append(1 + " "); rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+" "); } } for (Iterator iter = duplicates.iterator(); iter.hasNext(); ) { Reaction r = (Reaction)iter.next(); //if (!(r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)){ if (r instanceof PDepReaction) { rList.add(r); ODEReaction or = transferReaction(r, p_beginStatus, p_temperature, p_pressure); arrayString.append(or.rNum+" "+or.pNum+" "); for (int i=0;i<3;i++){ if (i<or.rNum) arrayString.append(or.rID[i]+" "); else arrayString.append(0+" "); } for (int i=0;i<3;i++){ if (i<or.pNum) arrayString.append(or.pID[i]+" "); else arrayString.append(0+" "); } //if (r.hasReverseReaction()) arrayString.append(1 + " "); //else //arrayString.append(0 + " "); rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " "); } } rString.append(arrayString.toString()+"\n"+rateString.toString()); return rString; } public void generatePDepReactionList(ReactionModel p_reactionModel, SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure, LinkedList nonPDepList, LinkedList pDepList) { CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)p_reactionModel; for (Iterator iter = PDepNetwork.getCoreReactions(cerm).iterator(); iter.hasNext(); ) { PDepReaction rxn = (PDepReaction) iter.next(); if (cerm.categorizeReaction(rxn) != 1) continue; //check if this reaction is not already in the list and also check if this reaction has a reverse reaction // which is already present in the list. if (rxn.getReverseReaction() == null) rxn.generateReverseReaction(); if (!rxn.reactantEqualsProduct() && !troeList.contains(rxn) && !troeList.contains(rxn.getReverseReaction()) && !thirdBodyList.contains(rxn) && !thirdBodyList.contains(rxn.getReverseReaction()) && !lindemannList.contains(rxn) && !lindemannList.contains(rxn.getReverseReaction())) { if (!pDepList.contains(rxn) && !pDepList.contains(rxn.getReverseReaction())){ pDepList.add(rxn); } else if (pDepList.contains(rxn) && !pDepList.contains(rxn.getReverseReaction())) continue; else if (!pDepList.contains(rxn) && pDepList.contains(rxn.getReverseReaction())){ Temperature T = new Temperature(298, "K"); if (rxn.calculateKeq(T)>0.999) { pDepList.remove(rxn.getReverseReaction()); pDepList.add(rxn); } } } } for (Iterator iter = p_reactionModel.getReactionSet().iterator(); iter.hasNext(); ) { Reaction r = (Reaction)iter.next(); if (r.isForward() && !(r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)) nonPDepList.add(r); } duplicates.clear(); } protected LinkedHashMap generateSpeciesStatus(ReactionModel p_reactionModel, double [] p_y, double [] p_yprime, int p_paraNum) { int neq = p_reactionModel.getSpeciesNumber()*(p_paraNum+1); if (p_y.length != neq) throw new DynamicSimulatorException(); if (p_yprime.length != neq) throw new DynamicSimulatorException(); LinkedHashMap speStatus = new LinkedHashMap(); for (Iterator iter = p_reactionModel.getSpecies(); iter.hasNext(); ) { Species spe = (Species)iter.next(); int id = getRealID(spe); if (id>p_y.length) throw new UnknownReactedSpeciesException(spe.getName()); double conc = p_y[id-1]; double flux = p_yprime[id-1]; System.out.println(String.valueOf(spe.getID()) + '\t' + spe.getName() + '\t' + String.valueOf(conc) + '\t' + String.valueOf(flux)); if (conc < 0) { if (Math.abs(conc) < 1.0E-19) conc = 0; else throw new NegativeConcentrationException("species " + spe.getName() + " has negative conc: " + String.valueOf(conc)); } SpeciesStatus ss = new SpeciesStatus(spe, 1, conc, flux); speStatus.put(spe,ss); } return speStatus; } public StringBuilder generateThirdBodyReactionList(ReactionModel p_reactionModel, SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) { int size = p_reactionModel.getReactionSet().size(); StringBuilder arrayString = new StringBuilder(); StringBuilder rateString = new StringBuilder(); StringBuilder tbrString = new StringBuilder(); Iterator iter = p_reactionModel.getReactionSet().iterator(); thirdBodyList = new LinkedList(); while (iter.hasNext()) { Reaction r = (Reaction)iter.next(); if ((r.isForward()) && (r instanceof ThirdBodyReaction) && !(r instanceof TROEReaction) && !(r instanceof LindemannReaction)) { ThirdBodyODEReaction or = (ThirdBodyODEReaction)transferReaction(r, p_beginStatus, p_temperature, p_pressure); thirdBodyList.add((ThirdBodyReaction)r); arrayString.append(or.rNum+" "+or.pNum+" "); for (int i=0;i<3;i++){ if (i<or.rNum) arrayString.append(or.rID[i]+" "); else arrayString.append(0+" "); } for (int i=0;i<3;i++){ if (i<or.pNum) arrayString.append(or.pID[i]+" "); else arrayString.append(0+" "); } if (r.hasReverseReaction()) arrayString.append(1 + " "); else arrayString.append(0 + " "); arrayString.append(or.numCollider+" "); for (int i=0; i<10; i++){ if (i < or.numCollider) arrayString.append(or.colliders[i] + " "); else arrayString.append(0 + " "); } rateString.append(or.rate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " " +or.inertColliderEfficiency+" "); for (int i=0; i<10; i++){ if (i < or.numCollider) rateString.append(or.efficiency[i] + " "); else rateString.append(0 + " "); } } } tbrString.append(arrayString.toString()+"\n"+rateString.toString()); return tbrString; } protected StringBuilder generateTROEReactionList(ReactionModel p_reactionModel, SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) { int size = p_reactionModel.getReactionSet().size(); StringBuilder arrayString = new StringBuilder(); StringBuilder rateString = new StringBuilder(); StringBuilder troeString = new StringBuilder(); Iterator iter = p_reactionModel.getReactionSet().iterator(); troeList = new LinkedList(); while (iter.hasNext()) { Reaction r = (Reaction)iter.next(); if (r.isForward() && r instanceof TROEReaction) { TROEODEReaction or = (TROEODEReaction)transferReaction(r, p_beginStatus, p_temperature, p_pressure); troeList.add((TROEReaction)r); arrayString.append(or.rNum+" "+or.pNum+" "); for (int i=0;i<3;i++){ if (i<or.rNum) arrayString.append(or.rID[i]+" "); else arrayString.append(0+" "); } for (int i=0;i<3;i++){ if (i<or.pNum) arrayString.append(or.pID[i]+" "); else arrayString.append(0+" "); } if (r.hasReverseReaction()) arrayString.append(1 + " "); else arrayString.append(0 + " "); arrayString.append(or.numCollider+" "); for (int i=0; i<10; i++){ if (i < or.numCollider) arrayString.append(or.colliders[i] + " "); else arrayString.append(0 + " "); } if (or.troe7) arrayString.append(0 + " "); else arrayString.append(1 + " "); rateString.append(or.highRate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " "+or.inertColliderEfficiency+" "); for (int i=0; i<10; i++){ if (i < or.numCollider) rateString.append(or.efficiency[i] + " "); else rateString.append(0 + " "); } rateString.append(or.a + " " + or.Tstar + " " + or.T2star + " " + or.T3star + " " + or.lowRate+ " "); } } troeString.append(arrayString.toString()+"\n"+rateString.toString()); return troeString; } protected StringBuilder generateLindemannReactionList(ReactionModel p_reactionModel, SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) { int size = p_reactionModel.getReactionSet().size(); StringBuilder arrayString = new StringBuilder(); StringBuilder rateString = new StringBuilder(); StringBuilder lindemannString = new StringBuilder(); Iterator iter = p_reactionModel.getReactionSet().iterator(); lindemannList = new LinkedList(); while (iter.hasNext()) { Reaction r = (Reaction)iter.next(); if (r.isForward() && r instanceof LindemannReaction) { LindemannODEReaction or = (LindemannODEReaction)transferReaction(r, p_beginStatus, p_temperature, p_pressure); lindemannList.add((LindemannReaction)r); arrayString.append(or.rNum+" "+or.pNum+" "); for (int i=0;i<3;i++){ if (i<or.rNum) arrayString.append(or.rID[i]+" "); else arrayString.append(0+" "); } for (int i=0;i<3;i++){ if (i<or.pNum) arrayString.append(or.pID[i]+" "); else arrayString.append(0+" "); } if (r.hasReverseReaction()) arrayString.append(1 + " "); else arrayString.append(0 + " "); arrayString.append(or.numCollider+" "); for (int i=0; i<10; i++){ if (i < or.numCollider) arrayString.append(or.colliders[i] + " "); else arrayString.append(0 + " "); } rateString.append(or.highRate + " " + or.A + " " + or.n + " " + or.E + " "+r.calculateKeq(p_temperature)+ " "+or.inertColliderEfficiency+" "); for (int i=0; i<10; i++){ if (i < or.numCollider) rateString.append(or.efficiency[i] + " "); else rateString.append(0 + " "); } rateString.append(or.lowRate+ " "); } } lindemannString.append(arrayString.toString()+"\n"+rateString.toString()); return lindemannString; } public int getRealID(Species p_species) { Integer id = (Integer)IDTranslator.get(p_species); if (id == null) { id = new Integer(IDTranslator.size()+1); IDTranslator.put(p_species, id); thermoString.append(p_species.calculateG(initialStatus.getTemperature()) + " "); } return id.intValue(); } protected void initializeWorkSpace() { for (int i=0; i<30; i++) info[i] = 0; info[2] = 1; //print out the time steps } protected void initializeConcentrations(SystemSnapshot p_beginStatus, ReactionModel p_reactionModel, ReactionTime p_beginTime, ReactionTime p_endTime, LinkedList initialSpecies) { y = new double[neq]; yprime = new double[neq]; for (Iterator iter = p_beginStatus.getSpeciesStatus(); iter.hasNext(); ) { SpeciesStatus ss = (SpeciesStatus)iter.next(); double conc = ss.getConcentration(); double flux = ss.getFlux(); if (ss.isReactedSpecies()) { Species spe = ss.getSpecies(); int id = getRealID(spe); //System.out.println(String.valueOf(spe.getID()) + '\t' + spe.getName() + '\t' + String.valueOf(conc) + '\t' + String.valueOf(flux)); y[id-1] = conc; yprime[id-1] = flux; } } } public ODEReaction transferReaction(Reaction p_reaction, SystemSnapshot p_beginStatus, Temperature p_temperature, Pressure p_pressure) { //System.out.println(p_reaction.getStructure().toString()+"\t"+p_reaction.calculateTotalRate(Global.temperature)); double startTime = System.currentTimeMillis(); double dT = 1; Temperature Tup = new Temperature(p_temperature.getStandard()+dT, Temperature.getStandardUnit()); Temperature Tlow = new Temperature(p_temperature.getStandard()-dT, Temperature.getStandardUnit()); int rnum = p_reaction.getReactantNumber(); int pnum = p_reaction.getProductNumber(); int [] rid = new int[rnum]; int index = 0; for (Iterator r_iter = p_reaction.getReactants(); r_iter.hasNext(); ) { Species s = (Species)r_iter.next(); rid[index] = getRealID(s); index++; } int [] pid = new int[pnum]; index = 0; for (Iterator p_iter = p_reaction.getProducts(); p_iter.hasNext(); ) { Species s = (Species)p_iter.next(); pid[index] = getRealID(s); index++; } //Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60; //ODEReaction or; if (p_reaction instanceof PDepReaction) { double rate = ((PDepReaction)p_reaction).calculateRate(p_temperature, p_pressure); if (String.valueOf(rate).equals("NaN")){ System.err.println(p_reaction.toChemkinString(p_temperature) + "Has bad rate probably due to Ea<DH"); rate = 0; } ODEReaction or = new ODEReaction(rnum, pnum, rid, pid, rate); //Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60; return or; } else { double rate = 0; if (p_reaction instanceof TemplateReaction) { //startTime = System.currentTimeMillis(); //rate = ((TemplateReaction)p_reaction).getRateConstant(); rate = ((TemplateReaction)p_reaction).calculateTotalRate(p_beginStatus.temperature); ODEReaction or = new ODEReaction(rnum, pnum, rid, pid, rate); //Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60; return or; } else if (p_reaction instanceof TROEReaction){//svp startTime = System.currentTimeMillis(); HashMap weightMap = ((ThirdBodyReaction)p_reaction).getWeightMap(); int weightMapSize = weightMap.size(); int [] colliders = new int[weightMapSize]; double [] efficiency = new double[weightMapSize]; Iterator colliderIter = weightMap.keySet().iterator(); int numCollider =0; for (int i=0; i<weightMapSize; i++){ String name = (String)colliderIter.next(); Species spe = SpeciesDictionary.getInstance().getSpeciesFromName(name); if (spe != null){ colliders[numCollider] = getRealID(spe); efficiency[numCollider] = ((Double)weightMap.get(name)).doubleValue(); numCollider++; } } Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60; double T2star, T3star, Tstar, a; T2star = ((TROEReaction)p_reaction).getT2star(); T3star = ((TROEReaction)p_reaction).getT3star(); Tstar = ((TROEReaction)p_reaction).getTstar(); a = ((TROEReaction)p_reaction).getA(); int direction = p_reaction.getDirection(); double Keq = p_reaction.calculateKeq(p_temperature); double lowRate = ((TROEReaction)p_reaction).getLow().calculateRate(p_temperature, -1); double highRate = ((TROEReaction)p_reaction).getKinetics().calculateRate(p_temperature, -1); double inertColliderEfficiency = ((ThirdBodyReaction)p_reaction).calculateThirdBodyCoefficientForInerts(p_beginStatus); boolean troe7 = ((TROEReaction)p_reaction).getTroe7(); TROEODEReaction or = new TROEODEReaction(rnum, pnum, rid, pid, direction, Keq, colliders, efficiency, numCollider, inertColliderEfficiency, T2star, T3star, Tstar, a, highRate, lowRate, troe7); return or; } else if (p_reaction instanceof LindemannReaction){ HashMap weightMap = ((ThirdBodyReaction)p_reaction).getWeightMap(); int weightMapSize = weightMap.size(); int [] colliders = new int[weightMapSize]; double [] efficiency = new double[weightMapSize]; Iterator colliderIter = weightMap.keySet().iterator(); int numCollider =0; for (int i=0; i<weightMapSize; i++){ String name = (String)colliderIter.next(); Species spe = SpeciesDictionary.getInstance().getSpeciesFromName(name); if (spe != null){ colliders[numCollider] = getRealID(spe); efficiency[numCollider] = ((Double)weightMap.get(name)).doubleValue(); numCollider++; } } int direction = p_reaction.getDirection(); double Keq = p_reaction.calculateKeq(p_temperature); double lowRate = ((LindemannReaction)p_reaction).getLow().calculateRate(p_temperature, -1); double highRate = ((LindemannReaction)p_reaction).getKinetics().calculateRate(p_temperature, -1); double inertColliderEfficiency = ((ThirdBodyReaction)p_reaction).calculateThirdBodyCoefficientForInerts(p_beginStatus); LindemannODEReaction or = new LindemannODEReaction(rnum, pnum, rid, pid, direction, Keq, colliders, efficiency, numCollider, inertColliderEfficiency, highRate, lowRate); return or; } else if (p_reaction instanceof ThirdBodyReaction){//svp startTime = System.currentTimeMillis(); HashMap weightMap = ((ThirdBodyReaction)p_reaction).getWeightMap(); int weightMapSize = weightMap.size(); int [] colliders = new int[weightMapSize]; double [] efficiency = new double[weightMapSize]; Iterator colliderIter = weightMap.keySet().iterator(); int numCollider =0; for (int i=0; i<weightMapSize; i++){ String name = (String)colliderIter.next(); Species spe = SpeciesDictionary.getInstance().getSpeciesFromName(name); if (spe != null){ colliders[numCollider] = getRealID(spe); efficiency[numCollider] = ((Double)weightMap.get(name)).doubleValue(); numCollider++; } } Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60; rate = p_reaction.calculateTotalRate(p_beginStatus.temperature); double inertColliderEfficiency = ((ThirdBodyReaction)p_reaction).calculateThirdBodyCoefficientForInerts(p_beginStatus); //rate = p_reaction.getRateConstant(); ThirdBodyODEReaction or = new ThirdBodyODEReaction(rnum, pnum, rid, pid, rate, colliders, efficiency,numCollider, inertColliderEfficiency); return or; } else{ rate = p_reaction.calculateTotalRate(p_beginStatus.temperature); //startTime = System.currentTimeMillis(); //rate = p_reaction.getRateConstant(); ODEReaction or = new ODEReaction(rnum, pnum, rid, pid, rate); //Global.transferReaction = Global.transferReaction + (System.currentTimeMillis() - startTime)/1000/60; return or; } } } public double getAtol() { return atol; } public int getReactionSize(){ return rList.size()+troeList.size()+thirdBodyList.size()+lindemannList.size(); } public int getMaxSpeciesNumber() { return IDTranslator.size() - 1; } public double getRtol() { return rtol; } public String getEdgeReactionString(CoreEdgeReactionModel model, HashMap edgeID, Reaction r, Temperature temperature, Pressure pressure) { int edgeSpeciesCounter = edgeID.size(); // Find the rate coefficient double k; if (r instanceof TemplateReaction) k = ((TemplateReaction) r).getRateConstant(temperature, pressure); else if (r instanceof PDepReaction) k = ((PDepReaction) r).calculateRate(temperature, pressure); else k = r.getRateConstant(temperature); if (k > 0) { int reacCount = 0; int prodCount = 0; int[] tempReacArray = {0, 0, 0}; int[] tempProdArray = {0, 0, 0}; //iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants for (Iterator rIter = r.getReactants(); rIter.hasNext();) { reacCount++; Species spe = (Species) rIter.next(); tempReacArray[reacCount - 1] = getRealID(spe); } //iterate over the products, selecting products which are not already in the core, counting and storing ID's (created sequentially in a HashMap, similar to getRealID) in tempProdArray, up to a maximum of 3 for (Iterator pIter = r.getProducts(); pIter.hasNext();) { Species spe = (Species) pIter.next(); if (model.containsAsUnreactedSpecies(spe)) { prodCount++; Integer id = (Integer) edgeID.get(spe); if (id == null) { edgeSpeciesCounter++; id = new Integer(edgeSpeciesCounter); edgeID.put(spe, id); } tempProdArray[prodCount - 1] = id; } } //update the output string with info for one reaction String str = reacCount + " " + prodCount + " " + tempReacArray[0] + " " + tempReacArray[1] + " " + tempReacArray[2] + " " + tempProdArray[0] + " " + tempProdArray[1] + " " + tempProdArray[2] + " " + k; return str; } else { throw new NegativeRateException(r.toChemkinString(temperature) + ": " + String.valueOf(k)); } } public void getAutoEdgeReactionInfo(CoreEdgeReactionModel model, Temperature p_temperature, Pressure p_pressure) { //IMPORTANT: this code should pass the information needed to perform the same checks as done by the validity testing in the Java code //much of code below is taken or based off of code from appendUnreactedSpeciesStatus in ReactionSystem.java StringBuilder edgeReacInfoString = new StringBuilder(); int edgeReactionCounter = 0; int edgeSpeciesCounter = 0; // First use reactions in unreacted reaction set, which is valid for both RateBasedRME and RateBasedPDepRME HashMap edgeID = new HashMap(); LinkedHashSet ur = model.getUnreactedReactionSet(); for (Iterator iur = ur.iterator(); iur.hasNext();) { edgeReactionCounter++; Reaction r = (Reaction) iur.next(); String str = getEdgeReactionString(model, edgeID, r, p_temperature, p_pressure); edgeReacInfoString.append("\n" + str); } edgeSpeciesCounter = edgeID.size();//update edge species counter (this will be important for the case of non-P-dep operation) // For the case where validityTester is RateBasedPDepVT (assumed to also be directly associated with use of RateBasedPDepRME), consider two additional types of reactions if (validityTester instanceof RateBasedPDepVT) { //first consider NetReactions (formerly known as PDepNetReactionList) for (Iterator iter0 = PDepNetwork.getNetworks().iterator(); iter0.hasNext();) { PDepNetwork pdn = (PDepNetwork) iter0.next(); for (ListIterator iter = pdn.getNetReactions().listIterator(); iter.hasNext(); ) { PDepReaction rxn = (PDepReaction) iter.next(); // boolean allCoreReac=true; //flag to check whether all the reactants are in the core; boolean forwardFlag=true;//flag to track whether the direction that goes to (as products) at least one edge species is forward or reverse (presumably from all core species) boolean edgeReaction=false;//flag to track whether this is an edge reaction //first determine the direction that gives unreacted products; this will set the forward flag for (int j = 0; j < rxn.getReactantNumber(); j++) { Species species = (Species) rxn.getReactantList().get(j); if (model.containsAsUnreactedSpecies(species)){ forwardFlag = false; //use the reverse reaction edgeReaction = true; } } for (int j = 0; j < rxn.getProductNumber(); j++) { Species species = (Species) rxn.getProductList().get(j); if (model.containsAsUnreactedSpecies(species)){ forwardFlag = true; //use the forward reaction edgeReaction = true; } } //check whether all reactants are in the core; if not, it is not a true edge reaction (alternatively, we could use an allCoreReac flag like elsewhere) if (edgeReaction){ if(forwardFlag){ for (int j = 0; j < rxn.getReactantNumber(); j++) { Species species = (Species) rxn.getReactantList().get(j); if(!model.containsAsReactedSpecies(species)) edgeReaction = false; } } else{ for (int j = 0; j < rxn.getProductNumber(); j++) { Species species = (Species) rxn.getProductList().get(j); if(!model.containsAsReactedSpecies(species)) edgeReaction = false; } } } //write the string for the reaction with an edge product (it has been assumed above that only one side will have an edge species (although both sides of the reaction could have a core species)) if(edgeReaction){ edgeReactionCounter++; if(forwardFlag){ String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure);//use the forward reaction edgeReacInfoString.append("\n" + str); } else{ String str = getEdgeReactionString(model, edgeID, (PDepReaction)rxn.getReverseReaction(), p_temperature, p_pressure);//use the reverse reaction edgeReacInfoString.append("\n" + str); } } } } //6/19/09 gmagoon: original code below; with new P-dep implementation, it would only take into account forward reactions //if (rxn.isEdgeReaction(model)) { // edgeReactionCounter++; // String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure); // edgeReacInfoString.append("\n" + str); //a potentially simpler approach based on the original approach (however, it seems like isEdgeReaction may return false even if there are some core products along with edge products): // PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction(); // if (rxn.isEdgeReaction(model)) { // edgeReactionCounter++; // String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure); // edgeReacInfoString.append("\n" + str); // else if (rxnReverse.isEdgeReaction(model)){ // edgeReactionCounter++; // String str = getEdgeReactionString(model, edgeID, rxn, p_temperature, p_pressure); // edgeReacInfoString.append("\n" + str); //second, consider kLeak of each reaction network so that the validity of each reaction network may be tested //in the original CHEMDIS approach, we included a reaction and pseudospecies for each kleak/P-dep network //with the FAME approach we still consider each P-dep network as a pseudospecies, but we have multiple reactions contributing to this pseudo-species, with each reaction having different reactants edgeSpeciesCounter = edgeID.size();//above functions use getEdgeReactionString, which only uses edgeSpeciesCounter locally; we need to update it for the current context for (Iterator iter1 = PDepNetwork.getNetworks().iterator(); iter1.hasNext();) { PDepNetwork pdn = (PDepNetwork)iter1.next(); //account for pseudo-edge species product by incrementing the edgeSpeciesCounter and storing the ID in the tempProdArray; each of these ID's will occur once and only once; thus, note that the corresponding PDepNetwork is NOT stored to the HashMap int prodCount=1;//prodCount will not be modified as each PDepNetwork will be treated as a pseudo-edge species product int[] tempProdArray = {0, 0, 0}; edgeSpeciesCounter++; tempProdArray[0]=edgeSpeciesCounter;//note that if there are no non-included reactions that have all core reactants for a particular P-dep network, then the ID will be allocated, but not used...hopefully this would not cause problems with the Fortran code double k = 0.0; // double k = pdn.getKLeak(index);//index in DASSL should correspond to the same (reactionSystem/TPcondition) index as used by kLeak // if (!pdn.isActive() && pdn.getIsChemAct()) { // k = pdn.getEntryReaction().calculateTotalRate(p_temperature); for (ListIterator<PDepReaction> iter = pdn.getNonincludedReactions().listIterator(); iter.hasNext(); ) {//cf. getLeakFlux in PDepNetwork PDepReaction rxn = iter.next(); int reacCount=0; int[] tempReacArray = {0, 0, 0}; boolean allCoreReac=false;//allCoreReac will be used to track whether all reactant species are in the core if (rxn.getReactant().getIncluded() && !rxn.getProduct().getIncluded()){ k = rxn.calculateRate(p_temperature, p_pressure); allCoreReac=true; //iterate over the reactants, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants for (ListIterator<Species> rIter = rxn.getReactant().getSpeciesListIterator(); rIter.hasNext(); ) { reacCount++; Species spe = (Species)rIter.next(); if(model.containsAsReactedSpecies(spe)){ tempReacArray[reacCount-1]=getRealID(spe); } else{ allCoreReac=false; } } } else if (!rxn.getReactant().getIncluded() && rxn.getProduct().getIncluded()){ PDepReaction rxnReverse = (PDepReaction)rxn.getReverseReaction(); k = rxnReverse.calculateRate(p_temperature, p_pressure); allCoreReac=true; //iterate over the products, counting and storing IDs in tempReacArray, up to a maximum of 3 reactants for (ListIterator<Species> rIter = rxn.getProduct().getSpeciesListIterator(); rIter.hasNext(); ) { reacCount++; Species spe = (Species)rIter.next(); if(model.containsAsReactedSpecies(spe)){ tempReacArray[reacCount-1]=getRealID(spe); } else{ allCoreReac=false; } } } if(allCoreReac){//only consider cases where all reactants are in the core edgeReactionCounter++; //update the output string with info for kLeak for one PDepNetwork edgeReacInfoString.append("\n" + reacCount + " " + prodCount + " " + tempReacArray[0] + " " + tempReacArray[1] + " " + tempReacArray[2] + " " + tempProdArray[0] + " " + tempProdArray[1] + " " + tempProdArray[2] + " " + k); } } } } //edgeSpeciesCounter = edgeID.size();
package ch.hsr.whitespace.javapilot.akka; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.zuehlke.carrera.relayapi.messages.PenaltyMessage; import akka.actor.ActorRef; import akka.actor.Props; import ch.hsr.whitespace.javapilot.akka.messages.ChangePowerMessage; import ch.hsr.whitespace.javapilot.akka.messages.SpeedupFactorFromNextPartMessage; import ch.hsr.whitespace.javapilot.akka.messages.SpeedupFinishedMessage; import ch.hsr.whitespace.javapilot.model.Power; import ch.hsr.whitespace.javapilot.model.track.TrackPart; public class StraightDrivingActor extends AbstractTrackPartDrivingActor { private final Logger LOGGER = LoggerFactory.getLogger(StraightDrivingActor.class); private static final int MINIMAL_BRAKE_DOWN_POWER = 30; private static final double SPEEDUP_DURATION_STEPS = 0.05; private Power currentBrakeDownPower; private boolean lastTurnWasTooFast = false; private long timeUntilBrake; private long initialDuration = 0; private double speedupFactor = 0.0; private double timeUtilBrakeDownFactor = 0.1; public static Props props(ActorRef pilot, TrackPart trackPart, int currentPower) { return Props.create(StraightDrivingActor.class, () -> new StraightDrivingActor(pilot, trackPart, currentPower)); } public StraightDrivingActor(ActorRef pilot, TrackPart trackPart, int currentPower) { super(pilot, trackPart, currentPower); this.currentBrakeDownPower = new Power(currentPower); } @Override public void onReceive(Object message) throws Exception { super.onReceive(message); if (message instanceof SpeedupFactorFromNextPartMessage) { handleSpeedupFactor((SpeedupFactorFromNextPartMessage) message); } else if (message instanceof PenaltyMessage && iAmDriving) { handlePenalty((PenaltyMessage) message); } } private void handlePenalty(PenaltyMessage message) { LOGGER.warn((char) 27 + "[31m" + "Driver #" + trackPart.getId() + ": got PENALTY" + (char) 27 + "[0m"); hasPenalty = true; speedupFactor = (message.getActualSpeed() / message.getSpeedLimit()) - 1.0; handleTooHighSpeed(); } private void handleTooHighSpeed() { lastTurnWasTooFast = true; if (!iAmSpeedingUp) { LOGGER.info("Driver#" + trackPart.getId() + " Last time until brake: " + timeUntilBrake); timeUntilBrake = timeUntilBrake + (int) (timeUntilBrake * -speedupFactor); LOGGER.info("Driver#" + trackPart.getId() + " New time until brake: " + timeUntilBrake + " (speedup-factor: " + speedupFactor + ")"); } } private void handleSpeedupFactor(SpeedupFactorFromNextPartMessage message) { if (initialDuration == 0) initialDuration = message.getLastDuration(); if (!hasPenalty) { speedupFactor = calcSpeedupFactor(message.getCurrentDuration()); } if (iAmSpeedingUp) LOGGER.info("Driver#" + trackPart.getId() + " speedup: " + speedupFactor); if (speedupFactor >= 0.1 && !drivingWithConstantPower) { handleTooHighSpeed(); } } private double calcSpeedupFactor(long currentDuration) { return (100 - ((100.0 / initialDuration) * currentDuration)) / 100.0; } @Override protected void evaluateAndSetNewPower() { if (iAmSpeedingUp) { Power maxPower = new Power(Power.MAX_POWER); LOGGER.info("Was last round too fast?: " + lastTurnWasTooFast); if (!lastTurnWasTooFast) { timeUtilBrakeDownFactor = timeUtilBrakeDownFactor + SPEEDUP_DURATION_STEPS; } else if (canWeReduceBrakeDownPower()) { int brakeDownValue = (int) (Math.max(currentBrakeDownPower.getValue() * SPEEDUP_DURATION_STEPS, 10)); LOGGER.info("BRAKE DOWN VALUE: " + brakeDownValue); currentBrakeDownPower = new Power(currentBrakeDownPower.getValue() - brakeDownValue); } else { timeUtilBrakeDownFactor = timeUtilBrakeDownFactor - SPEEDUP_DURATION_STEPS; stopSpeedup(); } calculateTimeUntilBrake(currentPower.calcDiffFactor(maxPower)); calculateBrakeDownPower(); currentPower = maxPower; } scheduleBrake(timeUntilBrake, currentBrakeDownPower); setPower(currentPower); lastTurnWasTooFast = false; } private boolean canWeReduceBrakeDownPower() { return currentBrakeDownPower.getValue() > MINIMAL_BRAKE_DOWN_POWER; } private void calculateBrakeDownPower() { int lastBrakeDownPower = currentBrakeDownPower.getValue(); currentBrakeDownPower = new Power(currentBrakeDownPower.getValue() + (int) (currentBrakeDownPower.getValue() * -speedupFactor)); LOGGER.info("Calculated brake down power: " + currentBrakeDownPower.getValue() + " (based on speedupfactor=" + speedupFactor + ", last-brakedown-power=" + lastBrakeDownPower + ")"); } private void calculateTimeUntilBrake(double powerDiffFactor) { timeUntilBrake = (long) (trackPart.getDuration() * timeUtilBrakeDownFactor * powerDiffFactor); LOGGER.info("Calculated time until brake: " + timeUntilBrake); } private void stopSpeedup() { if (iAmSpeedingUp) { getContext().parent().tell(new SpeedupFinishedMessage(trackPart), getSelf()); LOGGER.info("Driver#" + trackPart.getId() + " stopped speeding up ..."); } iAmSpeedingUp = false; } private void scheduleBrake(long timeUntilBrake, Power brakeDownPower) { if (brakeDownPower.getValue() == currentPower.getValue()) return; pilot.tell(new ChangePowerMessage(brakeDownPower, timeUntilBrake), getSelf()); } }
package com.bailei.study.jzoffer.interview13; import com.bailei.study.utils.Utils; public class DeleteNodeInList { public void deleteNode(ListNode head, ListNode toBeDeleted) { if (head == null || toBeDeleted == null) { throw new RuntimeException("head or toBeDeleted can not be null"); } if (head.next == null && head == toBeDeleted) { head = null; } if (toBeDeleted.next != null) { toBeDeleted.value = toBeDeleted.next.value; toBeDeleted.next = toBeDeleted.next.next; } else { ListNode node = head; while (node.next != toBeDeleted) { node = node.next; } node.next = null; toBeDeleted = null; } } public static void main(String[] args) { ListNode toBeDelete = new ListNode(7); ListNode head = new ListNode.Builder().node(0).node(toBeDelete) .node(1).node(2).node(3).node(4).node(5).build(); new DeleteNodeInList().deleteNode(head, toBeDelete); Utils.printList(head); } }
package com.censoredsoftware.demigods.command; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.helper.WrappedCommand; import com.censoredsoftware.demigods.language.Symbol; import com.censoredsoftware.demigods.language.Translation; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.player.DPlayer; import com.censoredsoftware.demigods.util.Maps2; import com.censoredsoftware.demigods.util.Messages; import com.censoredsoftware.demigods.util.Strings; import com.censoredsoftware.demigods.util.Titles; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; public class GeneralCommands extends WrappedCommand { public GeneralCommands() { super(false); } @Override public Set<String> getCommands() { return Sets.newHashSet("check", "owner", "binds", "leaderboard", "alliance"); } @Override public boolean processCommand(CommandSender sender, Command command, String[] args) { if(command.getName().equalsIgnoreCase("check")) return check(sender); else if(command.getName().equalsIgnoreCase("owner")) return owner(sender, args); else if(command.getName().equalsIgnoreCase("alliance")) return alliance(sender, args); else if(command.getName().equalsIgnoreCase("binds")) return binds(sender); else if(command.getName().equalsIgnoreCase("leaderboard")) return leaderboard(sender); return false; } private boolean check(CommandSender sender) { Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character == null) { player.sendMessage(ChatColor.RED + "You are nothing but a mortal. You have no worthy statistics."); return true; } // Define variables int kills = character.getKillCount(); int deaths = character.getDeathCount(); String charName = character.getName(); String deity = character.getDeity().getName(); String alliance = character.getAlliance(); int favor = character.getMeta().getFavor(); int maxFavor = character.getMeta().getMaxFavor(); int ascensions = character.getMeta().getAscensions(); int skillPoints = character.getMeta().getSkillPoints(); ChatColor deityColor = character.getDeity().getColor(); ChatColor favorColor = Strings.getColor(character.getMeta().getFavor(), character.getMeta().getMaxFavor()); // Send the user their info via chat Messages.tagged(sender, "Player Check"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Character: " + deityColor + charName); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Deity: " + deityColor + deity + ChatColor.WHITE + " of the " + ChatColor.GOLD + StringUtils.capitalize(alliance) + "s"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Favor: " + favorColor + favor + ChatColor.GRAY + " (of " + ChatColor.GREEN + maxFavor + ChatColor.GRAY + ")"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Ascensions: " + ChatColor.GREEN + ascensions); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Available Skill Points: " + ChatColor.GREEN + skillPoints); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Kills: " + ChatColor.GREEN + kills + ChatColor.WHITE + " / Deaths: " + ChatColor.RED + deaths); return true; } private boolean owner(CommandSender sender, String[] args) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); Player player = (Player) sender; if(args.length < 1) { player.sendMessage(ChatColor.RED + "You must select a character."); player.sendMessage(ChatColor.RED + "/owner <character>"); return true; } DCharacter charToCheck = DCharacter.Util.getCharacterByName(args[0]); if(charToCheck == null) player.sendMessage(ChatColor.RED + "That character doesn't exist."); else player.sendMessage(charToCheck.getDeity().getColor() + charToCheck.getName() + ChatColor.YELLOW + " belongs to " + charToCheck.getOfflinePlayer().getName() + "."); return true; } private boolean alliance(CommandSender sender, String[] args) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); Player player = (Player) sender; if(args.length < 1) return false; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character == null) { player.sendMessage(Demigods.LANGUAGE.getText(Translation.Text.DISABLED_MORTAL)); return true; } else character.chatWithAlliance(Joiner.on(" ").join(args)); return true; } private boolean binds(CommandSender sender) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); // Define variables Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character != null && !character.getMeta().getBinds().isEmpty()) { player.sendMessage(ChatColor.YELLOW + Titles.chatTitle("Currently Bound Abilities")); player.sendMessage(" "); // Get the binds and display info for(Map.Entry<String, Object> entry : character.getMeta().getBinds().entrySet()) player.sendMessage(ChatColor.GREEN + " " + StringUtils.capitalize(entry.getKey().toLowerCase()) + ChatColor.GRAY + " is bound to " + (Strings.beginsWithVowel(entry.getValue().toString()) ? "an " : "a ") + ChatColor.ITALIC + Strings.beautify(entry.getValue().toString()).toLowerCase() + ChatColor.GRAY + "."); player.sendMessage(" "); } else player.sendMessage(ChatColor.RED + "You currently have no ability binds."); return true; } private boolean leaderboard(CommandSender sender) { // Define variables List<DCharacter> characters = Lists.newArrayList(DCharacter.Util.getAllUsable()); Map<UUID, Double> scores = Maps.newLinkedHashMap(); for(int i = 0; i < characters.size(); i++) { DCharacter character = characters.get(i); double score = character.getKillCount() * (character.getDeathCount() == 0 ? character.getKillCount() / 1.0 : character.getKillCount() / character.getDeathCount()); if(score > 0) scores.put(character.getId(), score); } // Sort rankings scores = Maps2.sortByValue(scores); // Print info sender.sendMessage(" "); sender.sendMessage(ChatColor.YELLOW + Titles.chatTitle("Leaderboard")); sender.sendMessage(" Rankings are determined by kills and deaths."); sender.sendMessage(" "); int length = characters.size() > 15 ? 16 : characters.size() + 1; List<Map.Entry<UUID, Double>> list = Lists.newArrayList(scores.entrySet()); int count = 0; for(int i = list.size() - 1; i >= 0; i { count++; Map.Entry<UUID, Double> entry = list.get(i); if(count >= length) break; DCharacter character = DCharacter.Util.load(entry.getKey()); sender.sendMessage(ChatColor.GRAY + " " + ChatColor.RESET + count + ". " + character.getDeity().getColor() + character.getName() + ChatColor.RESET + ChatColor.GRAY + " (" + character.getPlayer() + ") " + ChatColor.RESET + "Kills: " + ChatColor.GREEN + character.getKillCount() + ChatColor.WHITE + " / Deaths: " + ChatColor.RED + character.getDeathCount()); } sender.sendMessage(" "); return true; } }
package com.censoredsoftware.demigods.command; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.deity.Alliance; import com.censoredsoftware.demigods.helper.WrappedCommand; import com.censoredsoftware.demigods.language.Symbol; import com.censoredsoftware.demigods.language.Translation; import com.censoredsoftware.demigods.player.DCharacter; import com.censoredsoftware.demigods.player.DPlayer; import com.censoredsoftware.demigods.util.*; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; public class GeneralCommands extends WrappedCommand { public GeneralCommands() { super(false); } @Override public Set<String> getCommands() { return Sets.newHashSet("check", "owner", "binds", "leaderboard", "alliance", "values", "names"); } @Override public boolean processCommand(CommandSender sender, Command command, String[] args) { if(command.getName().equalsIgnoreCase("check")) return check(sender); else if(command.getName().equalsIgnoreCase("owner")) return owner(sender, args); else if(command.getName().equalsIgnoreCase("alliance")) return alliance(sender, args); else if(command.getName().equalsIgnoreCase("binds")) return binds(sender); else if(command.getName().equalsIgnoreCase("leaderboard")) return leaderboard(sender); else if(command.getName().equalsIgnoreCase("values")) return values(sender); else if(command.getName().equalsIgnoreCase("names")) return names(sender); return false; } private boolean check(CommandSender sender) { Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character == null) { player.sendMessage(ChatColor.RED + "You are nothing but a mortal. You have no worthy statistics."); return true; } // Define variables int kills = character.getKillCount(); int deaths = character.getDeathCount(); String charName = character.getName(); String deity = character.getDeity().getName(); Alliance alliance = character.getAlliance(); int favor = character.getMeta().getFavor(); int maxFavor = character.getMeta().getMaxFavor(); int ascensions = character.getMeta().getAscensions(); int skillPoints = character.getMeta().getSkillPoints(); ChatColor deityColor = character.getDeity().getColor(); ChatColor favorColor = Strings.getColor(character.getMeta().getFavor(), character.getMeta().getMaxFavor()); // Send the user their info via chat Messages.tagged(sender, "Player Check"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Character: " + deityColor + charName); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Deity: " + deityColor + deity + ChatColor.WHITE + " of the " + ChatColor.GOLD + alliance.getName() + "s"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Favor: " + favorColor + favor + ChatColor.GRAY + " (of " + ChatColor.GREEN + maxFavor + ChatColor.GRAY + ")"); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Ascensions: " + ChatColor.GREEN + ascensions); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Available Skill Points: " + ChatColor.GREEN + skillPoints); sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.RESET + "Kills: " + ChatColor.GREEN + kills + ChatColor.WHITE + " / Deaths: " + ChatColor.RED + deaths); return true; } private boolean owner(CommandSender sender, String[] args) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); Player player = (Player) sender; if(args.length < 1) { player.sendMessage(ChatColor.RED + "You must select a character."); player.sendMessage(ChatColor.RED + "/owner <character>"); return true; } DCharacter charToCheck = DCharacter.Util.getCharacterByName(args[0]); if(charToCheck == null) player.sendMessage(ChatColor.RED + "That character doesn't exist."); else player.sendMessage(charToCheck.getDeity().getColor() + charToCheck.getName() + ChatColor.YELLOW + " belongs to " + charToCheck.getOfflinePlayer().getName() + "."); return true; } private boolean alliance(CommandSender sender, String[] args) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); Player player = (Player) sender; if(args.length < 1) return false; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character == null) { player.sendMessage(Demigods.LANGUAGE.getText(Translation.Text.DISABLED_MORTAL)); return true; } else character.chatWithAlliance(Joiner.on(" ").join(args)); return true; } private boolean binds(CommandSender sender) { if(!sender.hasPermission("demigods.basic")) return Messages.noPermission(sender); // Define variables Player player = (Player) sender; DCharacter character = DPlayer.Util.getPlayer(player).getCurrent(); if(character != null && !character.getMeta().getBinds().isEmpty()) { player.sendMessage(ChatColor.YELLOW + Titles.chatTitle("Currently Bound Abilities")); player.sendMessage(" "); // Get the binds and display info for(Map.Entry<String, Object> entry : character.getMeta().getBinds().entrySet()) player.sendMessage(ChatColor.GREEN + " " + StringUtils.capitalize(entry.getKey().toLowerCase()) + ChatColor.GRAY + " is bound to " + (Strings.beginsWithVowel(entry.getValue().toString()) ? "an " : "a ") + ChatColor.ITALIC + Strings.beautify(entry.getValue().toString()).toLowerCase() + ChatColor.GRAY + "."); player.sendMessage(" "); } else player.sendMessage(ChatColor.RED + "You currently have no ability binds."); return true; } private boolean leaderboard(CommandSender sender) { // Define variables List<DCharacter> characters = Lists.newArrayList(DCharacter.Util.getAllUsable()); Map<UUID, Double> scores = Maps.newLinkedHashMap(); for(int i = 0; i < characters.size(); i++) { DCharacter character = characters.get(i); double score = character.getKillCount() - character.getDeathCount(); if(score > 0) scores.put(character.getId(), score); } // Sort rankings scores = Maps2.sortByValue(scores, false); // Print info Messages.tagged(sender, "Leaderboard"); sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + " Rankings are determined by kills and deaths."); sender.sendMessage(" "); int length = characters.size() > 15 ? 16 : characters.size() + 1; List<Map.Entry<UUID, Double>> list = Lists.newArrayList(scores.entrySet()); int count = 0; for(int i = list.size() - 1; i >= 0; i { count++; Map.Entry<UUID, Double> entry = list.get(i); if(count >= length) break; DCharacter character = DCharacter.Util.load(entry.getKey()); sender.sendMessage(ChatColor.GRAY + " " + ChatColor.RESET + count + ". " + character.getDeity().getColor() + character.getName() + ChatColor.RESET + ChatColor.GRAY + " (" + character.getPlayerName() + ") " + ChatColor.RESET + "Kills: " + ChatColor.GREEN + character.getKillCount() + ChatColor.WHITE + " / Deaths: " + ChatColor.RED + character.getDeathCount()); } sender.sendMessage(" "); return true; } private boolean values(CommandSender sender) { // Define variables Player player = (Player) sender; int count = 0; // Send header Messages.tagged(sender, "Current High Value Tributes"); sender.sendMessage(" "); for(Map.Entry<Material, Integer> entry : Maps2.sortByValue(ItemValues.getTributeValuesMap(), true).entrySet()) { // Handle count if(count >= 10) break; count++; // Display value sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.YELLOW + Strings.beautify(entry.getKey().name()) + ChatColor.GRAY + " (currently worth " + ChatColor.GREEN + entry.getValue() + ChatColor.GRAY + " per item)"); } sender.sendMessage(" "); sender.sendMessage(ChatColor.ITALIC + "Values are constantly changing based on how players"); sender.sendMessage(ChatColor.ITALIC + "tribute, so check back often!"); if(player.getItemInHand() != null && !player.getItemInHand().getType().equals(Material.AIR)) { sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + "The items in your hand are worth " + ChatColor.GREEN + ItemValues.getValue(player.getItemInHand()) + ChatColor.GRAY + "."); } return true; } private boolean names(CommandSender sender) { // Print info Messages.tagged(sender, "Online Player Names"); sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + "" + ChatColor.UNDERLINE + " Immortals:"); sender.sendMessage(" "); // Characters for(DCharacter character : DCharacter.Util.getOnlineCharacters()) sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + character.getDeity().getColor() + character.getName() + ChatColor.GRAY + " is owned by " + ChatColor.WHITE + character.getPlayerName() + ChatColor.GRAY + "."); sender.sendMessage(" "); sender.sendMessage(ChatColor.GRAY + "" + ChatColor.UNDERLINE + " Mortals:"); sender.sendMessage(" "); // Mortals for(Player mortal : DPlayer.Util.getOnlineMortals()) sender.sendMessage(ChatColor.GRAY + " " + Symbol.RIGHTWARD_ARROW + " " + ChatColor.WHITE + mortal.getDisplayName() + "."); return true; } }
package com.continuuity.data.engine.hypersql; import com.continuuity.api.data.OperationException; import com.continuuity.api.data.OperationResult; import com.continuuity.common.utils.ImmutablePair; import com.continuuity.data.operation.StatusCode; import com.continuuity.data.table.OrderedVersionedColumnarTable; import com.continuuity.data.table.ReadPointer; import com.continuuity.data.table.Scanner; import com.google.common.base.Objects; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hbase.util.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Implementation of an OVCTable over a HyperSQL table. */ public class HyperSQLOVCTable implements OrderedVersionedColumnarTable { private static final Logger Log = LoggerFactory.getLogger(HyperSQLOVCTable.class); private final String tableName; private final Connection connection; HyperSQLOVCTable(final String tableName, Connection connection) { this.tableName = tableName; this.connection = connection; } private static final String ROW_TYPE = "VARBINARY(1024)"; private static final String COLUMN_TYPE = "VARBINARY(1024)"; private static final String VERSION_TYPE = "BIGINT"; private static final String TYPE_TYPE = "INT"; private static final String VALUE_TYPE = "VARBINARY(1024)"; private static final byte [] NULL_VAL = new byte [0]; private enum Type { UNDELETE_ALL (0), DELETE_ALL (1), DELETE (2), VALUE (3); int i; Type(int i) { this.i = i; } static Type from(int i) { switch (i) { case 0: return UNDELETE_ALL; case 1: return DELETE_ALL; case 2: return DELETE; case 3: return VALUE; } return null; } boolean isUndeleteAll() { return this == UNDELETE_ALL; } boolean isDeleteAll() { return this == DELETE_ALL; } boolean isDelete() { return this == DELETE; } @Override public String toString() { return Objects.toStringHelper(this) .add("name", name()) .add("int", this.i) .toString(); } } void initializeTable() throws OperationException { String createStatement = "CREATE CACHED TABLE " + this.tableName + " (" + "rowkey " + ROW_TYPE + " NOT NULL, " + "column " + COLUMN_TYPE + " NOT NULL, " + "version " + VERSION_TYPE + " NOT NULL, " + "kvtype " + TYPE_TYPE + " NOT NULL, " + "id BIGINT IDENTITY, " + "value " + VALUE_TYPE + " NOT NULL)"; String indexStatement = "CREATE INDEX theBigIndex" + this.tableName + " ON " + this.tableName + " (rowkey, column, version DESC, kvtype, id DESC)"; Statement stmt = null; try { stmt = this.connection.createStatement(); stmt.executeUpdate(createStatement); stmt.executeUpdate(indexStatement); } catch (SQLException e) { // fail silent if table/index already exists // SQL state for determining the duplicate table create exception if(!e.getSQLState().equalsIgnoreCase("42504")) { handleSQLException(e, "create"); } } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } } // Administrative Operations @Override public void clear() throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement("DELETE FROM " + this.tableName); ps.executeUpdate(); } catch (SQLException e) { handleSQLException(e, "delete"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } } // Simple Write Operations @Override public void put(byte[] row, byte[] column, long version, byte[] value) throws OperationException { performInsert(row, column, version, Type.VALUE, value); } @Override public void put(byte[] row, byte[][] columns, long version, byte[][] values) throws OperationException { performInsert(row, columns, version, Type.VALUE, values); } // Delete Operations @Override public void delete(byte[] row, byte[] column, long version) throws OperationException { performInsert(row, column, version, Type.DELETE, NULL_VAL); } @Override public void delete(byte[] row, byte[][] columns, long version) throws OperationException { performInsert(row, columns, version, Type.DELETE, generateDeleteVals(columns.length)); } @Override public void deleteAll(byte[] row, byte[] column, long version) throws OperationException { performInsert(row, column, version, Type.DELETE_ALL, NULL_VAL); } @Override public void deleteAll(byte[] row, byte[][] columns, long version) throws OperationException { performInsert(row, columns, version, Type.DELETE_ALL, generateDeleteVals(columns.length)); } @Override public void undeleteAll(byte[] row, byte[] column, long version) throws OperationException { performInsert(row, column, version, Type.UNDELETE_ALL, NULL_VAL); } @Override public void undeleteAll(byte[] row, byte[][] columns, long version) throws OperationException { performInsert(row, columns, version, Type.UNDELETE_ALL, generateDeleteVals(columns.length)); } private byte[][] generateDeleteVals(int length) { byte [][] values = new byte[length][]; for (int i=0;i<values.length;i++) values[i] = NULL_VAL; return values; } // Read-Modify-Write Operations @Override public long increment(byte[] row, byte[] column, long amount, ReadPointer readPointer, long writeVersion) throws OperationException { PreparedStatement ps = null; long newAmount = amount; try { try { ps = this.connection.prepareStatement( "SELECT version, kvtype, id, value " + "FROM " + this.tableName + " " + "WHERE rowkey = ? AND column = ? " + "ORDER BY version DESC, kvtype ASC, id DESC"); ps.setBytes(1, row); ps.setBytes(2, column); ResultSet result = ps.executeQuery(); ImmutablePair<Long, byte[]> latest = filteredLatest(result, readPointer); if (latest != null) { newAmount += Bytes.toLong(latest.getSecond()); } ps.close(); } catch (SQLException e) { handleSQLException(e, "select"); } try { ps = this.connection.prepareStatement( "INSERT INTO " + this.tableName + " (rowkey, column, version, kvtype, value) " + "VALUES ( ? , ? , ? , ? , ?)"); ps.setBytes(1, row); ps.setBytes(2, column); ps.setLong(3, writeVersion); ps.setInt(4, Type.VALUE.i); ps.setBytes(5, Bytes.toBytes(newAmount)); ps.executeUpdate(); } catch (SQLException e) { handleSQLException(e, "insert"); } } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } return newAmount; } @Override public Map<byte[], Long> increment(byte[] row, byte[][] columns, long[] amounts, ReadPointer readPointer, long writeVersion) throws OperationException { // TODO: This is not atomic across columns, it just loops over them Map<byte[],Long> ret = new TreeMap<byte[],Long>(Bytes.BYTES_COMPARATOR); for (int i=0; i<columns.length; i++) { ret.put(columns[i], increment(row, columns[i], amounts[i], readPointer, writeVersion)); } return ret; } @Override public void compareAndSwap(byte[] row, byte[] column, byte[] expectedValue, byte[] newValue, ReadPointer readPointer, long writeVersion) throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement( "SELECT version, kvtype, id, value " + "FROM " + this.tableName + " " + "WHERE rowkey = ? AND column = ? " + "ORDER BY version DESC, kvtype ASC, id DESC"); ps.setBytes(1, row); ps.setBytes(2, column); ResultSet result = ps.executeQuery(); ImmutablePair<Long, byte[]> latest = filteredLatest(result, readPointer); byte [] existingValue = latest == null ? null : latest.getSecond(); ps.close(); ps = null; // handle invalid cases regarding non-existent values if (existingValue == null && expectedValue != null) throw new OperationException(StatusCode.WRITE_CONFLICT, "CompareAndSwap expected value mismatch"); if (existingValue != null && expectedValue == null) throw new OperationException(StatusCode.WRITE_CONFLICT, "CompareAndSwap expected value mismatch"); // if nothing existed, just write // TODO: this is not atomic and thus is broken? how to make it atomic? if (expectedValue == null) { put(row, column, writeVersion, newValue); return; } // check if expected == existing, fail if not if (!Bytes.equals(expectedValue, existingValue)) throw new OperationException(StatusCode.WRITE_CONFLICT, "CompareAndSwap expected value mismatch"); // if newValue is null, just delete. // TODO: this can't be rolled back! if (newValue == null) { deleteAll(row, column, latest.getFirst()); return; } // Perform update! ps = this.connection.prepareStatement( "INSERT INTO " + this.tableName + " (rowkey, column, version, kvtype, value) VALUES ( ?, ? , ? , ? , ? )"); ps.setBytes(1, row); ps.setBytes(2, column); ps.setLong(3, writeVersion); ps.setInt(4, Type.VALUE.i); ps.setBytes(5, newValue); ps.executeUpdate(); } catch (SQLException e) { handleSQLException(e, "compareAndSwap"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } } // Read Operations @Override public OperationResult<Map<byte[], byte[]>> get(byte[] row, ReadPointer readPointer) throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement( "SELECT column, version, kvtype, id, value " + "FROM " + this.tableName + " " + "WHERE rowkey = ? " + "ORDER BY column ASC, version DESC, kvtype ASC, id DESC"); ps.setBytes(1, row); ResultSet result = ps.executeQuery(); return new OperationResult<Map<byte[], byte[]>>( filteredLatestColumns(result, readPointer)); } catch (SQLException e) { handleSQLException(e, "select"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } throw new InternalError("this point should never be reached."); } @Override public OperationResult<byte[]> get(byte[] row, byte[] column, ReadPointer readPointer) throws OperationException { OperationResult<ImmutablePair<byte[], Long>> res = getWithVersion(row, column, readPointer); if (res.isEmpty()) return new OperationResult<byte[]>(res.getStatus(), res.getMessage()); else return new OperationResult<byte[]>(res.getValue().getFirst()); } @Override public OperationResult<ImmutablePair<byte[], Long>> getWithVersion(byte[] row, byte[] column, ReadPointer readPointer) throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement( "SELECT version, kvtype, id, value " + "FROM " + this.tableName + " " + "WHERE rowkey = ? AND column = ? " + "ORDER BY version DESC, kvtype ASC, id DESC"); ps.setBytes(1, row); ps.setBytes(2, column); ResultSet result = ps.executeQuery(); ImmutablePair<Long,byte[]> latest = filteredLatest(result, readPointer); if (latest == null) return new OperationResult<ImmutablePair<byte[], Long>>( StatusCode.KEY_NOT_FOUND); return new OperationResult<ImmutablePair<byte[], Long>>( new ImmutablePair<byte[],Long>( latest.getSecond(), latest.getFirst())); } catch (SQLException e) { handleSQLException(e, "select"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } throw new InternalError("this point should never be reached."); } @Override public OperationResult<Map<byte[], byte[]>> get(byte[] row, byte[] startColumn, byte[] stopColumn, ReadPointer readPointer) throws OperationException { PreparedStatement ps = null; try { String columnChecks = ""; if (startColumn != null) columnChecks += " AND column >= ?"; if (stopColumn != null) columnChecks += " AND column < ?"; ps = this.connection.prepareStatement( "SELECT column, version, kvtype, id, value " + "FROM " + this.tableName + " " + "WHERE rowkey = ?" + columnChecks + " " + "ORDER BY column ASC, version DESC, kvtype ASC, id DESC"); ps.setBytes(1, row); int idx = 2; if (startColumn != null) { ps.setBytes(idx, startColumn); idx++; } if (stopColumn != null) { ps.setBytes(idx, stopColumn); } ResultSet result = ps.executeQuery(); if (result == null) { return new OperationResult<Map<byte[], byte[]>>( StatusCode.KEY_NOT_FOUND); } Map<byte[], byte[]> filtered = filteredLatestColumns(result, readPointer); if (filtered.isEmpty()) { return new OperationResult<Map<byte[], byte[]>>( StatusCode.COLUMN_NOT_FOUND); } else { return new OperationResult<Map<byte[], byte[]>>(filtered); } } catch (SQLException e) { handleSQLException(e, "select"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } throw new InternalError("this point should never be reached."); } @Override public OperationResult<Map<byte[], byte[]>> get(byte[] row, byte[][] columns, ReadPointer readPointer) throws OperationException { PreparedStatement ps = null; try { String [] columnChecks = new String[columns.length]; String columnCheck = "column = ?"; for (int i=0; i<columnChecks.length; i++) { columnChecks[i] = columnCheck; } columnCheck = StringUtils.join(columnChecks, " OR "); ps = this.connection.prepareStatement( "SELECT column, version, kvtype, id, value " + "FROM " + this.tableName + " " + "WHERE rowkey = ? AND (" + columnCheck + ") " + "ORDER BY column ASC, version DESC, kvtype ASC, id DESC"); ps.setBytes(1, row); int idx = 2; for (byte [] column : columns) { ps.setBytes(idx++, column); } ResultSet result = ps.executeQuery(); if (result == null) { return new OperationResult<Map<byte[], byte[]>>( StatusCode.KEY_NOT_FOUND); } Map<byte[], byte[]> filtered = filteredLatestColumns(result, readPointer); if (filtered.isEmpty()) { return new OperationResult<Map<byte[], byte[]>>( StatusCode.COLUMN_NOT_FOUND); } else { return new OperationResult<Map<byte[], byte[]>>(filtered); } } catch (SQLException e) { handleSQLException(e, "select"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } throw new InternalError("this point should never be reached."); } // Scan Operations @Override public List<byte[]> getKeys(int limit, int offset, ReadPointer readPointer) throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement( "SELECT rowkey, column, version, kvtype, id " + "FROM " + this.tableName + " " + "ORDER BY rowkey ASC, column ASC, version DESC, kvtype ASC, id DESC"); ResultSet result = ps.executeQuery(); List<byte[]> keys = new ArrayList<byte[]>(limit > 1024 ? 1024 : limit); int returned = 0; int skipped = 0; long lastDelete = -1; long undeleted = -1; byte [] lastRow = new byte[0]; byte [] curRow = new byte[0]; byte [] curCol = new byte [0]; byte [] lastCol = new byte [0]; while (result.next() && returned < limit) { // See if we already included this row byte [] row = result.getBytes(1); if (Bytes.equals(lastRow, row)) continue; // See if this is a new row (clear col/del tracking if so) if (!Bytes.equals(curRow, row)) { lastCol = new byte[0]; curCol = new byte[0]; lastDelete = -1; undeleted = -1; } curRow = row; // Check visibility of this entry long curVersion = result.getLong(3); // Check if this entry is visible, skip if not if (!readPointer.isVisible(curVersion)) continue; byte [] column = result.getBytes(2); // Check if this column has been completely deleted if (Bytes.equals(lastCol, column)) { continue; } // Check if this is a new column, reset delete pointers if so if (!Bytes.equals(curCol, column)) { curCol = column; lastDelete = -1; undeleted = -1; } // Check if type is a delete and execute accordingly Type type = Type.from(result.getInt(4)); if (type.isUndeleteAll()) { undeleted = curVersion; continue; } if (type.isDeleteAll()) { if (undeleted == curVersion) continue; else { // The rest of this column has been deleted, act like we returned it lastCol = column; continue; } } if (type.isDelete()) { lastDelete = curVersion; continue; } if (curVersion == lastDelete) continue; // Column is valid, therefore row is valid, add row lastRow = row; if (skipped < offset) { skipped++; } else { keys.add(row); returned++; } } return keys; } catch (SQLException e) { handleSQLException(e, "select"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } throw new InternalError("this point should never be reached."); } @Override public Scanner scan(byte[] startRow, byte[] stopRow, ReadPointer readPointer) { throw new UnsupportedOperationException("Scans currently not supported"); } @Override public Scanner scan(byte[] startRow, byte[] stopRow, byte[][] columns, ReadPointer readPointer) { throw new UnsupportedOperationException("Scans currently not supported"); } @Override public Scanner scan(ReadPointer readPointer) { throw new UnsupportedOperationException("Scans currently not supported"); } // Private Helper Methods private void performInsert(byte [] row, byte [] column, long version, Type type, byte [] value) throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement( "INSERT INTO " + this.tableName + " (rowkey, column, version, kvtype, value) VALUES ( ?, ?, ?, ?, ? )"); ps.setBytes(1, row); ps.setBytes(2, column); ps.setLong(3, version); ps.setInt(4, type.i); ps.setBytes(5, value); ps.executeUpdate(); } catch (SQLException e) { handleSQLException(e, "insert"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } } private void performInsert(byte [] row, byte [][] columns, long version, Type type, byte [][] values) throws OperationException { PreparedStatement ps = null; try { ps = this.connection.prepareStatement( "INSERT INTO " + this.tableName + " (rowkey, column, version, kvtype, value) VALUES ( ?, ?, ?, ?, ? )"); for (int i=0; i<columns.length; i++) { ps.setBytes(1, row); ps.setBytes(2, columns[i]); ps.setLong(3, version); ps.setInt(4, type.i); ps.setBytes(5, values[i]); ps.executeUpdate(); } } catch (SQLException e) { handleSQLException(e, "insert"); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { handleSQLException(e, "close"); } } } } /** * Result has (version, kvtype, id, value) * @throws SQLException */ private ImmutablePair<Long, byte[]> filteredLatest( ResultSet result, ReadPointer readPointer) throws SQLException { if (result == null) return null; long lastDelete = -1; long undeleted = -1; while (result.next()) { long curVersion = result.getLong(1); if (!readPointer.isVisible(curVersion)) continue; Type type = Type.from(result.getInt(2)); if (type.isUndeleteAll()) { undeleted = curVersion; continue; } if (type.isDeleteAll()) { if (undeleted == curVersion) continue; else break; } if (type.isDelete()) { lastDelete = curVersion; continue; } if (curVersion == lastDelete) continue; return new ImmutablePair<Long, byte[]>(curVersion, result.getBytes(4)); } return null; } /** * Result has (column, version, kvtype, id, value) * @throws SQLException */ private Map<byte[], byte[]> filteredLatestColumns(ResultSet result, ReadPointer readPointer) throws SQLException { Map<byte[],byte[]> map = new TreeMap<byte[],byte[]>(Bytes.BYTES_COMPARATOR); if (result == null) return map; byte [] curCol = new byte [0]; byte [] lastCol = new byte [0]; long lastDelete = -1; long undeleted = -1; while (result.next()) { long curVersion = result.getLong(2); // Check if this entry is visible, skip if not if (!readPointer.isVisible(curVersion)) continue; byte [] column = result.getBytes(1); // Check if this column has already been included in result, skip if so if (Bytes.equals(lastCol, column)) { continue; } // Check if this is a new column, reset delete pointers if so if (!Bytes.equals(curCol, column)) { curCol = column; lastDelete = -1; undeleted = -1; } // Check if type is a delete and execute accordingly Type type = Type.from(result.getInt(3)); if (type.isUndeleteAll()) { undeleted = curVersion; continue; } if (type.isDeleteAll()) { if (undeleted == curVersion) continue; else { // The rest of this column has been deleted, act like we returned it lastCol = column; continue; } } if (type.isDelete()) { lastDelete = curVersion; continue; } if (curVersion == lastDelete) continue; lastCol = column; map.put(column, result.getBytes(5)); } return map; } // TODO: Let out exceptions? These are only for code bugs since we are in // memory and file modes only so availability not an issue? private void handleSQLException(SQLException e, String where) throws OperationException { String msg = "HyperSQL exception on " + where + "(error code = " + e.getErrorCode() + ")"; Log.error(msg, e); throw new OperationException(StatusCode.SQL_ERROR, msg, e); } }
package com.creatubbles.ctbmod.client.gui; import java.awt.Point; import java.awt.Rectangle; import java.util.Arrays; import java.util.List; import lombok.Getter; import lombok.Synchronized; import lombok.Value; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; import org.apache.commons.lang3.ArrayUtils; import org.lwjgl.util.Dimension; import com.creatubbles.ctbmod.CTBMod; import com.creatubbles.ctbmod.common.http.Creation; import com.creatubbles.ctbmod.common.http.Creator; import com.creatubbles.ctbmod.common.http.Image; import com.creatubbles.ctbmod.common.http.Image.ImageType; import com.creatubbles.repack.enderlib.api.client.gui.IGuiScreen; import com.creatubbles.repack.enderlib.client.gui.widget.GuiToolTip; import com.google.common.collect.Lists; public class OverlayCreationList extends OverlayBase { @Value private class CreationAndLocation { private Creation creation; private Point location; private Rectangle bounds; private GuiToolTip tooltip; private CreationAndLocation(Creation c, Point p) { this.creation = c; this.location = p; this.bounds = new Rectangle(p.x, p.y, thumbnailSize, thumbnailSize); // TODO more localization here List<String> tt = Lists.newArrayList(); tt.add(c.getName()); tt.add(c.getCreators().length == 1 ? "Creator:" : "Creators:"); for (Creator creator : c.getCreators()) { tt.add(" " + creator.getName()); } this.tooltip = new GuiToolTip(bounds, tt); } } public static final ResourceLocation LOADING_TEX = new ResourceLocation(CTBMod.DOMAIN, "textures/gui/bubble_outline.png"); @Getter private Creation[] creations; @Getter private int paddingX = 4, paddingY = 4; @Getter private int minSpacing = 2; private int rows, cols; @Getter private int thumbnailSize = 16; @Getter private Creation selected; private List<CreationAndLocation> list = Lists.newArrayList(); private List<CreationAndLocation> listAbsolute = Lists.newArrayList(); private List<ISelectionCallback> callbacks = Lists.newArrayList(); private int scroll = 0; public OverlayCreationList(int x, int y) { super(x, y, new Dimension(83, 210)); } public void addCallback(ISelectionCallback callback) { this.callbacks.add(callback); callback.callback(getSelected()); } public void setCreations(Creation[] creations) { this.creations = ArrayUtils.clone(creations); rebuildList(); } @Override public void init(IGuiScreen screen) { super.init(screen); rebuildList(); } @Synchronized("list") private void rebuildList() { clear(); Creation[] creations = this.creations == null ? CTBMod.cache.getCreationCache() : this.creations; if (creations == null || creations.length == 0) { return; } Arrays.sort(creations); int row = 0; int col = 0; // This is the dimensions we have to work with for thumbnails int usableWidth = getSize().getWidth() - (paddingX * 2); // The minimum size a thumbnail can take up int widthPerThumbnail = thumbnailSize + minSpacing; // This fancy math figures out the max creations that can fit in the available width // Simple division won't work due to it counting the spacing after the last item cols = 0; // So the initial width ignores the spacing int usedWidth = thumbnailSize; while (usedWidth <= usableWidth) { cols++; usedWidth += widthPerThumbnail; } // The amount of thumbnails on each row/column rows = creations.length / cols; // Use the max spacing possible, but no less than minSpacing int minWidth = thumbnailSize * cols; int spacing = usableWidth - minWidth; if (cols > 1) { spacing /= cols - 1; } spacing = Math.max(minSpacing, spacing); for (Creation c : creations) { int xMin = xRel + paddingX, yMin = yRel + paddingY; int x = xMin + (col * (thumbnailSize + spacing)); int y = yMin + (row * (thumbnailSize + minSpacing)) - scroll; CreationAndLocation data = new CreationAndLocation(c, new Point(x, y)); CreationAndLocation absoluteData = new CreationAndLocation(c, new Point(x, y + scroll)); // Anything below the border is a waste to draw if (y > yRel + getHeight()) { listAbsolute.add(absoluteData); break; } // Anything completely above the border is a waste to draw if (y + thumbnailSize > yRel) { list.add(data); getGui().addToolTip(data.tooltip); } listAbsolute.add(absoluteData); col++; if (col >= cols) { row++; col = 0; } } } private void clear() { for (CreationAndLocation c : list) { getGui().removeToolTip(c.tooltip); } list.clear(); listAbsolute.clear(); } @Override @Synchronized("list") public void doDraw(int mouseX, int mouseY, float partialTick) { Minecraft.getMinecraft().getTextureManager().bindTexture(GuiCreator.OVERLAY_TEX); drawTexturedModalRect(xRel, yRel, 0, 0, getWidth() + 10, getHeight()); Minecraft mc = Minecraft.getMinecraft(); FontRenderer fr = mc.fontRendererObj; if (list.size() == 0) { drawCenteredString(fr, "No Creations", xRel + (getWidth() / 2), yRel + 4, 0xFFFFFF); } else { for (CreationAndLocation c : list) { GlStateManager.pushMatrix(); if (c.getCreation() == selected) { drawBoundingBox(c, 0xFF48C43D); } int x = c.getLocation().x; int y = c.getLocation().y; Image img = c.getCreation().getImage(); ImageType type = ImageType.LIST_VIEW; ResourceLocation res = img.getResource(type); int w = 16, h = 16; if (!img.hasSize(type)) { GlStateManager.enableBlend(); res = LOADING_TEX; } else { w = img.getWidth(type); h = img.getHeight(type); } if (res != null) { if (res != LOADING_TEX) { // Draw selection box if (isMouseInBounds(mouseX, mouseY) && c.getBounds().contains(mouseX - getGui().getGuiLeft(), mouseY - getGui().getGuiTop())) { drawBoundingBox(c, 0xFFFFFFFF); } } mc.getTextureManager().bindTexture(res); } int height = thumbnailSize; float v = 0; int pastBottom = (y + height) - (yRel + getHeight() - 1); int pastTop = (yRel + 1) - y; boolean clipV = false; if (pastBottom > 0) { height -= pastBottom; } else if (pastTop > 0) { clipV = true; height -= pastTop; } double heightRatio = (double) height / thumbnailSize; if (clipV) { v = h - ((float) heightRatio * h); } drawScaledCustomSizeModalRect(x, y + Math.max(0, pastTop), 0, v, w, (int) (h * heightRatio), thumbnailSize, height, w, h); GlStateManager.popMatrix(); } } } private void drawBoundingBox(CreationAndLocation loc, int color) { Rectangle bounds = loc.getBounds(); drawRect((int) bounds.getMinX() - 1, (int) Math.max(bounds.getMinY() - 1, yRel + 1), (int) bounds.getMaxX() + 1, (int) Math.min(bounds.getMaxY() + 1, yRel + getHeight()), color); GlStateManager.enableBlend(); GlStateManager.color(1, 1, 1, 1); } @Override public boolean handleMouseInput(int x, int y, int b) { if (b == 0) { if (!isMouseInBounds(x, y)) { return false; } for (CreationAndLocation c : list) { if (isMouseIn(x, y, c.getBounds())) { setSelected(c.getCreation()); return true; } } setSelected(null); return true; } return super.handleMouseInput(x, y, b); } private void setSelected(Creation creation) { if (creation != getSelected()) { selected = creation; for (ISelectionCallback callback : callbacks) { callback.callback(getSelected()); } } } public void setX(int x) { if (getX() != x) { rebuildList(); } super.setX(x); } public void setY(int y) { if (getY() != y) { rebuildList(); } super.setY(y); } public void setPaddingX(int paddingX) { if (this.paddingX != paddingX) { this.paddingX = paddingX; rebuildList(); } } public void setPaddingY(int paddingY) { if (this.paddingY != paddingY) { this.paddingY = paddingY; rebuildList(); } } public void setMinSpacing(int minSpacing) { if (this.minSpacing != minSpacing) { this.minSpacing = minSpacing; rebuildList(); } } public void setThumbnailSize(int thumbnailSize) { if (this.thumbnailSize != thumbnailSize) { this.thumbnailSize = thumbnailSize; rebuildList(); } } public int getMaxScroll() { return (rows * (thumbnailSize + minSpacing)) - getHeight() + minSpacing; } public void setScroll(int scroll) { if (this.scroll != scroll) { this.scroll = scroll; rebuildList(); } } }
import javafx.animation.FadeTransition; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.layout.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.util.Duration; import java.nio.file.Paths; import java.util.ArrayList; /** * The graphical view for the game and starting point of the program */ public class GameGUI extends Application{ private Polls polls; //holds all of the questions, which each hold their own answers int currentQuestion = 0; private MediaPlayer audio; //is what plays the audio ArrayList<AnswerTile> answerTiles; //holds all of the ties in the center, ordered by rank Caretaker caretaker; //what saves the game and provides the undo and redo features int leftTeam, rightTeam = 0; //used for keeping track of team scores Text leftPoints, currentPointsText, rightPoints; private int selectedTeam; //used to signify if the left(-1) or right(1) team is selected, or neither(0) int multiplier = 1; int currentPoints; int numWrong = 0; private Text leftMultiplier; private Text rightMultiplier; private HBox strikes; private HBox answers; private StackPane window; Rectangle2D screen; //used for increased readability when referencing the screen size void playAudio(String filename){ if(audio != null) audio.stop(); Media audioFile = new Media(Paths.get("src/resources/" + filename).toUri().toString()); audio = new MediaPlayer(audioFile); audio.play(); } void styleText(Text text, double size){ text.setFont(Font.font("Calibri", FontWeight.BLACK, size)); text.setStyle("-fx-fill: white; -fx-stroke: black; -fx-stroke-width: " + size/30 + "px"); } private void setImageAsBackground( Region region, String image, double width, double height ){ BackgroundImage bi = new BackgroundImage( new Image("resources\\" + image, width, height, false, true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT); region.setBackground( new Background(bi) ); } /** Highlights and selects the team given by -1(left), 0(deselect), and 1(right) */ private void selectTeam(int team){ if(team == -1){ selectedTeam = -1; setImageAsBackground(window, "left team selected.png", screen.getWidth(), screen.getHeight()); }else if(team == 0){ selectedTeam = 0; setImageAsBackground(window, "background.png", screen.getWidth(), screen.getHeight()); }else if(team == 1){ selectedTeam = 1; setImageAsBackground(window, "right team selected.png", screen.getWidth(), screen.getHeight()); } } void setupQuestion(int i){ numWrong = 0; currentPoints = 0; currentPointsText.setText("0"); selectTeam(0); for(AnswerTile tile: answerTiles) tile.clear(); if(currentQuestion < 0) currentQuestion = 0; if(currentQuestion > polls.questions.size()-1) currentQuestion = polls.questions.size()-1; Question q = polls.questions.get(i); for(int j=0; j<q.answers.size(); j++) answerTiles.get(j).setAnswer(q.answers.get(j)); } private void restart(){ setupQuestion(0); leftTeam = 0; leftPoints.setText("0"); rightTeam = 0; rightPoints.setText("0"); setMultiplier(1); } private void wrongAnswer(int wrong){ //Make the strike images to appear ArrayList<ImageView> strikemarks = new ArrayList<>(); for(int i=0; i<wrong; i++) strikemarks.add( new ImageView(new Image("resources\\strike.png")) ); //Make the transitions for the strikes to appear and disappear with FadeTransition disappear = new FadeTransition(Duration.millis(50), strikes); disappear.setFromValue(1); disappear.setToValue(0); disappear.setCycleCount(1); disappear.setOnFinished(e -> strikes.getChildren().clear()); FadeTransition appear = new FadeTransition(Duration.millis(50), strikes); appear.setFromValue(0); appear.setToValue(1); appear.setCycleCount(1); appear.setOnFinished(e -> Platform.runLater(() -> { try{ Thread.sleep(1000); //done in a separate thread to not halt user input }catch(Exception exc){exc.printStackTrace();} disappear.play(); }) ); //Style the strikes and add them to the screen for(ImageView img : strikemarks){ img.setPreserveRatio(true); img.setFitWidth(screen.getWidth()/5); strikes.getChildren().addAll(img); } //Actually play the animation playAudio("strike.mp3"); appear.play(); } void scoreAnswer(int answerValue){ currentPoints += answerValue * multiplier; currentPointsText.setText(Integer.toString(currentPoints)); } private void scoreQuestion(){ if(selectedTeam == -1){ leftTeam += currentPoints; leftPoints.setText(Integer.toString(leftTeam)); currentPoints = 0; currentPointsText.setText("0"); }else if(selectedTeam == 1){ rightTeam += currentPoints; rightPoints.setText(Integer.toString(rightTeam)); currentPoints = 0; currentPointsText.setText("0"); } } void setMultiplier(int newMultiplier){ if(newMultiplier < 1) return; this.multiplier = newMultiplier; if(multiplier == 1){ leftMultiplier.setText(""); BorderPane.setMargin(answers, new Insets(screen.getHeight()/21, 0, 0, screen.getWidth()/9.01)); rightMultiplier.setText(""); }else{ if(multiplier < 10){ double size = screen.getHeight()/6.5; leftMultiplier.setFont(Font.font("Calibri", FontWeight.BLACK, size)); leftMultiplier.setStyle("-fx-fill: #FFE900; -fx-stroke: black; -fx-stroke-width: " + size/30 + "px"); rightMultiplier.setFont(Font.font("Calibri", FontWeight.BLACK, size)); rightMultiplier.setStyle("-fx-fill: #FFE900; -fx-stroke: black; -fx-stroke-width: " + size/30 + "px"); leftMultiplier.setText(Integer.toString(multiplier) + "x"); rightMultiplier.setText(Integer.toString(multiplier) + "x"); BorderPane.setMargin(answers, new Insets(screen.getHeight()/21, 0, 0, screen.getWidth()/37)); BorderPane.setMargin(rightMultiplier, new Insets(0, screen.getWidth()/175, 0, 0)); }else{ double size = screen.getHeight()/10; leftMultiplier.setFont(Font.font("Calibri", FontWeight.BLACK, size)); leftMultiplier.setStyle("-fx-fill: #FFE900; -fx-stroke: black; -fx-stroke-width: " + size/30 + "px"); rightMultiplier.setFont(Font.font("Calibri", FontWeight.BLACK, size)); rightMultiplier.setStyle("-fx-fill: #FFE900; -fx-stroke: black; -fx-stroke-width: " + size/30 + "px"); leftMultiplier.setText(Integer.toString(multiplier) + "x"); rightMultiplier.setText(Integer.toString(multiplier) + "x"); BorderPane.setMargin(answers, new Insets(screen.getHeight()/21, 0, 0, screen.getWidth()/36)); } } } @Override public void init(){ polls = new Polls("questions.txt"); caretaker = new Caretaker(this); } @Override public void start(Stage stage){ //Setup the overall stage and the top layer for strike animations BorderPane game = new BorderPane(); strikes = new HBox(); strikes.setAlignment(Pos.CENTER); window = new StackPane(game, strikes); Scene scene = new Scene(window); //Setup the background of the program screen = Screen.getPrimary().getBounds(); setImageAsBackground(window, "background.png", screen.getWidth(), screen.getHeight()); //Areas for the team names, scores, and current question value BorderPane top = new BorderPane(); VBox leftFamily = new VBox(); leftFamily.setAlignment(Pos.CENTER); Text leftName = new Text("Hooffields"); styleText(leftName, screen.getHeight()/10.55); leftPoints = new Text("0"); styleText(leftPoints, screen.getHeight()/5.63); leftFamily.getChildren().addAll(leftName, leftPoints); top.setLeft(leftFamily); leftFamily.setSpacing(screen.getHeight()/100); BorderPane.setMargin(leftFamily, new Insets(screen.getHeight()/100, 0, 0, screen.getWidth()/28)); currentPointsText = new Text("0"); styleText(currentPointsText, screen.getHeight()/4.69); top.setCenter(currentPointsText); BorderPane.setMargin(currentPointsText, new Insets(screen.getHeight()/15, screen.getWidth()/30, 0, 0)); VBox rightFamily = new VBox(); rightFamily.setAlignment(Pos.CENTER); Text rightName = new Text("McColts"); styleText(rightName, screen.getHeight()/10.55); rightPoints = new Text("0"); styleText(rightPoints, screen.getHeight()/5.63); rightFamily.getChildren().addAll(rightName, rightPoints); top.setRight(rightFamily); rightFamily.setSpacing(screen.getHeight()/100); BorderPane.setMargin(rightFamily, new Insets(screen.getHeight()/100, screen.getWidth()/17, 0, 0)); game.setTop(top); //The multiplier symbols leftMultiplier = new Text(""); game.setLeft(leftMultiplier); BorderPane.setAlignment(leftMultiplier, Pos.CENTER_LEFT); rightMultiplier = new Text(""); game.setRight(rightMultiplier); BorderPane.setAlignment(rightMultiplier, Pos.CENTER_RIGHT); //The area containing the actual answers answerTiles = new ArrayList<>(); VBox leftAnswers = new VBox(); for(int i=1; i<6; i++) leftAnswers.getChildren().add(new AnswerTile(this, i)); leftAnswers.setSpacing(screen.getHeight()/106.6); VBox rightAnswers = new VBox(); for(int i=6; i<11; i++) rightAnswers.getChildren().add(new AnswerTile(this, i)); rightAnswers.setSpacing(screen.getHeight()/106.6); answers = new HBox(leftAnswers, rightAnswers); answers.setSpacing(screen.getWidth()/150); game.setCenter(answers); BorderPane.setMargin(answers, new Insets(screen.getHeight()/21, 0, 0, screen.getWidth()/9.01)); setupQuestion(0); //Handles user input with the program scene.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> { switch(key.getCode().getName()){ case "1": answerTiles.get(0).reveal(true); break; case "2": answerTiles.get(1).reveal(true); break; case "3": answerTiles.get(2).reveal(true); break; case "4": answerTiles.get(3).reveal(true); break; case "5": answerTiles.get(4).reveal(true); break; case "6": answerTiles.get(5).reveal(true); break; case "7": answerTiles.get(6).reveal(true); break; case "8": answerTiles.get(7).reveal(true); break; case "9": answerTiles.get(8).reveal(true); break; case "0": answerTiles.get(9).reveal(true); break; /** restart */ case "R": caretaker.save(); restart(); break; /** back */ case "B": caretaker.save(); setupQuestion(--currentQuestion); break; /** next */ case "N": caretaker.save(); setupQuestion(++currentQuestion); break; /** theme */ case "T": playAudio("theme.mp3"); break; /** strike */ case "X": caretaker.save(); wrongAnswer(numWrong); break; case "Z": caretaker.save(); if(numWrong > 0) --numWrong; break; case "C": caretaker.save(); if(numWrong < 3) ++numWrong; break; /** stop */ case "S": if(audio != null) audio.stop(); break; case "Left": selectTeam(-1); break; case "Right": selectTeam(1); break; case "Up": caretaker.save(); setMultiplier(multiplier+1); break; case "Down": caretaker.save(); setMultiplier(multiplier-1); break; /** score */ case "Space": caretaker.save(); scoreQuestion(); break; /** undo */ case "Backspace": caretaker.undo(); break; /** redo */ case "Enter": caretaker.redo(); break; } }); stage.setScene(scene); stage.setTitle("Family Feud"); stage.setFullScreen(true); stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH); //removes the esc hint and keeps it fullscreen stage.getIcons().add(new Image("resources\\icon.png")); stage.show(); } public static void main(String[] args){ Application.launch(args); }//todo - generalize once finished }
package com.cube.storm.ui.controller.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.ViewGroup; import com.cube.storm.UiSettings; import com.cube.storm.ui.model.Model; import com.cube.storm.ui.model.list.Divider; import com.cube.storm.ui.model.list.List; import com.cube.storm.ui.model.list.List.ListFooter; import com.cube.storm.ui.model.list.List.ListHeader; import com.cube.storm.ui.view.holder.ViewHolder; import com.cube.storm.ui.view.holder.ViewHolderController; import java.util.ArrayList; import java.util.Collection; /** * The base adapter used for displaying Storm views in a list. Using an adapter to do such a task has * the benefit of view recycling which makes the content smooth to scroll. * <p/> * This adapter only supports {@link com.cube.storm.ui.model.Model} classes which have a defined {@link com.cube.storm.ui.view.holder.Holder} counter-class. * <p/> * * This adapter only supports {@link com.cube.storm.ui.model.Model} classes which have a defined {@link com.cube.storm.ui.view.holder.ViewHolder} counter-class. * * <b>Usage</b> * <p/> * <b>Problems</b> * Problems can arise with this method of rendering content, specifically with render efficiency where * the views are not being recycled because there is only 1 of its view type in the list. This is the * equivalent of having all of the views inflated into a {@link android.widget.ScrollView}. The smoothness * of the scrolling (depending on how much content there is) diminishes with the amount of unique content * that the list is rendering. * * @author Callum Taylor * @project StormUI */ public class StormListAdapter extends RecyclerView.Adapter<ViewHolder<?>> { /** * The list of models of the views we are rendering in the list. This is a 1 dimensional representation * of a multi-dimensional 'sub listed' array set which is outlined by the json. When setting the items * in this list, the models have to be traversed in order to build the 1 dimensional list for the * adapter to work correctly. */ private ArrayList<Model> items = new ArrayList<Model>(); /** * The different unique item types. This is used to tell the adapter how many unique views we're * going to be rendering so it knows what and when to recycle. The list is just for index based * convenience, the object type in the list is a reference to the view holder class we will use * to render said view. */ private ArrayList<Class<? extends com.cube.storm.ui.view.holder.ViewHolderController>> itemTypes = new ArrayList<Class<? extends ViewHolderController>>(); private Context context; public StormListAdapter(Context context) { this.context = context; } public StormListAdapter(Context context, Collection<? extends Model> items) { this.context = context; setItems(items); } /** * Sets the items in the collection. Filters out any model that does not have a defined {@link com.cube.storm.ui.view.holder.ViewHolder} * * @param items The new items to set. Can be null to clear the list. */ public void setItems(@Nullable Collection<? extends Model> items) { if (items != null) { this.items = new ArrayList<Model>(items.size()); this.itemTypes = new ArrayList<Class<? extends ViewHolderController>>(items.size() / 2); for (Model item : items) { addItem(item); } } else { this.items = new ArrayList<Model>(0); this.itemTypes = new ArrayList<Class<? extends ViewHolderController>>(0); } } /** * Adds an item to the list, only if a holder class is found as returned by {@link com.cube.storm.ui.lib.factory.ViewFactory#getHolderForView(String)} * * @param item The model to add to the list */ public void addItem(@NonNull Model item) { if (item instanceof List) { boolean addDivider = false; if (((List)item).getHeader() != null && !TextUtils.isEmpty(UiSettings.getInstance().getTextProcessor().process(((List)item).getHeader().getContent()))) { ListHeader header = new ListHeader(); header.setHeader(((List)item).getHeader()); addItem(header); addDivider = true; } if (((List)item).getChildren() != null) { for (Model subItem : ((List)item).getChildren()) { if (subItem != null) { addItem(subItem); } } } if (((List)item).getFooter() != null && !TextUtils.isEmpty(UiSettings.getInstance().getTextProcessor().process(((List)item).getFooter().getContent()))) { ListFooter footer = new ListFooter(); footer.setFooter(((List)item).getFooter()); addItem(footer); addDivider = true; } if (addDivider) { addItem(new Divider()); } } else { Class<? extends ViewHolderController> holderClass = UiSettings.getInstance().getViewFactory().getHolderForView(item.getClassName()); if (holderClass != null) { this.items.add(item); } if (!this.itemTypes.contains(holderClass)) { this.itemTypes.add(holderClass); } } } public Model getItem(int position) { return items.get(position); } @Override public long getItemId(int position) { return ((Object)getItem(position)).hashCode(); } @Override public int getItemCount() { return items.size(); } @Override public com.cube.storm.ui.view.holder.ViewHolder<?> onCreateViewHolder(ViewGroup viewGroup, int i) { ViewHolderController holder = null; try { holder = itemTypes.get(getItemViewType(i)).newInstance(); holder.createViewHolder(viewGroup); } catch (Exception e) { throw new InstantiationError("Could not instantiate a new holder"); } return holder.getViewHolder(); } @Override public void onBindViewHolder(com.cube.storm.ui.view.holder.ViewHolder viewHolder, int position) { try { viewHolder.populateView(getItem(position)); } catch (Exception e) { e.printStackTrace(); } } @Override public int getItemViewType(int position) { Model view = items.get(position); return itemTypes.indexOf(UiSettings.getInstance().getViewFactory().getHolderForView(view.getClassName())); } }
import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Screen; import javafx.stage.Stage; import java.util.ArrayList; /** * The graphical view for the game and starting point of the program */ public class GameGUI extends Application{ private Polls polls; private Scene scene; private Thread audio; private ArrayList<AnswerTile> answerTiles; String leftName = "Apple"; String rightName = "Pie"; int leftTeam, rightTeam = 0; //used for keeping track of team scores boolean onLeft; //used to signify if the left team is highlighted or not int multiplier = 1; Rectangle2D screen; //used for increased readability when referencing the screen size private void playAudio(String filename){ stopAudio(); audio = new Thread(() -> { Media hit = new Media("src\\resources\\" + filename); MediaPlayer mediaPlayer = new MediaPlayer(hit); mediaPlayer.play(); }); } private void stopAudio(){ if(audio != null) if(audio.isAlive()) audio.interrupt(); } private void styleText(Text text, double size){ text.setFont(Font.font("Calibri", FontWeight.BLACK, size)); text.setStyle("-fx-fill: white; -fx-stroke: black; -fx-stroke-width: " + size/20 + "px"); } private class AnswerTile extends Rectangle{ int rank; Answer answer; AnswerTile(int i){ rank = i; answerTiles.add(this); } void setAnswer(Answer a){ answer = a; } void reveal(){ }//todo - animate the question revealing itself (flip while rotating in place && play sound) } @Override public void init(){ polls = new Polls("questions.txt"); screen = Screen.getPrimary().getVisualBounds(); } @Override public void start(Stage stage){ BorderPane window = new BorderPane(); scene = new Scene(window); //Areas for the team names, scores, and current question value BorderPane top = new BorderPane(); VBox leftFamily = new VBox(); leftFamily.setAlignment(Pos.CENTER); Text leftName = new Text("Hooffields"); Text leftPoints = new Text("6969"); styleText(leftName, 200); styleText(leftPoints, 375); leftFamily.getChildren().addAll(leftName, leftPoints); top.setLeft(leftFamily); leftFamily.setSpacing(screen.getHeight()/100); BorderPane.setMargin(leftFamily, new Insets(screen.getHeight()/100, 0, 0, screen.getWidth()/28)); Text currentPoints = new Text("6969"); styleText(currentPoints, 450); top.setCenter(currentPoints); BorderPane.setMargin(currentPoints, new Insets(screen.getHeight()/15, screen.getWidth()/80, 0, 0)); VBox rightFamily = new VBox(); rightFamily.setAlignment(Pos.CENTER); Text rightName = new Text("McColts"); Text rightPoints = new Text("6969"); styleText(rightName, 200); styleText(rightPoints, 375); rightFamily.getChildren().addAll(rightName, rightPoints); top.setRight(rightFamily); rightFamily.setSpacing(screen.getHeight()/100); BorderPane.setMargin(rightFamily, new Insets(screen.getHeight()/100, screen.getWidth()/18, 0, 0)); window.setTop(top); //The area containing the actual answers answerTiles = new ArrayList<>(); VBox leftAnswers = new VBox(); for(int i=1; i<6; i++) leftAnswers.getChildren().add(new AnswerTile(i)); VBox rightAnswers = new VBox(); for(int i=1; i<6; i++) rightAnswers.getChildren().add(new AnswerTile(i)); HBox answers = new HBox(leftAnswers, rightAnswers); window.setCenter(answers); //Handles user input with the program scene.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> { //todo - finish processing keyboard input here switch(key.getCode().getName()){ case "1": answerTiles.get(0).reveal(); break; case "2": answerTiles.get(1).reveal(); break; case "3": answerTiles.get(2).reveal(); break; case "4": answerTiles.get(3).reveal(); break; case "5": answerTiles.get(4).reveal(); break; case "6": answerTiles.get(5).reveal(); break; case "7": answerTiles.get(6).reveal(); break; case "8": answerTiles.get(7).reveal(); break; case "9": answerTiles.get(8).reveal(); break; case "0": answerTiles.get(9).reveal(); break; case "t": playAudio("theme.mp3"); break; //theme song case "x": playAudio("strike.mp3"); break; //strike sound case "s": stopAudio(); break; //stops all of the audio case "Left": onLeft = true; break; case "Right": onLeft = false; break; case "Space": break; case "Up": multiplier++; break; case "Down": if(multiplier > 1) multiplier--; break; case "Enter": break; //this goes forward if you've gone backwards w/o editing, else goes to fast money case "Backspace": break; //implement an undo function } }); //Setup the background of the program Rectangle2D screen =Screen.getPrimary().getBounds(); BackgroundImage bi = new BackgroundImage( new Image("resources\\background.png", screen.getWidth(), screen.getHeight(), false, true), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, BackgroundSize.DEFAULT); window.setBackground( new Background(bi) ); stage.setScene(scene); stage.setTitle("Family Feud"); stage.setFullScreen(true); stage.show(); } public static void main(String[] args){ Application.launch(args); } }
package com.englishtown.vertx.jersey.impl; import com.englishtown.vertx.jersey.JerseyHandler; import com.englishtown.vertx.jersey.JerseyServer; import org.vertx.java.core.AsyncResult; import org.vertx.java.core.Handler; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpServer; import org.vertx.java.core.http.RouteMatcher; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Container; import javax.inject.Inject; import javax.inject.Provider; /** * Default implementation of {@link JerseyServer} */ public class DefaultJerseyServer implements JerseyServer { final static String CONFIG_HOST = "host"; final static String CONFIG_PORT = "port"; final static String CONFIG_RECEIVE_BUFFER_SIZE = "receive_buffer_size"; final static String CONFIG_BACKLOG_SIZE = "backlog_size"; private final JerseyHandler jerseyHandler; private Handler<RouteMatcher> routeMatcherHandler; @Inject public DefaultJerseyServer( Provider<JerseyHandler> jerseyHandlerProvider) { this.jerseyHandler = jerseyHandlerProvider.get(); if (jerseyHandler == null) { throw new IllegalStateException("The JerseyHandler provider returned null"); } } @Override public void init(JsonObject config, Vertx vertx, final Container container) { init(config, vertx, container, null); } @Override public void init(JsonObject config, Vertx vertx, final Container container, final Handler<AsyncResult<HttpServer>> doneHandler) { // Get http server config values final String host = config.getString(CONFIG_HOST, "0.0.0.0"); final int port = config.getInteger(CONFIG_PORT, 80); int receiveBufferSize = config.getInteger(CONFIG_RECEIVE_BUFFER_SIZE, 0); int backlogSize = config.getInteger(CONFIG_BACKLOG_SIZE, 10000); // Create http server HttpServer server = vertx.createHttpServer(); // Performance tweak server.setAcceptBacklog(backlogSize); // Init jersey handler jerseyHandler.init(vertx, container, config); if (receiveBufferSize > 0) { // TODO: This doesn't seem to actually affect buffer size for dataHandler. Is this being used correctly or is it a Vertx bug? server.setReceiveBufferSize(receiveBufferSize); } // Set request handler, use route matcher if a route handler is provided. if (routeMatcherHandler == null) { server.requestHandler(jerseyHandler); } else { RouteMatcher rm = new RouteMatcher(); String pattern = jerseyHandler.getBaseUri().getPath() + "*"; rm.all(pattern, jerseyHandler); routeMatcherHandler.handle(rm); } // Start listening and log success/failure server.listen(port, host, new Handler<AsyncResult<HttpServer>>() { @Override public void handle(AsyncResult<HttpServer> result) { final String listenPath = "http://" + host + ":" + port; if (result.succeeded()) { container.logger().info("Http server listening for " + listenPath); } else { container.logger().error("Failed to start http server listening for " + listenPath, result.cause()); } if (doneHandler != null) { doneHandler.handle(result); } } }); } @Override public void routeMatcherHandler(Handler<RouteMatcher> handler) { this.routeMatcherHandler = handler; } }
package com.fasterxml.jackson.databind; import com.fasterxml.jackson.databind.cfg.ConfigFeature; /** * Enumeration that defines simple on/off features that affect * the way Java objects are deserialized from JSON *<p> * Note that features can be set both through * {@link ObjectMapper} (as sort of defaults) and through * {@link ObjectReader}. * In first case these defaults must follow "config-then-use" patterns * (i.e. defined once, not changed afterwards); all per-call * changes must be done using {@link ObjectReader}. *<p> * Note that features that do not indicate version of inclusion * were available in Jackson 2.0 (or earlier); only later additions * indicate version of inclusion. */ public enum DeserializationFeature implements ConfigFeature { /** * Feature that determines whether JSON floating point numbers * are to be deserialized into {@link java.math.BigDecimal}s * if only generic type description (either {@link Object} or * {@link Number}, or within untyped {@link java.util.Map} * or {@link java.util.Collection} context) is available. * If enabled such values will be deserialized as {@link java.math.BigDecimal}s; * if disabled, will be deserialized as {@link Double}s. * <p> * Feature is disabled by default, meaning that "untyped" floating * point numbers will by default be deserialized as {@link Double}s * (choice is for performance reason -- BigDecimals are slower than * Doubles). */ USE_BIG_DECIMAL_FOR_FLOATS(false), /** * Feature that determines whether JSON integral (non-floating-point) * numbers are to be deserialized into {@link java.math.BigInteger}s * if only generic type description (either {@link Object} or * {@link Number}, or within untyped {@link java.util.Map} * or {@link java.util.Collection} context) is available. * If enabled such values will be deserialized as * {@link java.math.BigInteger}s; * if disabled, will be deserialized as "smallest" available type, * which is either {@link Integer}, {@link Long} or * {@link java.math.BigInteger}, depending on number of digits. * <p> * Feature is disabled by default, meaning that "untyped" integral * numbers will by default be deserialized using whatever * is the most compact integral type, to optimize efficiency. */ USE_BIG_INTEGER_FOR_INTS(false), /** * Feature that determines how "small" JSON integral (non-floating-point) * numbers -- ones that fit in 32-bit signed integer (`int`) -- are bound * when target type is loosely typed as {@link Object} or {@link Number} * (or within untyped {@link java.util.Map} or {@link java.util.Collection} context). * If enabled, such values will be deserialized as {@link java.lang.Long}; * if disabled, they will be deserialized as "smallest" available type, * {@link Integer}. * In addition, if enabled, trying to bind values that do not fit in {@link java.lang.Long} * will throw a {@link com.fasterxml.jackson.core.JsonProcessingException}. *<p> * Note: if {@link #USE_BIG_INTEGER_FOR_INTS} is enabled, it has precedence * over this setting, forcing use of {@link java.math.BigInteger} for all * integral values. *<p> * Feature is disabled by default, meaning that "untyped" integral * numbers will by default be deserialized using {@link java.lang.Integer} * if value fits. * * @since 2.6 */ USE_LONG_FOR_INTS(false), /** * Feature that determines whether JSON Array is mapped to * <code>Object[]</code> or <code>List&lt;Object></code> when binding * "untyped" objects (ones with nominal type of <code>java.lang.Object</code>). * If true, binds as <code>Object[]</code>; if false, as <code>List&lt;Object></code>. *<p> * Feature is disabled by default, meaning that JSON arrays are bound as * {@link java.util.List}s. */ USE_JAVA_ARRAY_FOR_JSON_ARRAY(false), /** * Feature that determines standard deserialization mechanism used for * Enum values: if enabled, Enums are assumed to have been serialized using * return value of <code>Enum.toString()</code>; * if disabled, return value of <code>Enum.name()</code> is assumed to have been used. *<p> * Note: this feature should usually have same value * as {@link SerializationFeature#WRITE_ENUMS_USING_TO_STRING}. *<p> * Feature is disabled by default. */ READ_ENUMS_USING_TO_STRING(false), /** * Feature that determines whether encountering of unknown * properties (ones that do not map to a property, and there is * no "any setter" or handler that can handle it) * should result in a failure (by throwing a * {@link JsonMappingException}) or not. * This setting only takes effect after all other handling * methods for unknown properties have been tried, and * property remains unhandled. *<p> * Feature is enabled by default (meaning that a * {@link JsonMappingException} will be thrown if an unknown property * is encountered). */ FAIL_ON_UNKNOWN_PROPERTIES(true), /** * Feature that determines whether encountering of JSON null * is an error when deserializing into Java primitive types * (like 'int' or 'double'). If it is, a JsonProcessingException * is thrown to indicate this; if not, default value is used * (0 for 'int', 0.0 for double, same defaulting as what JVM uses). *<p> * Feature is disabled by default. */ FAIL_ON_NULL_FOR_PRIMITIVES(false), /** * Feature that determines whether JSON integer numbers are valid * values to be used for deserializing Java enum values. * If set to 'false' numbers are acceptable and are used to map to * ordinal() of matching enumeration value; if 'true', numbers are * not allowed and a {@link JsonMappingException} will be thrown. * Latter behavior makes sense if there is concern that accidental * mapping from integer values to enums might happen (and when enums * are always serialized as JSON Strings) *<p> * Feature is disabled by default. */ FAIL_ON_NUMBERS_FOR_ENUMS(false), /** * Feature that determines what happens when type of a polymorphic * value (indicated for example by {@link com.fasterxml.jackson.annotation.JsonTypeInfo}) * can not be found (missing) or resolved (invalid class name, unmappable id); * if enabled, an exception ir thrown; if false, null value is used instead. *<p> * Feature is enabled by default so that exception is thrown for missing or invalid * type information. * * @since 2.2 */ FAIL_ON_INVALID_SUBTYPE(true), /** * Feature that determines what happens when reading JSON content into tree * ({@link com.fasterxml.jackson.core.TreeNode}) and a duplicate key * is encountered (property name that was already seen for the JSON Object). * If enabled, {@link JsonMappingException} will be thrown; if disabled, no exception * is thrown and the new (later) value overwrites the earlier value. *<p> * Note that this property does NOT affect other aspects of data-binding; that is, * no detection is done with respect to POJO properties or {@link java.util.Map} * keys. New features may be added to control additional cases. *<p> * Feature is disabled by default so that no exception is thrown. * * @since 2.3 */ FAIL_ON_READING_DUP_TREE_KEY(false), /** * Feature that determines what happens when a property that has been explicitly * marked as ignorable is encountered in input: if feature is enabled, * {@link JsonMappingException} is thrown; if false, property is quietly skipped. *<p> * Feature is disabled by default so that no exception is thrown. * * @since 2.3 */ FAIL_ON_IGNORED_PROPERTIES(false), /** * Feature that determines what happens if an Object Id reference is encountered * that does not refer to an actual Object with that id ("unresolved Object Id"): * either an exception is thrown (<code>true</code>), or a null object is used * instead (<code>false</code>). * Note that if this is set to <code>false</code>, no further processing is done; * specifically, if reference is defined via setter method, that method will NOT * be called. *<p> * Feature is enabled by default, so that unknown Object Ids will result in an * exception being thrown, at the end of deserialization. * * @since 2.5 */ FAIL_ON_UNRESOLVED_OBJECT_IDS(true), /** * Feature that determines what happens if one or more Creator properties (properties * bound to parameters of Creator method (constructor or static factory method)) * are missing value to bind to from content. * If enabled, such missing values result in a {@link JsonMappingException} being * thrown with information on the first one (by index) of missing properties. * If disabled, and if property is NOT marked as required, * missing Creator properties are filled * with <code>null values</code> provided by deserializer for the type of parameter * (usually null for Object types, and default value for primitives; but redefinable * via custom deserializers). *<p> * Note that having an injectable value counts as "not missing". *<p> * Feature is disabled by default, so that no exception is thrown for missing creator * property values, unless they are explicitly marked as `required`. * * @since 2.6 */ FAIL_ON_MISSING_CREATOR_PROPERTIES(false), /** * Feature that determines what happens if one or more Creator properties (properties * bound to parameters of Creator method (constructor or static factory method)) * are bound to null values - either from the JSON or as a default value. This * is useful if you want to avoid nulls in your codebase, and particularly useful * if you are using Java or Scala optionals for non-mandatory fields. * Feature is disabled by default, so that no exception is thrown for missing creator * property values, unless they are explicitly marked as `required`. * * @since 2.8 */ FAIL_ON_NULL_CREATOR_PROPERTIES(false), /** * Feature that determines what happens when a property annotated with * {@link com.fasterxml.jackson.annotation.JsonTypeInfo.As#EXTERNAL_PROPERTY} is missing, * but associated type id is available. If enabled, {@link JsonMappingException} is always * thrown when property value is missing (if type id does exist); * if disabled, exception is only thrown if property is marked as `required`. *<p> * Feature is enabled by default, so that exception is thrown when a subtype property is * missing. * * @since 2.9 */ FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY(true), /** * Feature that determines whether Jackson code should catch * and wrap {@link Exception}s (but never {@link Error}s!) * to add additional information about * location (within input) of problem or not. If enabled, * most exceptions will be caught and re-thrown (exception * specifically being that {@link java.io.IOException}s may be passed * as is, since they are declared as throwable); this can be * convenient both in that all exceptions will be checked and * declared, and so there is more contextual information. * However, sometimes calling application may just want "raw" * unchecked exceptions passed as is. *<p> * Feature is enabled by default. */ WRAP_EXCEPTIONS(true), /** * Feature that determines whether it is acceptable to coerce non-array * (in JSON) values to work with Java collection (arrays, java.util.Collection) * types. If enabled, collection deserializers will try to handle non-array * values as if they had "implicit" surrounding JSON array. * This feature is meant to be used for compatibility/interoperability reasons, * to work with packages (such as XML-to-JSON converters) that leave out JSON * array in cases where there is just a single element in array. *<p> * Feature is disabled by default. */ ACCEPT_SINGLE_VALUE_AS_ARRAY(false), /** * Feature that determines whether it is acceptable to coerce single value array (in JSON) * values to the corresponding value type. This is basically the opposite of the {@link #ACCEPT_SINGLE_VALUE_AS_ARRAY} * feature. If more than one value is found in the array, a JsonMappingException is thrown. * <p> * * Feature is disabled by default * @since 2.4 */ UNWRAP_SINGLE_VALUE_ARRAYS(false), /** * Feature to allow "unwrapping" root-level JSON value, to match setting of * {@link SerializationFeature#WRAP_ROOT_VALUE} used for serialization. * Will verify that the root JSON value is a JSON Object, and that it has * a single property with expected root name. If not, a * {@link JsonMappingException} is thrown; otherwise value of the wrapped property * will be deserialized as if it was the root value. *<p> * Feature is disabled by default. */ UNWRAP_ROOT_VALUE(false), /** * Feature that can be enabled to allow JSON empty String * value ("") to be bound to POJOs as null. * If disabled, standard POJOs can only be bound from JSON null or * JSON Object (standard meaning that no custom deserializers or * constructors are defined; both of which can add support for other * kinds of JSON values); if enabled, empty JSON String can be taken * to be equivalent of JSON null. *<p> * Feature is disabled by default. */ ACCEPT_EMPTY_STRING_AS_NULL_OBJECT(false), /** * Feature that can be enabled to allow empty JSON Array * value (that is, <code>[ ]</code>) to be bound to POJOs as null. * If disabled, standard POJOs can only be bound from JSON null or * JSON Object (standard meaning that no custom deserializers or * constructors are defined; both of which can add support for other * kinds of JSON values); if enabled, empty JSON Array will be taken * to be equivalent of JSON null. *<p> * Feature is disabled by default. * * @since 2.5 */ ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT(false), /** * Feature that determines whether coercion from JSON floating point * number (anything with command (`.`) or exponent portion (`e` / `E')) * to an expected integral number (`int`, `long`, `java.lang.Integer`, `java.lang.Long`, * `java.math.BigDecimal`) is allowed or not. * If enabled, coercion truncates value; if disabled, a {@link JsonMappingException} * will be thrown. *<p> * Feature is enabled by default. * * @since 2.6 */ ACCEPT_FLOAT_AS_INT(true), /** * Feature that allows unknown Enum values to be parsed as null values. * If disabled, unknown Enum values will throw exceptions. *<p> * Note that in some cases this will basically ignore unknown Enum values; * this is the keys for keys of {@link java.util.EnumMap} and values * of {@link java.util.EnumSet} (because nulls are not accepted in these * cases). *<p> * Feature is disabled by default. * * @since 2.0 */ READ_UNKNOWN_ENUM_VALUES_AS_NULL(false), /** * Feature that allows unknown Enum values to be ignored and a predefined value specified through * {@link com.fasterxml.jackson.annotation.JsonEnumDefaultValue @JsonEnumDefaultValue} annotation. * If disabled, unknown Enum values will throw exceptions. * If enabled, but no predefined default Enum value is specified, an exception will be thrown as well. *<p> * Feature is disabled by default. * * @since 2.8 */ READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE(false), /** * Feature that controls whether numeric timestamp values are expected * to be written using nanosecond timestamps (enabled) or not (disabled), * <b>if and only if</b> datatype supports such resolution. * Only newer datatypes (such as Java8 Date/Time) support such resolution -- * older types (pre-Java8 <b>java.util.Date</b> etc) and Joda do not -- * and this setting <b>has no effect</b> on such types. *<p> * If disabled, standard millisecond timestamps are assumed. * This is the counterpart to {@link SerializationFeature#WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS}. *<p> * Feature is enabled by default, to support most accurate time values possible. * * @since 2.2 */ READ_DATE_TIMESTAMPS_AS_NANOSECONDS(true), /** * Feature that specifies whether context provided {@link java.util.TimeZone} * ({@link DeserializationContext#getTimeZone()} should be used to adjust Date/Time * values on deserialization, even if value itself contains timezone information. * If enabled, contextual <code>TimeZone</code> will essentially override any other * TimeZone information; if disabled, it will only be used if value itself does not * contain any TimeZone information. *<p> * Note that exact behavior depends on date/time types in question; and specifically * JDK type of {@link java.util.Date} does NOT have in-built timezone information * so this setting has no effect. * Further, while {@link java.util.Calendar} does have this information basic * JDK {@link java.text.SimpleDateFormat} is unable to retain parsed zone information, * and as a result, {@link java.util.Calendar} will always get context timezone * adjustment regardless of this setting. *<p> *<p> * Taking above into account, this feature is supported only by extension modules for * Joda and Java 8 date/tyime datatypes. * * @since 2.2 */ ADJUST_DATES_TO_CONTEXT_TIME_ZONE(true), /** * Feature that determines whether {@link ObjectReader} should * try to eagerly fetch necessary {@link JsonDeserializer} when * possible. This improves performance in cases where similarly * configured {@link ObjectReader} instance is used multiple * times; and should not significantly affect single-use cases. *<p> * Note that there should not be any need to normally disable this * feature: only consider that if there are actual perceived problems. *<p> * Feature is enabled by default. * * @since 2.1 */ EAGER_DESERIALIZER_FETCH(true) ; private final boolean _defaultState; private final int _mask; private DeserializationFeature(boolean defaultState) { _defaultState = defaultState; _mask = (1 << ordinal()); } @Override public boolean enabledByDefault() { return _defaultState; } @Override public int getMask() { return _mask; } @Override public boolean enabledIn(int flags) { return (flags & _mask) != 0; } }
package com.forgeessentials.protection; import static cpw.mods.fml.common.eventhandler.Event.Result.ALLOW; import static cpw.mods.fml.common.eventhandler.Event.Result.DENY; import static net.minecraftforge.event.entity.player.PlayerInteractEvent.Action.LEFT_CLICK_BLOCK; import static net.minecraftforge.event.entity.player.PlayerInteractEvent.Action.RIGHT_CLICK_AIR; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.UUID; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer.EnumStatus; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings.GameType; import net.minecraftforge.common.util.BlockSnapshot; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.item.ItemTossEvent; import net.minecraftforge.event.entity.living.LivingHurtEvent; import net.minecraftforge.event.entity.living.LivingSpawnEvent.CheckSpawn; import net.minecraftforge.event.entity.living.LivingSpawnEvent.SpecialSpawn; import net.minecraftforge.event.entity.player.AttackEntityEvent; import net.minecraftforge.event.entity.player.EntityInteractEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent.BreakEvent; import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent; import net.minecraftforge.event.world.ExplosionEvent; import com.forgeessentials.api.APIRegistry; import com.forgeessentials.api.UserIdent; import com.forgeessentials.api.permissions.AreaZone; import com.forgeessentials.api.permissions.WorldZone; import com.forgeessentials.api.permissions.Zone; import com.forgeessentials.commons.selections.Point; import com.forgeessentials.commons.selections.WarpPoint; import com.forgeessentials.commons.selections.WorldArea; import com.forgeessentials.commons.selections.WorldPoint; import com.forgeessentials.core.FEConfig; import com.forgeessentials.core.ForgeEssentials; import com.forgeessentials.core.misc.TeleportHelper; import com.forgeessentials.core.misc.Translator; import com.forgeessentials.protection.effect.CommandEffect; import com.forgeessentials.protection.effect.DamageEffect; import com.forgeessentials.protection.effect.PotionEffect; import com.forgeessentials.protection.effect.ZoneEffect; import com.forgeessentials.util.OutputHandler; import com.forgeessentials.util.PlayerInfo; import com.forgeessentials.util.PlayerUtil; import com.forgeessentials.util.ServerUtil; import com.forgeessentials.util.events.PlayerChangedZone; import com.forgeessentials.util.events.ServerEventHandler; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.eventhandler.Event.Result; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import cpw.mods.fml.common.gameevent.TickEvent; import cpw.mods.fml.relauncher.Side; public class ProtectionEventHandler extends ServerEventHandler { private boolean checkMajoritySleep; @SubscribeEvent(priority = EventPriority.HIGHEST) public void attackEntityEvent(AttackEntityEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; if (event.target == null || !(event.entityPlayer instanceof EntityPlayerMP)) return; EntityPlayerMP source = (EntityPlayerMP) event.entityPlayer; UserIdent sourceIdent = UserIdent.get(source); if (event.target instanceof EntityPlayer) { // player -> player EntityPlayer target = (EntityPlayer) event.target; if (!APIRegistry.perms.checkUserPermission(UserIdent.get(target), ModuleProtection.PERM_PVP) || !APIRegistry.perms.checkUserPermission(sourceIdent, ModuleProtection.PERM_PVP) || !APIRegistry.perms.checkUserPermission(sourceIdent, new WorldPoint(target), ModuleProtection.PERM_PVP)) { event.setCanceled(true); return; } } // player -> entity Entity target = event.target; WorldPoint targetPos = new WorldPoint(event.target); String permission = ModuleProtection.PERM_DAMAGE_TO + "." + EntityList.getEntityString(target); if (ModuleProtection.isDebugMode(source)) OutputHandler.chatNotification(source, permission); if (!APIRegistry.perms.checkUserPermission(sourceIdent, targetPos, permission)) { event.setCanceled(true); return; } permission = MobType.getMobType(target).getDamageToPermission(); if (ModuleProtection.isDebugMode(source)) OutputHandler.chatNotification(source, permission); if (!APIRegistry.perms.checkUserPermission(sourceIdent, targetPos, permission)) { event.setCanceled(true); return; } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void livingHurtEvent(LivingHurtEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; if (event.entityLiving == null) return; if (event.entityLiving instanceof EntityPlayerMP) { // living -> player (fall-damage, mob, dispenser, lava) EntityPlayerMP target = (EntityPlayerMP) event.entityLiving; { String permission = ModuleProtection.PERM_DAMAGE_BY + "." + event.source.damageType; if (ModuleProtection.isDebugMode(target)) OutputHandler.chatNotification(target, permission); if (!APIRegistry.perms.checkUserPermission(UserIdent.get(target), permission)) { event.setCanceled(true); return; } } if (event.source.getEntity() != null) { // non-player-entity (mob) -> player Entity source = event.source.getEntity(); String permission = ModuleProtection.PERM_DAMAGE_BY + "." + EntityList.getEntityString(source); if (ModuleProtection.isDebugMode(target)) OutputHandler.chatNotification(target, permission); if (!APIRegistry.perms.checkUserPermission(UserIdent.get(target), permission)) { event.setCanceled(true); return; } permission = MobType.getMobType(source).getDamageByPermission(); if (ModuleProtection.isDebugMode(target)) OutputHandler.chatNotification(target, permission); if (!APIRegistry.perms.checkUserPermission(UserIdent.get(target), permission)) { event.setCanceled(true); return; } } } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void entityInteractEvent(EntityInteractEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = UserIdent.get(event.entityPlayer); WorldPoint point = new WorldPoint(event.entityPlayer.dimension, (int) event.target.posX, (int) event.target.posY, (int) event.target.posZ); String permission = ModuleProtection.PERM_INTERACT_ENTITY + "." + EntityList.getEntityString(event.target); if (ModuleProtection.isDebugMode(event.entityPlayer)) OutputHandler.chatNotification(event.entityPlayer, permission); if (!APIRegistry.perms.checkUserPermission(ident, point, ModuleProtection.PERM_INTERACT_ENTITY)) { event.setCanceled(true); return; } } @SubscribeEvent(priority = EventPriority.NORMAL) public void breakEvent(BreakEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = event.getPlayer() instanceof EntityPlayerMP ? UserIdent.get(event.getPlayer()) : null; Block block = event.world.getBlock(event.x, event.y, event.z); String permission = ModuleProtection.getBlockBreakPermission(block, event.world, event.x, event.y, event.z); if (ModuleProtection.isDebugMode(event.getPlayer())) OutputHandler.chatNotification(event.getPlayer(), permission); WorldPoint point = new WorldPoint(event.getPlayer().dimension, event.x, event.y, event.z); if (!APIRegistry.perms.checkUserPermission(ident, point, permission)) { event.setCanceled(true); return; } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void placeEvent(BlockEvent.PlaceEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = event.player instanceof EntityPlayerMP ? UserIdent.get(event.player) : null; Block block = event.world.getBlock(event.x, event.y, event.z); String permission = ModuleProtection.getBlockPlacePermission(block, event.world, event.x, event.y, event.z); if (ModuleProtection.isDebugMode(event.player)) OutputHandler.chatNotification(event.player, permission); WorldPoint point = new WorldPoint(event.player.dimension, event.x, event.y, event.z); if (!APIRegistry.perms.checkUserPermission(ident, point, permission)) { event.setCanceled(true); } if (stringToGameType(APIRegistry.perms.getUserPermissionProperty(ident, ModuleProtection.PERM_GAMEMODE)) == GameType.CREATIVE && stringToGameType(APIRegistry.perms.getUserPermissionProperty(ident, point, ModuleProtection.PERM_GAMEMODE)) != GameType.CREATIVE) { OutputHandler.chatError(event.player, Translator.translate("Cannot place block outside creative area")); event.setCanceled(true); return; } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void multiPlaceEvent(BlockEvent.MultiPlaceEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = event.player instanceof EntityPlayerMP ? UserIdent.get(event.player) : null; for (BlockSnapshot b : event.getReplacedBlockSnapshots()) { Block block = event.world.getBlock(b.x, b.y, b.z); String permission = ModuleProtection.getBlockPlacePermission(block, event.world, event.x, event.y, event.z); if (ModuleProtection.isDebugMode(event.player)) OutputHandler.chatNotification(event.player, permission); WorldPoint point = new WorldPoint(event.player.dimension, b.x, b.y, b.z); if (!APIRegistry.perms.checkUserPermission(ident, point, permission)) { event.setCanceled(true); return; } } } @SubscribeEvent(priority = EventPriority.NORMAL) public void explosionEvent(ExplosionEvent.Start event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; int cx = (int) Math.floor(event.explosion.explosionX); int cy = (int) Math.floor(event.explosion.explosionY); int cz = (int) Math.floor(event.explosion.explosionZ); WorldArea area = new WorldArea(event.world, new Point(cx - event.explosion.explosionSize, cy - event.explosion.explosionSize, cz - event.explosion.explosionSize), new Point(cx + event.explosion.explosionSize, cy + event.explosion.explosionSize, cz + event.explosion.explosionSize)); if (!APIRegistry.perms.checkUserPermission(null, area, ModuleProtection.PERM_EXPLOSION)) { event.setCanceled(true); return; } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void playerInteractEvent(PlayerInteractEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = UserIdent.get(event.entityPlayer); WorldPoint point; if (event.action == RIGHT_CLICK_AIR) { MovingObjectPosition mop = PlayerUtil.getPlayerLookingSpot(event.entityPlayer); if (mop == null) point = new WorldPoint(event.entityPlayer.dimension, event.x, event.y, event.z); else point = new WorldPoint(event.entityPlayer.dimension, mop.blockX, mop.blockY, mop.blockZ); } else point = new WorldPoint(event.entityPlayer.dimension, event.x, event.y, event.z); // Check for block interaction if (event.action == Action.RIGHT_CLICK_BLOCK || event.action == Action.LEFT_CLICK_BLOCK) { Block block = event.world.getBlock(event.x, event.y, event.z); String permission = ModuleProtection.getBlockInteractPermission(block, event.world, event.x, event.y, event.z); if (ModuleProtection.isDebugMode(event.entityPlayer)) OutputHandler.chatNotification(event.entityPlayer, permission); boolean allow = APIRegistry.perms.checkUserPermission(ident, point, permission); event.useBlock = allow ? ALLOW : DENY; } // Check item (and block) usage ItemStack stack = event.entityPlayer.getCurrentEquippedItem(); if (stack != null && !(stack.getItem() instanceof ItemBlock)) { String permission = ModuleProtection.getItemUsePermission(stack); if (ModuleProtection.isDebugMode(event.entityPlayer)) OutputHandler.chatNotification(event.entityPlayer, permission); boolean allow = APIRegistry.perms.checkUserPermission(ident, point, permission); event.useItem = allow ? ALLOW : DENY; } if (anyCreativeModeAtPoint(event.entityPlayer, point) && stringToGameType(APIRegistry.perms.getUserPermissionProperty(ident, ModuleProtection.PERM_GAMEMODE)) != GameType.CREATIVE) { // If entity is in creative area, but player not, deny interaction event.useBlock = DENY; if (event.action != LEFT_CLICK_BLOCK) OutputHandler.chatError(event.entityPlayer, Translator.translate("Cannot interact with creative area if not in creative mode.")); } } @SubscribeEvent(priority = EventPriority.HIGHEST) public void playerSleepInBedEventHigh(PlayerSleepInBedEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = UserIdent.get(event.entityPlayer); WorldPoint point = new WorldPoint(event.entity.dimension, event.x, event.y, event.z); if (!APIRegistry.perms.checkUserPermission(ident, point, ModuleProtection.PERM_SLEEP)) { event.result = EnumStatus.NOT_POSSIBLE_HERE; OutputHandler.sendMessage(event.entityPlayer, Translator.translate("You are not allowed to sleep here")); return; } checkMajoritySleep = true; } private void checkMajoritySleep() { if (!checkMajoritySleep) return; checkMajoritySleep = false; WorldServer world = ServerUtil.getOverworld(); if (FEConfig.majoritySleep >= 1 || world.isDaytime()) return; int sleepingPlayers = 0; for (EntityPlayerMP player : ServerUtil.getPlayerList()) if (player.isPlayerSleeping()) sleepingPlayers++; float percentage = (float) sleepingPlayers / MinecraftServer.getServer().getCurrentPlayerCount(); ForgeEssentials.log.debug(String.format("Players sleeping: %.0f%%", percentage * 100)); if (percentage >= FEConfig.majoritySleep && percentage < 1) { if (world.getGameRules().getGameRuleBooleanValue("doDaylightCycle")) { long time = world.getWorldInfo().getWorldTime() + 24000L; world.getWorldInfo().setWorldTime(time - time % 24000L); } for (EntityPlayerMP player : ServerUtil.getPlayerList()) if (player.isPlayerSleeping()) player.wakeUpPlayer(false, false, true); // TODO: We change some vanilla behaviour here - is this ok? // Personally I think this is a good change though world.provider.resetRainAndThunder(); } } @SubscribeEvent(priority = EventPriority.NORMAL) public void checkSpawnEvent(CheckSpawn event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; if (!(event.entityLiving instanceof EntityLiving)) return; EntityLiving entity = (EntityLiving) event.entityLiving; WorldPoint point = new WorldPoint(entity); if (!APIRegistry.perms.checkUserPermission(null, point, ModuleProtection.PERM_MOBSPAWN_NATURAL + "." + EntityList.getEntityString(entity))) { event.setResult(Result.DENY); return; } if (!APIRegistry.perms.checkUserPermission(null, point, MobType.getMobType(entity).getSpawnPermission(false))) { event.setResult(Result.DENY); return; } } @SubscribeEvent(priority = EventPriority.NORMAL) public void specialSpawnEvent(SpecialSpawn event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; if (!(event.entityLiving instanceof EntityLiving)) return; EntityLiving entity = (EntityLiving) event.entityLiving; WorldPoint point = new WorldPoint(entity); if (!APIRegistry.perms.checkUserPermission(null, point, ModuleProtection.PERM_MOBSPAWN_FORCED + "." + EntityList.getEntityString(entity))) { event.setResult(Result.DENY); return; } if (!APIRegistry.perms.checkUserPermission(null, point, MobType.getMobType(entity).getSpawnPermission(true))) { event.setResult(Result.DENY); return; } } @SubscribeEvent(priority = EventPriority.LOWEST) public void itemPickupEvent(EntityItemPickupEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; UserIdent ident = event.entityPlayer instanceof EntityPlayerMP ? UserIdent.get(event.entityPlayer) : null; if (isItemBanned(ident, event.item.getEntityItem())) { event.setCanceled(true); event.item.setDead(); return; } if (isInventoryItemBanned(ident, event.item.getEntityItem())) { event.setCanceled(true); return; } } @SubscribeEvent(priority = EventPriority.LOWEST) public void entityJoinWorldEvent(EntityJoinWorldEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; if (event.entity instanceof EntityItem) { // 1) Do nothing if the whole world is creative! WorldZone worldZone = APIRegistry.perms.getServerZone().getWorldZone(event.world.provider.dimensionId); if (stringToGameType(worldZone.getGroupPermission(Zone.GROUP_DEFAULT, ModuleProtection.PERM_GAMEMODE)) != GameType.CREATIVE) { // 2) If creative mode is set for any group at the location where the block was destroyed, prevent drops if (anyCreativeModeAtPoint(null, new WorldPoint(event.entity))) { event.entity.setDead(); return; } } } } @SubscribeEvent(priority = EventPriority.LOWEST) public void harvestDropsEvent(HarvestDropsEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; WorldPoint point = new WorldPoint(event.world, event.x, event.y, event.z); // 1) Do nothing if the whole world is creative! WorldZone worldZone = APIRegistry.perms.getServerZone().getWorldZone(event.world.provider.dimensionId); if (stringToGameType(worldZone.getGroupPermission(Zone.GROUP_DEFAULT, ModuleProtection.PERM_GAMEMODE)) != GameType.CREATIVE) { // 2) If creative mode is set for any group at the location where the block was destroyed, prevent drops if (anyCreativeModeAtPoint(null, point)) { event.drops.clear(); return; } } for (Iterator<ItemStack> iterator = event.drops.iterator(); iterator.hasNext();) if (isItemBanned(point, iterator.next())) iterator.remove(); } @SubscribeEvent(priority = EventPriority.LOWEST) public void itemTossEvent(ItemTossEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; // 1) Do nothing if the whole world is creative! WorldZone worldZone = APIRegistry.perms.getServerZone().getWorldZone(event.entity.dimension); if (stringToGameType(worldZone.getGroupPermission(Zone.GROUP_DEFAULT, ModuleProtection.PERM_GAMEMODE)) != GameType.CREATIVE) { // 2) Destroy item when player in creative mode // 3) If creative mode is set for any group at the location where the block was destroyed, prevent drops if (getGamemode(event.player) == GameType.CREATIVE || anyCreativeModeAtPoint(event.player, new WorldPoint(event.entity))) { // event.entity.worldObj.removeEntity(event.target); event.entity.setDead(); return; } } } @SubscribeEvent public void playerOpenContainerEvent(PlayerOpenContainerEvent event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; // If it's the player's own inventory - ignore if (event.entityPlayer.openContainer == event.entityPlayer.inventoryContainer) return; checkPlayerInventory(event.entityPlayer); } @SubscribeEvent(priority = EventPriority.LOW) public void playerLoginEvent(PlayerLoggedInEvent event) { checkPlayerInventory(event.player); } @SubscribeEvent public void playerChangedZoneEvent(PlayerChangedZone event) { if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; EntityPlayerMP player = (EntityPlayerMP) event.entityPlayer; UserIdent ident = UserIdent.get(player); String inventoryGroup = APIRegistry.perms.getUserPermissionProperty(ident, event.afterPoint.toWorldPoint(), ModuleProtection.PERM_INVENTORY_GROUP); GameType lastGm = stringToGameType(APIRegistry.perms.getUserPermissionProperty(ident, event.beforePoint.toWorldPoint(), ModuleProtection.PERM_GAMEMODE)); GameType gm = stringToGameType(APIRegistry.perms.getUserPermissionProperty(ident, event.afterPoint.toWorldPoint(), ModuleProtection.PERM_GAMEMODE)); if (gm != GameType.NOT_SET || lastGm != GameType.NOT_SET) { // If leaving a creative zone and no other gamemode is set, revert to default (survival) if (lastGm != GameType.NOT_SET && gm == GameType.NOT_SET) gm = GameType.SURVIVAL; GameType playerGm = player.theItemInWorldManager.getGameType(); if (playerGm != gm) { // ForgeEssentials.log.info(String.format("Changing gamemode for %s from %s to %s", // ident.getUsernameOrUUID(), playerGm.getName(), gm.getName())); if (gm != GameType.CREATIVE) { // TODO: Teleport player slightly above ground to prevent fall-death } player.setGameType(gm); } if (gm == GameType.CREATIVE) inventoryGroup = "creative"; } // Apply inventory-group PlayerInfo pi = PlayerInfo.get(player); pi.setInventoryGroup(inventoryGroup); checkPlayerInventory(player); } private HashMap<UUID, List<ZoneEffect>> zoneEffects = new HashMap<>(); @SubscribeEvent(priority = EventPriority.HIGHEST) public void playerChangedZoneEventHigh(PlayerChangedZone event) { UserIdent ident = UserIdent.get(event.entityPlayer); List<ZoneEffect> effects = getZoneEffects(ident); effects.clear(); // Check knockback if (!APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_KNOCKBACK).equals(Zone.PERMISSION_FALSE)) { sendZoneDeniedMessage(event.entityPlayer); Vec3 center = event.afterPoint.toVec3(); if (event.afterZone instanceof AreaZone) { center = ((AreaZone) event.afterZone).getArea().getCenter().toVec3(); center.yCoord = event.beforePoint.getY(); } Vec3 delta = event.beforePoint.toVec3().subtract(center).normalize(); WarpPoint target = new WarpPoint(event.beforePoint.getDimension(), event.beforePoint.getX() - delta.xCoord, event.beforePoint.getY() - delta.yCoord, event.beforePoint.getZ() - delta.zCoord, event.afterPoint.getPitch(), event.afterPoint.getYaw()); TeleportHelper.doTeleport((EntityPlayerMP) event.entityPlayer, target); event.setCanceled(true); return; } // Check command effect String command = APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_COMMAND); if (command != null && !command.isEmpty()) { int interval = ServerUtil.parseIntDefault( APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_COMMAND_INTERVAL), 0); effects.add(new CommandEffect(ident.getPlayerMP(), interval, command)); } int damage = ServerUtil.parseIntDefault(APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_DAMAGE), 0); if (damage > 0) { int interval = ServerUtil.parseIntDefault( APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_DAMAGE_INTERVAL), 0); effects.add(new DamageEffect(ident.getPlayerMP(), interval, damage)); } // Check potion effect String potion = APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_POTION); if (potion != null && !potion.isEmpty()) { int interval = ServerUtil.parseIntDefault( APIRegistry.perms.getUserPermissionProperty(ident, event.afterZone, ModuleProtection.ZONE_POTION_INTERVAL), 0); effects.add(new PotionEffect(ident.getPlayerMP(), interval, potion)); } if (effects.isEmpty()) zoneEffects.remove(ident.getUuid()); else zoneEffects.put(ident.getUuid(), effects); } @SubscribeEvent public void serverTickEvent(TickEvent.ServerTickEvent event) { if (event.side != Side.SERVER || event.phase == TickEvent.Phase.END) return; for (List<ZoneEffect> effects : zoneEffects.values()) { for (ZoneEffect effect : effects) { effect.update(); if (effect.isLethal()) sendZoneDeniedMessage(effect.getPlayer()); } } if (checkMajoritySleep) checkMajoritySleep(); } @SubscribeEvent public void playerLoggedOutEvent(PlayerEvent.PlayerLoggedOutEvent event) { zoneEffects.remove(event.player.getPersistentID()); } public static GameType stringToGameType(String gm) { if (gm == null) return GameType.NOT_SET; switch (gm.toLowerCase()) { case "0": case "s": case "survival": return GameType.SURVIVAL; case "1": case "c": case "creative": return GameType.CREATIVE; case "2": case "a": case "adventure": return GameType.ADVENTURE; default: return GameType.NOT_SET; } } public static GameType getGamemode(EntityPlayer player) { return stringToGameType(APIRegistry.perms.getUserPermissionProperty(UserIdent.get(player), ModuleProtection.PERM_GAMEMODE)); } public static boolean anyCreativeModeAtPoint(EntityPlayer player, WorldPoint point) { if (player != null && stringToGameType(APIRegistry.perms.getUserPermissionProperty(UserIdent.get(player), point, ModuleProtection.PERM_GAMEMODE)) == GameType.CREATIVE) return true; for (String group : APIRegistry.perms.getServerZone().getGroups()) { if (stringToGameType(APIRegistry.perms.getGroupPermissionProperty(group, point, ModuleProtection.PERM_GAMEMODE)) == GameType.CREATIVE) return true; } return false; } public static boolean isItemBanned(UserIdent ident, ItemStack stack) { return !APIRegistry.perms.checkUserPermission(ident, ModuleProtection.getItemBanPermission(stack)); } public static boolean isItemBanned(WorldPoint point, ItemStack stack) { if (stack == null) return false; return !APIRegistry.perms.checkUserPermission(null, point, ModuleProtection.getItemBanPermission(stack)); } public static boolean isInventoryItemBanned(UserIdent ident, ItemStack stack) { return !APIRegistry.perms.checkUserPermission(ident, ModuleProtection.getItemInventoryPermission(stack)); } public static void checkPlayerInventory(EntityPlayer player) { UserIdent ident = player instanceof EntityPlayerMP ? UserIdent.get(player) : null; for (int slotIdx = 0; slotIdx < player.inventory.getSizeInventory(); slotIdx++) { ItemStack stack = player.inventory.getStackInSlot(slotIdx); if (stack != null) { if (isItemBanned(ident, stack)) { player.inventory.setInventorySlotContents(slotIdx, null); continue; } if (isInventoryItemBanned(ident, stack)) { EntityItem droppedItem = player.func_146097_a(stack, true, false); droppedItem.motionX = 0; droppedItem.motionY = 0; droppedItem.motionZ = 0; player.inventory.setInventorySlotContents(slotIdx, null); } } } } private static void sendZoneDeniedMessage(EntityPlayer player) { PlayerInfo pi = PlayerInfo.get(player); if (pi.checkTimeout("zone_denied_message")) { OutputHandler.chatError(player, ModuleProtection.MSG_ZONE_DENIED); pi.startTimeout("zone_denied_message", 4000); } } private List<ZoneEffect> getZoneEffects(UserIdent ident) { List<ZoneEffect> effects = zoneEffects.get(ident.getUuid()); if (effects == null) effects = new ArrayList<>(); return effects; } }
package com.github.eyce9000.iem.api.tools; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.bigfix.schemas.bes.FixletWithActions; import com.bigfix.schemas.bes.GroupRelevance; import com.bigfix.schemas.bes.RelevanceString; import com.bigfix.schemas.bes.SearchComponent; import com.bigfix.schemas.bes.SearchComponentGroupReference; import com.bigfix.schemas.bes.SearchComponentPropertyReference; import com.bigfix.schemas.bes.SearchComponentRelevance; import com.github.eyce9000.iem.api.IEMClient; import com.github.eyce9000.iem.api.relevance.RelevanceException; import com.github.eyce9000.iem.api.relevance.SessionRelevanceBuilder; import com.github.eyce9000.iem.api.relevance.SessionRelevanceQuery; import com.google.common.base.Optional; public class RelevanceTranslator { private SessionRelevanceQuery groupQuery; private IEMClient client; protected RelevanceTranslator(){}; public RelevanceTranslator(IEMClient client){ this.client = client; groupQuery = SessionRelevanceBuilder .fromRelevance("(id of it,name of it) of bes computer groups whose (name of it = \"${groupName}\")") .addColumns("groupId","groupName") .build(); } public RelevanceString buildRelevance(FixletWithActions fixlet) throws Exception{ if(fixlet.getRelevance()!=null && fixlet.getRelevance().size() > 0) return buildRelevance(fixlet.getRelevance()); else return buildRelevance(fixlet.getGroupRelevance()); } public RelevanceString buildRelevance(GroupRelevance relevance) throws Exception{ String function; if(relevance.isJoinByIntersection()) function = " AND "; else function = " OR "; List<String> relevanceStrings = new ArrayList<String>(); for(SearchComponent component : relevance.getSearchComponent()){ String r = null; if(component instanceof SearchComponentRelevance){ r = ((SearchComponentRelevance)component).getRelevance().getValue(); r = "exists true whose (if true then ("+r+") else false)"; } if(component instanceof SearchComponentPropertyReference){ r = ((SearchComponentPropertyReference)component).getRelevance().getValue(); r = "exists true whose (if true then ("+r+") else false)"; } if(component instanceof SearchComponentGroupReference){ r = buildRelevance((SearchComponentGroupReference)component).getValue(); } if(r!=null) relevanceStrings.add("("+r+")"); } String joined = "(version of client >= \"6.0.0.0\") AND ("+StringUtils.join(relevanceStrings,function)+")"; RelevanceString result = new RelevanceString(); result.setValue(joined); return result; } public RelevanceString buildRelevance(SearchComponentGroupReference component) throws Exception{ String format = "exists true whose (if true then (member of group %d of site \"actionsite\") else false)"; switch(component.getComparison()){ case IS_MEMBER: break; case IS_NOT_MEMBER: format = "not ("+format+")"; break; } Optional<Integer> idHolder = getGroupID(component.getGroupName()); if(!idHolder.isPresent()) throw new Exception("Unable to find group id for group name \""+component.getGroupName()+"\""); RelevanceString relevance = new RelevanceString(); relevance.setValue(String.format(format,idHolder.get())); return relevance; } public RelevanceString buildRelevance(List<RelevanceString> relevance){ if(relevance.size()==1) return relevance.get(0); List<String> relevanceStrings = new ArrayList<String>(); for(RelevanceString r : relevance){ relevanceStrings.add("("+r.getValue()+")"); } String builtRelevance = ""; for(int i=0; i<relevanceStrings.size(); i++){ String singleRelevance = relevanceStrings.get(i); if(i> 0){ builtRelevance += " AND "+singleRelevance; if(i<relevanceStrings.size()-1){ builtRelevance = "("+builtRelevance+")"; } } else{ builtRelevance = singleRelevance; } } RelevanceString newRelevance = new RelevanceString(); newRelevance.setValue(builtRelevance); return newRelevance; } private Optional<Integer> getGroupID(String groupName) throws RelevanceException{ groupQuery.getParameter(0).setValue(groupName); List<Map<String,Object>> results = client.executeQuery(groupQuery); if(results.size()==0) return Optional.absent(); else return Optional.of((Integer)results.get(0).get("groupId")); } }
package com.github.games647.scoreboardstats.pvpstats; import com.github.games647.scoreboardstats.BackwardsCompatibleUtil; import com.github.games647.scoreboardstats.ScoreboardStats; import com.github.games647.scoreboardstats.config.Lang; import com.github.games647.scoreboardstats.config.Settings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.metadata.MetadataValue; /** * This represents a handler for saving player stats. */ public class Database { private static final String METAKEY = "player_stats"; private final ScoreboardStats plugin; private final Map<String, Integer> toplist = Maps.newHashMapWithExpectedSize(Settings.getTopitems()); private final DatabaseConfiguration dbConfig; private HikariDataSource dataSource; public Database(ScoreboardStats plugin) { this.plugin = plugin; this.dbConfig = new DatabaseConfiguration(plugin); } /** * Get the cache player stats if they exists and the arguments are valid. * * @param request the associated player * @return the stats if they are in the cache */ public PlayerStats getCachedStats(Player request) { if (request != null) { for (MetadataValue metadata : request.getMetadata(METAKEY)) { if (metadata.value() instanceof PlayerStats) { return (PlayerStats) metadata.value(); } } } return null; } /** * Starts loading the stats for a specific player in an external thread. * * @param player the associated player */ public void loadAccountAsync(Player player) { if (getCachedStats(player) == null && dataSource != null) { Runnable statsLoader = new StatsLoader(plugin, dbConfig.isUuidUse(), player, this); Bukkit.getScheduler().runTaskAsynchronously(plugin, statsLoader); } } /** * Starts loading the stats for a specific player sync * * @param uniqueId the associated playername or uuid * @return the loaded stats */ public PlayerStats loadAccount(Object uniqueId) { if (uniqueId == null || dataSource == null) { return null; } else { Connection conn = null; PreparedStatement stmt = null; ResultSet resultSet = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT * FROM player_stats WHERE " + (dbConfig.isUuidUse() ? "uuid" : "playername") + "=?"); stmt.setString(1, uniqueId.toString()); resultSet = stmt.executeQuery(); return extractPlayerStats(resultSet); } catch (SQLException ex) { plugin.getLogger().log(Level.SEVERE, "Error loading player profile", ex); } finally { close(resultSet); close(stmt); close(conn); } return null; } } private PlayerStats extractPlayerStats(ResultSet resultSet) throws SQLException { if (resultSet.next()) { int id = resultSet.getInt(1); String unparsedUUID = resultSet.getString(2); UUID uuid = null; if (unparsedUUID != null) { uuid = UUID.fromString(unparsedUUID); } String playerName = resultSet.getString(3); int kills = resultSet.getInt(4); int deaths = resultSet.getInt(5); int mobkills = resultSet.getInt(6); int killstreak = resultSet.getInt(7); long lastOnline = resultSet.getLong(8); return new PlayerStats(id, uuid, playerName, kills, deaths, mobkills, killstreak, lastOnline); } else { //If there are no existing stat create a new object with empty stats return new PlayerStats(); } } /** * Starts loading the stats for a specific player sync * * @param player the associated player * @return the loaded stats */ public PlayerStats loadAccount(Player player) { if (player == null || dataSource == null) { return null; } else { if (dbConfig.isUuidUse()) { return loadAccount(player.getUniqueId()); } else { return loadAccount(player.getName()); } } } /** * Save PlayerStats async. * * @param stats PlayerStats data */ public void saveAsync(PlayerStats stats) { Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> save(Lists.newArrayList(stats))); } /** * Save the PlayerStats on the current Thread. * * @param stats PlayerStats data */ public void save(List<PlayerStats> stats) { if (stats != null && dataSource != null) { update(stats.stream() .filter(Objects::nonNull) .filter(PlayerStats::isModified) .filter(stat -> !stat.isNew()) .collect(Collectors.toList())); insert(stats.stream() .filter(Objects::nonNull) .filter(PlayerStats::isModified) .filter(PlayerStats::isNew) .collect(Collectors.toList())); } } private void update(List<PlayerStats> stats) { if (stats.isEmpty()) { return; } //Save the stats to the database Connection conn = null; PreparedStatement stmt = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("UPDATE player_stats " + "SET kills=?, deaths=?, killstreak=?, mobkills=?, last_online=?, playername=? " + "WHERE id=?"); conn.setAutoCommit(false); for (PlayerStats stat : stats) { stmt.setInt(1, stat.getKills()); stmt.setInt(2, stat.getDeaths()); stmt.setInt(3, stat.getKillstreak()); stmt.setInt(4, stat.getMobkills()); stmt.setLong(5, stat.getLastOnline()); stmt.setString(6, stat.getPlayername()); stmt.setInt(7, stat.getId()); stmt.addBatch(); } stmt.executeBatch(); conn.commit(); } catch (Exception ex) { plugin.getLogger().log(Level.SEVERE, "Error updating profiles", ex); } finally { close(stmt); close(conn); } } private void insert(List<PlayerStats> stats) { if (stats.isEmpty()) { return; } Connection conn = null; PreparedStatement stmt = null; ResultSet generatedKeys = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("INSERT INTO player_stats " + "(uuid, playername, kills, deaths, killstreak, mobkills, last_online) VALUES " + "(?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); conn.setAutoCommit(false); for (PlayerStats stat : stats) { stmt.setString(1, stat.getUuid() == null ? null : stat.getUuid().toString()); stmt.setString(2, stat.getPlayername()); stmt.setInt(3, stat.getKills()); stmt.setInt(4, stat.getDeaths()); stmt.setInt(5, stat.getKillstreak()); stmt.setInt(6, stat.getMobkills()); stmt.setLong(7, stat.getLastOnline()); stmt.addBatch(); } stmt.executeBatch(); conn.commit(); generatedKeys = stmt.getGeneratedKeys(); for (PlayerStats stat : stats) { if (!generatedKeys.next()) { break; } stat.setId(generatedKeys.getInt(1)); } } catch (Exception ex) { plugin.getLogger().log(Level.SEVERE, "Error inserting profiles", ex); } finally { close(generatedKeys); close(stmt); close(conn); } } /** * Starts saving all cache player stats and then clears the cache. */ public void saveAll() { try { plugin.getLogger().info(Lang.get("savingStats")); //If pvpstats are enabled save all stats that are in the cache List<PlayerStats> toSave = BackwardsCompatibleUtil.getOnlinePlayers().stream() .map(this::getCachedStats) .filter(Objects::nonNull) .filter(PlayerStats::isModified) .collect(Collectors.toList()); if (!toSave.isEmpty()) { save(toSave); } dataSource.close(); } finally { //Make rally sure we remove all even on error BackwardsCompatibleUtil.getOnlinePlayers() .forEach(player -> player.removeMetadata(METAKEY, plugin)); } } /** * Initialize a components and checking for an existing database */ public void setupDatabase() { //Check if pvpstats should be enabled dbConfig.loadConfiguration(); dataSource = new HikariDataSource(dbConfig.getServerConfig()); Connection conn = null; Statement stmt = null; try { conn = dataSource.getConnection(); stmt = conn.createStatement(); String createTableQuery = "CREATE TABLE IF NOT EXISTS player_stats ( " + "id integer PRIMARY KEY AUTO_INCREMENT, " + "uuid varchar(40), " + "playername varchar(16) not null, " + "kills integer not null, " + "deaths integer not null, " + "mobkills integer not null, " + "killstreak integer not null, " + "last_online timestamp not null )"; if (dbConfig.getServerConfig().getDriverClassName().contains("sqlite")) { createTableQuery = createTableQuery.replace("AUTO_INCREMENT", ""); dataSource.setMaximumPoolSize(1); } stmt.execute(createTableQuery); } catch (Exception ex) { plugin.getLogger().log(Level.SEVERE, "Error creating database ", ex); } finally { close(stmt); close(conn); } Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, this::updateTopList, 20 * 60 * 5, 0); Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, () -> { if (dataSource == null) { return; } Future<Collection<? extends Player>> syncPlayers = Bukkit.getScheduler() .callSyncMethod(plugin, BackwardsCompatibleUtil::getOnlinePlayers); try { Collection<? extends Player> onlinePlayers = syncPlayers.get(); List<PlayerStats> toSave = onlinePlayers.stream() .map(this::getCachedStats) .filter(Objects::nonNull) .filter(PlayerStats::isModified) .collect(Collectors.toList()); if (!toSave.isEmpty()) { save(toSave); } } catch (CancellationException cancelEx) { //ignore it on shutdown } catch (Exception ex) { plugin.getLogger().log(Level.SEVERE, null, ex); } }, 20 * 60, 20 * 60 * 5); registerEvents(); } /** * Get the a map of the best players for a specific category. * * @return a iterable of the entries */ public Collection<Map.Entry<String, Integer>> getTop() { synchronized (toplist) { return toplist.entrySet(); } } /** * Updates the toplist */ public void updateTopList() { String type = Settings.getTopType(); Map<String, Integer> newToplist; switch (type) { case "killstreak": newToplist = getTopList("killstreak", PlayerStats::getKillstreak); break; case "mob": newToplist = getTopList("mobkills", PlayerStats::getMobkills); break; default: newToplist = getTopList("kills", PlayerStats::getKills); break; } synchronized (toplist) { //set it after fetching so it's only blocking for a short time toplist.clear(); toplist.putAll(newToplist); } } private Map<String, Integer> getTopList(String type, Function<PlayerStats, Integer> valueMapper) { if (dataSource != null) { Connection conn = null; Statement stmt = null; ResultSet resultSet = null; try { conn = dataSource.getConnection(); stmt = conn.createStatement(); resultSet = stmt.executeQuery("SELECT * FROM player_stats " + "ORDER BY " + type + " desc " + "LIMIT " + Settings.getTopitems()); Map<String, Integer> result = Maps.newHashMap(); for (int i = 0; i < Settings.getTopitems(); i++) { PlayerStats stats = extractPlayerStats(resultSet); if (!stats.isNew()) { String entry = (i + 1) + ". " + stats.getPlayername(); result.put(entry, valueMapper.apply(stats)); } } return result; } catch (SQLException ex) { plugin.getLogger().log(Level.SEVERE, "Error loading top list", ex); } finally { close(resultSet); close(stmt); close(conn); } } return Collections.emptyMap(); } private void registerEvents() { if (Bukkit.getPluginManager().isPluginEnabled("InSigns")) { //Register this listener if InSigns is available new SignListener(plugin, "[Kill]", this); new SignListener(plugin, "[Death]", this); new SignListener(plugin, "[KDR]", this); new SignListener(plugin, "[Streak]", this); new SignListener(plugin, "[Mob]", this); } plugin.getReplaceManager().register(new StatsVariables(plugin, this)); Bukkit.getPluginManager().registerEvents(new StatsListener(plugin, this), plugin); } private void close(AutoCloseable closeable) { if (closeable != null) { try { closeable.close(); } catch (Exception ex) { //ignore } } } }
package com.github.jmchilton.galaxybootstrap; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.io.Files; import com.google.common.io.InputSupplier; import com.google.common.io.Resources; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Map; import org.ini4j.Ini; import org.ini4j.Profile.Section; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author John Chilton */ @SuppressWarnings("deprecation") public class GalaxyProperties { private static final Logger logger = LoggerFactory .getLogger(GalaxyProperties.class); private final Map<String, String> appProperties = Maps.newHashMap(); private final Map<String, String> serverProperties = Maps.newHashMap(); private int port = 8080; // default private String galaxyURL = adjustGalaxyURL(port); private boolean configureNestedShedTools = false; private Optional<URL> database = Optional.absent(); private static final String CONFIG_DIR_NAME = "config"; private static String adjustGalaxyURL(int port) { return "http://localhost:" + port + "/"; } public GalaxyProperties setAppProperty(final String name, final String value) { appProperties.put(name, value); return this; } public GalaxyProperties setServerProperty(final String name, final String value) { serverProperties.put(name, value); return this; } public GalaxyProperties prepopulateSqliteDatabase() { return prepopulateSqliteDatabase(Resources.getResource(GalaxyProperties.class, "universe.sqlite")); } /** * * @return True if it should be inferred that Galaxy is targeting a brand * new database and create_db.sh should be executed. */ public boolean isCreateDatabaseRequired() { // Logic in here could be better, database_url may be set and pointing at // an existing database - so there should be an option to disable this // without specifing a prepopulated sqlite database. return !database.isPresent(); } public GalaxyProperties prepopulateSqliteDatabase(final URL database) { this.database = Optional.of(database); // Set database auto migrate to true so database // is upgraded from revision in jar if needed. setAppProperty("database_auto_migrate", "true"); return this; } public GalaxyProperties assignFreePort() { port = IoUtils.findFreePort(); serverProperties.put("port", Integer.toString(port)); galaxyURL = adjustGalaxyURL(port); return this; } public GalaxyProperties configureNestedShedTools() { this.configureNestedShedTools = true; return this; } public void setAdminUser(final String username) { setAdminUsers(Lists.newArrayList(username)); } public void setAdminUsers(final Iterable<String> usernames) { final String usernamesStr = Joiner.on(",").join(usernames); logger.debug("Setting admin users: " + usernamesStr); setAppProperty("admin_users", usernamesStr); } /** * Determines if this is a pre-2014.10.06 release of Galaxy. * @param galaxyRoot The root directory of Galaxy. * @return True if this is a pre-2014.10.06 release of Galaxy, false otherwise. */ public boolean isPre20141006Release(File galaxyRoot) { if (galaxyRoot == null) { throw new IllegalArgumentException("galaxyRoot is null"); } else if (!galaxyRoot.exists()) { throw new IllegalArgumentException("galaxyRoot=" + galaxyRoot.getAbsolutePath() + " does not exist"); } File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return !(new File(configDirectory, "galaxy.ini.sample")).exists(); } /** * Gets the sample config ini for this Galaxy installation. * @param galaxyRoot The root directory of Galaxy. * @return A File object for the sample config ini for Galaxy. */ private File getConfigSampleIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini.sample"); } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini.sample"); } } /** * Gets the config ini for this Galaxy installation. * @param galaxyRoot The root directory of Galaxy. * @return A File object for the config ini for Galaxy. */ private File getConfigIni(File galaxyRoot) { if (isPre20141006Release(galaxyRoot)) { return new File(galaxyRoot, "universe_wsgi.ini"); } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); return new File(configDirectory, "galaxy.ini"); } } /** * Gets path to a config file for Galaxy relative to the Galaxy root directory. * This will check for the existence of the file and attempt to copy it from a *.sample file * if it does not exist. * @param galaxyRoot The Galaxy root directory. * @param configFileName The name of the config file to get. * @return The path to the config file relative to the Galaxy root. * @throws IOException If the copy failed. */ private String getConfigPathFromRoot(File galaxyRoot, String configFileName) throws IOException { if (isPre20141006Release(galaxyRoot)) { return configFileName; } else { File configDirectory = new File(galaxyRoot, CONFIG_DIR_NAME); File toolConf = new File(configDirectory, configFileName); // if config file does not exist, copy it from the .sample version if (!toolConf.exists()) { File toolConfSample = new File(configDirectory, configFileName + ".sample"); Files.copy(toolConfSample, toolConf); } return CONFIG_DIR_NAME + "/" + configFileName; } } /** * Gets a path for the tool_conf.xml file relative to the Galaxy root. * @param galaxyRoot The Galaxy root directory. * @return The path to the tool_conf.xml file. * @throws IOException If there was an error copying the *.sample file. */ private String getToolConfigPathFromRoot(File galaxyRoot) throws IOException { return getConfigPathFromRoot(galaxyRoot, "tool_conf.xml"); } /** * Gets a path for the shed_tool_conf.xml file relative to the Galaxy root. * @param galaxyRoot The Galaxy root directory. * @return The path to the shed_tool_conf.xml file. * @throws IOException If there was an error copying the *.sample file. */ private String getShedToolConfigPathFromRoot(File galaxyRoot) throws IOException { return getConfigPathFromRoot(galaxyRoot, "shed_tool_conf.xml"); } public void configureGalaxy(final File galaxyRoot) { try { if(configureNestedShedTools) { final File shedConf = new File(galaxyRoot, "shed_tool_conf.xml"); final InputSupplier<InputStream> shedToolConfSupplier = Resources.newInputStreamSupplier(getClass().getResource("shed_tool_conf.xml")); Files.copy(shedToolConfSupplier, shedConf); new File(galaxyRoot, "shed_tools").mkdirs(); } File sampleIni = getConfigSampleIni(galaxyRoot); File configIni = getConfigIni(galaxyRoot); final Ini ini = new Ini(new FileReader(sampleIni)); final Section appSection = ini.get("app:main"); final boolean toolsConfigured = appProperties.containsKey("tool_config_file"); if(!toolsConfigured && configureNestedShedTools) { String toolConfPath = getToolConfigPathFromRoot(galaxyRoot); String shedToolConfPath = getShedToolConfigPathFromRoot(galaxyRoot); appProperties.put("tool_config_file", toolConfPath + "," + shedToolConfPath); } // Without this, galaxy will not startup because of problems // with tool migration framework. if(!appProperties.containsKey("running_functional_tests")) { appProperties.put("running_functional_tests", "true"); } dumpMapToSection(appSection, appProperties); final Section serverSection = ini.get("server:main"); dumpMapToSection(serverSection, serverProperties); ini.store(configIni); final File databaseDirectory = new File(galaxyRoot, "database"); final File sqliteDatabase = new File(databaseDirectory, "universe.sqlite"); if(this.database.isPresent()) { final URL database = this.database.get(); Files.copy(Resources.newInputStreamSupplier(database), sqliteDatabase); } } catch(final IOException ioException) { throw new RuntimeException(ioException); } } private void dumpMapToSection(final Section section, final Map<String, String> values) { section.putAll(values); } public int getPort() { return port; } public String getGalaxyURL() { return galaxyURL; } }
package com.lagopusempire.multihomes.homeIO.database; import com.lagopusempire.multihomes.home.Home; import com.lagopusempire.multihomes.home.LoadResult; import com.lagopusempire.multihomes.homeIO.HomeIO; import com.lagopusempire.multihomes.homeIO.HomeListLoadedCallback; import com.lagopusempire.multihomes.homeIO.HomeLoadedCallback; import com.lagopusempire.multihomes.homeIO.HomesLoadedCallback; import java.sql.Connection; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.bukkit.plugin.java.JavaPlugin; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import static com.lagopusempire.multihomes.homeIO.database.ScriptKeys.*; /** * * @author MrZoraman */ public class DBHomeIO implements HomeIO { private final JavaPlugin plugin; private final Connection conn; public DBHomeIO(JavaPlugin plugin, Connection conn) { this.plugin = plugin; this.conn = conn; } @Override public void saveHome(final Home home, final Runnable callback) { final UUID uuid = home.getOwner(); plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { if(getHome(uuid, home.getName()) == null) { //home does not exist final String query = Scripts.getScript(CREATE_HOME); } else { //home exists, update it } plugin.getServer().getScheduler().runTask(plugin, () -> callback.run()); }); } @Override public void loadHomes(UUID uuid, HomesLoadedCallback callback) { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { final Map<String, Home> homes = new HashMap<>(); plugin.getServer().getScheduler().runTask(plugin, () -> callback.homesLoaded(homes)); }); throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void loadHome(UUID uuid, String homeName, HomeLoadedCallback callback) { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { final Home home = getHome(uuid, homeName); plugin.getServer().getScheduler().runTask(plugin, () -> callback.homeLoaded(home)); }); } @Override public void getHomeList(UUID uuid, HomeListLoadedCallback callback) { plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> { plugin.getServer().getScheduler().runTask(plugin, () -> { }); }); throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private Home getHome(UUID uuid, String homeName) { final String loadHomeQuery = Scripts.getScript(LOAD_HOME); try(final PreparedStatement stmt = conn.prepareStatement(loadHomeQuery)) { stmt.setString(1, uuid.toString()); stmt.setString(2, homeName); try(final ResultSet rs = stmt.executeQuery()) { if(rs.next()) { final double x = rs.getDouble("x"); final double y = rs.getDouble("y"); final double z = rs.getDouble("z"); final float yaw = rs.getFloat("yaw"); final float pitch = rs.getFloat("pitch"); final String worldName = rs.getString("world_name"); final World world = Bukkit.getWorld(worldName); if(world == null) { return new Home(uuid, homeName, LoadResult.NO_WORLD); } else { final Location loc = new Location(world, x, y, z, yaw, pitch); return new Home(uuid, homeName, loc); } } else { return new Home(uuid, homeName, LoadResult.DOES_NOT_EXIST); } } } catch (SQLException ex) { ex.printStackTrace(); } throw new IllegalStateException("Undefined state in DBHomeIO! (This is the developer's problem)"); } }
package com.smartling.marketo.sdk.rest.command.form; import com.google.common.collect.ImmutableMap; import com.smartling.marketo.sdk.domain.form.FormField; import java.util.Map; public class FormUtils { private FormUtils() { } public static Map<String, Object> copyFormFieldProperties(ImmutableMap.Builder<String, Object> builder, FormField formField) { if (formField.getLabel() != null) { builder.put("label", formField.getLabel()); } if (formField.getInstructions() != null) { builder.put("instructions", formField.getInstructions()); } if (formField.getValidationMessage() != null) { builder.put("validationMessage", formField.getValidationMessage()); } if (formField.getHintText() != null) { builder.put("hintText", formField.getHintText()); } if (formField.getDefaultValue() != null) { builder.put("defaultValue", formField.getDefaultValue()); } if (formField.getFieldMetaData() != null && formField.getFieldMetaData().getValues() != null) { builder.put("values", formField.getFieldMetaData()); } if (formField.isRequired() != null) { builder.put("required", formField.isRequired()); } return builder.build(); } }
package com.walkertribe.ian.protocol.core.setup; import com.walkertribe.ian.iface.PacketFactory; import com.walkertribe.ian.iface.PacketFactoryRegistry; import com.walkertribe.ian.iface.PacketReader; import com.walkertribe.ian.protocol.ArtemisPacket; import com.walkertribe.ian.protocol.ArtemisPacketException; import com.walkertribe.ian.protocol.core.ValueIntPacket; import com.walkertribe.ian.world.Artemis; /** * Set the ship you want to be on. You must send this packet before * SetConsolePacket. * @author dhleong */ public class SetShipPacket extends ValueIntPacket { public static void register(PacketFactoryRegistry registry) { register(registry, SubType.SET_SHIP, new PacketFactory() { @Override public Class<? extends ArtemisPacket> getFactoryClass() { return SetShipPacket.class; } @Override public ArtemisPacket build(PacketReader reader) throws ArtemisPacketException { return new SetShipPacket(reader); } }); } /** * Selects a ship to use during setup. Note that Artemis ship numbers are * one-based. */ public SetShipPacket(int shipNumber) { super(SubType.SET_SHIP, shipNumber - 1); // underlying packet wants index if (shipNumber < 1 || shipNumber > Artemis.SHIP_COUNT) { throw new IllegalArgumentException("Ship number must be between 1 and " + Artemis.SHIP_COUNT); } } private SetShipPacket(PacketReader reader) { super(SubType.SET_SHIP, reader); } public int getShipNumber() { return mArg + 1; } @Override protected void appendPacketDetail(StringBuilder b) { b.append(mArg + 1); } }
package crazypants.enderio.machine.invpanel; import java.awt.Rectangle; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.lwjgl.opengl.GL11; import com.enderio.core.client.gui.button.IconButton; import com.enderio.core.client.gui.button.MultiIconButton; import com.enderio.core.client.gui.button.ToggleButton; import com.enderio.core.client.gui.widget.GhostSlot; import com.enderio.core.client.gui.widget.GuiToolTip; import com.enderio.core.client.gui.widget.TextFieldEnder; import com.enderio.core.client.gui.widget.VScrollbar; import com.enderio.core.client.handlers.SpecialTooltipHandler; import com.enderio.core.client.render.EnderWidget; import com.enderio.core.client.render.RenderUtil; import com.enderio.core.common.util.ItemUtil; import crazypants.enderio.EnderIO; import crazypants.enderio.config.Config; import crazypants.enderio.fluid.Fluids; import crazypants.enderio.gui.IconEIO; import crazypants.enderio.jei.JeiAccessor; import crazypants.enderio.machine.gui.GuiMachineBase; import crazypants.enderio.machine.invpanel.client.CraftingHelper; import crazypants.enderio.machine.invpanel.client.DatabaseView; import crazypants.enderio.machine.invpanel.client.InventoryDatabaseClient; import crazypants.enderio.machine.invpanel.client.ItemEntry; import crazypants.enderio.machine.invpanel.client.SortOrder; import crazypants.enderio.network.PacketHandler; import crazypants.enderio.tool.SmartTank; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class GuiInventoryPanel extends GuiMachineBase<TileInventoryPanel> { private static final Rectangle inventoryArea = new Rectangle(24+107, 27, 108, 90); private static final Rectangle btnRefill = new Rectangle(24+85, 32, 20, 20); private static final Rectangle btnReturnArea = new Rectangle(24+6, 72, 5 * 18, 8); private static final int ID_SORT = 9876; private static final int ID_CLEAR = 9877; private static final int ID_SYNC = 9878; private static final int GHOST_COLUMNS = 6; private static final int GHOST_ROWS = 5; private final DatabaseView view; private final TextFieldEnder tfFilter; private String tfFilterExternalValue = null; private final IconButton btnSort; private final ToggleButton btnSync; private final GuiToolTip ttRefill; private final VScrollbar scrollbar; private final MultiIconButton btnClear; private final GuiToolTip ttSetReceipe; private int scrollPos; private int ghostSlotTooltipStacksize; private final String headerCrafting; private final String headerReturn; private final String headerStorage; private final String headerInventory; private final String infoTextFilter; private final String infoTextOffline; private CraftingHelper craftingHelper; private final Rectangle btnAddStoredRecipe = new Rectangle(); public GuiInventoryPanel(TileInventoryPanel te, Container container) { super(te, container, "inventorypanel"); redstoneButton.visible = false; configB.visible = false; for (int y = 0; y < GHOST_ROWS; y++) { for (int x = 0; x < GHOST_COLUMNS; x++) { getGhostSlots().add(new InvSlot(24 + 108 + x * 18, 28 + y * 18)); } } for (int i = 0; i < TileInventoryPanel.MAX_STORED_CRAFTING_RECIPES; i++) { getGhostSlots().add(new RecipeSlot(i, 7, 7 + i * 20)); } this.view = new DatabaseView(); int sortMode = te.getGuiSortMode(); int sortOrderIdx = sortMode >> 1; SortOrder[] orders = SortOrder.values(); if(sortOrderIdx >= 0 && te.getGuiSortMode() < orders.length) { view.setSortOrder(orders[sortOrderIdx], (sortMode & 1) != 0); } FontRenderer fr = Minecraft.getMinecraft().fontRendererObj; tfFilter = new TextFieldEnder(fr, 24 + 108, 11, 106, 10); tfFilter.setEnableBackgroundDrawing(false); tfFilter.setText(te.getGuiFilterString()); btnSync = new ToggleButton(this, ID_SYNC, 24 + 233, 46, IconEIO.CROSS, IconEIO.TICK); btnSync.setSelected(getTileEntity().getGuiSync()); btnSync.setSelectedToolTip(EnderIO.lang.localize("gui.enabled")); btnSync.setUnselectedToolTip(EnderIO.lang.localize("gui.disabled")); if (Loader.isModLoaded("NotEnoughItems")) { btnSync.setToolTip(EnderIO.lang.localize("gui.inventorypanel.tooltip.sync.nei")); if (getTileEntity().getGuiSync()) { updateNEI(tfFilter.getText()); } } else if (JeiAccessor.isJeiRuntimeAvailable()) { btnSync.setToolTip(EnderIO.lang.localize("gui.inventorypanel.tooltip.sync.jei")); btnSync.setSelectedToolTip(EnderIO.lang.localize("gui.enabled"), EnderIO.lang.localize("gui.inventorypanel.tooltip.sync.jei.line1"), EnderIO.lang.localize("gui.inventorypanel.tooltip.sync.jei.line2")); btnSync.setUnselectedToolTip(EnderIO.lang.localize("gui.disabled")); if (getTileEntity().getGuiSync()) { if (te.getGuiFilterString() != null && !te.getGuiFilterString().isEmpty()) { updateToJEI(te.getGuiFilterString()); } else { updateFromJEI(); } } } else { btnSync.setToolTip(EnderIO.lang.localize("gui.inventorypanel.tooltip.sync")); btnSync.setSelectedToolTip(EnderIO.lang.localize("gui.enabled")); btnSync.setUnselectedToolTip(EnderIO.lang.localize("gui.disabled")); btnSync.enabled = false; } btnSort = new IconButton(this, ID_SORT, 24+233, 27, getSortOrderIcon()) { @Override public boolean mousePressed(Minecraft mc1, int x, int y) { return mousePressedButton(mc1, x, y, 0); } @Override public boolean mousePressedButton(Minecraft mc1, int x, int y, int button) { if (button <= 1 && super.checkMousePress(mc1, x, y)) { toggleSortOrder(button == 0); return true; } return false; } }; scrollbar = new VScrollbar(this, 24+215, 27, 90); btnClear = new MultiIconButton(this, ID_CLEAR, 24+65, 60, EnderWidget.X_BUT, EnderWidget.X_BUT_PRESSED, EnderWidget.X_BUT_HOVER); textFields.add(tfFilter); headerCrafting = EnderIO.lang.localize("gui.inventorypanel.header.crafting"); headerReturn = EnderIO.lang.localize("gui.inventorypanel.header.return"); headerStorage = EnderIO.lang.localize("gui.inventorypanel.header.storage"); headerInventory = EnderIO.lang.localizeExact("container.inventory"); infoTextFilter = EnderIO.lang.localize("gui.inventorypanel.info.filter"); infoTextOffline = EnderIO.lang.localize("gui.inventorypanel.info.offline"); ArrayList<String> list = new ArrayList<String>(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.return.line"); addToolTip(new GuiToolTip(btnReturnArea, list) { @Override public boolean shouldDraw() { return super.shouldDraw() && !getTileEntity().isExtractionDisabled(); } }); list.clear(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.storage.line"); addToolTip(new GuiToolTip(btnReturnArea, list) { @Override public boolean shouldDraw() { return super.shouldDraw() && getTileEntity().isExtractionDisabled(); } }); list.clear(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.filterslot.line"); addToolTip(new GuiToolTip(new Rectangle(InventoryPanelContainer.FILTER_SLOT_X, InventoryPanelContainer.FILTER_SLOT_Y, 16, 16), list) { @Override public boolean shouldDraw() { return !getContainer().getSlotFilter().getHasStack() && super.shouldDraw(); } }); list.clear(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.refill.line"); ttRefill = new GuiToolTip(btnRefill, list); ttRefill.setIsVisible(false); addToolTip(ttRefill); list.clear(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.setrecipe.line"); ttSetReceipe = new GuiToolTip(btnRefill, list) { @Override public boolean shouldDraw() { return super.shouldDraw() && getContainer().hasCraftingRecipe(); } }; addToolTip(ttSetReceipe); list.clear(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.clear.line"); btnClear.setToolTip(list.toArray(new String[list.size()])); if (!Config.inventoryPanelFree) { addToolTip(new GuiToolTip(new Rectangle(36, 133, 16, 47), "") { @Override protected void updateText() { text.clear(); text.add(EnderIO.lang.localize("gui.inventorypanel.tooltip.fuelTank")); text.add(Fluids.toCapactityString(getTileEntity().fuelTank)); } }); } list.clear(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.addrecipe.line"); addToolTip(new GuiToolTip(btnAddStoredRecipe, list)); } @Override public void onGuiClosed() { int sortMode = (view.getSortOrder().ordinal() << 1); if(view.isSortOrderInverted()) { sortMode |= 1; } if (!btnSync.isSelected() || tfFilterExternalValue == null || !tfFilterExternalValue.equals(tfFilter.getText())) { getTileEntity().setGuiParameter(sortMode, tfFilter.getText(), btnSync.isSelected()); } else { getTileEntity().setGuiParameter(sortMode, "", btnSync.isSelected()); } super.onGuiClosed(); } public void setCraftingHelper(CraftingHelper craftingHelper) { if(this.craftingHelper != null) { this.craftingHelper.remove(); } this.craftingHelper = craftingHelper; ttRefill.setIsVisible(craftingHelper != null); ttSetReceipe.setIsVisible(craftingHelper == null); if(craftingHelper != null) { craftingHelper.install(); } } public void fillFromStoredRecipe(int index, boolean shift) { StoredCraftingRecipe recipe = getTileEntity().getStoredCraftingRecipe(index); if(recipe == null) { return; } if(getContainer().clearCraftingGrid()) { CraftingHelper helper = CraftingHelper.createFromRecipe(recipe); setCraftingHelper(helper); helper.refill(this, shift ? 64 : 1); } } @Override public void initGui() { super.initGui(); updateSortButton(); btnSort.onGuiInit(); btnClear.onGuiInit(); btnSync.onGuiInit(); addScrollbar(scrollbar); ((InventoryPanelContainer) inventorySlots).createGhostSlots(getGhostSlots()); } @Override public void actionPerformed(GuiButton b) throws IOException { super.actionPerformed(b); if (b.id == ID_CLEAR) { if (getContainer().clearCraftingGrid()) { setCraftingHelper(null); } } else if (b.id == ID_SYNC) { if (Loader.isModLoaded("NotEnoughItems")) { updateNEI(((ToggleButton) b).isSelected() ? tfFilter.getText() : ""); } } } @Override protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); bindGuiTexture(); int sx = guiLeft; int sy = guiTop; drawTexturedModalRect(sx + 24, sy, 0, 0, 232, ySize); drawTexturedModalRect(sx + 24 + 232, sy, 232, 0, 24, 68); if(craftingHelper != null) { boolean hover = btnRefill.contains(mouseX - sx, mouseY - sy); int iconX = hover ? (isShiftKeyDown() ? 48 : 24) : 0; drawTexturedModalRect(sx + btnRefill.x - 2, sy + btnRefill.y - 2, iconX, 232, 24, 24); } else if(getContainer().hasCraftingRecipe()) { boolean hover = btnRefill.contains(mouseX - sx, mouseY - sy); int iconX = hover ? 96 : 72; drawTexturedModalRect(sx + btnRefill.x - 2, sy + btnRefill.y - 2, iconX, 232, 24, 24); } TileInventoryPanel te = getTileEntity(); int y = sy; int numStoredRecipes = te.getStoredCraftingRecipes(); if(numStoredRecipes == 1) { drawTexturedModalRect(sx, y, 227, 225, 28, 30); y += 30; } else if(numStoredRecipes > 1) { drawTexturedModalRect(sx, y, 227, 225, 28, 24); y += 24; for(int i = 1; i < numStoredRecipes - 1; i++) { drawTexturedModalRect(sx, y, 198, 229, 28, 20); y += 20; } drawTexturedModalRect(sx, y, 198, 229, 28, 26); y += 26; } if(numStoredRecipes < TileInventoryPanel.MAX_STORED_CRAFTING_RECIPES && getContainer().hasNewCraftingRecipe()) { y += 2; btnAddStoredRecipe.x = 13; btnAddStoredRecipe.y = y - sy; btnAddStoredRecipe.width = 12; btnAddStoredRecipe.height = 14; boolean hover = btnAddStoredRecipe.contains(mouseX - sx, mouseY - sy); drawTexturedModalRect(sx + 13, y, 182, hover ? 241 : 225, 15, 14); } else { btnAddStoredRecipe.width = 0; btnAddStoredRecipe.height = 0; } SmartTank fuelTank = te.fuelTank; if (!Config.inventoryPanelFree) { drawTexturedModalRect(sx + 35, sy + 132, 232, 163, 18, 49); if (fuelTank.getFluidAmount() > 0) { RenderUtil.renderGuiTank(fuelTank.getFluid(), fuelTank.getCapacity(), fuelTank.getFluidAmount(), sx + 24 + 12, sy + 133, zLevel, 16, 47); } } final EnderWidget returnButton = te.isExtractionDisabled() ? btnReturnArea.contains(mouseX - sx, mouseY - sy) ? EnderWidget.STOP_BUT_HOVER : EnderWidget.STOP_BUT : btnReturnArea.contains(mouseX - sx, mouseY - sy) ? EnderWidget.RETURN_BUT_HOVER : EnderWidget.RETURN_BUT; GlStateManager.color(1, 1, 1, 1); EnderWidget.RETURN_BUT.getMap().render(returnButton, sx + 24 + 7, sy + 72, true); int headerColor = 0x404040; int focusedColor = 0x648494; FontRenderer fr = getFontRenderer(); fr.drawString(headerCrafting, sx + 24 + 7, sy + 6, headerColor); fr.drawString(te.isExtractionDisabled() ? headerStorage : headerReturn, sx + 24 + 7 + 10, sy + 72, btnReturnArea.contains(mouseX - sx, mouseY - sy) ? focusedColor : headerColor); fr.drawString(headerInventory, sx + 24 + 38, sy + 120, headerColor); super.drawGuiContainerBackgroundLayer(par1, mouseX, mouseY); if (JeiAccessor.isJeiRuntimeAvailable() && btnSync.isSelected()) { updateFromJEI(); } view.setDatabase(getDatabase()); view.setItemFilter(te.getItemFilter()); view.updateFilter(tfFilter.getText()); boolean update = view.sortItems(); scrollbar.setScrollMax(Math.max(0, (view.getNumEntries() + GHOST_COLUMNS - 1) / GHOST_COLUMNS - GHOST_ROWS)); if(update || scrollPos != scrollbar.getScrollPos()) { updateGhostSlots(); } if(te.isActive()) { tfFilter.setEnabled(true); if(!tfFilter.isFocused() && tfFilter.getText().isEmpty()) { fr.drawString(infoTextFilter, tfFilter.xPosition, tfFilter.yPosition, 0x707070); } } else { tfFilter.setEnabled(false); setText(tfFilter, ""); fr.drawString(infoTextOffline, tfFilter.xPosition, tfFilter.yPosition, 0x707070); } } @Override protected void onTextFieldChanged(TextFieldEnder tf, String old) { if (tf == tfFilter && btnSync.isSelected() && tfFilter.isFocused()) { if (Loader.isModLoaded("NotEnoughItems")) { updateNEI(tfFilter.getText()); } else if (JeiAccessor.isJeiRuntimeAvailable()) { updateToJEI(tfFilter.getText()); } } } private void updateNEI(String text) { // LayoutManager.searchField.setText(text); } private void updateToJEI(String text) { if (text != null && !text.isEmpty()) { JeiAccessor.setFilterText(text); } else { JeiAccessor.setFilterText(""); } } /* * A note on the JEI sync: * * When the GUI is opened, any text stored in the invPanel will take precedence. If there's no stored text, the text from the JEI field will be used. * * When text is entered into the search field, it is synced to JEI. When the field is cleared, that is synced, too. * * When text is entered into the JEI field, it is synced to the search field. But when it is cleared, that is not synced. This in on purpose, to give the user * a way to quickly look up (or cheat in) something without having to disable syncing. * * When the GUI is closed, text will be remembered if it was entered into the search field. If it was entered into the JEI field, it is not remembered. This * is important because it allows "locking" an invPanel to a search text and still have JEI sync. */ private void updateFromJEI() { final String filterText = JeiAccessor.getFilterText(); if (!filterText.isEmpty() && !filterText.equals(tfFilter.getText())) { tfFilter.setText(filterText); tfFilterExternalValue = filterText; } } @Override protected void drawFakeItemStack(int x, int y, ItemStack stack) { FontRenderer font = stack.getItem().getFontRenderer(stack); if(font == null) { font = fontRendererObj; } String str = null; if(stack.stackSize >= 1000) { int value = stack.stackSize / 1000; String unit = "k"; if(value >= 1000) { value /= 1000; unit = "m"; } str = value + unit; } else if(stack.stackSize > 1) { str = Integer.toString(stack.stackSize); } itemRender.renderItemAndEffectIntoGUI(stack, x, y); if(str != null) { GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_BLEND); GL11.glPushMatrix(); GL11.glTranslatef(x + 16, y + 16, 0); font.drawStringWithShadow(str, 1 - font.getStringWidth(str), -8, 0xFFFFFF); GL11.glPopMatrix(); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); } itemRender.renderItemOverlayIntoGUI(font, stack, x, y, ""); } @Override protected void drawGhostSlotTooltip(GhostSlot slot, int mouseX, int mouseY) { ItemStack stack = slot.getStack(); if(stack != null) { ghostSlotTooltipStacksize = stack.stackSize; try { renderToolTip(stack, mouseX, mouseY); } finally { ghostSlotTooltipStacksize = 0; } } } @Override public void drawHoveringText(List<String> list, int mouseX, int mouseY, FontRenderer font) { if(ghostSlotTooltipStacksize >= 1000) { list.add(TextFormatting.WHITE + EnderIO.lang.localize("gui.inventorypanel.tooltip.itemsstored", Integer.toString(ghostSlotTooltipStacksize))); } super.drawHoveringText(list, mouseX, mouseY, font); } public InventoryPanelContainer getContainer() { return (InventoryPanelContainer) inventorySlots; } public InventoryDatabaseClient getDatabase() { return getTileEntity().getDatabaseClient(); } private IconEIO getSortOrderIcon() { SortOrder order = view.getSortOrder(); boolean invert = view.isSortOrderInverted(); switch (order) { case NAME: return invert ? IconEIO.SORT_NAME_UP : IconEIO.SORT_NAME_DOWN; case COUNT: return invert ? IconEIO.SORT_SIZE_UP : IconEIO.SORT_SIZE_DOWN; case MOD: return invert ? IconEIO.SORT_MOD_UP : IconEIO.SORT_MOD_DOWN; default: return null; } } void toggleSortOrder(boolean next) { SortOrder order = view.getSortOrder(); SortOrder[] values = SortOrder.values(); int idx = order.ordinal(); if(next && view.isSortOrderInverted()) { order = values[(idx + 1) % values.length]; } else if(!next && !view.isSortOrderInverted()) { if(idx == 0) { idx = values.length; } order = values[idx - 1]; } view.setSortOrder(order, !view.isSortOrderInverted()); updateSortButton(); } private void updateSortButton() { SortOrder order = view.getSortOrder(); ArrayList<String> list = new ArrayList<String>(); SpecialTooltipHandler.addTooltipFromResources(list, "enderio.gui.inventorypanel.tooltip.sort." + order.name().toLowerCase(Locale.US) + (view.isSortOrderInverted() ? "_up" : "_down") + ".line"); btnSort.setIcon(getSortOrderIcon()); btnSort.setToolTip(list.toArray(new String[list.size()])); } private void updateGhostSlots() { scrollPos = scrollbar.getScrollPos(); int index = scrollPos * GHOST_COLUMNS; int count = view.getNumEntries(); for (int i = 0; i < GHOST_ROWS * GHOST_COLUMNS; i++, index++) { InvSlot slot = (InvSlot) getGhostSlots().get(i); if(index < count) { slot.entry = view.getItemEntry(index); slot.stack = slot.entry.makeItemStack(); } else { slot.entry = null; slot.stack = null; } } } @Override protected boolean showRecipeButton() { return false; } @Override public int getXSize() { return 280; } @Override public int getYSize() { return 212; } @Override protected void mouseClicked(int x, int y, int button) throws IOException { super.mouseClicked(x, y, button); x -= guiLeft; y -= guiTop; if(btnRefill.contains(x, y)) { if(craftingHelper != null) { playClickSound(); craftingHelper.refill(this, isShiftKeyDown() ? 64 : 1); } else if(getContainer().hasCraftingRecipe()) { playClickSound(); setCraftingHelper(CraftingHelper.createFromSlots(getContainer().getCraftingGridSlots())); } } if(btnAddStoredRecipe.contains(x, y)) { TileInventoryPanel te = getTileEntity(); if(te.getStoredCraftingRecipes() < TileInventoryPanel.MAX_STORED_CRAFTING_RECIPES && getContainer().hasNewCraftingRecipe()) { StoredCraftingRecipe recipe = new StoredCraftingRecipe(); if(recipe.loadFromCraftingGrid(getContainer().getCraftingGridSlots())) { playClickSound(); te.addStoredCraftingRecipe(recipe); } } } if(btnReturnArea.contains(x, y)) { TileInventoryPanel te = getTileEntity(); playClickSound(); te.setExtractionDisabled(!te.isExtractionDisabled()); } } private void playClickSound() { mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.UI_BUTTON_CLICK, 1.0F)); } @Override protected void mouseWheel(int x, int y, int delta) { super.mouseWheel(x, y, delta); if(draggingScrollbar == null) { x -= guiLeft; y -= guiTop; boolean shift = isShiftKeyDown(); if(inventoryArea.contains(x, y)) { if(!shift) { scrollbar.scrollBy(-Integer.signum(delta)); } else if(hoverGhostSlot instanceof InvSlot) { InvSlot invSlot = (InvSlot) hoverGhostSlot; InventoryDatabaseClient db = getDatabase(); if(invSlot.stack != null && invSlot.entry != null && db != null) { ItemStack itemStack = mc.thePlayer.inventory.getItemStack(); if (itemStack == null || ItemUtil.areStackMergable(itemStack, invSlot.stack)) { PacketHandler.INSTANCE.sendToServer(new PacketFetchItem(db.getGeneration(), invSlot.entry, -1, 1)); } } } } } } @Override protected void ghostSlotClicked(GhostSlot slot, int x, int y, int button) { if(slot instanceof InvSlot) { InvSlot invSlot = (InvSlot) slot; InventoryDatabaseClient db = getDatabase(); if(invSlot.entry != null && invSlot.stack != null && db != null) { int targetSlot; int count = Math.min(invSlot.stack.stackSize, invSlot.stack.getMaxStackSize()); if(button == 0) { if(isShiftKeyDown()) { InventoryPlayer playerInv = mc.thePlayer.inventory; targetSlot = playerInv.getFirstEmptyStack(); if(targetSlot >= 0) { targetSlot = getContainer().getSlotIndex(playerInv, targetSlot); } if(targetSlot < 0) { return; } } else { targetSlot = -1; } } else if(button == 1) { targetSlot = -1; if(isCtrlKeyDown()) { count = 1; } else { count = (count + 1) / 2; } } else { return; } PacketHandler.INSTANCE.sendToServer(new PacketFetchItem(db.getGeneration(), invSlot.entry, targetSlot, count)); } } else if(slot instanceof RecipeSlot) { RecipeSlot recipeSlot = (RecipeSlot) slot; if(recipeSlot.isVisible()) { if(button == 0) { fillFromStoredRecipe(recipeSlot.index, isShiftKeyDown()); } else if(button == 1) { getTileEntity().removeStoredCraftingRecipe(recipeSlot.index); } } } } class InvSlot extends GhostSlot { ItemEntry entry; ItemStack stack; InvSlot(int x, int y) { this.x = x; this.y = y; this.grayOut = false; this.stackSizeLimit = Integer.MAX_VALUE; } @Override public ItemStack getStack() { return stack; } } class RecipeSlot extends GhostSlot { final int index; RecipeSlot(int index, int x, int y) { this.index = index; this.x = x; this.y = y; } @Override public ItemStack getStack() { TileInventoryPanel te1 = getTileEntity(); StoredCraftingRecipe recipe = te1.getStoredCraftingRecipe(index); return recipe != null ? recipe.getResult(te1) : null; } @Override public boolean isVisible() { return index < getTileEntity().getStoredCraftingRecipes(); } } }
package de.uka.ipd.sdq.beagle.analysis; import de.uka.ipd.sdq.beagle.core.Blackboard; import de.uka.ipd.sdq.beagle.core.ResourceDemandingInternalAction; import de.uka.ipd.sdq.beagle.core.SEFFBranch; import de.uka.ipd.sdq.beagle.core.SEFFLoop; import de.uka.ipd.sdq.beagle.core.expressions.EvaluableExpression; import java.util.Set; /** * View of the {@link Blackboard} designed to be used by {@link ResultAnalyser}. Reading * information and adding results to the {@link Blackboard} is supported. * * @author Christoph Michelbach */ public class AnalyserBlackboardView { /** * Creates a new {@code AnalyserBlackboardView} for {@code blackboard}. * * @param blackboard The {@link Blackboard} to be accessed through the * {@code AnalyserBlackboardView}. */ public AnalyserBlackboardView(final Blackboard blackboard) { } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllRDIAs()}. * * @return all {@linkplain ResourceDemandingInternalAction resource demanding internal * actions} known to Beagle. Changes to the returned set will not modify the * blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllRDIAs() */ public Set<ResourceDemandingInternalAction> getAllRDIAs() { return null; } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches()}. * * @return all {@linkplain SEFFBranch SEFF branches} known to Beagle. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllSEFFBranches() */ public Set<SEFFBranch> getAllSEFFBranches() { return null; } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getAllSeffLoops()}. * * @return all {@linkplain SEFFLoop SEFF loops} known to Beagle. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getAllSeffLoops() */ public Set<SEFFLoop> getAllSEFFLoops() { return null; } public void proposeExpressionFor(final ResourceDemandingInternalAction rdia, final EvaluableExpression expression) { } public void proposeExpressionFor(final SEFFLoop loop, final EvaluableExpression expression) { } public void proposeExpressionFor(final SEFFBranch branch, final EvaluableExpression expression) { } /** * Delegates to {@link de.uka.ipd.sdq.beagle.core.Blackboard#getRDIAsToBeMeasured()}. * * @return All {@linkplain ResourceDemandingInternalAction resource demanding internal * actions} to be measured. Changes to the returned set will not modify the * blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getRDIAsToBeMeasured() */ public Set<ResourceDemandingInternalAction> getRDIAsToBeMeasured() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFBranchesToBeMeasured()}. * * @return All {@linkplain SEFFBranch SEFF branches} to be measured. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFBranchesToBeMeasured() */ public Set<SEFFBranch> getSEFFBranchesToBeMeasured() { return null; } /** * Delegates to * {@link de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFLoopsToBeMeasured()}. * * @return All {@linkplain SEFFLoop SEFF loops} to be measured. Changes to the * returned set will not modify the blackboard content. Is never {@code null}. * @see de.uka.ipd.sdq.beagle.core.Blackboard#getSEFFLoopsToBeMeasured() */ public Set<SEFFLoop> getSEFFLoopsToBeMeasured() { return null; } }
package edu.harvard.iq.dataverse; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author skraffmiller */ @Stateless @Named public class FeaturedDataverseServiceBean { @PersistenceContext(unitName = "VDCNet-ejbPU") private EntityManager em; @EJB DataverseServiceBean dataverseService; private static final Logger logger = Logger.getLogger(FeaturedDataverseServiceBean.class.getCanonicalName()); public List<DataverseFeaturedDataverse> findByDataverseId(Long dataverseId) { Query query = em.createQuery("select object(o) from DataverseFeaturedDataverse as o where o.dataverse.id = :dataverseId order by o.displayOrder"); query.setParameter("dataverseId", dataverseId); return query.getResultList(); } public List<Dataverse> findByDataverseIdQuick(Long dataverseId) { List<Object[]> searchResults = null; try { //searchResults = em.createNativeQuery("SELECT id, alias, name FROM dataverse WHERE id IN (select featureddataverse_id from DataverseFeaturedDataverse where dataverse_id = "+dataverseId+" order by displayOrder)").getResultList(); searchResults = em.createNativeQuery("SELECT d.id, d.alias, d.name FROM dataverse d, DataverseFeaturedDataverse f WHERE f.featureddataverse_id = d.id AND f.dataverse_id = "+dataverseId+" order by f.displayOrder").getResultList(); } catch (Exception ex) { return null; } List<Dataverse> ret = new ArrayList<>(); for (Object[] result : searchResults) { Long id = (Long)result[0]; if (id == null) { continue; } Dataverse dataverse = new Dataverse(); dataverse.setId(id); if (result[1] != null) { dataverse.setAlias((String)result[1]); } if (result[2] != null) { dataverse.setName((String)result[2]); } dataverse.setDataverseTheme(dataverseService.findDataverseThemeByIdQuick(id)); if (dataverse.getDataverseTheme()!=null){ logger.fine("THEME: "+dataverse.getDataverseTheme().getLogo()+", "+dataverse.getDataverseTheme().getLogoFormat()); } ret.add(dataverse); } return ret; } public List<DataverseFeaturedDataverse> findByRootDataverse() { return em.createQuery("select object(o) from DataverseFeaturedDataverse as o where o.dataverse.id = 1 order by o.displayOrder").getResultList(); } public void delete(DataverseFeaturedDataverse dataverseFeaturedDataverse) { em.remove(em.merge(dataverseFeaturedDataverse)); } public void deleteFeaturedDataversesFor( Dataverse d ) { em.createNamedQuery("DataverseFeaturedDataverse.removeByOwnerId") .setParameter("ownerId", d.getId()) .executeUpdate(); } public void create(int diplayOrder, Long featuredDataverseId, Long dataverseId) { DataverseFeaturedDataverse dataverseFeaturedDataverse = new DataverseFeaturedDataverse(); dataverseFeaturedDataverse.setDisplayOrder(diplayOrder); Dataverse dataverse = (Dataverse)em.find(Dataverse.class,dataverseId); dataverseFeaturedDataverse.setDataverse(dataverse); Dataverse featuredDataverse = (Dataverse)em.find(Dataverse.class,featuredDataverseId); dataverseFeaturedDataverse.setFeaturedDataverse(featuredDataverse); em.persist(dataverseFeaturedDataverse); } }
package edu.yu.einstein.wasp.batch; import java.util.Date; import java.util.List; import org.springframework.batch.item.ItemProcessor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import edu.yu.einstein.wasp.model.*; import edu.yu.einstein.wasp.service.*; /** * Create Software Run Processor * * creates a new run w/ for the sample/ job.software combination * - default values for name is job.name + software.name * creates a corresponding state for it w/ this state as a parent * that state will have jobid/sampleid and the new runid linked to it * state will have a task of 'runWrapTask' and status of 'CREATED' * */ @Component public class CreateSoftwareRunProcessor implements ItemProcessor { @Autowired StateService stateService; @Autowired TaskService taskService; @Autowired StatejobService statejobService; @Autowired StatesampleService statesampleService; @Autowired StaterunService staterunService; @Autowired RunService runService; @Autowired SoftwareService softwareService; protected final String targetTask = "runWrapTask"; protected final String targetStatus = "CREATED"; protected String softwareIName; public void setSoftwareIName(String s) { this.softwareIName = s; } @Override public State process(Object stateId) throws Exception { State state = stateService.getStateByStateId(((Integer) stateId).intValue()); List <JobSoftware> jobSoftwares = state.getStatejob().get(0).getJob().getJobSoftware(); // finds the right software for typeresource Software software = null; for (JobSoftware js: jobSoftwares) { if (softwareIName.equals(js.getSoftware().getTypeResource().getIName())) { software = js.getSoftware(); } } if (software == null) { throw new Exception("could not find software"); } Task task = taskService.getTaskByIName(targetTask); Sample sample = state.getStatesample().get(0).getSample(); // Makes the run Run run = new Run(); run.setSoftwareId(software.getSoftwareId()); run.setName(sample.getName() + " " + software.getName()); run.setSampleId(sample.getSampleId()); run.setStartts(new Date()); run.setIsActive(1); runService.save(run); // Makes the state and supporting tables State newState = new State(); newState.setTaskId(task.getTaskId()); newState.setStatus(targetStatus); newState.setName(sample.getName() + " " + software.getIName() + " " + task.getName()); newState.setSourceStateId(state.getStateId()); stateService.save(newState); Staterun newStaterun = new Staterun(); newStaterun.setStateId(newState.getStateId()); newStaterun.setRunId(run.getRunId()); staterunService.save(newStaterun); Statesample newStatesample = new Statesample(); newStatesample.setStateId(newState.getStateId()); newStatesample.setSampleId(run.getSampleId()); statesampleService.save(newStatesample); Statejob newStatejob = new Statejob(); newStatejob.setStateId(newState.getStateId()); newStatejob.setJobId(state.getStatejob().get(0).getJobId()); statejobService.save(newStatejob); return newState; } }
package gov.nasa.jpl.mbee.mdk.mms.sync.jms; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.core.Project; import com.nomagic.magicdraw.esi.EsiUtils; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import gov.nasa.jpl.mbee.mdk.api.incubating.MDKConstants; import gov.nasa.jpl.mbee.mdk.api.incubating.convert.Converters; import gov.nasa.jpl.mbee.mdk.emf.EMFImporter; import gov.nasa.jpl.mbee.mdk.json.ImportException; import gov.nasa.jpl.mbee.mdk.json.JacksonUtils; import gov.nasa.jpl.mbee.mdk.mms.actions.MMSLogoutAction; import gov.nasa.jpl.mbee.mdk.mms.sync.delta.SyncElements; import gov.nasa.jpl.mbee.mdk.mms.sync.status.SyncStatusConfigurator; import gov.nasa.jpl.mbee.mdk.options.MDKOptionsGroup; import gov.nasa.jpl.mbee.mdk.util.Changelog; import gov.nasa.jpl.mbee.mdk.util.MDUtils; import gov.nasa.jpl.mbee.mdk.util.TicketUtils; import javax.jms.*; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; public class JMSMessageListener implements MessageListener, ExceptionListener { private static final Map<String, Changelog.ChangeType> CHANGE_MAPPING = new LinkedHashMap<>(4); static { CHANGE_MAPPING.put("addedElements", Changelog.ChangeType.CREATED); CHANGE_MAPPING.put("deletedElements", Changelog.ChangeType.DELETED); CHANGE_MAPPING.put("movedElements", Changelog.ChangeType.UPDATED); CHANGE_MAPPING.put("updatedElements", Changelog.ChangeType.UPDATED); } private final AtomicBoolean disabled = new AtomicBoolean(true); private final AtomicBoolean exceptionHandlerRunning = new AtomicBoolean(); private int reconnectionAttempts = 0; private final Project project; private final Changelog<String, ObjectNode> inMemoryJMSChangelog = new Changelog<>(); { if (MDUtils.isDeveloperMode()) { inMemoryJMSChangelog.setShouldLogChanges(true); } } public void setDisabled(boolean disabled) { synchronized (this.disabled) { this.disabled.set(disabled); } } public boolean isDisabled() { synchronized (this.disabled) { return (disabled.get() || !MDKOptionsGroup.getMDKOptions().isChangeListenerEnabled()); } } private Message lastMessage; public boolean isExceptionHandlerRunning() { synchronized (this.exceptionHandlerRunning) { return exceptionHandlerRunning.get(); } } JMSMessageListener(Project project) { this.project = project; } @Override public void onMessage(Message message) { if (isDisabled()) { return; } lastMessage = message; if (!(message instanceof TextMessage)) { return; } final String text; try { text = ((TextMessage) message).getText(); } catch (JMSException e) { e.printStackTrace(); return; } if (MDKOptionsGroup.getMDKOptions().isLogJson()) { System.out.println("MMS TextMessage for " + Converters.getIProjectToIdConverter().apply(project.getPrimaryProject()) + " -" + System.lineSeparator() + text); } JsonNode messageJsonNode; try { messageJsonNode = JacksonUtils.getObjectMapper().readTree(text); } catch (IOException e) { e.printStackTrace(); return; } if (!messageJsonNode.isObject()) { return; } JsonNode refsJsonNode = messageJsonNode.get("refs"), syncedJsonNode = messageJsonNode.get("synced"), sourceJsonNode = messageJsonNode.get("source"), senderJsonNode = messageJsonNode.get("sender"); if (refsJsonNode != null && refsJsonNode.isObject()) { if (sourceJsonNode != null && sourceJsonNode.isTextual() && sourceJsonNode.asText().startsWith("magicdraw")) { return; } for (Map.Entry<String, Changelog.ChangeType> entry : CHANGE_MAPPING.entrySet()) { JsonNode changeJsonNode = refsJsonNode.get(entry.getKey()); if (changeJsonNode == null || !changeJsonNode.isArray()) { continue; } for (JsonNode sysmlIdJsonNode : changeJsonNode) { if (!sysmlIdJsonNode.isTextual() || sysmlIdJsonNode.asText().isEmpty()) { continue; } String id = sysmlIdJsonNode.asText(); try { ObjectNode elementJsonNode = JacksonUtils.getObjectMapper().createObjectNode(); elementJsonNode.put(MDKConstants.ID_KEY, id); if (EMFImporter.PreProcessor.SYSML_ID_VALIDATION.getFunction().apply(elementJsonNode, project, false, project.getPrimaryModel()) == null) { continue; } } catch (ImportException ignored) { continue; } inMemoryJMSChangelog.addChange(id, null, entry.getValue()); } SyncStatusConfigurator.getSyncStatusAction().update(); } } else if (syncedJsonNode != null && syncedJsonNode.isObject()) { if (senderJsonNode != null && senderJsonNode.isTextual() && senderJsonNode.asText().equals(TicketUtils.getUsername(project))) { return; } Changelog<String, Void> syncedChangelog = SyncElements.buildChangelog((ObjectNode) syncedJsonNode); if (syncedChangelog.isEmpty()) { return; } Collection<String> ignoredIds; if (project.isRemote()) { ignoredIds = new HashSet<>(); Collection<Element> locks = EsiUtils.getLockService(project).getLockedByMe(); for (Element lock : locks) { ignoredIds.add(lock.getLocalID()); } } else { ignoredIds = Collections.emptyList(); } for (Changelog.ChangeType changeType : Changelog.ChangeType.values()) { Map<String, ObjectNode> inMemoryJMSChanges = inMemoryJMSChangelog.get(changeType); Set<String> keys = syncedChangelog.get(changeType).keySet(); keys.removeAll(ignoredIds); keys.forEach(inMemoryJMSChanges::remove); } int size = syncedChangelog.flattenedSize(); if (MDUtils.isDeveloperMode()) { Application.getInstance().getGUILog().log("[INFO] " + project.getName() + " - Cleared up to " + size + " MMS element change" + (size != 1 ? "s" : "") + " as a result of another client syncing the model."); } SyncStatusConfigurator.getSyncStatusAction().update(); } } public Changelog<String, ObjectNode> getInMemoryJMSChangelog() { return inMemoryJMSChangelog; } public Message getLastMessage() { return lastMessage; } @Override public void onException(JMSException exception) { if (exceptionHandlerRunning.get()) { return; } exceptionHandlerRunning.set(true); Application.getInstance().getGUILog().log("[WARNING] " + project.getName() + " - Lost connection with MMS. Please check your network configuration."); JMSSyncProjectEventListenerAdapter.getProjectMapping(project).getJmsMessageListener().setDisabled(true); while (shouldAttemptToReconnect()) { int delay = Math.min(600, (int) Math.pow(2, reconnectionAttempts++)); Application.getInstance().getGUILog().log("[INFO] " + project.getName() + " - Attempting to reconnect to MMS in " + delay + " second" + (delay != 1 ? "s" : "") + "."); try { Thread.sleep(delay * 1000); } catch (InterruptedException ignored) { } if (!exceptionHandlerRunning.get()) { return; } if (shouldAttemptToReconnect()) { JMSSyncProjectEventListenerAdapter.closeJMS(project); JMSSyncProjectEventListenerAdapter.initializeJMS(project); } } if (!JMSSyncProjectEventListenerAdapter.getProjectMapping(project).getJmsMessageListener().isDisabled()) { reconnectionAttempts = 0; Application.getInstance().getGUILog().log("[INFO] " + project.getName() + " - Successfully reconnected to MMS after dropped connection."); } else { Application.getInstance().getGUILog().log("[WARNING] " + project.getName() + " - Failed to reconnect to MMS after dropped connection. Please manually login to MMS, or close and re-open the project, to re-initiate."); MMSLogoutAction.logoutAction(project); } reconnectionAttempts = 0; exceptionHandlerRunning.set(false); } private boolean shouldAttemptToReconnect() { return !project.isProjectClosed() && TicketUtils.isTicketSet(project) && JMSSyncProjectEventListenerAdapter.shouldEnableJMS(project) && JMSSyncProjectEventListenerAdapter.getProjectMapping(project).getJmsMessageListener().isDisabled(); } }
package hr.vsite.mentor.servlet.rest.resources; import java.util.List; import java.util.UUID; import javax.inject.Inject; import javax.inject.Provider; import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import hr.vsite.mentor.course.Course; import hr.vsite.mentor.course.CourseFilter; import hr.vsite.mentor.course.CourseManager; import hr.vsite.mentor.user.User; @Path("course") public class CourseResource { @Inject public CourseResource(Provider<CourseManager> courseProvider) { this.courseProvider = courseProvider; } @GET @Path("list") @Produces(MediaType.APPLICATION_JSON) @Transactional public List<Course> list( @QueryParam("title") String title, @QueryParam("author") User author, @QueryParam("count") Integer count, @QueryParam("offset") Integer offset ) { CourseFilter filter = new CourseFilter(); filter.setTitle(title); filter.setAuthor(author); return courseProvider.get().list(filter, count, offset); } @GET @Path("{course}") @Produces(MediaType.APPLICATION_JSON) public Course findById( @PathParam("course") Course course ) { if (course == null) throw new NotFoundException(); return course; } @PUT @Path("") @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Course insert(Course course) { return courseProvider.get().insert(course); } @POST @Path("{id}") @Transactional @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Course update( @PathParam("id") UUID id, Course course) { return courseProvider.get().update(id, course); } private final Provider<CourseManager> courseProvider; }
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the pairs function below. static int pairs(int k, int[] arr) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int count=0; for(int value:arr) map.put(value,Math.abs(value-k)); for(int value:arr){ int calculatedValue = map.get(value); if(calculatedValue!=value && map.containsKey(calculatedValue)) count++; } System.out.println(map); return count; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); String[] nk = scanner.nextLine().split(" "); int n = Integer.parseInt(nk[0]); int k = Integer.parseInt(nk[1]); int[] arr = new int[n]; String[] arrItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arrItem = Integer.parseInt(arrItems[i]); arr[i] = arrItem; } int result = pairs(k, arr); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } }
/** * Abstract base classes for implementing {@link org.eclipse.kapua.client.gateway.Client}s */ package org.eclipse.kapua.client.gateway.spi;
package hudson.plugins.emailext; import com.google.common.collect.Multimap; import hudson.model.AbstractBuild; import hudson.model.TaskListener; import hudson.plugins.emailext.plugins.EmailTrigger; /** * * @author acearl */ public class ExtendedEmailPublisherContext { private ExtendedEmailPublisher publisher; private AbstractBuild<?, ?> build; private EmailTrigger trigger; private TaskListener listener; private Multimap<String, EmailTrigger> triggered; public ExtendedEmailPublisherContext(ExtendedEmailPublisher publisher, AbstractBuild<?, ?> build, TaskListener listener) { this.publisher = publisher; this.build = build; this.listener = listener; } public ExtendedEmailPublisher getPublisher() { return publisher; } protected void setPublisher(ExtendedEmailPublisher publisher) { this.publisher = publisher; } public AbstractBuild<?, ?> getBuild() { return build; } protected void setBuild(AbstractBuild<?, ?> build) { this.build = build; } public EmailTrigger getTrigger() { return trigger; } protected void setTrigger(EmailTrigger trigger) { this.trigger = trigger; } public TaskListener getListener() { return listener; } protected void setListener(TaskListener listener) { this.listener = listener; } public Multimap<String, EmailTrigger> getTriggered() { return triggered; } protected void setTriggered(Multimap<String, EmailTrigger> triggered) { this.triggered = triggered; } }
package io.paymenthighway.model.response; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.UUID; /** * Tokenization response POJO */ public class TokenizationResponse extends Response { @JsonProperty("card_token") UUID cardToken; PartialCard card; Customer customer; @JsonProperty("cardholder_authentication") String cardholderAuthentication; @JsonProperty("recurring") Boolean recurring; public UUID getCardToken() { return cardToken; } public PartialCard getCard() { return this.card; } public Customer getCustomer() { return customer; } public String getCardholderAuthentication() { return cardholderAuthentication; } public Boolean getRecurring() { return recurring; } }
package com.platform; import android.app.Activity; import android.content.Context; import android.util.Log; import com.breadwallet.presenter.activities.MainActivity; import com.breadwallet.tools.manager.SharedPreferencesManager; import com.breadwallet.tools.security.KeyStoreManager; import com.breadwallet.wallet.BRWalletManager; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static android.R.attr.name; import static com.breadwallet.R.string.request; public class APIClient { public static final String TAG = APIClient.class.getName(); // proto is the transport protocol to use for talking to the API (either http or https) private static final String PROTO = "https"; // host is the server(s) on which the API is hosted private static final String HOST = "api.breadwallet.com"; // convenience getter for the API endpoint private static final String BASE_URL = PROTO + "://" + HOST; //feePerKb url private static final String FEE_PER_KB_URL = "/v1/fee-per-kb"; //token private static final String TOKEN = "/token"; private static final String ME = "/me"; //singleton instance private static APIClient ourInstance; private static final String GET = "GET"; private static final String POST = "POST"; private Activity ctx; public static synchronized APIClient getInstance(Activity context) { if (ourInstance == null) ourInstance = new APIClient(context); return ourInstance; } private APIClient(Activity context) { ctx = context; } public static synchronized APIClient getInstance() { if (ourInstance == null) ourInstance = new APIClient(); return ourInstance; } private APIClient() { } //returns the fee per kb or 0 if something went wrong public long feePerKb() { try { String strUtl = BASE_URL + FEE_PER_KB_URL; Request request = new Request.Builder().url(strUtl).get().build(); String response = sendRequest(request, false); JSONObject object = new JSONObject(response); return (long) object.getInt("fee_per_kb"); } catch (JSONException e) { e.printStackTrace(); } return 0; } public String buyBitcoinMe() { if (ctx == null) ctx = MainActivity.app; if (ctx == null) return null; String strUtl = BASE_URL + ME; Log.e(TAG, "buyBitcoinMe: strUrl: " + strUtl); Request request = new Request.Builder() .url(strUtl) .get() .build(); String response = sendRequest(request, true); if (response.equalsIgnoreCase("401")) { getToken(); response = sendRequest(request, true); } Log.e(TAG, "buyBitcoinMe: response: " + response); // if (response.isEmpty()) return null; // JSONObject obj = new JSONObject(response); // String token = obj.getString("token"); // KeyStoreManager.putToken(token.getBytes(), ctx); return null; } public String getToken() { if (ctx == null) ctx = MainActivity.app; if (ctx == null) return null; try { String strUtl = BASE_URL + TOKEN; Log.e(TAG, "getToken: strUrl: " + strUtl); JSONObject requestMessageJSON = new JSONObject(); String base58PubKey = BRWalletManager.getAuthPublicKeyForAPI(KeyStoreManager.getAuthKey(ctx)); Log.e(TAG, "getToken: base58PubKey: " + base58PubKey); requestMessageJSON.put("pubKey", base58PubKey); requestMessageJSON.put("deviceID", SharedPreferencesManager.getDeviceId(ctx)); Log.e(TAG, "getToken: message: " + requestMessageJSON.toString()); final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create(JSON, requestMessageJSON.toString()); Request request = new Request.Builder() .url(strUtl) .header("Content-Type", "application/json") .header("Accept", "application/json") .post(requestBody).build(); String response = sendRequest(request, false); Log.e(TAG, "getToken: response: " + response); if (response.isEmpty()) return null; JSONObject obj = new JSONObject(response); String token = obj.getString("token"); KeyStoreManager.putToken(token.getBytes(), ctx); return token; } catch (JSONException e) { e.printStackTrace(); } return null; } private String createRequest(String reqMethod, String base58Body, String contentType, String dateHeader, String url) { return (reqMethod == null ? "" : reqMethod) + "\n" + (base58Body == null ? "" : base58Body) + "\n" + (contentType == null ? "" : contentType) + "\n" + (dateHeader == null ? "" : dateHeader) + "\n" + (url == null ? "" : url) + "\n"; } public String signRequest(String request) { return BRWalletManager.signString(request, KeyStoreManager.getAuthKey(ctx)); } public String sendRequest(Request request, boolean needsAuth) { String result = ""; int responseCode = 0; if (needsAuth) { Request.Builder modifiedRequest = request.newBuilder(); String base58Body = ""; if (request.body() != null) { base58Body = BRWalletManager.base58ofSha256(request.body().toString()); } SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); String httpDate = sdf.format(new Date(System.currentTimeMillis())); request = modifiedRequest.header("Date", httpDate.substring(0, httpDate.length() - 6)).build(); String requestString = createRequest(request.method(), base58Body, request.header("Content-Type"), request.header("Date"), "/me"); Log.e(TAG, "sendRequest: requestString: " + requestString); String signedRequest = signRequest(requestString); String token = new String(KeyStoreManager.getToken(ctx)); if (token.isEmpty()) token = getToken(); if (token == null || token.isEmpty()) { Log.e(TAG, "sendRequest: failed to retrieve token"); return null; } String authValue = "bread " + token + ":" + signedRequest; Log.e(TAG, "sendRequest: authValue: " + authValue); modifiedRequest = request.newBuilder(); request = modifiedRequest.header("Authorization", authValue).build(); } try { OkHttpClient client = new OkHttpClient(); Log.e(TAG, "sendRequest: dateHeader: " + request.header("Date")); Log.e(TAG, "sendRequest: Authorization: " + request.header("Authorization")); Response response = client.newCall(request).execute(); System.out.println("sendRequest: getResponseCode : " + response.code()); System.out.println("sendRequest: getResponseMessage: " + response.message()); responseCode = response.code(); result = response.body().string(); Log.e(TAG, "sendRequest: result: " + result); Log.e(TAG, "sendRequest: server date: " + response.header("Date")); } catch (IOException e) { e.printStackTrace(); } return result.isEmpty() ? String.valueOf(responseCode) : result; } public void updateBundle(Context context, String name) { if (name == null) { Log.e(TAG, "updateBundle: name is null"); return; } String bundles = "bundles"; String bundlesFileName = String.format("/%s", bundles); String bundleFileName = String.format("/%s/%s.tar", bundles, name); String bundleFileNameExtracted = String.format("/%s/%s-extracted", bundles, name); // Log.e(TAG, "updateBundle: bundlesFileName: " + bundlesFileName); // Log.e(TAG, "updateBundle: bundleFileName: " + bundleFileName); // Log.e(TAG, "updateBundle: bundleFileNameExtracted: " + bundleFileNameExtracted); File bundlesFolder = new File(context.getFilesDir().getAbsolutePath() + bundlesFileName); File bundleFile = new File(context.getFilesDir().getAbsolutePath() + bundleFileName); File bundleExtractedFolder = new File(context.getFilesDir().getAbsolutePath() + bundleFileNameExtracted); // Log.e(TAG, "updateBundle: bundlesFolder: " + bundlesFolder.toString()); // Log.e(TAG, "updateBundle: bundleFile: " + bundleFile.toString()); // Log.e(TAG, "updateBundle: bundleExtractedFolder: " + bundleExtractedFolder.toString()); // Log.e(TAG, "updateBundle: bundlesFolder.exists: " + bundlesFolder.exists()); // Log.e(TAG, "updateBundle: bundleFile.exists: " + bundleFile.exists()); // Log.e(TAG, "updateBundle: bundleExtractedFolder.exists: " + bundleExtractedFolder.exists()); FileOutputStream bundlesOutStream = null; FileOutputStream extractedOutStream = null; try { bundlesOutStream = new FileOutputStream(bundlesFolder); extractedOutStream = new FileOutputStream(bundleExtractedFolder); // outputStream.write(string.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { bundlesOutStream.close(); extractedOutStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (bundleFile.exists()) { Log.e(TAG, "updateBundle: exists, fetching diff for most recent version"); } } }
package pl.shockah.godwit; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.InputProcessor; import java.util.Comparator; import java.util.List; import javax.annotation.Nonnull; import lombok.experimental.Delegate; import pl.shockah.util.SortedLinkedList; public class InputManager { @Nonnull protected static final Comparator<Processor> orderComparator = (o1, o2) -> -Float.compare(o1.order, o2.order); @Nonnull final InputMultiplexer multiplexer = new InputMultiplexer(); @Nonnull private final List<Processor> processors = new SortedLinkedList<>(orderComparator); public void addProcessor(Processor processor) { processors.add(processor); resetupMultiplexer(); } public void removeProcessor(Processor processor) { processors.remove(processor); resetupMultiplexer(); } protected void resetupMultiplexer() { int count = multiplexer.getProcessors().size; for (int i = 0; i < count; i++) { multiplexer.removeProcessor(0); } for (Processor processor : processors) { multiplexer.addProcessor(processor); } } public static abstract class Processor implements InputProcessor { public final float order; public Processor(float order) { this.order = order; } } public static abstract class Adapter extends Processor { public Adapter(float order) { super(order); } @Override public boolean keyDown(int keycode) { return false; } @Override public boolean keyUp(int keycode) { return false; } @Override public boolean keyTyped(char character) { return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return false; } @Override public boolean mouseMoved(int screenX, int screenY) { return false; } @Override public boolean scrolled(int amount) { return false; } } public static class Delegated extends Processor { @Delegate @Nonnull public final InputProcessor delegate; public Delegated(float order, @Nonnull InputProcessor delegate) { super(order); this.delegate = delegate; } } }