answer
stringlengths
17
10.2M
package vue; import java.awt.GridLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.util.ArrayList; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTabbedPane; public class AidePanel extends UtilePanel{ String aPropos= "GestiNotes par Patrick Dominguès et Raphaël Duchaîne de InnovTech" + "\nMontréal,Québec" + "\nVersion 2 (04/11/2016)" + "\nVersion 1 (12/10/2016)" + "\n" + "\nQuand on demanda aux ingénieurs de InnovTech de concevoir le futur du gestionnaire scolaire," + "\n(un produit qui serait à la fois convivial, efficace et graphique) la majorité de ceux présents a lancé l'éponge." + "\nMais les deux qui restèrent ont vraiment fait de gros efforts pour accoucher de ce bijou de technologie."; String instructions="Pour utiliser ce bijou d'innovation, il faut savoir:" + "\n-Que chaque groupe ne peut comprendre que 10 eleves" + "\n-Qu'un eleve doit être initialisé avec nom, prenom et date " + "\n-Que l'on ne peut pas enlever d'eleve dans cette version" + "\n-Que l'aide se trouve ici" + "\n-Que 2 et 2 font 4"; //variables //Constructeur public AidePanel(UtileFrame fenetre) { super(fenetre); GridLayout gl = new GridLayout(13, 6, 0, 25); //Cree GridLayout simplePanel.setLayout(gl); addBouton("?"); addBouton("À Propos"); addBouton("Quitter"); } public AidePanel(){ this(null); } //Get-Set //toString @Override public void actionPerformed(ActionEvent event) { // Methode recoit evenement if (((JButton) event.getSource()).getText() == "Quitter") { fenetre.quitter(); } if (((JButton) event.getSource()).getText() == "?") { instructions(); } if (((JButton) event.getSource()).getText() == "À Propos") { aPropos(); } } private void aPropos() { JOptionPane.showMessageDialog(simplePanel, aPropos,"À Propos",JOptionPane.INFORMATION_MESSAGE); } //Instruction sur l'utilisation du programme private void instructions() { JOptionPane.showMessageDialog(simplePanel, instructions,"Instructions",JOptionPane.INFORMATION_MESSAGE); } //quitter le programme public void quitter() throws HeadlessException { //Permet l'arret du programme int reponse = JOptionPane.showConfirmDialog(null, "Voulez-vous vraiment quitter?", "Quitter", JOptionPane.YES_NO_OPTION); if (reponse == JOptionPane.YES_OPTION) { System.exit(0); } } }
package com.akiban.server.expression.std; import com.akiban.server.types.ValueSource; import com.akiban.server.expression.Expression; import org.junit.Test; import static org.junit.Assert.*; public class SysDateExpressionTest { @Test public void test() throws InterruptedException { ValueSource date = (new SysDateExpression().evaluation()).eval(); long dt = System.currentTimeMillis(); assertEquals("current time in seconds: " + dt, (dt)/1000, date.getTimestamp(), 1); // dt and date could be a few millisecs away } @Test public void testConst() { Expression sys = new SysDateExpression(); assertFalse("SysDateExpression is const" , sys.isConstant()); } }
package com.cobalt.cdpipeline.cdresult; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Test; import com.atlassian.bamboo.chains.ChainResultsSummary; import com.atlassian.bamboo.chains.ChainStageResult; import com.atlassian.bamboo.resultsummary.ResultsSummary; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class SetCurrentBuildInfoTest { @Test public void testWithNoBuilds() { CDResultFactory fac = new CDResultFactory("Project", "Project - Plan", createNBuildResults(0)); fac.setCurrentBuildInfo(); assertEquals("Date of cdresult's lastUpdateTime should be null (default) when there are no builds.", null, fac.cdresult.getLastUpdateTime()); assertEquals("cdresult's currentBuild should be null (default) when there are no builds.", null, fac.cdresult.getCurrentBuild()); } @Test public void testWithOnlyOneBuild() { testForNBuilds(1); } @Test public void testWithSmallNumberOfBuilds() { testForNBuilds(5); } @Test public void testWithBiggerNumberOfBuilds() { testForNBuilds(30); } // Test cdresult's lastUpdateTime and currentBuild's build-key and build-number // against the first element in the build list (assumingly the most current build). private void testForNBuilds(int N) { List<ResultsSummary> buildList = createNBuildResults(N); CDResultFactory fac = new CDResultFactory("Project", "Project - Plan", buildList); fac.setCurrentBuildInfo(); ChainResultsSummary expectedBuild = (ChainResultsSummary) buildList.get(0); assertEquals("Date of cdresult's lastUpdateTime doesn't match.", expectedBuild.getBuildCompletedDate().getTime(), fac.cdresult.getLastUpdateTime().getTime()); assertEquals("Build-key of cdresult's currentBuild doesn't match.", expectedBuild.getBuildKey(), fac.cdresult.getCurrentBuild().getBuildKey()); assertEquals("Build-number of cdresult's currentBuild doesn't match.", expectedBuild.getBuildNumber(), fac.cdresult.getCurrentBuild().getBuildNumber()); } private List<ResultsSummary> createNBuildResults(int N) { List<ResultsSummary> buildList = new ArrayList<ResultsSummary>(); for (int i = N; i >= 1; i ChainResultsSummary build = mock(ChainResultsSummary.class); when(build.getBuildCompletedDate()).thenReturn(new Date(i)); when(build.getBuildKey()).thenReturn("Build " + i); when(build.getBuildNumber()).thenReturn(i); when(build.getStageResults()).thenReturn(new ArrayList<ChainStageResult>()); buildList.add(build); } return buildList; } }
package com.github.olivergondza.dumpling.cli; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import java.io.File; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import com.github.olivergondza.dumpling.Util; import com.github.olivergondza.dumpling.TestThread; import com.github.olivergondza.dumpling.factory.ThreadDumpFactoryTest; /** * Test interoperability between groovy and groovysh command. * * @author ogondza */ @RunWith(Theories.class) public class GroovyRuntimeTest extends AbstractCliTest { @DataPoints public static String[] commands() { return new String[] {"groovy", "groovysh"}; } @Theory public void executeScript(String command) { stdin("println D.load.jvm.threads.size() instanceof Integer;%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(this, succeeded()); assertThat(out.toString().trim(), containsString("true")); } @Theory public void filter(String command) throws Exception { stdin("D.load.threaddump('" + Util.resourceFile("producer-consumer.log") + "').threads.where(nameIs('owning_thread')).collect { it.name };%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(this, succeeded()); assertThat(out.toString().trim(), containsString("[owning_thread]")); } @Theory public void loadTreaddump(String command) throws Exception { assertLoadThreaddump(command, "D.load.threaddump('%s').threads.where(nameIs('main'));%n"); } @Theory public void loadTreaddumpDolar(String command) throws Exception { assertLoadThreaddump(command, "$load.threaddump('%s').threads.where(nameIs('main'));%n"); } private void assertLoadThreaddump(String command, String script) throws Exception { File file = Util.resourceFile(ThreadDumpFactoryTest.class, "openjdk-1.7.0_60.log"); stdin(String.format(script, file.getAbsolutePath())); run(command); assertThat(exitValue, equalTo(0)); assertThat(err.toString(), isEmptyString()); assertThat(out.toString(), containsString("\"main\"")); } @Theory public void loadPid(String command) { assertLoadPid(command, "D.load.process(%d).threads.where(nameIs('remotely-observed-thread'));%n"); } @Theory public void loadPidDolar(String command) { assertLoadPid(command, "$load.process(%d).threads.where(nameIs('remotely-observed-thread'));%n"); } private void assertLoadPid(String command, String script) { thread = TestThread.runThread(); stdin(String.format(script, Util.currentPid())); run(command); assertThat(exitValue, equalTo(0)); assertThat(err.toString(), isEmptyString()); assertThat(out.toString(), containsString("\"remotely-observed-thread\"")); } @Theory public void loadPidOverJmx(String command) { assertLoadPidOverJmx(command, "D.load.jmx(%d).threads.where(nameIs('remotely-observed-thread'));%n"); } @Theory public void loadPidOverJmxDolar(String command) { assertLoadPidOverJmx(command, "$load.jmx(%d).threads.where(nameIs('remotely-observed-thread'));%n"); } private void assertLoadPidOverJmx(String command, String script) { thread = TestThread.runThread(); stdin(String.format(script, Util.currentPid())); run(command); assertThat(exitValue, equalTo(0)); assertThat(err.toString(), isEmptyString()); assertThat(out.toString(), containsString("\"remotely-observed-thread\"")); } @Theory public void loadJmx(String command) throws Exception { assertLoadJmx(command, "println D.load.jmx('%s').threads.where(nameIs('remotely-observed-thread'));%n"); } @Theory public void loadJmxDolar(String command) throws Exception { assertLoadJmx(command, "println $load.jmx('%s').threads.where(nameIs('remotely-observed-thread'));%n"); } private void assertLoadJmx(String command, String script) throws Exception { process = TestThread.runJmxObservableProcess(false); stdin(String.format(script, TestThread.JMX_CONNECTION)); run(command); assertThat(exitValue, equalTo(0)); assertThat(err.toString(), isEmptyString()); assertThat(out.toString(), containsString("\"remotely-observed-thread\"")); } @Theory public void loadSymbolsFromOtherDumplingPackages(String command) { stdin("new Deadlocks(); ThreadStatus.valueOf(0); new JvmRuntimeFactory(); new CommandFailedException('');%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(this, succeeded()); } @Theory public void failTheScript(String command) { stdin("new ThereIsNoSuchClass();%n"); run(command); assertThat(err.toString(), containsString("unable to resolve class ThereIsNoSuchClass")); } @Theory public void printToOutAndErr(String command) { stdin("out.println('stdout content'); err.println('stderr content');%n"); run(command); assertThat(exitValue, equalTo(0)); assertThat(err.toString(), containsString("stderr content")); assertThat(out.toString(), containsString("stdout content")); } @Theory public void groovyGrep(String command) { stdin("print D.load.jvm.threads.grep().getClass();%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyGrepWithArg(String command) { stdin("print D.load.jvm.threads.grep { it.name == 'blocked_thread' }.getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyFindAll(String command) { stdin("print D.load.jvm.threads.findAll().getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyFindAllWithArg(String command) { stdin("print D.load.jvm.threads.findAll { it.name == 'blocked_thread' }.getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyAsImmutable(String command) { stdin("print D.load.jvm.threads.asImmutable().getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyIntersect(String command) { stdin("rt = D.load.jvm; print rt.threads.intersect(rt.threads).getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyPlus(String command) { stdin("rt = D.load.jvm; threadSum = rt.threads + rt.threads; print threadSum.getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void groovyToSet(String command) { stdin("print D.load.jvm.threads.toSet().getClass()%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("class com.github.olivergondza.dumpling.model.jvm.JvmThreadSet")); assertThat(this, succeeded()); } @Theory public void stateFilter(String command) { String choices = "it.status.new || it.status.runnable || it.status.sleeping || it.status.waiting || it.status.parked || it.status.blocked || it.status.terminated"; stdin("print D.load.jvm.threads.grep { " + choices + " }.empty%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("false")); assertThat(this, succeeded()); } @Theory public void cliArguments(String command) { stdin("print \"${D.args[1]} ${D.args[0]}!\"%n"); run(command, "World", "Hello"); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("Hello World!")); assertThat(this, succeeded()); } @Theory public void help(String command) { stdin("print D%n"); run(command); assertThat(err.toString(), equalTo("")); assertThat(out.toString(), containsString("D.args: java.util.List%n CLI arguments passed to the script")); assertThat(out.toString(), containsString("D.load.threaddump(String): com.github.olivergondza.dumpling.model.ProcessRuntime")); assertThat(this, succeeded()); } }
package com.imcode.imcms.controller.api; import com.imcode.imcms.components.datainitializer.CategoryDataInitializer; import com.imcode.imcms.components.datainitializer.DocumentDataInitializer; import com.imcode.imcms.components.datainitializer.UserDataInitializer; import com.imcode.imcms.config.TestConfig; import com.imcode.imcms.config.WebTestConfig; import com.imcode.imcms.controller.AbstractControllerTest; import com.imcode.imcms.domain.dto.*; import com.imcode.imcms.domain.exception.DocumentNotExistException; import com.imcode.imcms.domain.service.*; import com.imcode.imcms.mapping.jpa.User; import com.imcode.imcms.model.Role; import com.imcode.imcms.model.TextDocumentTemplate; import com.imcode.imcms.persistence.entity.Meta; import com.imcode.imcms.persistence.entity.Meta.Permission; import imcode.server.Imcms; import imcode.server.document.NoPermissionToEditDocumentException; import imcode.server.user.RoleId; import imcode.server.user.UserDomainObject; import org.apache.commons.lang3.NotImplementedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.transaction.annotation.Transactional; import java.io.File; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.DO_NOT_SHOW; import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE; import static org.junit.Assert.*; @Transactional @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class, WebTestConfig.class}) public class DocumentControllerTest extends AbstractControllerTest { private TextDocumentDTO createdTextDoc; @Autowired private DocumentDataInitializer documentDataInitializer; @Autowired private UserDataInitializer userDataInitializer; @Autowired private CategoryDataInitializer categoryDataInitializer; @Autowired private CategoryService categoryService; @Autowired private TextDocumentTemplateService textDocumentTemplateService; @Autowired private TemplateService templateService; @Autowired private CommonContentService commonContentService; @Autowired private RoleService roleService; @Override protected String controllerPath() { return "/documents"; } @Before public void setUp() throws Exception { createdTextDoc = documentDataInitializer.createTextDocument(); final UserDomainObject user = new UserDomainObject(1); user.addRoleId(RoleId.SUPERADMIN); Imcms.setUser(user); // means current user is admin now } @Test public void getDocument() throws Exception { final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void getDocument_When_NotExist_Expect_Correct_Exception() throws Exception { final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + ((Long) System.currentTimeMillis()).intValue()); performRequestBuilderExpectException(DocumentNotExistException.class, requestBuilder); } @Test public void get_When_IdIsNull_Expect_DefaultEmptyTextDocumentDtoReturned() throws Exception { final Meta.DocumentType documentType = Meta.DocumentType.TEXT; final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("type", "" + documentType); final String response = getJsonResponse(requestBuilder); final TextDocumentDTO documentDTO = fromJson(response, TextDocumentDTO.class); assertNull(documentDTO.getId()); assertEquals(documentDTO.getType(), documentType); assertFalse(documentDTO.getCommonContents().isEmpty()); assertEquals(documentDTO.getCommonContents(), commonContentService.createCommonContents()); assertEquals(documentDTO.getPublicationStatus(), Meta.PublicationStatus.NEW); assertEquals(documentDTO.getTemplate(), TextDocumentTemplateDTO.createDefault()); } @Test public void saveDocument_When_NoChanges_Expect_NoError() throws Exception { performPostWithContentExpectOk(createdTextDoc); } @Test public void save_When_UserNotAdmin_Expect_NoPermissionToEditDocumentException() throws Exception { final UserDomainObject user = new UserDomainObject(1); user.addRoleId(RoleId.USERS); Imcms.setUser(user); // means current user is not admin now performPostWithContentExpectException(createdTextDoc, NoPermissionToEditDocumentException.class); } @Test public void save_With_Target_Expected_Saved() throws Exception { createdTextDoc.setTarget("test"); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CustomCommonContentsSet_Expect_Saved() throws Exception { final List<CommonContentDTO> commonContents = createdTextDoc.getCommonContents(); for (int i = 0; i < commonContents.size(); i++) { CommonContentDTO commonContentDTO = commonContents.get(i); commonContentDTO.setHeadline("Test headline " + i); commonContentDTO.setMenuText("Test menu text " + i); commonContentDTO.setMenuImageURL("Test menu image url " + i); commonContentDTO.setEnabled((i % 2) == 0); } performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_TargetAndAliasChanged_Expect_Saved() throws Exception { final String newTarget = "_blank"; final String newAlias = "test-alias"; createdTextDoc.setTarget(newTarget); createdTextDoc.setAlias(newAlias); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_DifferentPublicationStatusSet_Expect_Saved() throws Exception { final Meta.PublicationStatus statusApproved = Meta.PublicationStatus.APPROVED; final Meta.PublicationStatus statusDisapproved = Meta.PublicationStatus.DISAPPROVED; final Meta.PublicationStatus statusNew = Meta.PublicationStatus.NEW; final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); // approved createdTextDoc.setPublicationStatus(statusApproved); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); // disapproved createdTextDoc.setPublicationStatus(statusDisapproved); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); // new createdTextDoc.setPublicationStatus(statusNew); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CreatedAndModifiedAndArchivedAndPublishedAndDepublishedAttributesSet_Expect_Saved() throws Exception { final User user = userDataInitializer.createData("testUser"); final Supplier<AuditDTO> auditCreator = () -> { final AuditDTO auditDTO = new AuditDTO(); auditDTO.setDateTime(new Date()); auditDTO.setId(user.getId()); auditDTO.setBy(user.getLogin()); return auditDTO; }; final AuditDTO createdAudit = auditCreator.get(); final AuditDTO modifiedAudit = auditCreator.get(); final AuditDTO archivedAudit = auditCreator.get(); final AuditDTO publishedAudit = auditCreator.get(); final AuditDTO depublishedAudit = auditCreator.get(); createdTextDoc.setCreated(createdAudit); createdTextDoc.setModified(modifiedAudit); createdTextDoc.setArchived(archivedAudit); createdTextDoc.setPublished(publishedAudit); createdTextDoc.setPublicationEnd(depublishedAudit); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); // only for nullable things final AuditDTO emptyArchivedAudit = new AuditDTO(); final AuditDTO emptyPublishedAudit = new AuditDTO(); final AuditDTO emptyDepublishedAudit = new AuditDTO(); createdTextDoc.setArchived(emptyArchivedAudit); createdTextDoc.setPublished(emptyPublishedAudit); createdTextDoc.setPublicationEnd(emptyDepublishedAudit); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CustomMissingLanguagePropertySet_Expect_Saved() throws Exception { createdTextDoc.setDisabledLanguageShowMode(SHOW_IN_DEFAULT_LANGUAGE); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); createdTextDoc.setDisabledLanguageShowMode(DO_NOT_SHOW); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CustomKeywordsSet_Expect_Saved() throws Exception { final Set<String> keywords = new HashSet<>(); keywords.add("test keyword 1"); keywords.add("test keyword 2"); keywords.add("test keyword 3"); keywords.add("test keyword 4"); keywords.add("test keyword 5"); keywords.add("test keyword 6"); createdTextDoc.setKeywords(keywords); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); final int prevSize = keywords.size(); keywords.remove("test keyword 1"); assertEquals(keywords.size() + 1, prevSize); createdTextDoc.setKeywords(keywords); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_SearchEnabledAndDisabled_Expect_Saved() throws Exception { createdTextDoc.setSearchDisabled(true); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); createdTextDoc.setSearchDisabled(false); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CategoriesIsSet_Expect_Saved() throws Exception { categoryDataInitializer.createData(50); final Set<CategoryDTO> categories = categoryService.getAll().stream() .filter(categoryDTO -> categoryDTO.getId() % 2 == 0) .map(CategoryDTO::new) .collect(Collectors.toSet()); createdTextDoc.setCategories(categories); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); final Set<CategoryDTO> categories1 = categoryService.getAll().stream() .filter(categoryDTO -> categoryDTO.getId() % 2 == 1) .map(CategoryDTO::new) .collect(Collectors.toSet()); createdTextDoc.setCategories(categories1); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CustomAccessRulesSet_Expect_Saved() throws Exception { final Map<Integer, Permission> roleIdToPermission = new HashMap<>(); for (Permission permission : Permission.values()) { final Role role = roleService.save(new RoleDTO(null, "test_role_" + permission)); roleIdToPermission.put(role.getId(), permission); } createdTextDoc.setRoleIdToPermission(roleIdToPermission); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); final Map<Integer, Permission> roleIdToPermission1 = new HashMap<>(); createdTextDoc.setRoleIdToPermission(roleIdToPermission1); performPostWithContentExpectOk(createdTextDoc); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_RestrictedPermissionsSet_Expect_Saved() throws Exception { final Set<RestrictedPermissionDTO> restrictedPermissions = new HashSet<>(); final RestrictedPermissionDTO restricted1 = new RestrictedPermissionDTO(); restricted1.setPermission(Permission.RESTRICTED_1); restricted1.setEditDocInfo(true); restricted1.setEditImage(false); restricted1.setEditLoop(true); restricted1.setEditMenu(false); restricted1.setEditText(true); final RestrictedPermissionDTO restricted2 = new RestrictedPermissionDTO(); restricted2.setPermission(Permission.RESTRICTED_2); restricted2.setEditDocInfo(false); restricted2.setEditImage(true); restricted2.setEditLoop(false); restricted2.setEditMenu(true); restricted2.setEditText(false); restrictedPermissions.add(restricted1); restrictedPermissions.add(restricted2); createdTextDoc.setRestrictedPermissions(restrictedPermissions); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } @Test public void save_When_CustomTemplateSet_Expect_Saved() throws Exception { final String templateName = "test_" + System.currentTimeMillis(); final int docId = createdTextDoc.getId(); final File templateDirectory = templateService.getTemplateDirectory(); final File templateFile = new File(templateDirectory, templateName + ".jsp"); try { assertTrue(templateFile.createNewFile()); final TemplateDTO template = new TemplateDTO(templateName, false); templateService.save(template); final TextDocumentTemplateDTO templateDTO = new TextDocumentTemplateDTO(docId, templateName, templateName); final TextDocumentTemplate savedTemplate = textDocumentTemplateService.save(templateDTO); assertNotNull(savedTemplate); createdTextDoc.setTemplate(templateDTO); performPostWithContentExpectOk(createdTextDoc); final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) .param("docId", "" + createdTextDoc.getId()); performRequestBuilderExpectedOkAndJsonContentEquals(requestBuilder, asJson(createdTextDoc)); } finally { assertTrue(templateFile.delete()); } } @Test public void delete_When_UserIsNotAdmin_Expect_NoPermissionToEditDocumentException() throws Exception { final UserDomainObject user = new UserDomainObject(1); user.addRoleId(RoleId.USERS); Imcms.setUser(user); // means current user is not admin now performDeleteWithContentExpectException(createdTextDoc, NotImplementedException.class); } @Test public void delete_When_DocumentExistAndUserIsAdmin_Expect_NoError() throws Exception { performDeleteWithContentExpectException(createdTextDoc, NotImplementedException.class); // todo: change when will be implemented to this: // final MockHttpServletRequestBuilder requestBuilder = getDeleteRequestBuilderWithContent(createdDoc); // performRequestBuilderExpectedOk(requestBuilder); } // todo: uncomment when docs deletion will be needed // @Test // public void delete_When_DocumentExistAndUserIsAdmin_Expect_DocumentNotExistExceptionAfterDeletion() throws Exception { // delete_When_DocumentExistAndUserIsAdmin_Expect_NoError(); // final MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(controllerPath()) // .param("docId", "" + createdDoc.getId()); // performRequestBuilderExpectException(DocumentNotExistException.class, requestBuilder); }
package com.ociweb.gl.example.parallel; import org.junit.Test; import com.ociweb.gl.api.GreenRuntime; import com.ociweb.gl.test.ParallelClientLoadTester; import com.ociweb.gl.test.ParallelClientLoadTesterConfig; import com.ociweb.gl.test.ParallelClientLoadTesterPayload; public class NamedMessagePassingTest { @Test public void runTest() { //order supervisor blocks because it must have 1 incoming pipe for each //of the N unit pipes coming in or data can be hidden !!! //need more threads for volume?? boolean telemetry = true; GreenRuntime.run(new NamedMessagePassingApp(telemetry)); ParallelClientLoadTesterPayload payload = new ParallelClientLoadTesterPayload("{\"key1\":\"value\",\"key2\":123}"); ParallelClientLoadTesterConfig config1 = new ParallelClientLoadTesterConfig(8, 2000, 8080, "/test", false); GreenRuntime.testConcurrentUntilShutdownRequested( new ParallelClientLoadTester(config1, null), 200_000); ParallelClientLoadTesterConfig config2 = new ParallelClientLoadTesterConfig(16, 10_000, 8080, "/test", telemetry); config2.simultaneousRequestsPerTrackBits = 5; config2.responseTimeoutNS = 1_000_000_000L; config2.rate = 10_000L; config2.ensureLowLatency = false; GreenRuntime.testConcurrentUntilShutdownRequested( new ParallelClientLoadTester(config2, null), 200_000); } }
import java.util.*; class Main { public static HashMap<String, String> lista = new HashMap<>(); private static void Put(String teste, String outra) { for (int i = 0; i < 100000; i++) if (lista.containsKey("antonio")) lista.put(teste, outra); } private static void Replace(String teste, String outra) { for (int i = 0; i < 100000; i++) lista.replace(teste, outra); } public static void main(String[] args) { long inicio = System.currentTimeMillis(); Put("antonio", "antonio"); System.out.println("Put: " + (System.currentTimeMillis() - inicio) + " ms"); inicio = System.currentTimeMillis(); Replace("antonio", "antonio"); System.out.println("Replace: " + (System.currentTimeMillis() - inicio) + " ms"); } }
package org.mskcc.shenkers.control.alignment; import org.mskcc.shenkers.control.alignment.LocalAlignment; import htsjdk.samtools.SAMSequenceDictionary; import htsjdk.samtools.liftover.ChainParser; import htsjdk.samtools.util.Interval; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.zip.GZIPInputStream; import javafx.util.Pair; import org.apache.commons.lang3.StringUtils; import org.mskcc.shenkers.model.datatypes.GenomeSpan; import static org.testng.Assert.*; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * * @author Soma */ public class ChainParserNGTest { public ChainParserNGTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { } @AfterMethod public void tearDownMethod() throws Exception { } /** * * @param s * @param e * @param start * @param eend * @return whether (s,e) is nested within (start,end) */ public static boolean isContained(int s, int e, int start, int end) { return s > start - 1 && e < end + 1 && s < e + 1; } /** * * @param s * @param e * @param start * @param eend * @return whether (s,e) is nested within (start,end) */ public static boolean overlaps(int s, int e, int start, int end) { return (s > start - 1 && s < end + 1) || (e > start - 1 && e < end + 1) || (start > s - 1 && end < e + 1); } public static int[] intersection(int s1, int e1, int s2, int e2) { if (!overlaps(s1, e1, s2, e2)) { throw new RuntimeException(String.format("intervals (%d,%d) and (%d,%d) do not overlap", s1, e1, s2, e2)); } return new int[]{Math.max(s1, s2), Math.min(e1, e2)}; } public static LocalAlignment trim(LocalAlignment blocks, Interval query_i, Interval target_i) { List<Pair<Integer, Integer>> fromBlocks = new ArrayList<>(); List<Pair<Integer, Integer>> toBlocks = new ArrayList<>(); for (int i = 0; i < blocks.fromBlocks.size(); i++) { Pair<Integer, Integer> fromBlock = blocks.fromBlocks.get(i); Pair<Integer, Integer> toBlock = blocks.toBlocks.get(i); assert isContained(fromBlock.getKey(), fromBlock.getValue(), query_i.getStart(), query_i.getEnd()) : "it is assumed that all blocks in query will be contained in the query interval"; // if this block overlaps it is either OK as is, or needs to be trimmed if (overlaps(toBlock.getKey(), toBlock.getValue(), target_i.getStart(), target_i.getEnd())) { if (isContained(toBlock.getKey(), toBlock.getValue(), target_i.getStart(), target_i.getEnd())) { fromBlocks.add(fromBlock); toBlocks.add(toBlock); } else { int offsetTargetStart = toBlock.getKey() < target_i.getStart() ? target_i.getStart() - toBlock.getKey() : 0; int offsetTargetEnd = toBlock.getValue() > target_i.getEnd() ? toBlock.getKey() - target_i.getEnd() : 0; Pair<Integer, Integer> offsetToBlock = new Pair<>(toBlock.getKey() + offsetTargetStart, toBlock.getValue() - offsetTargetEnd); Pair<Integer, Integer> offsetFromBlock = blocks.toNegativeStrand ? new Pair<>(fromBlock.getKey() + offsetTargetEnd, fromBlock.getValue() - offsetTargetStart) : new Pair<>(fromBlock.getKey() + offsetTargetStart, fromBlock.getValue() - offsetTargetEnd) ; fromBlocks.add(offsetFromBlock); toBlocks.add(offsetToBlock); } } } return new LocalAlignment(blocks.fromSequenceName, blocks.toSequenceName, blocks.toNegativeStrand, fromBlocks, toBlocks); } /** * Test of getChainIntersections method, of class ChainParser. */ @Test public void testGetChainIntersections() throws FileNotFoundException { // File f = new File("/home/sol/Downloads/dm3.droYak2.chain"); File f = new File("/home/sol/Downloads/dm3.droYak2.chain"); // Scanner scan = new Scanner(f); // int i=0; // int j=0; // PrintStream out = new PrintStream(new File("C:/Users/sol/Downloads/dm3.droYak2.chain")); // while(scan.hasNext()){ // String line = scan.nextLine(); // System.out.println(i+"\t"+line); // if(i==185681) // break; // out.println(line); // out.close(); // System.exit(0); // chrX:411720-413080 // chr3R 27905053 28832112 // chain 747933599 chr3R 27905053 + 46 27900188 chr3R 28832112 + 366441 28829329 2 // chr3R:9536-9791 // 90 chain 970691389 chr3L 24543557 + 43412 23775837 chr3L 24197627 + 750 24183090 1 //chr3L:74548-74869 Interval interval = new Interval("chr3L", 74548, 74869); System.out.println("loading chain file"); ChainParser instance = new ChainParser(f); System.out.println("calculating intersections"); List<LocalAlignment> chainIntersections = instance.getChainIntersections(interval); for (LocalAlignment blocks : chainIntersections) { // chr3L:74548-74869 //chr3L:42085-42438 blocks = trim(blocks, new Interval("chr3L", 74548, 74869), new Interval("chr3L", 42088, 42438)); StringBuilder gapped1 = new StringBuilder(); StringBuilder gapped2 = new StringBuilder(); gapped1.append(StringUtils.repeat("X", blocks.blockSizes.get(0))); gapped2.append(StringUtils.repeat("X", blocks.blockSizes.get(0))); int last1 = blocks.fromBlocks.get(0).getValue(); int last2 = blocks.toNegativeStrand ? blocks.toBlocks.get(0).getKey() : blocks.toBlocks.get(0).getValue(); for (int i = 1; i < blocks.fromBlocks.size(); i++) { System.out.println(String.format("%s:%d-%d %d", blocks.fromSequenceName, blocks.fromBlocks.get(i).getKey(), blocks.fromBlocks.get(i).getValue(), blocks.fromBlocks.get(i).getValue() - blocks.fromBlocks.get(i).getKey())); System.out.println(String.format("%s:%d-%d %d", blocks.toSequenceName, blocks.toBlocks.get(i).getKey(), blocks.toBlocks.get(i).getValue(), blocks.toBlocks.get(i).getValue() - blocks.toBlocks.get(i).getKey())); System.err.println(""); gapped1.append(StringUtils.repeat("X", blocks.fromBlocks.get(i).getKey() - last1 - 1)); gapped2.append(StringUtils.repeat("-", blocks.fromBlocks.get(i).getKey() - last1 - 1)); int gap2 = blocks.toNegativeStrand ? last2 - blocks.toBlocks.get(i).getValue() - 1 : blocks.toBlocks.get(i).getKey() - last2 - 1; gapped2.append(StringUtils.repeat("X", gap2)); gapped1.append(StringUtils.repeat("-", gap2)); gapped1.append(StringUtils.repeat("X", blocks.blockSizes.get(i))); gapped2.append(StringUtils.repeat("X", blocks.blockSizes.get(i))); last1 = blocks.fromBlocks.get(i).getValue(); last2 = blocks.toNegativeStrand ? blocks.toBlocks.get(i).getKey() : blocks.toBlocks.get(i).getValue(); } System.out.println(gapped1.toString()); System.out.println(gapped2.toString()); System.out.println(gapped1.toString().replaceAll("-", "").length()); System.out.println(gapped2.toString().replaceAll("-", "").length()); System.out.println(74869 - 74548 + 1); System.out.println(42438 - 42085 + 1); } // chr3L:74548-74869 //chr3L:42085-42438 System.out.println(chainIntersections.size()); // List expResult = null; // List result = instance.getChainIntersections(interval); // assertEquals(result, expResult); // // TODO review the generated test code and remove the default call to fail. // fail("The test case is a prototype."); ; } }
package org.skife.muckery.jdbi.immutables; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.hubspot.rosetta.jdbi.RosettaMapperFactory; import com.hubspot.rosetta.jdbi.RosettaObjectMapperOverride; import org.immutables.value.Value; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.muckery.jdbi.H2Rule; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class ImmutableMappingTest { @Rule public final H2Rule h2 = new H2Rule(); private DBI dbi; @Before public void setUp() throws Exception { this.dbi = new DBI(this.h2); try (Handle h = this.dbi.open()) { h.execute("create table something (id int primary key, name varchar) "); } } @Test public void testExplicit() throws Exception { try (Handle h = this.dbi.open()) { h.execute("insert into something (id, name) values (1, 'Brian'), (2, 'Derrick'), (3, 'Francisco')"); final List<Something> rs = h.createQuery("select id, name from something order by id") .map((_i, r, _c) -> Something.create(r.getInt("id"), r.getString("name"))) .list(); assertThat(rs).containsExactly(Something.create(1, "Brian"), Something.create(2, "Derrick"), Something.create(3, "Francisco")); } } @Test public void testWithRosetta() throws Exception { try (Handle h = this.dbi.open()) { rosetify(h); h.execute("insert into something (id, name) values (1, 'Brian'), (2, 'Derrick'), (3, 'Francisco')"); final List<Something> rs = h.createQuery("select id, name from something order by id") .mapTo(Something.class) .list(); assertThat(rs).containsExactly(Something.create(1, "Brian"), Something.create(2, "Derrick"), Something.create(3, "Francisco")); } } @Test public void testJacksonStuff() throws Exception { final ObjectMapper mapper = new ObjectMapper(); mapper.readValue("{\"name\":\"Tatu\",\"id\":\"42\"}", Something.class); } @Value.Immutable @JsonDeserialize(as = ImmutableSomething.class) interface Something { Integer id(); String name(); static ImmutableSomething.Builder builder() { return ImmutableSomething.builder(); } static Something create(final int id, final String name) { return ImmutableSomething.builder().id(id).name(name).build(); } } private static void rosetify(final Handle h) { new RosettaObjectMapperOverride(new ObjectMapper().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)) .override(h); h.registerMapper(new RosettaMapperFactory()); } }
package uk.co.jamiecruwys; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.Collections; import java.util.List; import uk.co.jamiecruwys.statefulview.R; public abstract class StatefulListingFragment<ITEM_TYPE> extends StatefulFragment<ITEM_TYPE> { private static final String SAVED_LAYOUT_MANAGER = "saved_layout_manager"; protected RecyclerView recycler; protected RecyclerView.Adapter adapter; private Parcelable savedLayoutManager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); recycler = (RecyclerView)view.findViewById(R.id.recycler); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState == null) { refresh(Collections.EMPTY_LIST); } else { savedLayoutManager = savedInstanceState.getParcelable(SAVED_LAYOUT_MANAGER); } } public void refresh(@NonNull List<ITEM_TYPE> items) { recycler.setLayoutManager(provideLayoutManager()); adapter = provideAdapter(items); recycler.setAdapter(adapter); RecyclerView.ItemDecoration itemDecoration = provideItemDecoration(); if (itemDecoration != null) { recycler.addItemDecoration(itemDecoration); } recycler.getLayoutManager().onRestoreInstanceState(savedLayoutManager); } @Override public int provideLoadedLayout() { return R.layout.stateful_listing; } /** * Provide the layout manager to use for the listing * * @return {@link android.support.v7.widget.RecyclerView.LayoutManager} to use for the listing */ @NonNull protected RecyclerView.LayoutManager provideLayoutManager() { return new LinearLayoutManager(getContext()); } /** * Provide the adapter to use for the listing * * @param items to seed the adapter with * * @return {@link RecyclerView.Adapter} to use for the listing */ @NonNull protected abstract RecyclerView.Adapter provideAdapter(@NonNull List<ITEM_TYPE> items); /** * Provide any item decoration you want applied to the listing * * @return {@link android.support.v7.widget.RecyclerView.ItemDecoration} you want applied to the listing */ @Nullable protected RecyclerView.ItemDecoration provideItemDecoration() { return null; } @Override public void onListingDataRetrieved(@NonNull List<ITEM_TYPE> items) { // Do not continue if the fragment is detached from an activity if (!isAdded() || getActivity() == null) { return; } super.onListingDataRetrieved(items); refresh(items); } @Override public void onSaveInstanceState(Bundle outState) { outState.putParcelable(SAVED_LAYOUT_MANAGER, recycler.getLayoutManager().onSaveInstanceState()); super.onSaveInstanceState(outState); } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListModel; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListModel; import javax.swing.SortOrder; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.hyperlink.EditorPaneLinkVisitor; import org.jdesktop.swingx.hyperlink.LinkModel; import org.jdesktop.swingx.hyperlink.LinkModelAction; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.treetable.FileSystemModel; /** * Test of JXHyperlink visuals. Raw usage and as hyperlinkRenderer. * <p> * * @author Jeanette Winzenburg */ public class JXHyperlinkVisualCheck extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXHyperlinkVisualCheck.class .getName()); public JXHyperlinkVisualCheck() { super("JXHyperlinkLabel Test"); } public static void main(String[] args) throws Exception { JXHyperlinkVisualCheck test = new JXHyperlinkVisualCheck(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Table.*"); // test.runInteractiveTests("interactive.*List.*"); // test.runInteractiveTests("interactive.*Tree.*"); // test.runInteractiveTests("interactive.*Underline.*"); test.runInteractive("Link"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #6-swingx: convenience api for setting uri's * @throws URISyntaxException */ public void interactiveHyperlinkURI() throws URISyntaxException { JXHyperlink link = new JXHyperlink(); URI uri = new URI("mailto:java-net@java.sun.com"); link.setURI(uri); showInFrame(link, "uri"); } /** * Issue #441-swingx: underline not showing for html text. * While text wrapping as such is working with html text the * underline is only under the last line. */ public void interactiveHtmlUnderlineWrapping() { Action action = new AbstractAction("<html><b><i>Bold Italic Link and another loong way way out part of the text</i></b></html>") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; JXHyperlink hyperlink = new JXHyperlink(action ); // hyperlink.setMargin(new Insets(10, 10, 10, 10)); hyperlink.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JFrame frame = wrapInFrame(hyperlink, "show html underline "); frame.setSize(200, 200); frame.setVisible(true); } /** * Issue #441-swingx: underline not showing for html text. * */ public void interactiveHtmlUnderlineButton() { Action action = new AbstractAction("<html><b><i>Bold Italic Link</i></b></html>") { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; JXHyperlink hyperlink = new JXHyperlink(action ); // hyperlink.setMargin(new Insets(10, 10, 10, 10)); hyperlink.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JFrame frame = wrapInFrame(hyperlink, "show html underline "); frame.setSize(200, 200); frame.setVisible(true); } /** * visually check how differently configured buttons behave on * clicked. * */ public void interactiveCompareClicked() { JComponent box = Box.createVerticalBox(); JXHyperlink noActionHyperlink = new JXHyperlink(); noActionHyperlink.setText("have no action - auto-click"); box.add(noActionHyperlink); AbstractHyperlinkAction<?> doNothingAction = createEmptyLinkAction("have do nothing action - follow action"); JXHyperlink doNothingActionHyperlink = new JXHyperlink(doNothingAction); box.add(doNothingActionHyperlink); AbstractHyperlinkAction<?> doNothingAction2 = createEmptyLinkAction("have do nothing action - overrule"); JXHyperlink overruleActionHyperlink = new JXHyperlink(doNothingAction2); overruleActionHyperlink.setOverrulesActionOnClick(true); box.add(overruleActionHyperlink); JXFrame frame = wrapInFrame(box, "compare clicked control"); frame.setVisible(true); } public void interactiveUnderlineButton() { Action action = new AbstractAction("LinkModel@somewhere") { public void actionPerformed(ActionEvent e) { LOG.info("gotcha!"); } }; JXHyperlink hyperlink = new JXHyperlink(action ); // JButton hyperlink = new JButton("LinkModel somewhere"); // hyperlink.setMargin(new Insets(10, 10, 10, 10)); hyperlink.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JXPanel panel = new JXPanel(new BorderLayout()); panel.add(hyperlink); panel.add(new JLabel("south"), BorderLayout.SOUTH); panel.add(new JLabel("north"), BorderLayout.NORTH); JFrame frame = wrapInFrame(panel, "show underline - no link action"); frame.setSize(200, 200); frame.setVisible(true); } public void interactiveLink() throws Exception { JXEditorPane pane = new JXEditorPane(); pane.setEditable(false); EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(pane); LinkModel localLink = new LinkModel("Click me! - local text", null, JXEditorPaneTest.class.getResource("resources/test.html")); LinkModelAction<?> localAction = new LinkModelAction<LinkModel>(localLink, visitor); JXHyperlink localHyperlink = new JXHyperlink(localAction); LinkModel externalLink = new LinkModel("Click me! - external text", null, new URL("http://swingx.java.net")); LinkModelAction<?> externalAction = new LinkModelAction<LinkModel>(externalLink, visitor); JXHyperlink externalHyperlink = new JXHyperlink(externalAction); JPanel panel = new JPanel(new BorderLayout()); panel.add(new JScrollPane(visitor.getOutputComponent())); panel.add(externalHyperlink, BorderLayout.NORTH); panel.add(localHyperlink, BorderLayout.SOUTH); JFrame frame = wrapInFrame(panel, "simple hyperlink"); frame.setSize(200, 200); frame.setVisible(true); } public void interactiveTreeLinkRendererSimpleText() { AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTree tree = new JXTree(new FileSystemModel()); tree.setRolloverEnabled(true); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.setCellRenderer(new DefaultTreeRenderer(provider)); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "tree and simple links"); frame.setVisible(true); } /** * Table url activation, disabled tooltips. */ public void interactiveTableHyperlinkNoTooltip() { JXTable table = new JXTable(createModelWithLinks()); EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); LinkModelAction<?> action = new LinkModelAction<LinkModel>(visitor) { @Override protected void updateFromTarget() { super.updateFromTarget(); putValue(Action.SHORT_DESCRIPTION, null); } }; // set the default renderer for LinkModel - which is basically // a bean wrapped around an URL table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer (new HyperlinkProvider(action, LinkModel.class))); JXFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "table and simple links"); frame.setVisible(true); } /** * Table with both simple "hyperlinks" targets and url activation. */ public void interactiveTableHyperlinkSimpleText() { JXTable table = new JXTable(createModelWithLinks()); EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); LinkModelAction<?> action = new LinkModelAction<LinkModel>(visitor); // set the default renderer for LinkModel - which is basically // a bean wrapped around an URL table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer (new HyperlinkProvider(action, LinkModel.class))); // JW: editor mis-use is not recommended but possible... // the LinkRenderer in its role as editor is not yet deprecated but should // soon. Without registering a specialized editor the column should // not editable - otherwise the "normal" default editor would jump in // LinkModelAction action2 = new LinkModelAction<LinkModel>(visitor); // table.setDefaultEditor(LinkModel.class, new LinkRenderer(action2, LinkModel.class)); // simple activatable action on the target in the first column AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; // the action will be activated only if the column is not-editable // here that's done in the model // TODO JW: revisit table.getColumn(0).setCellRenderer(new DefaultTableRenderer( new HyperlinkProvider(simpleAction))); JXFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "table and simple links"); frame.setVisible(true); } /** * Check visuals of hyperlink and highlighter. * Issue #513-swingx: no rollover effect for disabled table. * Hyperlink is disabled automatically by DefaultVisuals, no need * to disable the xxRolloverController. * */ public void interactiveTableHyperlinkLFStripingHighlighter() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); final JXTable table = new JXTable(createModelWithLinks()); LinkModelAction<?> action = new LinkModelAction<LinkModel>(visitor); table.setDefaultRenderer(LinkModel.class, new DefaultTableRenderer (new HyperlinkProvider(action, LinkModel.class))); table.setHighlighters(HighlighterFactory.createSimpleStriping()); Action enabled = new AbstractAction("toggle table enabled") { public void actionPerformed(ActionEvent e) { table.setEnabled(!table.isEnabled()); } }; JXFrame frame = wrapWithScrollingInFrame(table, visitor.getOutputComponent(), "show link renderer in table with LF striping highlighter"); addAction(frame, enabled); frame.setVisible(true); } /** * Custom link target action in JXList. */ public void interactiveListHyperlikPlayer() { AbstractHyperlinkAction<Player> linkAction = new AbstractHyperlinkAction<Player>() { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } @Override protected void installTarget() { setName(getTarget() != null ? getTarget().name : ""); } }; JXList list = new JXList(createPlayerModel(), true); list.setRolloverEnabled(true); // descending order - check if the action is performed for the // correct value list.setSortOrder(SortOrder.DESCENDING); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(linkAction, Player.class))); JFrame frame = wrapWithScrollingInFrame(list, "show simple bean link renderer in list"); frame.setVisible(true); } private ListModel createPlayerModel() { DefaultListModel model = new DefaultListModel(); model.addElement(new Player("Henry", 10)); model.addElement(new Player("Berta", 112)); model.addElement(new Player("Dave", 20)); return model; } public static class Player { String name; int score; public Player(String name, int score) { this.name = name; this.score = score; } @Override public String toString() { return name + " has score: " + score; } } /** * Simple target action. * */ public void interactiveListHyperlinkSimpleText() { AbstractHyperlinkAction<Object> linkAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXList list = new JXList(createTextOnlyListModel(20)); list.setRolloverEnabled(true); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(linkAction))); JFrame frame = wrapWithScrollingInFrame(list, "show simple link renderer in list"); frame.setVisible(true); } /** * ListModel with LinkModel. * */ public void interactiveListHyperlink() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXList list = new JXList(createListModelWithLinks(20)); list.setRolloverEnabled(true); LinkModelAction<?> action = new LinkModelAction<LinkModel>(visitor); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(action, LinkModel.class))); JFrame frame = wrapWithScrollingInFrame(list, visitor.getOutputComponent(), "show link renderer in list"); frame.setVisible(true); } /** * Visuals of Hyperlink/Highlighter interaction. * */ public void interactiveListHyperlinkLFStripingHighlighter() { EditorPaneLinkVisitor visitor = new EditorPaneLinkVisitor(); JXList list = new JXList(createListModelWithLinks(20)); LinkModelAction<?> action = new LinkModelAction<LinkModel>(visitor); list.setCellRenderer(new DefaultListRenderer( new HyperlinkProvider(action, LinkModel.class))); list.setRolloverEnabled(true); list.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(list, visitor.getOutputComponent(), "show link renderer in list with LFStriping highlighter"); frame.setVisible(true); } private ListModel createTextOnlyListModel(int count) { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < count; i++) { model.addElement("text } return model; } private ListModel createListModelWithLinks(int count) { DefaultListModel model = new DefaultListModel(); for (int i = 0; i < count; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addElement(link); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } private TableModel createModelWithLinks() { String[] columnNames = { "text - not-editable", "Link not-editable", "Bool editable", "Bool not-editable" }; DefaultTableModel model = new DefaultTableModel(columnNames, 0) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } @Override public boolean isCellEditable(int row, int column) { return !getColumnName(column).contains("not"); } }; for (int i = 0; i < 4; i++) { try { LinkModel link = new LinkModel("a link text " + i, null, new URL("http://some.dummy.url" + i)); if (i == 1) { URL url = JXEditorPaneTest.class.getResource("resources/test.html"); link = new LinkModel("a link text " + i, null, url); } model.addRow(new Object[] {"text only " + i, link, Boolean.TRUE, Boolean.TRUE }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return model; } protected AbstractHyperlinkAction<Object> createEmptyLinkAction() { AbstractHyperlinkAction<Object> linkAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub } }; return linkAction; } protected AbstractHyperlinkAction<?> createEmptyLinkAction(String name) { AbstractHyperlinkAction<?> linkAction = createEmptyLinkAction(); linkAction.setName(name); return linkAction; } /** * make auto-run happy in the absence of real test methods. * */ public void testDummy() { } }
package gui; import java.awt.Dimension; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.UIManager; public class Main extends JFrame implements ComponentListener{ private static final long serialVersionUID = 1L; FractalPanel fp = new FractalPanel(); // Declare menu bar items JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); JMenuItem file_exit = new JMenuItem("Exit"); JMenu view = new JMenu("View"); JCheckBoxMenuItem view_zoom = new JCheckBoxMenuItem("Zoom"); JCheckBoxMenuItem view_full = new JCheckBoxMenuItem("Full Screen"); JMenu help = new JMenu("Help"); JMenuItem help_about = new JMenuItem("About Fractal Visualizer"); public Main(){ setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("Fractal Visualizer"); setMinimumSize(new Dimension(200,200)); file.add(file_exit); view.add(view_zoom); view.add(view_full); help.add(help_about); menubar.add(file); menubar.add(view); menubar.add(help); setJMenuBar(menubar); fp.addComponentListener(this); add(fp); pack(); setResizable(false); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } new Main(); } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentResized(ComponentEvent e) { fp.renderImage(); } public void componentShown(ComponentEvent e) { } }
package kbasesearchengine.test.integration; import static kbasesearchengine.test.common.TestCommon.set; import static kbasesearchengine.test.main.NarrativeInfoDecoratorTest.narrInfoTuple; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.apache.http.HttpHost; import org.ini4j.Ini; import org.ini4j.Profile.Section; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import kbasesearchengine.AccessFilter; import kbasesearchengine.GetObjectsInput; import kbasesearchengine.GetObjectsOutput; import kbasesearchengine.KBaseSearchEngineClient; import kbasesearchengine.KBaseSearchEngineServer; import kbasesearchengine.MatchFilter; import kbasesearchengine.ObjectData; import kbasesearchengine.SearchObjectsInput; import kbasesearchengine.SearchObjectsOutput; import kbasesearchengine.SortingRule; import kbasesearchengine.authorization.TemporaryAuth2Client; import kbasesearchengine.authorization.TemporaryAuth2Client.Auth2Exception; import kbasesearchengine.common.FileUtil; import kbasesearchengine.common.GUID; import kbasesearchengine.common.ObjectJsonPath; import kbasesearchengine.events.handler.SourceData; import kbasesearchengine.events.handler.WorkspaceEventHandler; import kbasesearchengine.parse.ParsedObject; import kbasesearchengine.search.ElasticIndexingStorage; import kbasesearchengine.system.IndexingRules; import kbasesearchengine.system.ObjectTypeParsingRules; import kbasesearchengine.system.SearchObjectType; import kbasesearchengine.system.StorageObjectType; import kbasesearchengine.test.common.TestCommon; import kbasesearchengine.test.controllers.elasticsearch.ElasticSearchController; import kbasesearchengine.test.controllers.workspace.WorkspaceController; import kbasesearchengine.test.data.TestDataLoader; import kbasesearchengine.test.main.NarrativeInfoDecoratorTest; import us.kbase.auth.AuthToken; import us.kbase.common.service.ServerException; import us.kbase.common.service.Tuple5; import us.kbase.common.service.UObject; import us.kbase.common.test.controllers.mongo.MongoController; import us.kbase.test.auth2.authcontroller.AuthController; import us.kbase.workspace.CreateWorkspaceParams; import us.kbase.workspace.WorkspaceClient; public class SearchAPIIntegrationTest { /* Tests the integration of the compiled search server, translation classes, and index storage * classes. * * As of 2/6/2018, these are: * KBaseSearchEngineServer * SearchMethods * ElasticIndexingStorage * * ... and associated classes. Decorators for SearchMethods were in the works. * */ //TODO TEST add more tests. Should have reasonable integration tests for basic happy paths and a few unhappy paths. private static Path tempDirPath; private static MongoController mongo; private static AuthController auth; private static AuthToken userToken; private static ElasticSearchController es; private static ElasticIndexingStorage indexStorage; private static WorkspaceController ws; private static MongoDatabase wsdb; private static MongoClient mc; private static WorkspaceClient wsCli1; private static KBaseSearchEngineServer searchServer; private static KBaseSearchEngineClient searchCli; private static URL authURL; @BeforeClass public static void prepare() throws Exception { TestCommon.stfuLoggers(); tempDirPath = Paths.get(TestCommon.getTempDir()).resolve("SearchAPIIntegrationTest"); // should refactor to just use NIO at some point FileUtils.deleteQuietly(tempDirPath.toFile()); tempDirPath.toFile().mkdirs(); final Path searchTypesDir = Files.createDirectories(tempDirPath.resolve("searchtypes")); installSearchTypes(searchTypesDir); final Path mappingsDir = Files.createDirectories(tempDirPath.resolve("searchmappings")); installSearchMappings(mappingsDir); // set up mongo, needed for auth and workspace mongo = new MongoController( TestCommon.getMongoExe(), tempDirPath, TestCommon.useWiredTigerEngine()); mc = new MongoClient("localhost:" + mongo.getServerPort()); // set up auth auth = new AuthController( TestCommon.getJarsDir(), "localhost:" + mongo.getServerPort(), "SearchAPIIntTestAuth", tempDirPath); authURL = new URL("http://localhost:" + auth.getServerPort() + "/testmode"); System.out.println("started auth server at " + authURL); TestCommon.createAuthUser(authURL, "user1", "display1"); TestCommon.createAuthUser(authURL, "user2", "display2"); final String token1 = TestCommon.createLoginToken(authURL, "user1"); final String token2 = TestCommon.createLoginToken(authURL, "user2"); userToken = new AuthToken(token1, "user1"); final AuthToken wsadmintoken = new AuthToken(token2, "user2"); // set up elastic search es = new ElasticSearchController(TestCommon.getElasticSearchExe(), tempDirPath); // set up Workspace, only needed for getting allowed access group ids ws = new WorkspaceController( TestCommon.getWorkspaceVersion(), TestCommon.getJarsDir(), "localhost:" + mongo.getServerPort(), "SearchAPIIntTestWSDB", "TestEventDB", wsadmintoken.getUserName(), authURL, tempDirPath); System.out.println("Started workspace on port " + ws.getServerPort()); wsdb = mc.getDatabase("SearchAPIIntTestWSDB"); URL wsUrl = new URL("http://localhost:" + ws.getServerPort()); wsCli1 = new WorkspaceClient(wsUrl, userToken); wsCli1.setIsInsecureHttpConnectionAllowed(true); final String esIndexPrefix = "test_" + System.currentTimeMillis(); final HttpHost esHostPort = new HttpHost("localhost", es.getServerPort()); final ElasticIndexingStorage esStorage = new ElasticIndexingStorage(esHostPort, FileUtil.getOrCreateSubDir(tempDirPath.toFile(), "esbulk")); esStorage.setIndexNamePrefix(esIndexPrefix + "."); indexStorage = esStorage; searchServer = startupSearchServer(esIndexPrefix, tempDirPath.resolve("SearchServiceTemp"), wsadmintoken, searchTypesDir, mappingsDir); searchCli = new KBaseSearchEngineClient( new URL("http://localhost:" + searchServer.getServerPort()), userToken); searchCli.setIsInsecureHttpConnectionAllowed(true); } private static void installSearchTypes(final Path target) throws IOException { installTestFile("EmptyAType.json", target); installTestFile("TwoVersions.yaml", target); installTestFile("NoIndexingRules.yaml", target); } private static void installTestFile(final String fileName, final Path target) throws IOException { final String file = TestDataLoader.load(fileName); Files.write(target.resolve(fileName), file.getBytes()); } private static void installSearchMappings(final Path target) throws IOException { installTestFile("TwoVersionsMapping.yaml", target); } protected static class ServerThread extends Thread { private KBaseSearchEngineServer server; protected ServerThread(KBaseSearchEngineServer server) { this.server = server; } public void run() { try { server.startupServer(); } catch (Exception e) { System.err.println("Can't start server:"); e.printStackTrace(); } } } private static KBaseSearchEngineServer startupSearchServer( final String esIndexPrefix, final Path tempDir, final AuthToken indexerToken, final Path typesDir, final Path typeMappingDir) throws Exception { //write the server config file: File iniFile = File.createTempFile("test", ".cfg", new File(TestCommon.getTempDir())); if (iniFile.exists()) { iniFile.delete(); } System.out.println("Created temporary config file: " + iniFile.getAbsolutePath()); Ini ini = new Ini(); Section searchini = ini.add("KBaseSearchEngine"); searchini.add("auth-service-url", "http://localhost:" + auth.getServerPort() + "/testmode/api/legacy/KBase"); searchini.add("auth-service-url-allow-insecure", "true"); searchini.add("workspace-url", "http://localhost:" + ws.getServerPort()); searchini.add("scratch", tempDir); searchini.add("indexer-token", indexerToken.getToken()); searchini.add("elastic-host", "localhost"); searchini.add("elastic-port", es.getServerPort()); searchini.add("elastic-namespace", esIndexPrefix); searchini.add("types-dir", typesDir); searchini.add("type-mappings-dir", typeMappingDir); ini.store(iniFile); iniFile.deleteOnExit(); //set up env Map<String, String> env = TestCommon.getenv(); env.put("KB_DEPLOYMENT_CONFIG", iniFile.getAbsolutePath()); final KBaseSearchEngineServer server = new KBaseSearchEngineServer(); new ServerThread(server).start(); System.out.println("Main thread waiting for search server to start up"); while (server.getServerPort() == null) { Thread.sleep(1000); } return server; } @Before public void init() throws Exception { TestCommon.destroyDB(wsdb); indexStorage.dropData(); } @AfterClass public static void tearDownClass() throws Exception { final boolean deleteTempFiles = TestCommon.getDeleteTempFiles(); if (searchServer != null) { searchServer.stopServer(); } if (ws != null) { ws.destroy(deleteTempFiles); } if (auth != null) { auth.destroy(deleteTempFiles); } if (mc != null) { mc.close(); } if (mongo != null) { mongo.destroy(deleteTempFiles); } if (es != null) { es.destroy(deleteTempFiles); } if (tempDirPath != null && tempDirPath.toFile().exists() && deleteTempFiles) { FileUtils.deleteQuietly(tempDirPath.toFile()); } } @Test public void sourceTags() throws Exception { wsCli1.createWorkspace(new CreateWorkspaceParams() .withWorkspace("sourceTags")); indexStorage.indexObjects( ObjectTypeParsingRules.getBuilder( new SearchObjectType("SourceTags", 1), new StorageObjectType("foo", "bar")) .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) .build()) .build(), SourceData.getBuilder(new UObject(new HashMap<>()), "objname1", "creator") .withSourceTag("refdata") .withSourceTag("testnarr") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1/1/1"), ImmutableMap.of(new GUID("WS:1/1/1"), new ParsedObject( "{\"whee\": \"imaprettypony1\"}", ImmutableMap.of("whee", Arrays.asList("imaprettypony1")))), false); final ObjectData expected1 = new ObjectData() .withData(new UObject(ImmutableMap.of("whee", "imaprettypony1"))) .withGuid("WS:1/1/1") .withKeyProps(ImmutableMap.of("whee", "imaprettypony1")) .withCreator("creator") .withType("SourceTags") .withTypeVer(1L) .withObjectName("objname1") .withTimestamp(10000L); indexStorage.indexObjects( ObjectTypeParsingRules.getBuilder( new SearchObjectType("SourceTags", 1), new StorageObjectType("foo", "bar")) .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) .build()) .build(), SourceData.getBuilder(new UObject(new HashMap<>()), "objname2", "creator") .withSourceTag("refdata") .withSourceTag("narrative") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1/2/1"), ImmutableMap.of(new GUID("WS:1/2/1"), new ParsedObject( "{\"whee\": \"imaprettypony\"}", ImmutableMap.of("whee", Arrays.asList("imaprettypony")))), false); final ObjectData expected2 = new ObjectData() .withData(new UObject(ImmutableMap.of("whee", "imaprettypony"))) .withGuid("WS:1/2/1") .withKeyProps(ImmutableMap.of("whee", "imaprettypony")) .withCreator("creator") .withType("SourceTags") .withTypeVer(1L) .withObjectName("objname2") .withTimestamp(10000L); final SearchObjectsOutput res1 = searchObjects(new MatchFilter() .withSourceTags(Arrays.asList("narrative"))); assertThat("incorrect object count", res1.getObjects().size(), is(1)); TestCommon.compare(res1.getObjects().get(0), expected2); final SearchObjectsOutput res2 = searchObjects(new MatchFilter() .withSourceTags(Arrays.asList("narrative")) .withSourceTagsBlacklist(1L)); assertThat("incorrect object count", res2.getObjects().size(), is(1)); TestCommon.compare(res2.getObjects().get(0), expected1); } // @Test // public void narrativeDecoration() throws Exception { // wsCli1.createWorkspace(new CreateWorkspaceParams() // .withWorkspace("dummyWS1")); // final long wsdate = WorkspaceEventHandler.parseDateToEpochMillis(wsCli1.createWorkspace( // new CreateWorkspaceParams() // .withWorkspace("decorate") // .withMeta(ImmutableMap.of( // "narrative", "6", // "narrative_nice_name", "Kevin"))) // .getE4()); // indexStorage.indexObjects( // ObjectTypeParsingRules.getBuilder( // new SearchObjectType("Deco", 1), // new StorageObjectType("foo", "bar")) // .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) // .build()) // .build(), // SourceData.getBuilder(new UObject(new HashMap<>()), "objname11", "creator11") // .build(), // Instant.ofEpochMilli(10000), // null, // new GUID("WS:2/1/1"), // ImmutableMap.of(new GUID("WS:2/1/1"), new ParsedObject( // "{\"whee\": \"imaprettypony1\"}", // ImmutableMap.of("whee", Arrays.asList("imaprettypony1")))), // false); // final ObjectData expected1 = new ObjectData() // .withData(new UObject(ImmutableMap.of("whee", "imaprettypony1"))) // .withGuid("WS:2/1/1") // .withKeyProps(ImmutableMap.of("whee", "imaprettypony1")) // .withCreator("creator11") // .withType("Deco") // .withTypeVer(1L) // .withObjectName("objname11") // .withTimestamp(10000L); // final SearchObjectsOutput res = searchObjects(new MatchFilter()); // assertThat("incorrect object count", res.getObjects().size(), is(1)); // TestCommon.compare(res.getObjects().get(0), expected1); // final Map<Long, Tuple5<String, Long, Long, String, String>> expected = ImmutableMap.of( // 2L, narrInfoTuple("Kevin", 6L, wsdate, userToken.getUserName(), "display1")); // NarrativeInfoDecoratorTest.compare(res.getAccessGroupNarrativeInfo(), expected); @Test public void highlightTest () throws Exception{ wsCli1.createWorkspace(new CreateWorkspaceParams() .withWorkspace("highlight")); indexStorage.indexObjects( ObjectTypeParsingRules.getBuilder( new SearchObjectType("SourceTags", 1), new StorageObjectType("foo", "bar")) .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) .build()) .build(), SourceData.getBuilder(new UObject(new HashMap<>()), "objname1", "creator") .withSourceTag("refdata") .withSourceTag("testnarr") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1/1/1"), ImmutableMap.of(new GUID("WS:1/1/1"), new ParsedObject( "{\"whee\": \"imaprettypony1\"}", ImmutableMap.of("whee", Arrays.asList("imaprettypony1")))), false); //default for highlighting is off -- mainly b/c of search tags final kbasesearchengine.PostProcessing pp = new kbasesearchengine.PostProcessing(); //1L to get this to be true pp.setIncludeHighlight(1L); final MatchFilter filter = new MatchFilter().withFullTextInAll("objname1"); Map<String, List<String>> highlight = new HashMap<>(); highlight.put("object_name", Arrays.asList("<em>objname1</em>")); final ObjectData expected = new ObjectData() .withData(new UObject(ImmutableMap.of("whee", "imaprettypony1"))) .withGuid("WS:1/1/1") .withKeyProps(ImmutableMap.of("whee", "imaprettypony1")) .withCreator("creator") .withType("SourceTags") .withTypeVer(1L) .withObjectName("objname1") .withHighlight(highlight) .withTimestamp(10000L); SearchObjectsInput params = new SearchObjectsInput() .withPostProcessing(pp) .withAccessFilter(new AccessFilter()) .withMatchFilter(filter); SearchObjectsOutput res = searchCli.searchObjects(params); final ObjectData actual = res.getObjects().get(0); TestCommon.compare(actual, expected); //highlight in objects assertThat("incorrect highlight", actual.getHighlight(), is(expected.getHighlight())); //test b/c highlight is unable to find number/dates and may return null final MatchFilter filter2 = new MatchFilter().withFullTextInAll("WS:1/1/1"); SearchObjectsInput params2 = new SearchObjectsInput() .withPostProcessing(pp) .withAccessFilter(new AccessFilter()) .withMatchFilter(filter2); SearchObjectsOutput res2 = searchCli.searchObjects(params2); final ObjectData actual2 = res2.getObjects().get(0); TestCommon.compare(actual2, expected); assertThat("highlight should return empty map", actual2.getHighlight(), is(Collections.emptyMap())); } private SearchObjectsOutput searchObjects(final MatchFilter mf) throws Exception { try { return searchCli.searchObjects(new SearchObjectsInput() .withAccessFilter(new AccessFilter()) .withMatchFilter(mf)); } catch (ServerException e) { System.out.println("Exception server side trace:\n" + e.getData()); throw e; } } @Test public void sort() throws Exception { wsCli1.createWorkspace(new CreateWorkspaceParams() .withWorkspace("sort")); indexStorage.indexObjects( ObjectTypeParsingRules.getBuilder( new SearchObjectType("Sort", 1), new StorageObjectType("foo", "bar")) .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) .build()) .build(), SourceData.getBuilder(new UObject(new HashMap<>()), "objname1", "creator1") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1/1/1"), ImmutableMap.of(new GUID("WS:1/1/1"), new ParsedObject( "{\"whee\": \"imaprettypony1\"}", ImmutableMap.of("whee", Arrays.asList("imaprettypony1")))), false); indexStorage.indexObjects( ObjectTypeParsingRules.getBuilder( new SearchObjectType("Sort", 1), new StorageObjectType("foo", "bar")) .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) .build()) .build(), SourceData.getBuilder(new UObject(new HashMap<>()), "objname1", "creator2") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1/2/1"), ImmutableMap.of(new GUID("WS:1/2/1"), new ParsedObject( "{\"whee\": \"imaprettypony1\"}", ImmutableMap.of("whee", Arrays.asList("imaprettypony1")))), false); final SearchObjectsOutput res = searchCli.searchObjects(new SearchObjectsInput() .withAccessFilter(new AccessFilter()) .withMatchFilter(new MatchFilter()) .withSortingRules(Arrays.asList(new SortingRule() .withAscending(0L) .withIsObjectProperty(0L) .withProperty("creator")))); final List<String> guids = res.getObjects().stream().map(od -> od.getGuid()).collect( Collectors.toList()); assertThat("incorrect order", guids, is(Arrays.asList("WS:1/2/1", "WS:1/1/1"))); assertThat("incorrect sort rules count", res.getSortingRules().size(), is(1)); final SortingRule sr = res.getSortingRules().get(0); assertThat("incorrect property", sr.getProperty(), is("creator")); assertThat("incorrect ascending", sr.getAscending(), is(0L)); assertThat("incorrect is object property", sr.getIsObjectProperty(), is(0L)); } @Test public void status() throws Exception { final Map<String, Object> res = searchCli.status(); // since the test working relies on the presence of the git.properties doc, which may // or may not be present given on how the test is run, we just check that something // is returned for the git properties. assertThat("null git url", res.get("git_url"), is(notNullValue())); assertThat("null git commit", res.get("git_commit_hash"), is(notNullValue())); System.out.println(res); res.remove("git_url"); res.remove("git_commit_hash"); final Map<String, Object> expected = ImmutableMap.of( "state", "OK", "message", "", "version", "0.1.0"); assertThat("incorrect status output", res, is(expected)); } @Test public void pruneNarrative() throws Exception { wsCli1.createWorkspace(new CreateWorkspaceParams() .withWorkspace("narprune")); final Map<String, Object> data = new HashMap<>(); data.put("source", "a long string"); data.put("code_output", "another long string"); data.put("app_output", "yet another long string"); data.put("app_info", "yup, another long string here"); data.put("app_input", "my god will this reign of long string terror every end"); data.put("job_ids", "3"); data.put("title", "a title"); indexStorage.indexObjects( ObjectTypeParsingRules.getBuilder( new SearchObjectType("Narrative", 1), new StorageObjectType("WS", "Narrative")) .withIndexingRule(IndexingRules.fromPath(new ObjectJsonPath("whee")) .build()) .build(), SourceData.getBuilder(new UObject(new HashMap<>()), "objname1", "creator1") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1/1/1"), ImmutableMap.of(new GUID("WS:1/1/1"), new ParsedObject( new ObjectMapper().writeValueAsString(data), data.entrySet().stream().collect(Collectors.toMap( e -> e.getKey(), e -> Arrays.asList(e.getValue()))))), false); final GetObjectsOutput ret = searchCli.getObjects(new GetObjectsInput() .withGuids(Arrays.asList("WS:1/1/1"))); assertThat("incorrect data count", ret.getObjects().size(), is(1)); final ObjectData od2 = ret.getObjects().get(0); assertThat("incorrect data", od2.getData(), is((UObject) null)); assertThat("incorrect keyprops", od2.getKeyProps(), is(ImmutableMap.of("title", "a title"))); final SearchObjectsOutput res = searchObjects(new MatchFilter()); assertThat("incorrect data count", res.getObjects().size(), is(1)); final ObjectData od = res.getObjects().get(0); assertThat("incorrect data", od.getData(), is((UObject) null)); assertThat("incorrect keyprops", od.getKeyProps(), is(ImmutableMap.of("title", "a title"))); } @Test public void construct() throws Exception { final TemporaryAuth2Client client = new TemporaryAuth2Client( new URL("http://localhost:1000/whee")); assertThat("incorrect url", client.getURL(), is(new URL("http://localhost:1000/whee/"))); final TemporaryAuth2Client client2 = new TemporaryAuth2Client( new URL("http://localhost:1000/whee/")); assertThat("incorrect url", client2.getURL(), is(new URL("http://localhost:1000/whee/"))); } @Test public void authClientGetDisplayNames() throws Exception { final TemporaryAuth2Client client = new TemporaryAuth2Client(authURL); assertThat("incorrect users", client.getUserDisplayNames( userToken.getToken(), set("user1", "user2")), is(ImmutableMap.of("user1", "display1", "user2", "display2"))); } @Test public void authClientGetDisplayNamesEmptyInput() throws Exception { final TemporaryAuth2Client client = new TemporaryAuth2Client(authURL); assertThat("incorrect users", client.getUserDisplayNames(userToken.getToken(), set()), is(Collections.emptyMap())); } @Test public void authClientGetDisplayNamesServerError() throws Exception { final TemporaryAuth2Client client = new TemporaryAuth2Client( new URL("http://localhost:" + auth.getServerPort())); try { client.getUserDisplayNames(userToken.getToken(), set("Baduser")); fail("expected exception"); } catch (Auth2Exception got) { TestCommon.assertExceptionCorrect(got, new Auth2Exception( "Auth service returned error code 400 with call id " + got.getCallID().get() + // there's some software gore for you // https://github.com/kbase/auth2/blob/73160676e4b64c9316c1c93023e20514519744d7/src/us/kbase/auth2/service/api/Users.java#L68 ": 30010 Illegal user name: Illegal user name [Baduser]: " + "30010 Illegal user name: Illegal character in user name Baduser: B")); } } @Test public void authClientFailConstruct() throws Exception { try { new TemporaryAuth2Client(null); fail("expected exception"); } catch (Exception got) { TestCommon.assertExceptionCorrect(got, new NullPointerException("authURL")); } } @Test public void authClientgetDisplayNamesBadInput() { failAuthClientGetDisplayNames(null, set(), new IllegalArgumentException("token cannot be null or whitespace only")); failAuthClientGetDisplayNames(" \t \n ", set(), new IllegalArgumentException("token cannot be null or whitespace only")); failAuthClientGetDisplayNames("t", null, new NullPointerException("userNames")); failAuthClientGetDisplayNames("t", set("n", null), new IllegalArgumentException("Null or whitespace only entry in userNames")); failAuthClientGetDisplayNames("t", set("n", " \t \n "), new IllegalArgumentException("Null or whitespace only entry in userNames")); } private void failAuthClientGetDisplayNames( final String token, final Set<String> userNames, final Exception expected) { try { new TemporaryAuth2Client(authURL).getUserDisplayNames(token, userNames); fail("expected exception"); } catch (Exception got) { TestCommon.assertExceptionCorrect(got, expected); } } }
// SwingDisplayWindow.java package imagej.ui.swing.display; import imagej.awt.AWTDisplayWindow; import imagej.awt.AWTEventDispatcher; import imagej.data.DataObject; import imagej.data.Dataset; import imagej.data.event.DatasetRestructuredEvent; import imagej.display.DisplayView; import imagej.display.EventDispatcher; import imagej.display.event.ZoomEvent; import imagej.event.EventSubscriber; import imagej.event.Events; import java.awt.Adjustable; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import net.imglib2.img.Axes; import net.imglib2.img.Axis; import net.miginfocom.swing.MigLayout; /** * Swing implementation of display window. * * @author Curtis Rueden * @author Grant Harris * @author Barry DeZonia */ public class SwingDisplayWindow extends JFrame implements AWTDisplayWindow { // TODO - Rework internal logic to use a JPanel, not a JFrame. // In this way, the GUI components could be used in other contexts. private final SwingImageDisplay display; private final JLabel imageLabel; private final JPanel sliders; private ArrayList<EventSubscriber<?>> subscribers; public SwingDisplayWindow(final SwingImageDisplay display) { this.display = display; imageLabel = new JLabel(" "); final int prefHeight = imageLabel.getPreferredSize().height; imageLabel.setPreferredSize(new Dimension(0, prefHeight)); final JPanel graphicPane = new JPanel(); graphicPane.setLayout(new MigLayout("ins 0", "fill,grow", "fill,grow")); graphicPane.setBorder(new LineBorder(Color.black)); graphicPane.add(display.getImageCanvas()); sliders = new JPanel(); sliders.setLayout(new MigLayout("fillx,wrap 2", "[right|fill,grow]")); final JPanel pane = new JPanel(); pane.setLayout(new BorderLayout()); pane.setBorder(new EmptyBorder(3, 3, 3, 3)); setContentPane(pane); pane.add(imageLabel, BorderLayout.NORTH); pane.add(graphicPane, BorderLayout.CENTER); pane.add(sliders, BorderLayout.SOUTH); subscribeToEvents(); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } // -- DisplayWindow methods -- @Override public SwingImageDisplay getDisplay() { return display; } @Override public void update() { setLabel(makeLabel()); for (final DisplayView view : display.getViews()) view.update(); } @Override public void redoLayout() { for (final DisplayView view : display.getViews()) { final Dataset dataset = getDataset(view); if (dataset == null) continue; createSliders(view); sliders.setVisible(sliders.getComponentCount() > 0); setTitle(makeTitle(dataset, 1.0)); setLabel(makeLabel()); // CTR TODO - for 2.0-alpha2 we are limiting displays to a single view. // But most of the infrastructure is in place to support multiple views. // We just need to do something more intelligent here regarding the // slider panel (i.e., multiple groups of sliders), then expose the // multi-view capabilities in the UI. break; } pack(); setVisible(true); } @Override public void setLabel(final String s) { imageLabel.setText(s); } @Override public void addEventDispatcher(final EventDispatcher dispatcher) { final AWTEventDispatcher awtDispatcher = (AWTEventDispatcher) dispatcher; addKeyListener(awtDispatcher); addWindowListener(awtDispatcher); } // -- Helper methods -- private void subscribeToEvents() { subscribers = new ArrayList<EventSubscriber<?>>(); final EventSubscriber<ZoomEvent> zoomSubscriber = new EventSubscriber<ZoomEvent>() { @SuppressWarnings("synthetic-access") @Override public void onEvent(final ZoomEvent event) { if (event.getCanvas() != getDisplay().getImageCanvas()) return; // CTR TODO - Fix zoom label to show beyond just the active view. final DisplayView activeView = getDisplay().getActiveView(); final Dataset dataset = getDataset(activeView); setTitle(makeTitle(dataset, event.getScale())); } }; subscribers.add(zoomSubscriber); Events.subscribe(ZoomEvent.class, zoomSubscriber); final EventSubscriber<DatasetRestructuredEvent> dsRestructuredSubscriber = new EventSubscriber<DatasetRestructuredEvent>() { @SuppressWarnings("synthetic-access") @Override public void onEvent(DatasetRestructuredEvent event) { DisplayView view = getDisplay().getActiveView(); final Dataset ds = getDataset(view); if (event.getObject() != ds) return; createSliders(view); } }; subscribers.add(dsRestructuredSubscriber); Events.subscribe(DatasetRestructuredEvent.class, dsRestructuredSubscriber); } private void createSliders(final DisplayView view) { final Dataset dataset = getDataset(view); final long[] dims = dataset.getDims(); final Axis[] axes = dataset.getAxes(); sliders.removeAll(); for (int i = 0; i < dims.length; i++) { if (Axes.isXY(axes[i])) continue; if (dims[i] == 1) continue; final JLabel label = new JLabel(axes[i].getLabel()); label.setHorizontalAlignment(SwingConstants.RIGHT); final long max = dims[i] + 1; if (max < 1 || max > Integer.MAX_VALUE) { throw new IllegalArgumentException("Dimension " out of range: " + max); } final JScrollBar slider = new JScrollBar(Adjustable.HORIZONTAL, 1, 1, 1, (int) max); final int axisNumber = i; slider.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(final AdjustmentEvent e) { final int position = slider.getValue() - 1; view.setPosition(position, axisNumber); update(); } }); sliders.add(label); sliders.add(slider); } } private String makeLabel() { // CTR TODO - Fix window label to show beyond just the active view. final DisplayView view = display.getActiveView(); final Dataset dataset = getDataset(view); final int xIndex = dataset.getAxisIndex(Axes.X); final int yIndex = dataset.getAxisIndex(Axes.Y); final long[] dims = dataset.getDims(); final Axis[] axes = dataset.getAxes(); final long[] pos = view.getPlanePosition(); final StringBuilder sb = new StringBuilder(); for (int i = 0, p = -1; i < dims.length; i++) { if (Axes.isXY(axes[i])) continue; p++; if (dims[i] == 1) continue; sb.append(axes[i] + ": " + (pos[p] + 1) + "/" + dims[i] + "; "); } sb.append(dims[xIndex] + "x" + dims[yIndex] + "; "); sb.append(dataset.getTypeLabel()); return sb.toString(); } private String makeTitle(final Dataset dataset, final double scale) { final String datasetName = dataset.getName(); if (scale == 1.0) return datasetName; // exactly 100% zoom final String infoString = String.format("%s (%.2f%%)", datasetName, scale * 100); return infoString; } private Dataset getDataset(final DisplayView view) { final DataObject dataObject = view.getDataObject(); return dataObject instanceof Dataset ? (Dataset) dataObject : null; } }
package VASSAL.build.module; import VASSAL.build.AutoConfigurable; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.MassKeyCommand; import VASSAL.command.Command; import VASSAL.configure.TranslatableStringEnum; import VASSAL.configure.VisibilityCondition; import VASSAL.i18n.Resources; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * A Global Key Command that is automatically invoked on game start-up, * once the various Key Listeners have been started. * <p> * As of 3.6, multiple Startup Global Key Commands can be depended on to * process in the correct order. * * @author Pieter Geerkens * */ public class StartupGlobalKeyCommand extends GlobalKeyCommand implements GameComponent { public static final String WHEN_TO_APPLY = "whenToApply"; //NON-NLS public static final String APPLY_FIRST_LAUNCH_OF_SESSION = "firstLaunchOfSession"; //NON-NLS public static final String APPLY_EVERY_LAUNCH_OF_SESSION = "everyLaunchOfSession"; //NON-NLS public static final String APPLY_START_OF_GAME_ONLY = "startOfGameOnly"; //NON-NLS public String whenToApply = APPLY_FIRST_LAUNCH_OF_SESSION; private boolean hasEverApplied = false; // Has ever been applied during this session (NOT saved with game state) private boolean hasAppliedThisGame = false; // Has ever been applied during this *game* (Saved with game state) public static class Prompt extends TranslatableStringEnum { @Override public String[] getValidValues(AutoConfigurable target) { return new String[]{ APPLY_FIRST_LAUNCH_OF_SESSION, APPLY_EVERY_LAUNCH_OF_SESSION, APPLY_START_OF_GAME_ONLY }; } @Override public String[] getI18nKeys(AutoConfigurable target) { return new String[] { "Editor.StartupGlobalKeyCommand.first_launch_of_session", "Editor.StartupGlobalKeyCommand.every_launch_of_session", "Editor.StartupGlobalKeyCommand.start_of_game_only" }; } } @SuppressWarnings("removal") public StartupGlobalKeyCommand() { super(); condition = null; /* These four fields pertaining to the physical representation of the * GKC on the toolbar are not applicable in this implementation. */ launch.setAttribute(BUTTON_TEXT, ""); //NON-NLS launch.setAttribute(TOOLTIP, ""); //NON-NLS launch.setAttribute(ICON, ""); //NON-NLS launch.setAttribute(HOTKEY, ""); //NON-NLS } @SuppressWarnings("removal") public StartupGlobalKeyCommand(MassKeyCommand gkc) { super(gkc); condition = null; /* These four fields pertaining to the physical representation of the * GKC on the toolbar are not applicable in this implementation. */ launch.setAttribute(BUTTON_TEXT, ""); //NON-NLS launch.setAttribute(TOOLTIP, ""); //NON-NLS launch.setAttribute(ICON, ""); //NON-NLS launch.setAttribute(HOTKEY, ""); //NON-NLS } @Override public void addTo(Buildable parent) { super.addTo(parent); GameModule.getGameModule().getGameState().addGameComponent(this); } public static String getConfigureTypeName() { return Resources.getString("Editor.StartupGlobalKeyCommand.component_type"); } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("Map.html", "StartupGlobalKeyCommand"); //NON-NLS } @SuppressWarnings("removal") @Override public VisibilityCondition getAttributeVisibility(String key) { if (List.of(BUTTON_TEXT, TOOLTIP, ICON, HOTKEY).contains(key)) { return () -> false; } else { return super.getAttributeVisibility(key); } } @Override public String[] getAttributeDescriptions() { final List<String> descs = new ArrayList<>(); descs.add(Resources.getString("Editor.StartupGlobalKeyCommand.when_to_apply")); Collections.addAll(descs, super.getAttributeDescriptions()); return descs.toArray(new String[0]); } @Override public String[] getAttributeNames() { final List<String> names = new ArrayList<>(); names.add(WHEN_TO_APPLY); // Filter some of the crazy out of the original MassKeyCommand list, so we can add more things "safely" for (final String n : super.getAttributeNames()) { if (List.of(CHECK_VALUE, CHECK_PROPERTY, AFFECTED_PIECE_NAMES).contains(n)) { continue; } names.add(n); } return names.toArray(new String[0]); } @Override public Class<?>[] getAttributeTypes() { final List<Class<?>> types = new ArrayList<>(); types.add(Prompt.class); Collections.addAll(types, super.getAttributeTypes()); return types.toArray(new Class<?>[0]); } @Override public void setAttribute(String key, Object value) { if (WHEN_TO_APPLY.equals(key)) { if (value instanceof String) { whenToApply = (String)value; } } else { super.setAttribute(key, value); } } @Override public String getAttributeValueString(String key) { if (WHEN_TO_APPLY.equals(key)) { return whenToApply; } else { return super.getAttributeValueString(key); } } public boolean applyIfNotApplied() { if (APPLY_FIRST_LAUNCH_OF_SESSION.equals(whenToApply)) { if (hasEverApplied) { return false; } } else if (APPLY_START_OF_GAME_ONLY.equals(whenToApply)) { if (hasAppliedThisGame) { return false; } } hasEverApplied = true; // This one will be false again next time anything calls GameState.setup(true) hasAppliedThisGame = true; // This one will be remembered as part of the game state (i.e. even after loading a game) apply(); return true; } @Override public void setup(boolean gameStarting) { hasAppliedThisGame = false; } @Override public Command getRestoreCommand() { return new UpdateStartupGlobalKeyCommand(hasAppliedThisGame); } /** * Our "command" format for remembering whether the key command has been applied during this game */ private class UpdateStartupGlobalKeyCommand extends Command { private final boolean appliedThisGame; public UpdateStartupGlobalKeyCommand(boolean appliedThisGame) { this.appliedThisGame = appliedThisGame; } @Override protected void executeCommand() { hasAppliedThisGame = appliedThisGame; } @Override protected Command myUndoCommand() { return null; } } }
package io.vertx.ext.consul; import io.vertx.codegen.annotations.Fluent; import io.vertx.codegen.annotations.ProxyGen; import io.vertx.codegen.annotations.ProxyIgnore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.serviceproxy.ProxyHelper; import java.util.List; @ProxyGen @VertxGen public interface ConsulService extends ConsulClient { /** * Create a proxy to a service that is deployed somewhere on the event bus * * @param vertx the Vert.x instance * @param address the address the service is listening on on the event bus * @return the service */ static ConsulService createEventBusProxy(Vertx vertx, String address) { return ProxyHelper.createProxy(ConsulService.class, vertx, address); } @Override @Fluent ConsulService agentInfo(Handler<AsyncResult<JsonObject>> resultHandler); @Override @Fluent ConsulService coordinateNodes(Handler<AsyncResult<List<Coordinate>>> resultHandler); @Override @Fluent ConsulService coordinateDatacenters(Handler<AsyncResult<List<DcCoordinates>>> resultHandler); @Override @Fluent ConsulService getValue(String key, Handler<AsyncResult<KeyValue>> resultHandler); @Override @Fluent ConsulService getValueBlocking(String key, BlockingQueryOptions options, Handler<AsyncResult<KeyValue>> resultHandler); @Override @Fluent ConsulService deleteValue(String key, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService getValues(String keyPrefix, Handler<AsyncResult<List<KeyValue>>> resultHandler); @Override @Fluent ConsulService getValuesBlocking(String keyPrefix, BlockingQueryOptions options, Handler<AsyncResult<List<KeyValue>>> resultHandler); @Override @Fluent ConsulService deleteValues(String keyPrefix, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService putValue(String key, String value, Handler<AsyncResult<Boolean>> resultHandler); @Override @Fluent ConsulService putValueWithOptions(String key, String value, KeyValueOptions options, Handler<AsyncResult<Boolean>> resultHandler); @Override @Fluent ConsulService createAclToken(AclToken token, Handler<AsyncResult<String>> idHandler); @Override @Fluent ConsulService updateAclToken(AclToken token, Handler<AsyncResult<String>> idHandler); @Override @Fluent ConsulService cloneAclToken(String id, Handler<AsyncResult<String>> idHandler); @Override @Fluent ConsulService listAclTokens(Handler<AsyncResult<List<AclToken>>> resultHandler); @Override @Fluent ConsulService infoAclToken(String id, Handler<AsyncResult<AclToken>> tokenHandler); @Override @Fluent ConsulService destroyAclToken(String id, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService fireEvent(String name, Handler<AsyncResult<Event>> resultHandler); @Override @Fluent ConsulService fireEventWithOptions(String name, EventOptions options, Handler<AsyncResult<Event>> resultHandler); @Override @Fluent ConsulService listEvents(Handler<AsyncResult<List<Event>>> resultHandler); @Override @Fluent ConsulService registerService(ServiceOptions serviceOptions, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService maintenanceService(MaintenanceOptions maintenanceOptions, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService deregisterService(String id, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService catalogServiceNodes(String service, Handler<AsyncResult<List<Service>>> resultHandler); @Override @Fluent ConsulService catalogServiceNodesWithTag(String service, String tag, Handler<AsyncResult<List<Service>>> resultHandler); @Override @Fluent ConsulService catalogDatacenters(Handler<AsyncResult<List<String>>> resultHandler); @Override @Fluent ConsulService catalogNodes(Handler<AsyncResult<List<Node>>> resultHandler); @Override @Fluent ConsulService catalogServices(Handler<AsyncResult<List<Service>>> resultHandler); @Override @Fluent ConsulService localServices(Handler<AsyncResult<List<Service>>> resultHandler); @Override @Fluent ConsulService catalogNodeServices(String node, Handler<AsyncResult<List<Service>>> resultHandler); @Override @Fluent ConsulService localChecks(Handler<AsyncResult<List<Check>>> resultHandler); @Override @Fluent ConsulService registerCheck(CheckOptions checkOptions, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService deregisterCheck(String checkId, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService passCheck(String checkId, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService passCheckWithNote(String checkId, String note, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService warnCheck(String checkId, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService warnCheckWithNote(String checkId, String note, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService failCheck(String checkId, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService failCheckWithNote(String checkId, String note, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService updateCheck(String checkId, CheckStatus status, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService updateCheckWithNote(String checkId, CheckStatus status, String note, Handler<AsyncResult<Void>> resultHandler); @Override @Fluent ConsulService leaderStatus(Handler<AsyncResult<String>> resultHandler); @Override @Fluent ConsulService peersStatus(Handler<AsyncResult<List<String>>> resultHandler); @Override @Fluent ConsulService createSession(Handler<AsyncResult<String>> idHandler); @Override @Fluent ConsulService createSessionWithOptions(SessionOptions options, Handler<AsyncResult<String>> idHandler); @Override @Fluent ConsulService infoSession(String id, Handler<AsyncResult<Session>> resultHandler); @Override @Fluent ConsulService renewSession(String id, Handler<AsyncResult<Session>> resultHandler); @Override @Fluent ConsulService listSessions(Handler<AsyncResult<List<Session>>> resultHandler); @Override @Fluent ConsulService listNodeSessions(String nodeId, Handler<AsyncResult<List<Session>>> resultHandler); @Override @Fluent ConsulService destroySession(String id, Handler<AsyncResult<Void>> resultHandler); @Override @ProxyIgnore void close(); }
package com.google.job.data; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.*; import com.google.firestore.FireStoreUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** Tests for {@link JobsDatabase} class. */ public final class JobsDatabaseTest { // TODO(issue/15): Add failure test case // TODO(issue/16): Move the clear database method as @After private static final String TEST_JOB_COLLECTION = "Jobs"; private static final int BATCH_SIZE = 10; JobsDatabase jobsDatabase; Firestore firestore; /** Delete a collection in batches to avoid out-of-memory errors. * Batch size may be tuned based on document size (atmost 1MB) and application requirements. */ private void deleteCollection(CollectionReference collection, int batchSize) { try { // retrieve a small batch of documents to avoid out-of-memory errors ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get(); int deleted = 0; // future.get() blocks on document retrieval List<QueryDocumentSnapshot> documents = future.get().getDocuments(); for (QueryDocumentSnapshot document : documents) { document.getReference().delete(); ++deleted; } if (deleted >= batchSize) { // retrieve and delete another batch deleteCollection(collection, batchSize); } } catch (Exception e) { System.err.println("Error deleting collection : " + e.getMessage()); } } @Before public void setUp() { jobsDatabase = new JobsDatabase(); firestore = FireStoreUtils.getFireStore(); } @Test public void addJob_NormalInput_success() throws ExecutionException, InterruptedException { // Arrange. String expectedJobName = "Software Engineer"; Job job = new Job(expectedJobName); // Act. Future<DocumentReference> addedJobFuture = jobsDatabase.addJob(job); // Assert. DocumentReference documentReference = addedJobFuture.get(); // Asynchronously retrieve the document. ApiFuture<DocumentSnapshot> future = documentReference.get(); // future.get() blocks on response. DocumentSnapshot document = future.get(); String jobId = document.getId(); Job actualJob = document.toObject(Job.class); String actualJobName = actualJob.getJobTitle(); assertEquals(expectedJobName, actualJobName); // firestore.collection(TEST_JOB_COLLECTION).document(jobId).delete(); } @Test public void setJob_NormalInput_success() throws ExecutionException, InterruptedException { // Arrange. Job oldJob = new Job("Noogler"); Future<DocumentReference> addedJobFuture = firestore.collection(TEST_JOB_COLLECTION) .add(oldJob); DocumentReference documentReference = addedJobFuture.get(); // Asynchronously retrieve the document. ApiFuture<DocumentSnapshot> future = documentReference.get(); // future.get() blocks on response. DocumentSnapshot document = future.get(); String jobId = document.getId(); String expectedJobName = "Googler"; Job job = new Job(expectedJobName); // Act. Future<WriteResult> editedDocRef = jobsDatabase.setJob(jobId, job); // Assert. // future.get() blocks on response. editedDocRef.get(); ApiFuture<DocumentSnapshot> documentSnapshotApiFuture = firestore.collection(TEST_JOB_COLLECTION). document(jobId).get(); DocumentSnapshot documentSnapshot = documentSnapshotApiFuture.get(); Job actualJob = documentSnapshot.toObject(Job.class); String actualJobName = actualJob.getJobTitle(); assertEquals(expectedJobName, actualJobName); // firestore.collection(TEST_JOB_COLLECTION).document(jobId).delete(); } @Test public void fetchJob_NormalInput_success() throws ExecutionException, InterruptedException { // Arrange. Job job = new Job("Programmer"); Future<DocumentReference> addedJobFuture = firestore.collection(TEST_JOB_COLLECTION).add(job); DocumentReference documentReference = addedJobFuture.get(); // Asynchronously retrieve the document. ApiFuture<DocumentSnapshot> future = documentReference.get(); // future.get() blocks on response. DocumentSnapshot document = future.get(); String jobId = document.getId(); // Act. Optional<Job> jobOptional = jobsDatabase.fetchJob(jobId).get(); // Assert. assertTrue(jobOptional.isPresent()); Job actualJob = jobOptional.get(); String actualJobName = actualJob.getJobTitle(); String expectedJobName = "Programmer"; assertEquals(expectedJobName, actualJobName); // firestore.collection(TEST_JOB_COLLECTION).document(jobId).delete(); } @After public void clearCollection() { deleteCollection(firestore.collection(TEST_JOB_COLLECTION), BATCH_SIZE); } }
package org.jboss.as.web.deployment; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.catalina.Host; import org.apache.catalina.Loader; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.ContextConfig; import org.jboss.as.ee.naming.NamespaceSelectorService; import org.jboss.as.naming.context.NamespaceContextSelector; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.web.NamingListener; import org.jboss.as.web.WebSubsystemServices; import org.jboss.as.web.deployment.component.ComponentInstantiator; import org.jboss.as.web.security.JBossWebRealm; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.modules.Module; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistryException; import org.jboss.msc.service.ServiceTarget; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.security.AuthenticationManager; import org.jboss.security.AuthorizationManager; import org.jboss.security.SecurityConstants; import org.jboss.security.SecurityUtil; import org.jboss.vfs.VirtualFile; /** * @author Emanuel Muckenhuber * @author Anil.Saldhana@redhat.com */ public class WarDeploymentProcessor implements DeploymentUnitProcessor { private final String defaultHost; public WarDeploymentProcessor(String defaultHost) { if (defaultHost == null) { throw new IllegalArgumentException("null default host"); } this.defaultHost = defaultHost; } /** {@inheritDoc} */ @Override public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); if (metaData == null) { return; } Collection<String> hostNames = metaData.getMergedJBossWebMetaData().getVirtualHosts(); if (hostNames == null || hostNames.isEmpty()) { hostNames = Collections.singleton(defaultHost); } String hostName = hostNames.iterator().next(); // FIXME: Support automagic aliases ? if (hostName == null) { throw new IllegalStateException("null host name"); } processDeployment(hostName, metaData, deploymentUnit, phaseContext.getServiceTarget()); } @Override public void undeploy(final DeploymentUnit context) { } protected void processDeployment(final String hostName, final WarMetaData warMetaData, final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget) throws DeploymentUnitProcessingException { final VirtualFile deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); final Module module = deploymentUnit.getAttachment(Attachments.MODULE); if (module == null) { throw new DeploymentUnitProcessingException("failed to resolve module for deployment " + deploymentRoot); } final ClassLoader classLoader = module.getClassLoader(); final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData(); // Create the context final StandardContext webContext = new StandardContext(); final ContextConfig config = new JBossContextConfig(deploymentUnit); webContext.addInstanceListener(NamingListener.class.getName()); // Set the deployment root try { webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath()); } catch (IOException e) { throw new DeploymentUnitProcessingException(e); } webContext.addLifecycleListener(config); // Set the path name final String deploymentName = deploymentUnit.getName(); String pathName = null; if (metaData.getContextRoot() == null) { pathName = deploymentRoot.getName(); if (pathName.equals("ROOT.war")) { pathName = ""; } else { pathName = "/" + pathName.substring(0, pathName.length() - 4); } } else { pathName = metaData.getContextRoot(); if ("/".equals(pathName)) { pathName = ""; } } webContext.setPath(pathName); webContext.setIgnoreAnnotations(true); webContext.setCrossContext(!metaData.isDisableCrossContext()); final WebInjectionContainer injectionContainer = new WebInjectionContainer(module.getClassLoader()); final Map<String, ComponentInstantiator> components = deploymentUnit .getAttachment(WebAttachments.WEB_COMPONENT_INSTANTIATORS); if (components != null) { for (Map.Entry<String, ComponentInstantiator> entry : components.entrySet()) { injectionContainer.addInstantiator(entry.getKey(), entry.getValue()); } } webContext.setInstanceManager(injectionContainer); final Loader loader = new WebCtxLoader(classLoader); webContext.setLoader(loader); // Set the session cookies flag according to metadata switch (metaData.getSessionCookies()) { case JBossWebMetaData.SESSION_COOKIES_ENABLED: webContext.setCookies(true); break; case JBossWebMetaData.SESSION_COOKIES_DISABLED: webContext.setCookies(false); break; } String metaDataSecurityDomain = metaData.getSecurityDomain(); if (metaDataSecurityDomain != null) { metaDataSecurityDomain = metaDataSecurityDomain.trim(); } // Get the realm details from the domain model JBossWebRealm realm = new JBossWebRealm(); String securityDomain = metaDataSecurityDomain == null ? SecurityConstants.DEFAULT_APPLICATION_POLICY : SecurityUtil .unprefixSecurityDomain(metaDataSecurityDomain); // Set the current tccl and save it ClassLoader tcl = SecurityActions.getContextClassLoader(); // Set the Module Class loader as the tccl such that the JNDI lookup of the JBoss Authentication/Authz managers succeed SecurityActions.setContextClassLoader(classLoader); try { AuthenticationManager authM = getAuthenticationManager(securityDomain); realm.setAuthenticationManager(authM); AuthorizationManager authzM = getAuthorizationManager(securityDomain); realm.setAuthorizationManager(authzM); webContext.setRealm(realm); } catch (NamingException e1) { throw new RuntimeException(e1); } finally { SecurityActions.setContextClassLoader(tcl); } try { ServiceName namespaceSelectorServiceName = deploymentUnit.getServiceName().append(NamespaceSelectorService.NAME); WebDeploymentService webDeploymentService = new WebDeploymentService(webContext); serviceTarget.addService(WebSubsystemServices.JBOSS_WEB.append(deploymentName), webDeploymentService) .addDependency(WebSubsystemServices.JBOSS_WEB_HOST.append(hostName), Host.class, new WebContextInjector(webContext)).addDependencies(injectionContainer.getServiceNames()) .addDependency(namespaceSelectorServiceName, NamespaceContextSelector.class, webDeploymentService.getNamespaceSelector()).setInitialMode(Mode.ACTIVE).install(); } catch (ServiceRegistryException e) { throw new DeploymentUnitProcessingException("Failed to add JBoss web deployment service", e); } } private AuthenticationManager getAuthenticationManager(String secDomain) throws NamingException { InitialContext ic = new InitialContext(); return (AuthenticationManager) ic.lookup(SecurityConstants.JAAS_CONTEXT_ROOT + "/" + secDomain + "/authenticationMgr"); } private AuthorizationManager getAuthorizationManager(String secDomain) throws NamingException { InitialContext ic = new InitialContext(); return (AuthorizationManager) ic.lookup(SecurityConstants.JAAS_CONTEXT_ROOT + "/" + secDomain + "/authorizationMgr"); } }
package com.opengamma.bloombergexample.loader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import javax.time.calendar.LocalDate; import javax.time.calendar.Period; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.fudgemsg.FudgeMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; import com.google.common.collect.BiMap; import com.google.common.collect.Sets; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.bbg.BloombergConstants; import com.opengamma.bbg.BloombergFields; import com.opengamma.bbg.referencedata.ReferenceDataProvider; import com.opengamma.bbg.util.BloombergDataUtils; import com.opengamma.bbg.util.BloombergTickerParserEQOption; import com.opengamma.component.tool.AbstractTool; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.financial.security.equity.EquitySecurity; import com.opengamma.financial.security.equity.GICSCode; import com.opengamma.financial.security.option.OptionType; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.UniqueId; import com.opengamma.integration.tool.IntegrationToolContext; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesInfoDocument; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesInfoSearchRequest; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesInfoSearchResult; import com.opengamma.master.portfolio.ManageablePortfolio; import com.opengamma.master.portfolio.ManageablePortfolioNode; import com.opengamma.master.portfolio.PortfolioDocument; import com.opengamma.master.portfolio.PortfolioMaster; import com.opengamma.master.portfolio.PortfolioSearchRequest; import com.opengamma.master.portfolio.PortfolioSearchResult; import com.opengamma.master.position.ManageablePosition; import com.opengamma.master.position.ManageableTrade; import com.opengamma.master.position.PositionDocument; import com.opengamma.master.security.ManageableSecurity; import com.opengamma.master.security.SecuritySearchRequest; import com.opengamma.master.security.SecuritySearchResult; import com.opengamma.util.generate.scripts.Scriptable; import com.opengamma.util.tuple.Pair; /** * A portfolio loader which generates a sensible portfolio of liquid equities and options on them Also see DemoEquityOptionPortfolioLoader. */ @Scriptable public class DemoEquityOptionCollarPortfolioLoader extends AbstractTool<IntegrationToolContext> { private static final String TOOL_NAME = "Demo Equity Option Portfolio Loader"; private static final String PORTFOLIO_NAME_OPT = "p"; private static final String OPTION_DEPTH_OPT = "d"; private static final String NUM_CONTRACTS_OPT = "n"; private static final String NUM_INDEX_MEMBERS_OPT = "m"; private static final String BLOOMBERG_EQUITY_TICKER_SUFFIX = " Equity"; private static final Logger s_logger = LoggerFactory.getLogger(DemoEquityOptionCollarPortfolioLoader.class); private static final Map<String, String> INDEXES_TO_EXCHANGE = getIndexToExchangeMap(); private static final Set<String> EXCLUDED_SECTORS = Sets.newHashSet("Financials"); private static final Period[] MEMBER_OPTION_PERIODS = new Period[] {Period.ofMonths(3), Period.ofMonths(6) }; private BigDecimal _numContracts; private int _numOptions; private int _numMembers; /** * In units of currency */ private static final BigDecimal VALUE_OF_UNDERLYING = BigDecimal.valueOf(100000); /** * The default genearted portfolio name. */ public static final String PORTFOLIO_NAME = "Equity Option Portfolio"; private static Map<String, String> getIndexToExchangeMap() { final Map<String, String> ret = new HashMap<String, String>(); ret.put("SPX", "US"); //S&P 500 -> combined US // ret.put("IBX", "BZ"); //Sao Paulo Stock Exchange IBrX Index -> combined Brazil //ret.put("TW50", "TT"); // FTSE TWSE Taiwan 50 Indx -> Taiwan Stock Exchange return ret; } /** * Main method to run the tool. No arguments are needed. * * @param args the arguments, unused */ public static void main(final String[] args) { // CSIGNORE final boolean success = new DemoEquityOptionCollarPortfolioLoader().initAndRun(args, IntegrationToolContext.class); System.exit(success ? 0 : 1); } protected ManageablePortfolio generatePortfolio(final String portfolioName) { final ReferenceDataProvider referenceDataProvider = getToolContext().getBloombergReferenceDataProvider(); final ManageablePortfolio portfolio = new ManageablePortfolio(portfolioName); //Is this a hack? final ManageablePortfolioNode rootNode = portfolio.getRootNode(); portfolio.setRootNode(rootNode); // String indexTickerSuffix = " Index"; final Set<String> memberEquities = new HashSet<String>(); for (final Entry<String, String> entry : INDEXES_TO_EXCHANGE.entrySet()) { final String indexTickerSuffix = " Index"; final String underlying = entry.getKey(); final String ticker = underlying + indexTickerSuffix; //don't add index (delete at some point) // addNodes(rootNode, ticker, false, INDEX_OPTION_PERIODS); final Set<String> indexMembers = BloombergDataUtils.getIndexMembers(referenceDataProvider, ticker); for (final String member : indexMembers) { final String symbol = getBloombergEquitySymbol(entry.getValue(), member); //time series errors for Walmart //Todo: investegate & fix if ("WMT US Equity".equals(symbol)) { continue; } memberEquities.add(symbol); } } // Sort the symbols for the current index by market cap (highest to lowest), skipping any in the list of EXCLUDED_SECTORS final TreeMap<Double, String> equityByMarketCap = new TreeMap<Double, String>(); final Map<String, FudgeMsg> refDataMap = referenceDataProvider.getReferenceData(memberEquities, Sets.newHashSet(BloombergFields.CURRENT_MARKET_CAP_FIELD, BloombergConstants.FIELD_GICS_SUB_INDUSTRY)); for (final String equity : memberEquities) { final FudgeMsg fieldData = refDataMap.get(equity); if (fieldData == null) { throw new OpenGammaRuntimeException("Information not found for equity: " + equity); } final String gicsCodeString = fieldData.getString(BloombergConstants.FIELD_GICS_SUB_INDUSTRY); if (gicsCodeString == null) { continue; } final GICSCode gicsCode = GICSCode.of(gicsCodeString); if (EXCLUDED_SECTORS.contains(gicsCode.getSectorDescription())) { continue; } final Double marketCap = fieldData.getDouble(BloombergFields.CURRENT_MARKET_CAP_FIELD); equityByMarketCap.put(marketCap, equity); } // Add a given number of symbols (MEMBERS_DEPTH) to the portfolio and store in a List // When adding to the portfolio, add a collar of options with PVs distributed equally +/- around 0 int count = 0; final List<String> chosenEquities = new ArrayList<String>(); for (final Entry<Double, String> entry : equityByMarketCap.descendingMap().entrySet()) { if (count++ >= _numMembers) { break; } addNodes(rootNode, entry.getValue(), true, MEMBER_OPTION_PERIODS); chosenEquities.add(entry.getValue()); } s_logger.info("Generated collar portfolio for {}", chosenEquities); return portfolio; } private String getBloombergEquitySymbol(final String base, final String member) { return member.split(" ")[0] + " " + base + BLOOMBERG_EQUITY_TICKER_SUFFIX; } private void addNodes(final ManageablePortfolioNode rootNode, final String underlying, final boolean includeUnderlying, final Period[] expiries) { final ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); } final ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); final HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); final double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); final Set<ExternalId> optionChain = getOptionChain(ticker); //TODO: reuse positions/nodes? final String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); final String formattedName = MessageFormatter.format("[{}] {}", underlying, longName); final ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); final BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } final TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (final ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); final BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption.getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); final LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } final Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); final BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); final BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); final BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (int i = 0; i < expiries.length; i++) { final Period bucketPeriod = expiries[i]; final ManageablePortfolioNode bucketNode = new ManageablePortfolioNode(bucketPeriod.toString().substring(1)); final LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run final LocalDate targetExpiry = nowish.plus(bucketPeriod); final LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.warn("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info("Using time {} for bucket {} ({})", new Object[] {chosenExpiry, bucketPeriod, targetExpiry }); final Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); final TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (final BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); final double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } //cascading collar? final BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); final Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info("strikes length {} index {} strike of index {}", new Object[] {Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); final StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); //Short Calls final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); //Avoid generating empty nodes } } for (final ExternalId optionTicker : tickersToLoad) { final ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (final Exception ex) { s_logger.error("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } } private void spreadOptions(final ManageablePortfolioNode bucketNode, final Collection<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> options, final OptionType type, final int scale, final Set<ExternalId> tickersToLoad, final BigDecimal underlyingAmount, final boolean includeUnderlying, final int targetNumber) { if (targetNumber == 0) { return; } final Collection<BloombergTickerParserEQOption> chosen = new ArrayList<BloombergTickerParserEQOption>(); int remaining = targetNumber; for (final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair : options) { BloombergTickerParserEQOption option; if (type == OptionType.PUT) { option = pair.getSecond(); } else { option = pair.getFirst(); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(option.getIdentifier()); final HistoricalTimeSeries ts = getToolContext().getHistoricalTimeSeriesSource().getHistoricalTimeSeries(loadedTs.getUniqueId(), LocalDate.now().minusWeeks(1), true, LocalDate.now(), true); if (ts.getTimeSeries().isEmpty()) { s_logger.info("No recent time series points for " + option.getIdentifier()); // leave in for now // continue; //This option is not liquid enough for us } } catch (final Exception ex) { s_logger.warn("Failed to get time series for " + option.getIdentifier(), ex); //TODO: stop refetching this series each time continue; //This option is not liquid enough for us } } chosen.add(option); remaining if (remaining == 0) { break; } } if (chosen.size() == 0) { s_logger.warn("Couldn't find any liquid " + type + " options from " + options); return; //TODO: should we try another expiry? } for (final BloombergTickerParserEQOption option : chosen) { tickersToLoad.add(option.getIdentifier()); addPosition(bucketNode, BigDecimal.valueOf(scale).multiply(_numContracts), option.getIdentifier()); } } private void addPosition(final ManageablePortfolioNode node, final BigDecimal amount, final ExternalId optionTicker) { final ManageablePosition position = new ManageablePosition(amount, optionTicker); final LocalDate tradeDate = getRandomTradeDate(optionTicker); final ManageableTrade trade = new ManageableTrade(amount, optionTicker, tradeDate, null, ExternalId.of("CPARTY", "BACS")); position.addTrade(trade); final PositionDocument doc = new PositionDocument(position); final PositionDocument added = getToolContext().getPositionMaster().add(doc); node.addPosition(added); } private LocalDate getRandomTradeDate(final ExternalId ticker) { final int tradeAge = (int) (3 + (Math.random() * 30)); final LocalDate tradeDate = LocalDate.now().minusDays(tradeAge); //TODO: pick a date for which PX_LAST is known return tradeDate; } private Set<ExternalId> getOptionChain(final ExternalId ticker) { if (ticker.getScheme() != ExternalSchemes.BLOOMBERG_TICKER) { throw new OpenGammaRuntimeException("Not a bloomberg ticker " + ticker); } final ReferenceDataProvider referenceDataProvider = getToolContext().getBloombergReferenceDataProvider(); final Set<ExternalId> optionChain = BloombergDataUtils.getOptionChain(referenceDataProvider, ticker.getValue()); //TODO [BBG-88] this query shouldn't get cached permanently if (optionChain == null) { throw new OpenGammaRuntimeException("Failed to get option chain for " + ticker); } s_logger.info("Got option chain {}", optionChain); return optionChain; } private double getOrLoadMostRecentPoint(HistoricalTimeSeriesInfoDocument timeSeriesInfo) { HistoricalTimeSeries timeSeries = getAllowedRecentPoints(timeSeriesInfo); if (timeSeries == null || timeSeries.getTimeSeries().isEmpty()) { if (timeSeries == null) { timeSeriesInfo = loadTimeSeries(timeSeriesInfo); } else if (timeSeries.getTimeSeries().isEmpty()) { timeSeries = updateTimeSeries(timeSeries); } timeSeries = getAllowedRecentPoints(timeSeriesInfo); if (timeSeries == null || timeSeries.getTimeSeries().isEmpty()) { throw new OpenGammaRuntimeException("Couldn't load recent points for " + timeSeriesInfo); } } final Double latestValue = timeSeries.getTimeSeries().getLatestValue(); if (latestValue == null) { throw new OpenGammaRuntimeException("Unexpected null latest vaule"); } return latestValue; } private HistoricalTimeSeries getAllowedRecentPoints(final HistoricalTimeSeriesInfoDocument timeSeriesInfo) { final LocalDate from = oldestTimeSeriesAllowed(); final HistoricalTimeSeries timeSeries = getToolContext().getHistoricalTimeSeriesSource().getHistoricalTimeSeries(timeSeriesInfo.getUniqueId().toLatest(), from, true, LocalDate.now(), true); return timeSeries; } private HistoricalTimeSeriesInfoDocument getOrLoadTimeSeries(final ExternalId ticker) { return getOrLoadTimeSeries(ticker, ExternalIdBundle.of(ticker)); } private HistoricalTimeSeriesInfoDocument getOrLoadTimeSeries(final ExternalId ticker, final ExternalIdBundle idBundle) { final ExternalIdBundle searchBundle = idBundle.withoutScheme(ExternalSchemes.ISIN); //For things which move country, e.g. ISIN(VALE5 BZ Equity) == ISIN(RIODF US Equity) final HistoricalTimeSeriesInfoSearchRequest htsRequest = new HistoricalTimeSeriesInfoSearchRequest(searchBundle); htsRequest.setDataField("PX_LAST"); final HistoricalTimeSeriesInfoSearchResult htsSearch = getToolContext().getHistoricalTimeSeriesMaster().search(htsRequest); switch (htsSearch.getDocuments().size()) { case 0: return loadTimeSeries(idBundle); case 1: break; default: throw new OpenGammaRuntimeException("Multiple time series match " + htsSearch); } final HistoricalTimeSeriesInfoDocument timeSeriesInfo = htsSearch.getDocuments().get(0); s_logger.debug("Loaded time series info {} for underlying {}", timeSeriesInfo, ticker); return timeSeriesInfo; } private HistoricalTimeSeriesInfoDocument loadTimeSeries(ExternalIdBundle idBundle) { final ReferenceDataProvider referenceDataProvider = getToolContext().getBloombergReferenceDataProvider(); if (idBundle.getExternalId(ExternalSchemes.BLOOMBERG_BUID) == null && idBundle.getExternalId(ExternalSchemes.BLOOMBERG_TICKER) != null) { //For some reason loading some series by TICKER fails, but BUID works final BiMap<String, ExternalIdBundle> map = BloombergDataUtils.convertToBloombergBuidKeys(Collections.singleton(idBundle), referenceDataProvider); if (map.size() != 1) { throw new OpenGammaRuntimeException("Failed to get buid"); } for (final String key : map.keySet()) { final String buid = referenceDataProvider.getReferenceDataValue(key, BloombergConstants.FIELD_ID_BBG_UNIQUE); idBundle = idBundle.withExternalId(ExternalSchemes.bloombergTickerSecurityId(buid)); } } final ExternalIdBundle searchBundle = idBundle.withoutScheme(ExternalSchemes.ISIN); // For things which move country, e.g. ISIN(VALE5 BZ Equity) == ISIN(RIODF US Equity) final Map<ExternalId, UniqueId> timeSeries = getToolContext().getHistoricalTimeSeriesLoader().addTimeSeries(searchBundle.getExternalIds(), "CMPL", "PX_LAST", LocalDate.now().minusYears(1), null); if (timeSeries.size() != 1) { throw new OpenGammaRuntimeException("Failed to load time series " + idBundle + " " + timeSeries); } for (final UniqueId uid : timeSeries.values()) { return getToolContext().getHistoricalTimeSeriesMaster().get(uid); } throw new OpenGammaRuntimeException("Unexpected state"); } private HistoricalTimeSeries updateTimeSeries(final HistoricalTimeSeries timeSeries) { if (!getToolContext().getHistoricalTimeSeriesLoader().updateTimeSeries(timeSeries.getUniqueId())) { throw new OpenGammaRuntimeException("Failed to update time series " + timeSeries); } //Force a cache miss on the source final HistoricalTimeSeriesInfoDocument newUid = getToolContext().getHistoricalTimeSeriesMaster().get(timeSeries.getUniqueId().toLatest()); return getToolContext().getHistoricalTimeSeriesSource().getHistoricalTimeSeries(newUid.getUniqueId()); } private HistoricalTimeSeriesInfoDocument loadTimeSeries(final HistoricalTimeSeriesInfoDocument timeSeriesInfo) { final ExternalIdBundle idBundle = timeSeriesInfo.getInfo().getExternalIdBundle().toBundle(LocalDate.now()); return loadTimeSeries(idBundle); } private LocalDate oldestTimeSeriesAllowed() { return LocalDate.now().minusWeeks(1); } private ManageableSecurity getOrLoadEquity(final ExternalId ticker) { final ManageableSecurity underlyingSecurity = getOrLoadSecurity(ticker); if (!EquitySecurity.SECURITY_TYPE.equals(underlyingSecurity.getSecurityType())) { throw new OpenGammaRuntimeException("Underlying is not an equity"); } return underlyingSecurity; } private ManageableSecurity getOrLoadSecurity(final ExternalId ticker) { final SecuritySearchResult underlyingSearch = getToolContext().getSecurityMaster().search(new SecuritySearchRequest(ticker)); switch (underlyingSearch.getDocuments().size()) { case 0: s_logger.debug("Loading security for underlying {}", ticker); return loadSecurity(ticker); case 1: return underlyingSearch.getSingleSecurity(); default: // Duplicate securities in the master s_logger.warn("Multiple securities matched search for ticker {}. Using the first. {}", ticker, underlyingSearch); return underlyingSearch.getFirstSecurity(); } } private ManageableSecurity loadSecurity(final ExternalId ticker) { final ExternalIdBundle tickerBundle = ExternalIdBundle.of(ticker); final Collection<ExternalIdBundle> bundles = Collections.singleton(tickerBundle); final Map<ExternalIdBundle, UniqueId> loaded = getToolContext().getSecurityLoader().loadSecurity(bundles); final UniqueId loadedSec = loaded.get(tickerBundle); if (loadedSec == null) { throw new OpenGammaRuntimeException("Failed to load security for " + ticker); } return getToolContext().getSecurityMaster().get(loadedSec).getSecurity(); } /** * Stores the portfolio. * * @param portfolio the portfolio, not null */ private void storePortfolio(final ManageablePortfolio portfolio) { final PortfolioMaster portfolioMaster = getToolContext().getPortfolioMaster(); final PortfolioSearchRequest req = new PortfolioSearchRequest(); req.setName(portfolio.getName()); final PortfolioSearchResult result = portfolioMaster.search(req); switch (result.getDocuments().size()) { case 0: s_logger.info("Creating new portfolio"); portfolioMaster.add(new PortfolioDocument(portfolio)); break; case 1: final UniqueId previousId = result.getDocuments().get(0).getUniqueId(); s_logger.info("Updating portfolio {}", previousId); portfolio.setUniqueId(previousId); final PortfolioDocument document = new PortfolioDocument(portfolio); document.setUniqueId(previousId); portfolioMaster.update(document); break; default: throw new OpenGammaRuntimeException("Multiple portfolios matching " + req); } } @Override protected Options createOptions(final boolean mandatoryConfigResource) { final Options options = super.createOptions(mandatoryConfigResource); options.addOption(createPortfolioNameOption()); options.addOption(createOptionDepthOption()); options.addOption(createNumContractsOption()); options.addOption(createNumMembersOption()); return options; } private static Option createPortfolioNameOption() { OptionBuilder.withLongOpt("portfolio"); OptionBuilder.withDescription("The name of the portfolio to create/update"); OptionBuilder.hasArg(); OptionBuilder.withArgName("resource"); OptionBuilder.isRequired(); return OptionBuilder.create(PORTFOLIO_NAME_OPT); } private static Option createOptionDepthOption() { OptionBuilder.withLongOpt("depth"); OptionBuilder.withDescription("Number of options on either side of the strike price"); OptionBuilder.hasArg(); OptionBuilder.withArgName("resource"); OptionBuilder.isRequired(); return OptionBuilder.create(OPTION_DEPTH_OPT); } private static Option createNumContractsOption() { OptionBuilder.withLongOpt("contracts"); OptionBuilder.withDescription("Number of contracts for each option"); OptionBuilder.hasArg(); OptionBuilder.withArgName("resource"); OptionBuilder.isRequired(); return OptionBuilder.create(NUM_CONTRACTS_OPT); } private static Option createNumMembersOption() { OptionBuilder.withLongOpt("members"); OptionBuilder.withDescription("Number underlyers from index to include"); OptionBuilder.hasArg(); OptionBuilder.withArgName("resource"); OptionBuilder.isRequired(); return OptionBuilder.create(NUM_INDEX_MEMBERS_OPT); } @Override protected void doRun() throws Exception { s_logger.info(TOOL_NAME + " is initialising..."); s_logger.info("Current working directory is " + System.getProperty("user.dir")); s_logger.info("Using portfolio \"{}\"", PORTFOLIO_NAME); s_logger.info("num index members: " + _numMembers); s_logger.info("Option Depth: " + _numOptions); s_logger.info("num contracts: {}", _numContracts.toString()); final ManageablePortfolio portfolio = generatePortfolio(PORTFOLIO_NAME); storePortfolio(portfolio); s_logger.info(TOOL_NAME + " is finished."); } public void setNumContracts(final BigDecimal numContracts) { _numContracts = numContracts; } public void setNumOptions(final int numOptions) { _numOptions = numOptions; } public void setNumMembers(final int numMembers) { _numMembers = numMembers; } }
package org.sagebionetworks.repo.manager.migration; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_FILES_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_FILES_STORAGE_LOCATION_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_STORAGE_LOCATION_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_FILES; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_STORAGE_LOCATION; import java.util.List; import org.sagebionetworks.repo.model.dbo.DBOBasicDao; import org.sagebionetworks.repo.model.dbo.DatabaseObject; import org.sagebionetworks.repo.model.dbo.dao.DBOStorageLocationDAOImpl; import org.sagebionetworks.repo.model.dbo.persistence.DBOFileHandle; import org.sagebionetworks.repo.model.dbo.persistence.DBOFileHandle.MetadataType; import org.sagebionetworks.repo.model.dbo.persistence.DBOStorageLocation; import org.sagebionetworks.repo.model.file.UploadType; import org.sagebionetworks.repo.model.migration.MigrationType; import org.sagebionetworks.repo.model.project.ExternalStorageLocationSetting; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import com.amazonaws.util.StringUtils; import com.google.common.collect.Lists; public class ExternalLocationIdSetterListener implements MigrationTypeListener { private static final String GET_ALL_STORAGE_LOCATIONS_SQL = "SELECT * FROM " + TABLE_STORAGE_LOCATION + " WHERE " + COL_STORAGE_LOCATION_ID + " != " + DBOStorageLocationDAOImpl.DEFAULT_STORAGE_LOCATION_ID; private static final String UPDATE_STORAGE_LOCATION_ID_SQL = "UPDATE " + TABLE_FILES + " SET " + COL_FILES_STORAGE_LOCATION_ID + " = ? WHERE " + COL_FILES_ID + " = ?"; @Autowired private DBOBasicDao dboBasicDao; @Autowired private JdbcTemplate jdbcTemplate; private static class Location { String url; Long storageLocationId; public Location(String url, Long storageLocationId) { this.url = url; this.storageLocationId = storageLocationId; } } @Override public <D extends DatabaseObject<?>> void afterCreateOrUpdate(MigrationType type, List<D> delta) { if (type != MigrationType.FILE_HANDLE) { return; } // get all storage locations (they are migrated before the file handles) List<DBOStorageLocation> storageLocations = jdbcTemplate.query(GET_ALL_STORAGE_LOCATIONS_SQL, new DBOStorageLocation().getTableMapping()); List<Location> locations = Lists.newArrayList(); for (DBOStorageLocation storageLocation : storageLocations) { if (storageLocation.getUploadType() != UploadType.SFTP) { continue; } if (!(storageLocation.getData() instanceof ExternalStorageLocationSetting)) { continue; } ExternalStorageLocationSetting externalStorageLocationSetting = (ExternalStorageLocationSetting) storageLocation.getData(); if (StringUtils.isNullOrEmpty(externalStorageLocationSetting.getUrl())) { continue; } locations.add(new Location(externalStorageLocationSetting.getUrl(), storageLocation.getId())); } for (D d : delta) { DBOFileHandle fileHandle = (DBOFileHandle) d; if (fileHandle.getMetadataTypeEnum() == MetadataType.EXTERNAL && fileHandle.getStorageLocationId() == null) { // see if we can find the storage location id String url = fileHandle.getKey(); if (url.startsWith("sftp: for (Location location : locations) { if (url.startsWith(location.url)) { jdbcTemplate.update(UPDATE_STORAGE_LOCATION_ID_SQL, location.storageLocationId, fileHandle.getId()); break; } } } } } } @Override public void beforeDeleteBatch(MigrationType type, List<Long> idsToDelete) { // nothing here } }
package net.formula97.andorid.car_kei_bo; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.ListView; import android.widget.AdapterView; import android.widget.SimpleCursorAdapter; import android.widget.TableLayout; import android.widget.TextView; /** * Activity * @author kazutoshi */ public class CarList extends Activity implements OnClickListener { private DbManager dbman = new DbManager(this); public static SQLiteDatabase db; Cursor cCarList = null; Cursor selectedRow = null; TextView textView_CarListTitleContainer; TextView tv_label_value_defaultcar; TableLayout TableLayout1; ListView listView_CarList; Button button_addFuelRecord; private int defaultCarID; private String defaultCarName; // ListView private int currentCarID; private String currentCarName; /** * * ActivityonCreate() * */ public CarList() { } /** * ActivityID * @param savedInstanceState Bundle * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.carlist); textView_CarListTitleContainer = (TextView)findViewById(R.id.textView_CarListTitleContainer); tv_label_value_defaultcar = (TextView)findViewById(R.id.tv_label_value_defaultcar); button_addFuelRecord = (Button)findViewById(R.id.button_addFuelRecord); listView_CarList = (ListView)findViewById(R.id.listView_CarList); } /** * Menu * @param menu * @return truefalse * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // MenuInflatergetMenuInflater() MenuInflater inflater = getMenuInflater(); // res/menu/menu.xml inflater.inflate(R.menu.optionsmenu, menu); return true; } /** * [Menu] * XML * @param item MenuItem * @return booleantruefalse * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { /* * switch * * .... */ //Intent configActivity = new Intent(this, Config.class); // Intent addCarActivity = new Intent(this, AddMyCar.class); //Intent carListActivity = new Intent(this, CarList.class); // switch (item.getItemId()) { case R.id.optionsmenu_closeAPP: finish(); return true; // case R.id.optionsmenu_call_preference: // startActivity(configActivity); // return true; case R.id.optionsmenu_addcar: startActivity(addCarActivity); return true; case R.id.optionsmenu_carlist: // CarListtrue //startActivity(carListActivity); return true; default: return false; } } /** * ActivityActivity * DBCursor * @see android.app.Activity#onPause() */ @Override protected void onPause() { super.onPause(); // CursorDB closeDbAndCursorIfOpen(); } /** * Activity * DBCursor * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { super.onDestroy(); // CursorDB closeDbAndCursorIfOpen(); } /** * Activity * * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume(); db = dbman.getReadableDatabase(); // Array // count()1AdapterCAR_MASTER // Adapter if (dbman.hasCarRecords(db)) { // Adapter cCarList = dbman.getCarList(db); Log.i("CAR_MASTER", "Got " + String.valueOf(cCarList.getCount()) + " records, including " + String.valueOf(cCarList.getColumnCount()) + " columns."); for (int i =0; i < cCarList.getColumnCount(); i++) { Log.i("CAR_MASTER", "name of Column Index " + String.valueOf(i) + ":" + cCarList.getColumnName(i)); } // AdapterListView String[] from = { "_id", "CAR_NAME", "CURRENT_FUEL_MILEAGE", "FUELMILEAGE_LABEL", "CURRENT_RUNNING_COST", "RUNNINGCOST_LABEL"}; int[] to = {R.id.tv_carID, R.id.tv_element_CarName, R.id.tv_value_FuelMileage, R.id.tv_unit_fuelMileage, R.id.tv_value_RunningCosts, R.id.tv_unit_runningCosts}; SimpleCursorAdapter sca = new SimpleCursorAdapter(getApplicationContext(), R.layout.listviewelement_carlist, cCarList, from, to); listView_CarList.setAdapter(sca); registerForContextMenu(listView_CarList); button_addFuelRecord.setOnClickListener(this); defaultCarID = dbman.getDefaultCarId(db); defaultCarName = dbman.getDefaultCarName(db); tv_label_value_defaultcar.setText(defaultCarName); // onItemClick listView_CarList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // LogCat Log.d("onItemClick", "ListView item pressed."); Log.d("onItemClick", "parent = " + parent.toString()); Log.d("onItemClick", "v = " + v.toString()); Log.d("onItemClick", "position = " + String.valueOf(position)); Log.d("onItemClick", "id = " + String.valueOf(id)); // ListView selectedRow = (Cursor)listView_CarList.getItemAtPosition(position); currentCarID = selectedRow.getInt(selectedRow.getColumnIndex("_id")); currentCarName = selectedRow.getString(selectedRow.getColumnIndex("CAR_NAME")); selectedRow.close(); showMileageList(currentCarID, currentCarName); } }); } } /** * * @param v ViewView * @see android.view.View.OnClickListener#onClick(View) */ //@Override public void onClick(View v) { // LogCat Log.d("onClick", "Button pressed."); Log.d("onClick", "v = " + v.toString()); } /** * * @param item MenuItem */ @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.ctxitem_add_mileage: addMileage(currentCarID, currentCarName); break; case R.id.ctxitem_delete_car: deleteCar(currentCarID, currentCarName); break; case R.id.ctxitem_edit_car_preference: editCarPreference(currentCarID, currentCarName); break; case R.id.ctxitem_set_default_car: changeAsDefault(currentCarID, currentCarName); break; case R.id.ctxitem_show_mileage: showMileageList(currentCarID, currentCarName); break; default: return super.onContextItemSelected(item); } return true; } /** * * onCreateContextMenu()Cursor selectedRow * * onResume() * @param menu MenuMenu * @see android.app.Activity#onContextMenuClosed(Menu) */ @Override public void onContextMenuClosed(Menu menu) { // TODO super.onContextMenuClosed(menu); onResume(); } /** * * XML * @param menu ContextMenu * @param v View * @param menuInfo ContextMenuInfo * @see android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // ListView AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo; selectedRow = (Cursor)listView_CarList.getItemAtPosition(acmi.position); currentCarID = selectedRow.getInt(selectedRow.getColumnIndex("_id")); currentCarName = selectedRow.getString(selectedRow.getColumnIndex("CAR_NAME")); // LocCat Log.d("onCreateContextMenu", "ContextMenu created, v = " + String.valueOf(v.getId())); Log.d("onCreateContextMenu", "row number = " + currentCarID); Log.d("onCreateContextMenu", "Car Name = " + currentCarName); // XML getMenuInflater().inflate(R.menu.context_carlist, menu); menu.setHeaderTitle(getString(R.string.ctxmenutitle_carlist)); // Cursor selectedRow.close(); } /** * Activity * Activityvoid * @param carId intCAR_ID * @param carName StringCAR_NAME */ protected void showMileageList(int carId, String carName) { // DBCursor closeDbAndCursorIfOpen(); Log.d(getResources().toString(), "CAR_ID : " + String.valueOf(carId)); Log.d(getResources().toString(), "CAR_NAME : " + carName); // CAR_IDCAR_NAMEstartActivity Intent i = new Intent(getApplicationContext(), MileageList.class); i.putExtra("CAR_ID", carId); i.putExtra("CAR_NAME", carName); startActivity(i); } /** * Activity * @param carId intCAR_ID * @param carName StringCAR_NAME */ protected void addMileage(int carId, String carName) { // DBCursor closeDbAndCursorIfOpen(); // CAR_IDCAR_NAMEstartActivity Intent i = new Intent(getApplicationContext(), FuelMileageAdd.class); i.putExtra("CAR_ID", carId); i.putExtra("CAR_NAME", carName); startActivity(i); } protected void changeAsDefault(int carId, String carName) { } protected void editCarPreference(int carId, String carName) { } protected void deleteCar(int carId, String carName) { } /** * CursorDB * */ protected void closeDbAndCursorIfOpen() { if (db.isOpen()) { if (dbman.hasCarRecords(db)) { if (cCarList.isClosed() != true) { cCarList.close(); } } Log.d(getApplication().toString(),"SQLite database is closing."); dbman.close(); } // if (selectedRow.isClosed() != true) { // selectedRow.close(); } }
package io; import java.awt.Image; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.logging.Logger; import javax.imageio.ImageIO; /** * Class for database communication. */ public class MySQL{ private static final HashMap<String, String> prepStmts = new HashMap<String, String>(); protected static Logger logger = Logger.getLogger(MySQL.class.getName()); protected final String RS_CLOSE_ERR = "Could not close ResultSet: "; protected final String SQL_OP_ERR = "MySQL operation failed: "; protected final ConnectionPool connPool; public MySQL(ConnectionPool connPool){ this.connPool = connPool; } static{ init(); } /** * Initialize the class, preparing the statements needed for the methods. */ private static void init(){ generateStatements(); addPrepStmt("addCache" , "REPLACE INTO cache SET id=?"); addPrepStmt("addThumb" , "INSERT INTO thumbs (url, filename, thumb) VALUES(?,?,?)"); addPrepStmt("getThumb" , "SELECT thumb FROM thumbs WHERE url = ? ORDER BY filename ASC"); addPrepStmt("pending" , "SELECT count(*) FROM filter WHERE status = 1"); addPrepStmt("isCached" , "SELECT timestamp FROM `cache` WHERE `id` = ?"); addPrepStmt("isArchive" , "SELECT * FROM `archive` WHERE `id` = ?"); addPrepStmt("isDnw" , "SELECT * FROM `dnw` WHERE `id` = ?"); addPrepStmt("prune" , "DELETE FROM `cache` WHERE `timestamp` < ?"); addPrepStmt("isHashed" , "SELECT id FROM `hash` WHERE `id` = ?"); addPrepStmt("addHash" , "INSERT INTO hash (id, dir, filename, size) VALUES (?,?,?,?)"); addPrepStmt("deleteHash" , "DELETE FROM hash WHERE id = ?"); addPrepStmt("deleteFilter" , "DELETE FROM filter WHERE id = ?"); addPrepStmt("deleteDnw" , "DELETE FROM dnw WHERE id = ?"); addPrepStmt("deleteBlock" , "DELETE FROM block WHERE id = ?"); addPrepStmt("deleteArchive" , "DELETE FROM archive WHERE id = ?"); addPrepStmt("isBlacklisted" , "SELECT * FROM `block` WHERE `id` = ?"); addPrepStmt("getDirectory" , "SELECT id FROM dirlist WHERE dirpath = ?"); addPrepStmt("getFilename" , "SELECT id FROM filelist WHERE filename = ?"); addPrepStmt("getSetting" , "SELECT param FROM settings WHERE name = ?"); } private static void generateStatements(){ for(MySQLtables table : MySQLtables.values()){ addPrepStmt("size"+table.toString(), "SELECT count(*) FROM "+table.toString()); } } protected Connection getConnection(){ try { return connPool.getConnection(); } catch (SQLException e) { logger.warning("Failed to get database connection"); } return null; } protected static void addPrepStmt(String id, String stmt){ try { if(prepStmts.containsKey(id)) throw new IllegalArgumentException("Key is already present"); prepStmts.put(id, stmt); } catch (NullPointerException npe){ logger.severe("Prepared Statement could not be created, invalid connection"); } catch (IllegalArgumentException iae){ logger.severe("Prepared Statement could not be created, "+iae.getMessage()); } } public boolean batchExecute(String[] statements){ Connection cn = getConnection(); Statement req = null; try { for(String sql : statements){ req = cn.createStatement(); req.execute(sql); req.close(); } } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); return false; } finally { silentClose(cn, null, null); } return true; } // public void addPrepStmt(String id,String stmt,int param1, int param2){ // PreparedStatement toAdd = null; // try { // toAdd = cn.prepareStatement(stmt,param1,param2); // prepStmts.put(id, toAdd); // } catch (SQLException e) { // logger.severe("Prepared Statement could not be created,\n"+e.getMessage()+ // "\n"+id // +"\n"+stmt); // public void addPrepStmt(String id,String stmt,int param1){ // PreparedStatement toAdd = null; // try { // toAdd = cn.prepareStatement(stmt,param1); // prepStmts.put(id, toAdd); // } catch (SQLException e) { // logger.severe("Prepared Statement could not be created,\n"+e.getMessage()+ // "\n"+id // +"\n"+stmt); // } catch (NullPointerException npe) { // logger.severe("Could not add Prepared Statment, invalid connection"); protected PreparedStatement getPrepStmt(String command){ if(prepStmts.containsKey(command)){ Connection cn = getConnection(); PreparedStatement prepStmt = null; try { prepStmt = cn.prepareStatement(prepStmts.get(command)); } catch (SQLException e) { logger.warning("Failed to create prepared statement for command \""+command+"\""); } return prepStmt; }else{ logger.warning("Prepared statment command \""+command+"\" not found.\nHas this object been initialized?"); return null; } } protected void silentClose(Connection cn, PreparedStatement ps, ResultSet rs){ if(rs != null) try{rs.close();}catch(SQLException e){} if(ps != null) try{ps.close();}catch(SQLException e){} if(cn != null) try{cn.close();}catch(SQLException e){} } protected void closeAll(PreparedStatement ps){ Connection cn = null; ResultSet rs = null; if(ps == null) return; try{cn = ps.getConnection();}catch(SQLException e){} try{rs = ps.getResultSet();}catch(SQLException e){} if(rs != null) try{rs.close();}catch(SQLException e){} if(ps != null) try{ps.close();}catch(SQLException e){} if(cn != null) try{cn.close();}catch(SQLException e){} } /** * Add the current URL to the cache, or update it's Timestamp if it * already exists. Method will return true if the URL is already present, * otherwise false. * @param url URL to be added * @return true if URL is already present else false. * Retruns true on error. */ public boolean addCache(URL url){ String id = url.toString(); PreparedStatement ps = getPrepStmt("addCache"); try { ps.setString(1, id); int res = ps.executeUpdate(); if(res > 1) return true; // entry was present else return false; // entry is new } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } return true; } public void addThumb(String url,String filename, byte[] data){ Connection cn = getConnection(); Blob blob = null; PreparedStatement ps = getPrepStmt("addThumb"); try { blob = cn.createBlob(); blob.setBytes(1, data); ps.setString(1, url); ps.setString(2, filename); ps.setBlob(3, blob); ps.executeUpdate(); } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); }finally{ try { if(blob != null) blob.free(); } catch (SQLException e) { logger.severe(e.getMessage()); } closeAll(ps); silentClose(cn, ps, null); } } public boolean addHash(String hash, String path, long size) { PreparedStatement ps = getPrepStmt("addHash"); try{ int[] pathId = addPath(path); if (pathId == null){ logger.warning("Invalid path data"); return false; } ps.setString(1, hash); ps.setInt(2, pathId[0]); ps.setInt(3, pathId[1]); ps.setLong(4, size); ps.execute(); return true; } catch(SQLException e){ logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } return false; } /** * Get the number of pending filter items. * @return Number of pending items. */ public int getPending(){ return simpleIntQuery("pending"); } public ArrayList<Image> getThumb(String url){ Blob blob = null; ArrayList<Image> images = new ArrayList<Image>(); InputStream is; String command = "getThumb"; ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { ps.setString(1, url); rs = ps.executeQuery(); while(rs.next()){ blob = rs.getBlob(1); is = new BufferedInputStream(blob.getBinaryStream()); images.add(ImageIO.read(is)); is.close(); blob.free(); } return images; } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } catch (IOException e) { logger.severe(e.getMessage()); }finally{ closeAll(ps); silentClose(null, ps, rs); } return null; } public int size(MySQLtables table){ return simpleIntQuery("size"+table.toString()); } /** * Check the ID against the cache. * @param uniqueID ID to check * @return true if the ID is present otherwise false. * Returns true on errors. */ public boolean isCached(URL url){ return isCached(url.toString()); } /** * Check the ID against the cache. * @param uniqueID ID to check * @return true if the ID is present otherwise false. * Returns true on errors. */ public boolean isCached(String uniqueID){ return simpleBooleanQuery("isCached", uniqueID, true); } public boolean isArchived(String hash){ return simpleBooleanQuery("isArchive", hash, true); } public boolean isDnw(String hash){ return simpleBooleanQuery("isDnw", hash, true); } public boolean isHashed(String hash){ return simpleBooleanQuery("isHashed", hash, true); } public boolean isBlacklisted(String hash){ return simpleBooleanQuery("isBlacklisted", hash, false); } private boolean simpleBooleanQuery(String command, String key, Boolean defaultReturn){ ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { ps.setString(1, key); rs = ps.executeQuery(); boolean b = rs.next(); return b; } catch (SQLException e) { logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); } finally{ closeAll(ps); } return defaultReturn; } private int simpleIntQuery(String command){ ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); if(ps == null){ logger.warning("Could not carry out query for command \""+command+"\""); return -1; } try { rs = ps.executeQuery(); rs.next(); int intValue = rs.getInt(1); return intValue; } catch (SQLException e) { logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); } finally{ closeAll(ps); } return -1; } private String simpleStringQuery(String command){ ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); if(ps == null){ logger.warning("Could not carry out query for command \""+command+"\""); return null; } try { rs = ps.executeQuery(); rs.next(); String string = rs.getString(1); return string; } catch (SQLException e) { logger.warning(SQL_OP_ERR+command+": "+e.getMessage()); } finally{ closeAll(ps); closeResultSet(rs, command); } return null; } public void pruneCache(long maxAge){ PreparedStatement ps = getPrepStmt("prune"); try { ps.setTimestamp(1,new Timestamp(maxAge)); ps.executeUpdate(); } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } } public void delete(MySQLtables table, String id){ PreparedStatement ps = getPrepStmt("delete"+table.toString()); if(ps == null){ logger.warning("Could not delete entry "+ id +" for table "+table.toString()); return; } try { ps.setString(1, id); ps.executeUpdate(); } catch (Exception e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally { closeAll(ps); } } public void sendStatement(String sqlStatment){ Connection cn = getConnection(); Statement req = null; try { req = cn.createStatement(); req.execute(sqlStatment); req.close(); } catch (SQLException e) { logger.warning("Failed to execute statement id: "+sqlStatment+"\n"+e.getMessage()); } finally { if(req != null) try{req.close();} catch (SQLException e){} silentClose(cn, null, null); } } public String getSetting(DBsettings settingName){ String command = "getSetting"; ResultSet rs = null; PreparedStatement ps = getPrepStmt(command); try { ps.setString(1, settingName.toString()); rs = ps.executeQuery(); rs.next(); String string = rs.getString(1); return string; } catch (SQLException e) { logger.warning(SQL_OP_ERR+e.getMessage()); } finally{ closeAll(ps); silentClose(null, ps, rs); } return null; } private int[] addPath(String fullPath){ int pathValue; Connection cn = null; PreparedStatement addDir = null; PreparedStatement addFile = null; try{ cn = getConnection(); addDir = cn.prepareStatement("INSERT INTO dirlist (dirpath) VALUES (?)",PreparedStatement.RETURN_GENERATED_KEYS); addFile = cn.prepareStatement("INSERT INTO filelist (filename) VALUES (?)",PreparedStatement.RETURN_GENERATED_KEYS); int split = fullPath.lastIndexOf("\\")+1; String filename = fullPath.substring(split).toLowerCase(); // bar.txt String path = fullPath.substring(0,split).toLowerCase(); // D:\foo\ int[] pathId = new int[2]; pathValue = pathLookupQuery("getDirectory", path); pathId[0] = pathAddQuery(addDir, pathValue, path); pathValue = pathLookupQuery("getFilename", filename); pathId[1] = pathAddQuery(addFile, pathValue, filename); return pathId; } catch (SQLException e) { logger.severe(e.getMessage()); } finally { silentClose(null, addDir, null); silentClose(cn, addFile, null); } return null; } private int pathLookupQuery(String command, String path) throws SQLException{ PreparedStatement ps = getPrepStmt(command); ps.setString(1, path); ResultSet rs = ps.executeQuery(); int pathValue = -1; try{ if(rs.next()){ pathValue = rs.getInt(1); } }catch (SQLException e){ throw e; }finally{ closeAll(ps); } return pathValue; } private int pathAddQuery(PreparedStatement ps, int pathLookUp, String path) throws SQLException{ int pathValue = -1; ResultSet rs = null; try{ if(pathLookUp == -1){ ps.setString(1, path); ps.execute(); rs = ps.getGeneratedKeys(); rs.next(); pathValue = rs.getInt(1); } else { pathValue = pathLookUp; } }catch (SQLException e){ throw e; } return pathValue; } private void closeResultSet(ResultSet rs, String command){ if(rs != null){ try{ rs.close(); }catch (SQLException e){ logger.warning(RS_CLOSE_ERR+e.getMessage()+" for command \""+command+"\""); } } } }
package net.minecraft.src.CraftGuide; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import net.minecraft.src.Block; import net.minecraft.src.CraftingManager; import net.minecraft.src.FurnaceRecipes; import net.minecraft.src.ItemStack; import net.minecraft.src.ModLoader; import net.minecraft.src.ShapedRecipes; import net.minecraft.src.ShapelessRecipes; import net.minecraft.src.CraftGuide.API.ICraftGuideRecipe; import net.minecraft.src.CraftGuide.API.IRecipeFilter2; import net.minecraft.src.CraftGuide.API.IRecipeGenerator; import net.minecraft.src.CraftGuide.API.IRecipeProvider; import net.minecraft.src.CraftGuide.API.IRecipeFilter; import net.minecraft.src.CraftGuide.ui.IRecipeCacheListener; public class RecipeCache { private SortedSet<CraftType> craftingTypes = new TreeSet<CraftType>(); private Map<CraftType, List<ICraftGuideRecipe>> craftResults = new HashMap<CraftType, List<ICraftGuideRecipe>>(); private List<ICraftGuideRecipe> typeResults; private List<ICraftGuideRecipe> filteredResults; private RecipeGenerator generator = new RecipeGenerator(); private ItemStack filterItem = null; private List<IRecipeCacheListener> listeners = new LinkedList<IRecipeCacheListener>(); private Set<CraftType> currentTypes = null; private SortedSet<CraftType> allItems = new TreeSet<CraftType>(); RecipeCache() { reset(); } public void reset() { Map<ItemStack, List<ICraftGuideRecipe>> rawRecipes = generateRecipes(); ReflectionAPI.applyFilters(rawRecipes); filterRawRecipes(rawRecipes); craftResults.clear(); for(ItemStack key: rawRecipes.keySet()) { CraftType type = CraftType.getInstance(key); if(!craftResults.containsKey(type)) { craftResults.put(type, new ArrayList<ICraftGuideRecipe>()); } craftResults.get(type).addAll(rawRecipes.get(key)); } generateAllItemList(); craftingTypes.addAll(craftResults.keySet()); setTypes(currentTypes); for(IRecipeCacheListener listener: listeners) { listener.onReset(this); } } private void generateAllItemList() { allItems.clear(); for(List<ICraftGuideRecipe> type: craftResults.values()) { for(ICraftGuideRecipe recipe: type) { for(ItemStack item: recipe.getItems()) { if(item != null) { allItems.add(CraftType.getInstance(item)); } } } } removeUselessDuplicates(); } private void removeUselessDuplicates() { Map<CraftType, Integer> wild = new HashMap<CraftType, Integer>(); for(CraftType item: allItems) { if(item.getStack().getItemDamage() == -1) { wild.put(item, 1); } else { for(CraftType type: wild.keySet()) { if(item.getStack().itemID == type.getStack().itemID) { wild.put(type, wild.get(type) + 1); } } } } for(CraftType type: wild.keySet()) { if(wild.get(type) == 2) { allItems.remove(type); } } } private Map<ItemStack, List<ICraftGuideRecipe>> generateRecipes() { generator.clearRecipes(); for(Object object: ReflectionAPI.APIObjects) { if(object instanceof IRecipeProvider) { ((IRecipeProvider)object).generateRecipes(generator); } } return generator.getRecipes(); } private void filterRawRecipes(Map<ItemStack, List<ICraftGuideRecipe>> rawRecipes) { for(Object object: ReflectionAPI.APIObjects) { if(object instanceof IRecipeFilter2) { rawRecipes = ((IRecipeFilter2)object).removeRecipes(rawRecipes); } else if(object instanceof IRecipeFilter) { for(ItemStack type: rawRecipes.keySet()) { rawRecipes.put(type, ((IRecipeFilter)object).removeRecipes(rawRecipes.get(type))); } } } } public void setTypes(Set<CraftType> types) { typeResults = new ArrayList<ICraftGuideRecipe>(); currentTypes = types; if(types == null) { for(CraftType type: craftingTypes) { typeResults.addAll(craftResults.get(type)); } } else { for(CraftType type: craftingTypes) { if(types.contains(type)) { typeResults.addAll(craftResults.get(type)); } } } filter(filterItem); } public List<ICraftGuideRecipe> getRecipes() { return filteredResults; } public void filter(ItemStack filter) { filterItem = filter; if(filter == null) { filteredResults = typeResults; } else { filteredResults = new ArrayList<ICraftGuideRecipe>(); for(ICraftGuideRecipe recipe: typeResults) { if(recipe.containsItem(filter)) { filteredResults.add(recipe); } } } for(IRecipeCacheListener listener: listeners) { listener.onChange(this); } } public ItemStack getFilterItem() { return filterItem; } public Set<CraftType> getCraftTypes() { return craftingTypes; } public void addListener(IRecipeCacheListener listener) { listeners.add(listener); } public SortedSet<CraftType> getAllItems() { return allItems; } }
package org.skyve.wildcat.generate; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.skyve.CORE; import org.skyve.domain.Bean; import org.skyve.domain.types.Decimal; import org.skyve.domain.types.converters.Converter; import org.skyve.domain.types.converters.Format.TextCase; import org.skyve.domain.types.converters.decimal.Decimal2Integer; import org.skyve.domain.types.converters.decimal.Decimal2IntegerPercentage; import org.skyve.domain.types.converters.decimal.Decimal2OneDecimalPlace; import org.skyve.domain.types.converters.decimal.Decimal2TwoDecimalPlacesPercentage; import org.skyve.domain.types.converters.decimal.Decimal5Integer; import org.skyve.domain.types.converters.decimal.Decimal5IntegerPercentage; import org.skyve.domain.types.converters.decimal.Decimal5OneDecimalPlace; import org.skyve.domain.types.converters.decimal.Decimal5TimeDuration; import org.skyve.domain.types.converters.decimal.Decimal5TwoDecimalPlaces; import org.skyve.domain.types.converters.decimal.Decimal5TwoDecimalPlacesPercentage; import org.skyve.domain.types.converters.decimal.currency.Decimal2DollarsAndCents; import org.skyve.domain.types.converters.decimal.currency.Decimal5DollarsAndCents; import org.skyve.domain.types.converters.integer.SimplePercentage; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.metadata.model.Persistent; import org.skyve.metadata.model.document.Association; import org.skyve.metadata.model.document.Bizlet.DomainValue; import org.skyve.metadata.model.document.Collection; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.DomainType; import org.skyve.metadata.model.document.Reference; import org.skyve.metadata.module.Module; import org.skyve.metadata.module.query.DocumentQueryDefinition; import org.skyve.metadata.module.query.QueryColumn; import org.skyve.metadata.user.User; import org.skyve.metadata.view.model.list.ListModel; import org.skyve.metadata.view.widget.bound.FilterParameter; import org.skyve.metadata.view.widget.bound.Parameter; import org.skyve.util.Binder; import org.skyve.util.Binder.TargetMetaData; import org.skyve.wildcat.bind.BindUtil; import org.skyve.wildcat.metadata.customer.CustomerImpl; import org.skyve.wildcat.metadata.model.document.DocumentImpl; import org.skyve.wildcat.metadata.model.document.field.ConvertableField; import org.skyve.wildcat.metadata.model.document.field.Date; import org.skyve.wildcat.metadata.model.document.field.DateTime; import org.skyve.wildcat.metadata.model.document.field.Decimal10; import org.skyve.wildcat.metadata.model.document.field.Decimal2; import org.skyve.wildcat.metadata.model.document.field.Decimal5; import org.skyve.wildcat.metadata.model.document.field.Field; import org.skyve.wildcat.metadata.model.document.field.LengthField; import org.skyve.wildcat.metadata.model.document.field.LongInteger; import org.skyve.wildcat.metadata.model.document.field.Text; import org.skyve.wildcat.metadata.model.document.field.TextFormat; import org.skyve.wildcat.metadata.model.document.field.Time; import org.skyve.wildcat.metadata.model.document.field.Timestamp; import org.skyve.wildcat.metadata.model.document.field.validator.DateValidator; import org.skyve.wildcat.metadata.model.document.field.validator.DecimalValidator; import org.skyve.wildcat.metadata.model.document.field.validator.IntegerValidator; import org.skyve.wildcat.metadata.model.document.field.validator.LongValidator; import org.skyve.wildcat.metadata.model.document.field.validator.TextValidator; import org.skyve.wildcat.metadata.view.HorizontalAlignment; import org.skyve.wildcat.metadata.view.widget.bound.input.HTML; import org.skyve.wildcat.metadata.view.widget.bound.input.InputWidget; import org.skyve.wildcat.metadata.view.widget.bound.input.Lookup; import org.skyve.wildcat.metadata.view.widget.bound.input.LookupDescription; import org.skyve.wildcat.metadata.view.widget.bound.input.Radio; import org.skyve.wildcat.metadata.view.widget.bound.input.RichText; public class SmartClientGenerateUtils { private SmartClientGenerateUtils() { // nothing to do } public static class SmartClientLookupDefinition { private boolean bindingToDataGrid; // The data source for the drop down box private String optionDataSource; private String displayField; // List Grid fields for option data source private List<String> pickListFields = new ArrayList<>(); // Filter fields for option data source private List<String> filterFields = new ArrayList<>(); private DocumentQueryDefinition query; private boolean canCreate; private boolean canUpdate; SmartClientLookupDefinition(boolean bindingToDataGrid, User user, Customer customer, Module module, Document document, Reference reference, LookupDescription lookup) throws MetaDataException { this.bindingToDataGrid = bindingToDataGrid; String queryName = (lookup == null) ? null : lookup.getQuery(); // Use reference query name if none provided in lookup if (queryName == null) { queryName = reference.getQueryName(); } // Use the default query if none is defined, else get the named query. if (queryName == null) { query = module.getDocumentDefaultQuery(customer, reference.getDocumentName()); queryName = query.getName(); } else { query = module.getDocumentQuery(queryName); } StringBuilder sb = new StringBuilder(128); sb.append(module.getName()).append('_').append(queryName).append('_'); sb.append(document.getName()).append('_').append(reference.getName()); optionDataSource = sb.toString(); String descriptionBinding = (lookup == null) ? null : lookup.getDescriptionBinding(); displayField = (descriptionBinding == null) ? Bean.BIZ_KEY : descriptionBinding.replace('.', '_'); Document queryDocument = module.getDocument(customer, query.getDocumentName()); canCreate = user.canCreateDocument(queryDocument); canUpdate = user.canUpdateDocument(queryDocument); Set<String> dropDownColumns = (lookup == null) ? null : lookup.getDropDownColumns(); if ((dropDownColumns == null) || dropDownColumns.isEmpty()) { pickListFields.add(displayField); } else { for (QueryColumn column : query.getColumns()) { String alias = column.getName(); if (alias == null) { alias = column.getBinding(); } if (dropDownColumns.contains(alias)) { if (column.isProjected()) { SmartClientQueryColumnDefinition def = SmartClientGenerateUtils.getQueryColumn(user, customer, module, queryDocument, column); pickListFields.add(def.getName()); // only add fields that can use the substring operator if (! def.isOnlyEqualsFilterOperators()) { filterFields.add(def.getName()); } } } } } } public String getDisplayField() { return displayField; } public void setDisplayField(String displayField) { this.displayField = displayField; } public String getOptionDataSource() { return optionDataSource; } public void setOptionDataSource(String optionDataSource) { this.optionDataSource = optionDataSource; } public List<String> getPickListFields() { return pickListFields; } public List<String> getFilterFields() { return filterFields; } public DocumentQueryDefinition getQuery() { return query; } public void setQuery(DocumentQueryDefinition query) { this.query = query; } public boolean isBindingToDataGrid() { return bindingToDataGrid; } public void setBindingToDataGrid(boolean bindingToDataGrid) { this.bindingToDataGrid = bindingToDataGrid; } public boolean getCanCreate() { return canCreate; } public void setCanCreate(boolean canCreate) { this.canCreate = canCreate; } public boolean getCanUpdate() { return canUpdate; } public void setCanUpdate(boolean canUpdate) { this.canUpdate = canUpdate; } } protected static class SmartClientAttributeDefinition { protected SmartClientLookupDefinition lookup; protected String name; protected String title; protected String type = "text"; protected String editorType; protected Integer length; protected String mask; protected String textBoxStyle; protected String validation; protected String valueMap; protected boolean required = false; protected TargetMetaData target; @SuppressWarnings("synthetic-access") protected SmartClientAttributeDefinition(Customer customer, Module module, Document document, String binding) throws MetaDataException { name = binding.replace('.', '_'); title = name; this.target = BindUtil.getMetaDataForBinding(customer, module, document, binding); Document bindingDocument = target.getDocument(); Attribute bindingAttribute = target.getAttribute(); if (binding.endsWith(Bean.BIZ_KEY)) { if (bindingDocument != null) { title = bindingDocument.getSingularAlias(); } else { title = DocumentImpl.getBizKeyAttribute().getDisplayName(); } } if ((bindingDocument != null) && (bindingAttribute != null)) { title = bindingAttribute.getDisplayName(); required = bindingAttribute.isRequired(); DomainType domainType = bindingAttribute.getDomainType(); if (domainType != null) { // constant domain types if (DomainType.constant.equals(domainType)) { valueMap = getConstantDomainValueMapString(customer, bindingDocument, bindingAttribute); } else { // variant or dynamic // this valueMap will be replaced in client logic but this defn ensures that the // select widget doesn't try to use the form's data source to get values when opened valueMap = "[' ']"; } type = "enum"; } else { DateValidator dateValidator = null; DecimalValidator decimalValidator = null; IntegerValidator integerValidator = null; LongValidator longValidator = null; if (bindingAttribute instanceof Text) { Text text = (Text) bindingAttribute; determineMaskAndStyle(text, this); TextValidator validator = text.getValidator(); if (validator != null) { @SuppressWarnings("unchecked") Converter<String> converter = (Converter<String>) text.getConverterForCustomer(customer); StringBuilder sb = new StringBuilder(128); sb.append("{expression:'").append(validator.getRegularExpression().replaceAll("'", "\'")); sb.append("',type:'regexp',errorMessage:'"); sb.append(processString(validator.constructMessage(title, converter))); sb.append("'}"); validation = sb.toString(); } } else if (bindingAttribute instanceof Date) { dateValidator = ((Date) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof DateTime) { dateValidator = ((DateTime) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof Time) { dateValidator = ((Time) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof Timestamp) { dateValidator = ((Timestamp) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof Decimal2) { decimalValidator = ((Decimal2) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof Decimal5) { decimalValidator = ((Decimal5) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof Decimal10) { decimalValidator = ((Decimal10) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof org.skyve.wildcat.metadata.model.document.field.Integer) { integerValidator = ((org.skyve.wildcat.metadata.model.document.field.Integer) bindingAttribute).getValidator(); } else if (bindingAttribute instanceof LongInteger) { longValidator = ((LongInteger) bindingAttribute).getValidator(); } try { if (dateValidator != null) { @SuppressWarnings("unchecked") Converter<java.util.Date> converter = (Converter<java.util.Date>) ((ConvertableField) bindingAttribute).getConverterForCustomer(customer); StringBuilder sb = new StringBuilder(128); sb.append('{'); java.util.Date min = dateValidator.getMin(); if (min != null) { sb.append("min:Date.parseSchemaDate('").append(Binder.convert(java.util.Date.class, min)).append("'),"); } java.util.Date max = dateValidator.getMax(); if (max != null) { sb.append("max:Date.parseSchemaDate('").append(Binder.convert(java.util.Date.class, max)).append("'),"); } sb.append("type:'dateRange',errorMessage:'"); sb.append(processString(dateValidator.constructMessage(title, converter))); sb.append("'}"); validation = sb.toString(); } else if (decimalValidator != null) { @SuppressWarnings("unchecked") Converter<Decimal> converter = (Converter<Decimal>) ((ConvertableField) bindingAttribute).getConverterForCustomer(customer); StringBuilder sb = new StringBuilder(128); sb.append('{'); Decimal min = decimalValidator.getMin(); if (min != null) { sb.append("min:").append(min).append(','); } Decimal max = decimalValidator.getMax(); if (max != null) { sb.append("max:").append(max).append(','); } sb.append("type:'floatRange',errorMessage:'"); sb.append(processString(decimalValidator.constructMessage(title, converter))); sb.append("'}"); Integer precision = decimalValidator.getPrecision(); if (precision != null) { sb.append(",{precision:").append(precision).append(",roundToPrecision:true,type:'floatPrecision',errorMessage:'"); sb.append(processString(decimalValidator.constructMessage(title, converter))); sb.append("'}"); } validation = sb.toString(); } else if (integerValidator != null) { @SuppressWarnings("unchecked") Converter<Integer> converter = (Converter<Integer>) ((ConvertableField) bindingAttribute).getConverterForCustomer(customer); StringBuilder sb = new StringBuilder(128); sb.append('{'); Integer min = integerValidator.getMin(); if (min != null) { sb.append("min:").append(min).append(','); } Integer max = integerValidator.getMax(); if (max != null) { sb.append("max:").append(max).append(','); } sb.append("type:'integerRange',errorMessage:'"); sb.append(processString(integerValidator.constructMessage(title, converter))); sb.append("'}"); validation = sb.toString(); } else if (longValidator != null) { @SuppressWarnings("unchecked") Converter<Long> converter = (Converter<Long>) ((ConvertableField) bindingAttribute).getConverterForCustomer(customer); StringBuilder sb = new StringBuilder(128); sb.append('{'); Long min = longValidator.getMin(); if (min != null) { sb.append("min:").append(min).append(','); } Long max = longValidator.getMax(); if (max != null) { sb.append("max:").append(max).append(','); } sb.append("type:'integerRange',errorMessage:'"); sb.append(processString(longValidator.constructMessage(title, converter))); sb.append("'}"); validation = sb.toString(); } } catch (Exception e) { throw new MetaDataException("Could not convert min/max values to javascript validator.", e); } } AttributeType attributeType = bindingAttribute.getAttributeType(); Converter<?> converter = null; if (bindingAttribute instanceof LengthField) { LengthField field = (LengthField) bindingAttribute; length = new Integer(field.getLength()); } else if (bindingAttribute instanceof ConvertableField) { ConvertableField field = (ConvertableField) bindingAttribute; converter = field.getConverterForCustomer(customer); } else if (bindingAttribute instanceof Collection) { name = Bean.DOCUMENT_ID; type = "enum"; } switch (attributeType) { case text: break; // already assigned at initialisation case memo: type = "text"; editorType = "TextAreaItem"; break; case markup: type = "richText"; break; case bool: type = "boolean"; break; case colour: type = "text"; editorType = "ColorItem"; break; case decimal2: type = "bizDecimal2"; if (converter instanceof Decimal2DollarsAndCents) { type = "bizDollarsAndCents"; } else if (converter instanceof Decimal2Integer) { type = "bizDecimal0"; } else if (converter instanceof Decimal2IntegerPercentage) { type = "bizIntegerPercentage"; } else if (converter instanceof Decimal2TwoDecimalPlacesPercentage) { type = "bizTwoDecimalPlacesPercentage"; } else if (converter instanceof Decimal2OneDecimalPlace) { type = "bizDecimal1"; } break; case decimal5: type = "bizDecimal5"; if (converter instanceof Decimal5DollarsAndCents) { type = "bizDollarsAndCents"; } else if (converter instanceof Decimal5Integer) { type = "bizDecimal0"; } else if (converter instanceof Decimal5IntegerPercentage) { type = "bizIntegerPercentage"; } else if (converter instanceof Decimal5OneDecimalPlace) { type = "bizDecimal1"; } else if (converter instanceof Decimal5TimeDuration) { type = "bizTimeDuration"; } else if (converter instanceof Decimal5TwoDecimalPlacesPercentage) { type = "bizTwoDecimalPlacesPercentage"; } else if (converter instanceof Decimal5TwoDecimalPlaces) { type = "bizDecimal2"; } break; case decimal10: type = "bizDecimal10"; break; case enumeration: type = "enum"; editorType = "select"; break; case integer: case longInteger: type = "integer"; if (converter instanceof SimplePercentage) { type = "bizIntegerPercentage"; } break; case date: case dateTime: case timestamp: type = (converter == null) ? "DD_MMM_YYYY" : converter.getClass().getSimpleName(); break; case time: type = (converter == null) ? "HH24_MI" : converter.getClass().getSimpleName(); break; case content: type = "bizUpload"; break; case geometry: type = "geometry"; break; case association: type = "enum"; break; case collection: // nothing yet break; default: } } } public TargetMetaData getTarget() { return target; } public String getEditorType() { return editorType; } public void setEditorType(String editorType) { this.editorType = editorType; } public SmartClientLookupDefinition getLookup() { return lookup; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValueMap() { return valueMap; } void setMask(String mask) { this.mask = mask; } void setTextBoxStyle(String textBoxStyle) { this.textBoxStyle = textBoxStyle; } // cannot get the filter row to either // 1) be a combo box in either the editor or the filter editor // result.append("',editorType:'ComboBoxItem"); // the search string is not sent in the request unless // result.append(",filterFields:['bizId', 'bizKey']"); // but including this has unexpected results also // 2) get the filter row to be a text field bound to the description binding of the field // this hangs the UI when trying to display the list void appendEditorProperties(StringBuilder result, boolean forDataGrid) { if (lookup == null) { if ((! required) && ("select".equals(type) || "enum".equals(type))) { result.append(",editorProperties:{allowEmptyValue:true}"); } else if ("geometry".equals(type)) { result.append(",formatCellValue:function(v){return GeometryItem.format(v)}"); } else { if ((mask != null) || (textBoxStyle != null)) { result.append(",editorProperties:{"); if (mask != null) { result.append("mask:'").append(mask).append("',maskSaveLiterals:true"); if (textBoxStyle != null) { result.append(','); } } if (textBoxStyle != null) { // trailing space coz SC adds more classes result.append("textBoxStyle:'").append(textBoxStyle).append(" '"); } result.append('}'); } if (validation != null) { result.append(",validators:[").append(validation).append(']'); } } } else { boolean bindingToDataGrid = lookup.isBindingToDataGrid(); result.append(",editorProperties:{optionDataSource:'").append(lookup.getOptionDataSource()); result.append("',valueField:'").append(Bean.DOCUMENT_ID); result.append("',displayField:'").append(lookup.getDisplayField()); result.append("',fetchMissingValues:false,autoFetchData:false,selectOnFocus:true,completeOnTab:true,textMatchStyle:'substring'"); if (! required) { result.append(",allowEmptyValue:true"); } // defaultDynamicValue and value map processing result.append(",defaultDynamicValue:'if(this.grid){var r=this.grid.getRecord(this.rowNum);var v=(r?r."); if (! bindingToDataGrid) { result.append(name); } else { result.append(Bean.DOCUMENT_ID); } result.append(":null);if(v){var vm=this.valueMap;vm[v]=r."); if (! bindingToDataGrid) { result.append(name).append('_'); } result.append(lookup.getDisplayField()); result.append(";return v;}}',valueMap:{}}"); // changed if (forDataGrid) { // result.append(",changed:'if(this.grid){var r=this.grid.getRecord(this.rowNum);if(r){r."); // String referenceBinding = bindingToDataGrid ? Bean.DOCUMENT_ID : name; // result.append(referenceBinding); // result.append("=this.getValue();r."); // if (! bindingToDataGrid) { // result.append(name).append('_'); // result.append(lookup.getDisplayField()); // result.append("=this.getDisplayValue();return r.").append(referenceBinding).append(";}}'"); } else { result.append(",filterEditorProperties:{optionDataSource:'").append(lookup.getOptionDataSource()); result.append("',valueField:'").append(Bean.DOCUMENT_ID); result.append("',displayField:'").append(lookup.getDisplayField()); result.append("',fetchMissingValues:false,autoFetchData:false,selectOnFocus:true,completeOnTab:true,textMatchStyle:'substring'}"); } result.append(",sortByDisplayField:true,valueField:'"); if (! bindingToDataGrid) { result.append(name); } else { result.append(Bean.DOCUMENT_ID); } result.append("',displayField:'"); if (! bindingToDataGrid) { result.append(name).append('_'); } result.append(lookup.getDisplayField()); result.append("',pickListFields:["); List<String> pickListFields = lookup.getPickListFields(); for (String pickListField : pickListFields) { result.append("{name:'").append(pickListField).append("'},"); } if (! pickListFields.isEmpty()) { result.setLength(result.length() - 1); // remove last pick list field comma } result.append(']'); List<String> filterFields = lookup.getFilterFields(); if (! filterFields.isEmpty()) { result.append(",filterFields:["); for (String filterField : filterFields) { result.append('\'').append(filterField).append("',"); } result.setLength(result.length() - 1); // remove last pick list field comma result.append(']'); } } } } public static class SmartClientDataGridFieldDefinition extends SmartClientAttributeDefinition { protected HorizontalAlignment align; protected boolean editable; protected Integer pixelWidth; protected String defaultValueJavascriptExpression; SmartClientDataGridFieldDefinition(User user, Customer customer, Module module, Document document, InputWidget widget, String dataGridBindingOverride) throws MetaDataException { super(customer, module, document, (dataGridBindingOverride == null) ? widget.getBinding() : dataGridBindingOverride); // for datagrids, ensure that enum types are text so that valueMaps don't have to be set all the time. if ("enum".equals(type)) { type = "text"; } Attribute attribute = target.getAttribute(); if (attribute instanceof Field) { // determine the defaultValue expression for the list grid defaultValueJavascriptExpression = ((Field) attribute).getDefaultValue(); if (defaultValueJavascriptExpression != null) { AttributeType attributeType = attribute.getAttributeType(); if (AttributeType.date.equals(attributeType) || AttributeType.dateTime.equals(attributeType) || AttributeType.time.equals(attributeType) || AttributeType.timestamp.equals(attributeType)) { defaultValueJavascriptExpression = new StringBuilder(128).append("Date.parseSchemaDate('").append(defaultValueJavascriptExpression).append("')").toString(); } else if (! (AttributeType.bool.equals(attributeType) || AttributeType.integer.equals(attributeType) || AttributeType.longInteger.equals(attributeType))) { defaultValueJavascriptExpression = new StringBuilder(128).append('\'').append(defaultValueJavascriptExpression).append('\'').toString(); } } } if ((attribute instanceof Reference) && (widget instanceof LookupDescription)) { // widget could be a combo for instance editorType = "comboBox"; lookup = new SmartClientLookupDefinition(dataGridBindingOverride != null, user, customer, module, document, (Reference) attribute, (LookupDescription) widget); } // By default a SmartClientDataGridDefinition sets memo fields to a text area. if ((attribute != null) && AttributeType.memo.equals(attribute.getAttributeType())) { if ((widget instanceof RichText) || (widget instanceof HTML)) { editorType = null; } } // set the default alignment if (attribute != null) { AttributeType attributeType = attribute.getAttributeType(); if (AttributeType.date.equals(attributeType) || AttributeType.dateTime.equals(attributeType) || AttributeType.time.equals(attributeType) || AttributeType.timestamp.equals(attributeType) || AttributeType.decimal2.equals(attributeType) || AttributeType.decimal5.equals(attributeType) || AttributeType.decimal10.equals(attributeType) || AttributeType.integer.equals(attributeType) || AttributeType.longInteger.equals(attributeType)) { align = HorizontalAlignment.right; } else if (AttributeType.bool.equals(attributeType)) { align = HorizontalAlignment.centre; } else { align = HorizontalAlignment.left; } } } public HorizontalAlignment getAlign() { return align; } public void setAlign(HorizontalAlignment align) { this.align = align; } public boolean getEditable() { return editable; } public void setEditable(boolean editable) { this.editable = editable; } public Integer getPixelWidth() { return pixelWidth; } public void setPixelWidth(Integer pixelWidth) { this.pixelWidth = pixelWidth; } public String toJavascript() { StringBuilder result = new StringBuilder(128); result.append("name:'"); result.append(name); result.append("',title:'"); result.append(processString(title)); result.append("',type:'"); result.append(type).append('\''); if (defaultValueJavascriptExpression != null) { result.append(",defaultValue:").append(defaultValueJavascriptExpression); } if (editorType != null) { result.append(",editorType:'").append(editorType).append('\''); } appendEditorProperties(result, true); if (required) { result.append(",bizRequired:true,requiredMessage:'").append(processString(title)).append(" is required.'"); } if (valueMap != null) { result.append(",valueMap:").append(valueMap); } if (align != null) { result.append(",align:'").append(align.toAlignmentString()).append('\''); } if (length != null) { result.append(",length:").append(length); } if (! editable) { result.append(",canEdit:false"); } if (pixelWidth != null) { result.append(",width:").append(pixelWidth); } // TODO fix this //result.append(",changed:'alert(item.grid.getSelectedRecord().bizId)'"); return result.toString(); } } public static class SmartClientFieldDefinition extends SmartClientDataGridFieldDefinition { private HorizontalAlignment textAlign; private String helpText; SmartClientFieldDefinition(User user, Customer customer, Module module, Document document, InputWidget widget) throws MetaDataException { super(user, customer, module, document, widget, null); Attribute attribute = target.getAttribute(); if (attribute != null) { helpText = attribute.getDescription(); if (AttributeType.time.equals(attribute.getAttributeType())) { textAlign = HorizontalAlignment.right; } } // Use a drop down for grids but in the edit view, use the radio group as specified if (widget instanceof Radio) { editorType = null; // is set to "select" in the SmartClientDataGridFieldDefinition } // Use a combo box for grids but in the edit view, use the lookup description as specified if (widget instanceof LookupDescription) { editorType = null; // is set to "comboBox" in the SmartClientDataGridFieldDefinition } } public String getHelpText() { return helpText; } public void setHelpText(String helpText) { this.helpText = helpText; } @Override public String toJavascript() { StringBuilder result = new StringBuilder(128); result.append("name:'"); result.append(name); result.append("',title:'"); result.append(processString(title)); result.append("',type:'"); result.append(type); if (editorType != null) { result.append("',editorType:'").append(editorType); } if (length != null) { result.append("',length:").append(length); } else { result.append('\''); } if (valueMap != null) { result.append(",valueMap:").append(valueMap); } if (required) { result.append(",bizRequired:true,requiredMessage:'").append(processString(title)).append(" is required.'"); } else { if ("select".equals(type)) { result.append(",allowEmptyValue:true"); } } if (mask != null) { result.append(",mask:'").append(mask).append("',maskSaveLiterals:true"); } if (textBoxStyle != null) { // trailing space coz SC adds more classes result.append(",textBoxStyle:'").append(textBoxStyle).append(" '"); } if (validation != null) { result.append(",validators:[").append(validation).append(']'); } if (textAlign != null) { result.append(",textAlign:'").append(textAlign.toAlignmentString()).append('\''); } if (helpText != null) { result.append(",icons:[{src:'icons/help.png',tabIndex:-1,showOver:true,neverDisable:true,prompt:'"); result.append("<em><b>").append(title).append("</b></em><p/>"); result.append(processString(helpText, false, true)); result.append("',click:'isc.say(this.prompt)'}]"); } if (lookup != null) { result.append(",optionDataSource:'").append(lookup.getOptionDataSource()); result.append("',valueField:'").append(Bean.DOCUMENT_ID); result.append("',displayField:'").append(lookup.getDisplayField()); result.append("',pickListFields:["); List<String> pickListFields = lookup.getPickListFields(); for (String pickListField : pickListFields) { result.append("{name:'").append(pickListField).append("'},"); } if (! pickListFields.isEmpty()) { result.setLength(result.length() - 1); // remove last pick list field comma } result.append(']'); List<String> filterFields = lookup.getFilterFields(); if (! filterFields.isEmpty()) { result.append(",filterFields:["); for (String filterField : filterFields) { result.append('\'').append(filterField).append("',"); } result.setLength(result.length() - 1); // remove last pick list field comma result.append(']'); } } return result.toString(); } } public static class SmartClientQueryColumnDefinition extends SmartClientAttributeDefinition { private boolean canFilter = true; private boolean canSave = true; private boolean detail = false; private boolean canSortClientOnly = false; private boolean onlyEqualsFilterOperators = false; SmartClientQueryColumnDefinition(User user, Customer customer, Module module, Document document, QueryColumn column) throws MetaDataException { super(customer, module, document, (column.getBinding() == null) ? column.getName() : column.getBinding()); String displayName = column.getDisplayName(); if (displayName != null) { title = displayName; } Attribute attribute = target.getAttribute(); if (attribute != null) { DomainType domainType = attribute.getDomainType(); if (domainType != null) { onlyEqualsFilterOperators = true; if (DomainType.variant.equals(domainType) || DomainType.dynamic.equals(domainType)) { canSave = false; } } else { if (attribute instanceof Text) { Text text = (Text) attribute; determineMaskAndStyle(text, this); } } if (attribute instanceof Association) { String targetDocumentName = ((Association) attribute).getDocumentName(); Document targetDocument = module.getDocument(customer, targetDocumentName); Persistent targetPersistent = targetDocument.getPersistent(); if (targetPersistent.getName() != null) { // this is a persistent target document - not a mapped document type = "text"; editorType = "comboBox"; lookup = new SmartClientLookupDefinition(false, user, customer, module, document, (Reference) attribute, null); } } } canFilter = column.isFilterable(); detail = column.isHidden(); canSortClientOnly = (! column.isSortable()); canSave = canSave && column.isEditable(); } public boolean isCanFilter() { return canFilter; } public void setCanFilter(boolean canFilter) { this.canFilter = canFilter; } public boolean isCanSave() { return canSave; } public void setCanSave(boolean canSave) { this.canSave = canSave; } public boolean isCanSortClientOnly() { return canSortClientOnly; } public void setCanSortClientOnly(boolean canSortClientOnly) { this.canSortClientOnly = canSortClientOnly; } public boolean isDetail() { return detail; } public void setDetail(boolean detail) { this.detail = detail; } public String getMask() { return mask; } public boolean isOnlyEqualsFilterOperators() { return onlyEqualsFilterOperators; } public String toJavascript() { StringBuilder result = new StringBuilder(64); result.append("name:'"); result.append(name); result.append("',title:'"); result.append(processString(title)); result.append("',type:'"); result.append(type); if (editorType != null) { result.append("',editorType:'").append(editorType); } if (length != null) { result.append("',length:").append(length); } else { result.append('\''); } appendEditorProperties(result, false); if (valueMap != null) { result.append(",valueMap:").append(valueMap); } if (required) { result.append(",bizRequired:true,requiredMessage:'").append(processString(title)).append(" is required.'"); } if (! canFilter) { result.append(",canFilter:false"); } if (! canSave) { result.append(",canSave:false"); } if (detail) { result.append(",detail:true"); } if (canSortClientOnly) { // TODO should use the listgridcolumn to set sorting off result.append(",canSortClientOnly:true"); } if (onlyEqualsFilterOperators) { result.append(",validOperators:['equals','notEqual']"); } else if ("geometry".equals(type)) { result.append(",validOperators:GeometryItem.validOperators"); } return result.toString(); } } private static String getConstantDomainValueMapString(Customer customer, Document document, Attribute attribute) throws MetaDataException { List<DomainValue> values = ((DocumentImpl) document).getDomainValues((CustomerImpl) customer, DomainType.constant, attribute, null); StringBuilder sb = new StringBuilder(64); sb.append('{'); for (DomainValue value : values) { sb.append('\'').append(value.getCode()).append("':'"); sb.append(processString(value.getDescription())).append("',"); } if (values.isEmpty()) { // no values sb.append('}'); } else { sb.setCharAt(sb.length() - 1, '}'); // replace last comma } return sb.toString(); } public static Map<String, String> getConstantDomainValueMap(Customer customer, Document document, Attribute attribute) throws MetaDataException { List<DomainValue> values = ((DocumentImpl) document).getDomainValues((CustomerImpl) customer, DomainType.constant, attribute, null); Map<String, String> result = new TreeMap<>(); for (DomainValue value : values) { result.put(value.getCode(), processString(value.getDescription())); } return result; } /** * My spec is * A - alphanumeric * # - digit * L - letter * * SC spec is * Character Description * 0 Digit (0 through 9) or plus [+] or minus [-] signs * 9 Digit or space * # Digit * L Letter (A through Z) * ? Letter (A through Z) or space * A Letter or digit * a Letter or digit * C Any character or space * < Causes all characters that follow to be converted to lowercase * > Causes all characters that follow to be converted to uppercase * * This method escapes anything that should be literal and then * converts the expression taking into consideration the case setting. * * @param text * @return */ static void determineMaskAndStyle(Text text, SmartClientAttributeDefinition def) { String mask = null; TextFormat format = text.getFormat(); if (format != null) { mask = format.getMask(); if (mask != null) { // first escape characters with meaning mask = mask.replace("0", "\\0"); mask = mask.replace("9", "\\9"); mask = mask.replace("?", "\\?"); mask = mask.replace("a", "\\a"); mask = mask.replace("C", "\\C"); mask = mask.replace("<", "\\<"); mask = mask.replace(">", "\\>"); } TextCase textCase = format.getCase(); if (TextCase.capital.equals(textCase)) { if (mask == null) { def.setTextBoxStyle("textItem bizhubTextCapital"); } else { int lIndex = mask.indexOf('L'); if (lIndex >= 0) { mask = new StringBuilder(mask).replace(lIndex, lIndex + 1, ">L<").toString(); } } } else if (TextCase.lower.equals(textCase)) { if (mask == null) { def.setTextBoxStyle("textItem bizhubTextLower"); } else { mask = '<' + mask; } } else if (TextCase.upper.equals(textCase)) { if (mask == null) { def.setTextBoxStyle("textItem bizhubTextUpper"); } else { mask = '>' + mask; } } } def.setMask(mask); } public static SmartClientQueryColumnDefinition getQueryColumn(User user, Customer customer, Module module, Document document, QueryColumn column) throws MetaDataException { return new SmartClientQueryColumnDefinition(user, customer, module, document, column); } /** * Get the smart client field definition given the widget/binding. * If bindingOverride is defined, it will be used to determine the field to use. * bindingOverride is used when a Datagrid has a lookupDescription which has no binding. * That is, the lookupDescription is for the entire dataGrid entity. * * @param customer * @param module * @param document * @param widget The widget metadata to use to define the smart client form field * @param bindingOverride If defined, specifies a different binding to use. * @return * @throws MetaDataException */ public static SmartClientFieldDefinition getField(User user, Customer customer, Module module, Document document, InputWidget widget) throws MetaDataException { return new SmartClientFieldDefinition(user, customer, module, document, widget); } public static SmartClientDataGridFieldDefinition getDataGridField(User user, Customer customer, Module module, Document document, InputWidget widget, String dataGridBinding) throws MetaDataException { return new SmartClientDataGridFieldDefinition(user, customer, module, document, widget, dataGridBinding); } /** * Appends a data source definition from a document list model. * @param user * @param customer * @param model * @param toAppendTo definition is appended to this * @return The ID for the query definition generated. * @throws MetaDataException */ public static String appendDataSourceDefinition(User user, Customer customer, Module owningModule, Document owningDocument, String modelName, boolean config, StringBuilder toAppendTo, Set<String> visitedQueryNames) throws MetaDataException { ListModel<Bean> model = CORE.getRepository().getListModel(customer, owningDocument, modelName); Document drivingDocument = model.getDrivingDocument(); Module drivingDocumentModule = customer.getModule(drivingDocument.getOwningModuleName()); return appendDataSourceDefinition(user, customer, owningModule.getName(), owningDocument, drivingDocumentModule, drivingDocument, null, modelName, model.getDescription(), model.getColumns(), null, null, config, toAppendTo, visitedQueryNames); } /** * Appends a data source definition from a module query. * @param customer * @param query * @param dataSourceIDOverride ID of created data source if mandated * @param hiddenBindings Extra bindings to include in the data source - not mandatory * @param config Whether to create a partial config data source defn for the menu items * @param toAppendTo definition is appended to this * @return The ID for the query definition generated. * @throws MetaDataException */ public static String appendDataSourceDefinition(User user, Customer customer, DocumentQueryDefinition query, String dataSourceIDOverride, Lookup forLookup, boolean config, StringBuilder toAppendTo, Set<String> visitedQueryNames) throws MetaDataException { String documentName = query.getDocumentName(); Module documentModule = query.getDocumentModule(customer); Module owningModule = query.getOwningModule(); Document drivingDocument = documentModule.getDocument(customer, documentName); return appendDataSourceDefinition(user, customer, owningModule.getName(), drivingDocument, documentModule, drivingDocument, query.getName(), null, query.getDescription(), query.getColumns(), dataSourceIDOverride, forLookup, config, toAppendTo, visitedQueryNames); } @SuppressWarnings("null") private static String appendDataSourceDefinition(User user, Customer customer, String owningModuleName, Document owningDocument, Module drivingDocumentModule, Document drivingDocument, String queryName, String modelName, String description, List<QueryColumn> columns, String dataSourceIDOverride, Lookup forLookup, boolean config, StringBuilder toAppendTo, Set<String> visitedQueryNames) throws MetaDataException { // dataSourceId -> defn Map<String, String> childDataSources = new TreeMap<>(); String drivingDocumentName = drivingDocument.getName(); String dataSourceId = null; if (dataSourceIDOverride != null) { dataSourceId = dataSourceIDOverride; } else if (queryName != null) { dataSourceId = new StringBuilder(32).append(owningModuleName).append('_').append(queryName).toString(); } else if (modelName != null) { // NB 4 tokens, not 3 dataSourceId = new StringBuilder(32).append(owningModuleName).append('_').append(owningDocument.getName()).append("__").append(modelName).toString(); } if (visitedQueryNames == null) { toAppendTo.append("if(window.").append(dataSourceId); toAppendTo.append("){}else{isc.RestDataSource.create({dataFormat:'json',dataURL:'smartlist',"); toAppendTo.append("operationBindings:[{operationType:'fetch',dataProtocol:'postParams'},"); toAppendTo.append("{operationType:'update',dataProtocol:'postParams'},"); toAppendTo.append("{operationType:'add',dataProtocol:'postParams'},"); toAppendTo.append("{operationType:'remove',dataProtocol:'postParams'}],"); } else { if (visitedQueryNames.contains(dataSourceId)) { return dataSourceId; } toAppendTo.append('{'); } toAppendTo.append("ID:'").append(dataSourceId); toAppendTo.append("',modoc:'"); toAppendTo.append(drivingDocumentModule.getName()); toAppendTo.append('.'); toAppendTo.append(drivingDocumentName); toAppendTo.append("',icon:'").append(drivingDocument.getIcon32x32RelativeFileName()); if (! config) { // ensure all filtering is server-side // this enables the summary row to always stay in sync toAppendTo.append("',criteriaPolicy:'dropOnChange"); } toAppendTo.append("',canCreate:").append(user.canCreateDocument(drivingDocument)); toAppendTo.append(",canUpdate:").append(user.canUpdateDocument(drivingDocument)); toAppendTo.append(",canDelete:").append(user.canDeleteDocument(drivingDocument)); toAppendTo.append(",title:'"); toAppendTo.append(processString(description)); toAppendTo.append("',fields:["); if (! config) { toAppendTo.append("{name:'bizTagged',title:'Tag',type:'boolean',validOperators:['equals']},"); toAppendTo.append("{name:'bizFlagComment',title:'Flag'},"); //,length:1024} long length makes filter builder use a text area } if (drivingDocumentName.equals(drivingDocument.getParentDocumentName())) { // hierarchical toAppendTo.append("{name:'bizParentId',title:'Parent ID',type:'text',hidden:true,foreignKey:'"); toAppendTo.append(dataSourceId).append(".bizId'},"); } List<String> hiddenBindingsList = new ArrayList<>(); if (forLookup instanceof LookupDescription) { hiddenBindingsList.add(((LookupDescription) forLookup).getDescriptionBinding()); } if (forLookup != null) { List<FilterParameter> parameters = forLookup.getParameters(); if (parameters != null) { for (Parameter parameter : parameters) { hiddenBindingsList.add(parameter.getName()); } } } for (QueryColumn column : columns) { if (! column.isProjected()) { continue; } SmartClientQueryColumnDefinition def = getQueryColumn(user, customer, drivingDocumentModule, drivingDocument, column); toAppendTo.append('{').append(def.toJavascript()).append("},"); SmartClientLookupDefinition lookup = def.getLookup(); if (lookup != null) { StringBuilder childDataSourceDefinition = new StringBuilder(512); String childDataSourceId = appendDataSourceDefinition(user, customer, lookup.getQuery(), lookup.getOptionDataSource(), null, config, childDataSourceDefinition, visitedQueryNames); childDataSources.put(childDataSourceId, childDataSourceDefinition.toString()); } if (hiddenBindingsList != null) { hiddenBindingsList.remove(column.getBinding()); } } if (! config) { // for filtering toAppendTo.append("{name: 'operator', type: 'text', hidden: true},"); toAppendTo.append("{name: 'criteria', type: 'text', hidden: true},"); // standard for all rows toAppendTo.append("{name: 'bizId', primaryKey: true, hidden: true},"); toAppendTo.append("{name:'bizLock', hidden: true},"); } for (String hiddenBinding : hiddenBindingsList) { toAppendTo.append("{name:'").append(hiddenBinding.replace('.', '_')); toAppendTo.append("',type:'text',hidden:true},"); } if (toAppendTo.charAt(toAppendTo.length() - 1) == ',') { // if we have a comma then we at least have a field in the data source toAppendTo.setLength(toAppendTo.length() - 1); // remove the last field comma } toAppendTo.append("]"); if (visitedQueryNames == null) { toAppendTo.append("});}\n"); } else { toAppendTo.append("},\n"); visitedQueryNames.add(dataSourceId); } // Add any child datasources found for (String childDataSourceDefinition : childDataSources.values()) { toAppendTo.append(childDataSourceDefinition).append('\n'); } return dataSourceId; } public static String processString(String value) { return processString(value, true, true); } public static String processString(String value, boolean escapeDoubleQuotes, boolean escapeNewLines) { if (value == null) { return null; } String result = value.replace("'", "\\'"); if (escapeDoubleQuotes) { result = result.replace("\"", "&quot;"); } if (escapeNewLines) { result = result.replace("\n", "<br/>"); } else { result = result.replace("\n", ""); } return result; } }
package net.wurstclient.features.mods; import java.lang.reflect.Field; import java.util.Collection; import java.util.Comparator; import java.util.TreeMap; import net.wurstclient.features.Mod; import net.wurstclient.features.mods.combat.*; import net.wurstclient.features.mods.fun.DerpMod; import net.wurstclient.features.mods.fun.HeadRollMod; import net.wurstclient.features.mods.fun.HeadlessMod; import net.wurstclient.features.mods.fun.LsdMod; import net.wurstclient.features.mods.fun.MileyCyrusMod; import net.wurstclient.features.mods.fun.SkinDerpMod; import net.wurstclient.features.mods.fun.TiredMod; import net.wurstclient.features.mods.items.CmdBlockMod; import net.wurstclient.features.mods.items.CrashChestMod; import net.wurstclient.features.mods.items.CrashTagMod; import net.wurstclient.features.mods.items.KillPotionMod; import net.wurstclient.features.mods.items.TrollPotionMod; import net.wurstclient.features.mods.retro.FastBowMod; import net.wurstclient.features.mods.retro.FastEatMod; import net.wurstclient.features.mods.retro.ForcePushMod; import net.wurstclient.features.mods.retro.RegenMod; public class ModManager { private final TreeMap<String, Mod> mods = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); public final AntiAfkMod antiAfkMod = new AntiAfkMod(); public final AntiBlindMod antiBlindMod = new AntiBlindMod(); public final AntiCactusMod antiCactusMod = new AntiCactusMod(); public final AntiFireMod antiFireMod = new AntiFireMod(); public final AntiKnockbackMod antiKnockbackMod = new AntiKnockbackMod(); public final AntiPotionMod antiPotionMod = new AntiPotionMod(); public final AntiSpamMod antiSpamMod = new AntiSpamMod(); public final AutoArmorMod autoArmorMod = new AutoArmorMod(); public final AutoBuildMod autoBuildMod = new AutoBuildMod(); public final AutoLeaveMod autoLeaveMod = new AutoLeaveMod(); public final AutoEatMod autoEatMod = new AutoEatMod(); public final AutoFishMod autoFishMod = new AutoFishMod(); public final AutoMineMod autoMineMod = new AutoMineMod(); public final AutoRespawnMod autoRespawnMod = new AutoRespawnMod(); public final AutoSignMod autoSignMod = new AutoSignMod(); public final AutoSplashPotMod autoSplashPotMod = new AutoSplashPotMod(); public final AutoSoupMod autoSoupMod = new AutoSoupMod(); public final AutoSprintMod autoSprintMod = new AutoSprintMod(); public final AutoStealMod autoStealMod = new AutoStealMod(); public final AutoSwitchMod autoSwitchMod = new AutoSwitchMod(); public final AutoSwordMod autoSwordMod = new AutoSwordMod(); public final AutoToolMod autoToolMod = new AutoToolMod(); public final AutoWalkMod autoWalkMod = new AutoWalkMod(); public final BaseFinderMod baseFinderMod = new BaseFinderMod(); public final BlinkMod blinkMod = new BlinkMod(); public final BoatFlyMod boatFlyMod = new BoatFlyMod(); public final BonemealAuraMod bonemealAuraMod = new BonemealAuraMod(); public final BowAimbotMod bowAimbotMod = new BowAimbotMod(); public final BuildRandomMod buildRandomMod = new BuildRandomMod(); public final BunnyHopMod bunnyHopMod = new BunnyHopMod(); public final CaveFinderMod caveFinderMod = new CaveFinderMod(); public final ChestEspMod chestEspMod = new ChestEspMod(); public final ClickAuraMod clickAuraMod = new ClickAuraMod(); public final CmdBlockMod cmdBlockMod = new CmdBlockMod(); public final CrashChestMod crashChestMod = new CrashChestMod(); public final CrashTagMod crashTagMod = new CrashTagMod(); public final CriticalsMod criticalsMod = new CriticalsMod(); public final DerpMod derpMod = new DerpMod(); public final DolphinMod dolphinMod = new DolphinMod(); public final ExtraElytraMod extraElytraMod = new ExtraElytraMod(); public final FancyChatMod fancyChatMod = new FancyChatMod(); public final FastBreakMod fastBreakMod = new FastBreakMod(); public final FastBowMod fastBowMod = new FastBowMod(); public final FastEatMod fastEatMod = new FastEatMod(); public final FastLadderMod fastLadderMod = new FastLadderMod(); public final FastPlaceMod fastPlaceMod = new FastPlaceMod(); public final FightBotMod fightBotMod = new FightBotMod(); public final FlightMod flightMod = new FlightMod(); public final FollowMod followMod = new FollowMod(); public final ForceOpMod forceOpMod = new ForceOpMod(); public final ForcePushMod forcePushMod = new ForcePushMod(); public final FreecamMod freecamMod = new FreecamMod(); public final FullbrightMod fullbrightMod = new FullbrightMod(); public final GhostHandMod ghostHandMod = new GhostHandMod(); public final GlideMod glideMod = new GlideMod(); public final HeadlessMod headlessMod = new HeadlessMod(); public final HeadRollMod headRollMod = new HeadRollMod(); public final HealthTagsMod healthTagsMod = new HealthTagsMod(); public final HighJumpMod highJumpMod = new HighJumpMod(); public final HomeMod homeMod = new HomeMod(); public final InstantBunkerMod instantBunkerMod = new InstantBunkerMod(); public final InvisibilityMod invisibilityMod = new InvisibilityMod(); public final ItemEspMod itemEspMod = new ItemEspMod(); public final JesusMod jesusMod = new JesusMod(); public final JetpackMod jetpackMod = new JetpackMod(); public final KaboomMod kaboomMod = new KaboomMod(); public final KillauraLegitMod killauraLegitMod = new KillauraLegitMod(); public final KillauraMod killauraMod = new KillauraMod(); public final KillPotionMod killPotionMod = new KillPotionMod(); public final LiquidsMod liquidsMod = new LiquidsMod(); public final LogSpammerMod logSpammerMod = new LogSpammerMod(); public final LsdMod lsdMod = new LsdMod(); public final MassTpaMod massTpaMod = new MassTpaMod(); public final MenuWalkMod menuWalkMod = new MenuWalkMod(); public final MileyCyrusMod mileyCyrusMod = new MileyCyrusMod(); public final MobEspMod mobEspMod = new MobEspMod(); public final MultiAuraMod multiAuraMod = new MultiAuraMod(); public final NameProtectMod nameProtectMod = new NameProtectMod(); public final NameTagsMod nameTagsMod = new NameTagsMod(); public final NavigatorMod navigatorMod = new NavigatorMod(); public final NoClipMod noClipMod = new NoClipMod(); public final NoFallMod noFallMod = new NoFallMod(); public final NoHurtcamMod noHurtcamMod = new NoHurtcamMod(); public final NoOverlayMod noOverlayMod = new NoOverlayMod(); public final NoSlowdownMod noSlowdownMod = new NoSlowdownMod(); public final NoWeatherMod noWeatherMod = new NoWeatherMod(); public final NoWebMod noWebMod = new NoWebMod(); public final NukerMod nukerMod = new NukerMod(); public final NukerLegitMod nukerLegitMod = new NukerLegitMod(); public final OverlayMod overlayMod = new OverlayMod(); public final PanicMod panicMod = new PanicMod(); public final ParkourMod parkourMod = new ParkourMod(); public final PhaseMod phaseMod = new PhaseMod(); public final PlayerEspMod playerEspMod = new PlayerEspMod(); public final PlayerFinderMod playerFinderMod = new PlayerFinderMod(); public final PotionSaverMod potionSaverMod = new PotionSaverMod(); public final ProphuntEspMod prophuntEspMod = new ProphuntEspMod(); public final ProtectMod protectMod = new ProtectMod(); public final RegenMod regenMod = new RegenMod(); public final RemoteViewMod remoteViewMod = new RemoteViewMod(); public final SafeWalkMod safeWalkMod = new SafeWalkMod(); public final ScaffoldWalkMod scaffoldWalkMod = new ScaffoldWalkMod(); public final SearchMod searchMod = new SearchMod(); public final SkinDerpMod skinDerpMod = new SkinDerpMod(); public final SneakMod sneakMod = new SneakMod(); public final SpammerMod spammerMod = new SpammerMod(); public final SpeedHackMod speedHackMod = new SpeedHackMod(); public final SpeedNukerMod speedNukerMod = new SpeedNukerMod(); public final SpiderMod spiderMod = new SpiderMod(); public final StepMod stepMod = new StepMod(); public final TemplateToolMod templateToolMod = new TemplateToolMod(); public final ThrowMod throwMod = new ThrowMod(); public final TimerMod timerMod = new TimerMod(); public final TiredMod tiredMod = new TiredMod(); public final TracersMod tracersMod = new TracersMod(); public final TpAuraMod tpAuraMod = new TpAuraMod(); public final TrajectoriesMod trajectoriesMod = new TrajectoriesMod(); public final TriggerBotMod triggerBotMod = new TriggerBotMod(); public final TrollPotionMod trollPotionMod = new TrollPotionMod(); public final TrueSightMod trueSightMod = new TrueSightMod(); public final TunnellerMod tunnellerMod = new TunnellerMod(); public final XRayMod xRayMod = new XRayMod(); public ModManager() { try { for(Field field : ModManager.class.getFields()) if(field.getName().endsWith("Mod")) { Mod mod = (Mod)field.get(this); mods.put(mod.getName(), mod); mod.initSettings(); } }catch(Exception e) { e.printStackTrace(); } } public Mod getModByName(String name) { return mods.get(name); } public Collection<Mod> getAllMods() { return mods.values(); } public int countMods() { return mods.size(); } }
package org.knowm.xchange.okcoin; import java.util.ArrayList; import java.util.List; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.account.Balance; import org.knowm.xchange.dto.account.FundingRecord; import org.knowm.xchange.dto.account.FundingRecord.Status; import org.knowm.xchange.dto.account.FundingRecord.Type; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.okcoin.v3.dto.account.OkexDepositRecord; import org.knowm.xchange.okcoin.v3.dto.account.OkexFundingAccountRecord; import org.knowm.xchange.okcoin.v3.dto.account.OkexSpotAccountRecord; import org.knowm.xchange.okcoin.v3.dto.account.OkexWithdrawalRecord; import org.knowm.xchange.okcoin.v3.dto.marketdata.OkexOrderBook; import org.knowm.xchange.okcoin.v3.dto.marketdata.OkexOrderBookEntry; import org.knowm.xchange.okcoin.v3.dto.marketdata.OkexSpotTicker; import org.knowm.xchange.okcoin.v3.dto.trade.FuturesAccountsResponse.FuturesAccount; import org.knowm.xchange.okcoin.v3.dto.trade.OkexOpenOrder; import org.knowm.xchange.okcoin.v3.dto.trade.Side; import org.knowm.xchange.okcoin.v3.dto.trade.SwapAccountsResponse.SwapAccountInfo; public class OkexAdaptersV3 { public static Balance convert(OkexFundingAccountRecord rec) { return new Balance.Builder() .currency(Currency.getInstance(rec.getCurrency())) .available(rec.getAvailable()) .frozen(rec.getBalance().subtract(rec.getAvailable())) .total(rec.getBalance()) .build(); } public static Balance convert(OkexSpotAccountRecord rec) { return new Balance.Builder() .currency(Currency.getInstance(rec.getCurrency())) .available(rec.getAvailable()) .frozen(rec.getBalance().subtract(rec.getAvailable())) .total(rec.getBalance()) .build(); } public static Balance convert(String currency, FuturesAccount acc) { return new Balance.Builder() .currency(Currency.getInstance(currency.toUpperCase())) .total(acc.getEquity()) .build(); } public static Balance convert(SwapAccountInfo rec) { return new Balance.Builder() .currency(toPair(rec.getInstrumentId()).base) .total(rec.getEquity()) .build(); } public static String toSpotInstrument(CurrencyPair pair) { return pair == null ? null : pair.base.getCurrencyCode() + "-" + pair.counter.getCurrencyCode(); } /** * there are different types of instruments: spot (ie 'ETH-BTC'), future (ie 'BCH-USD-190927'), * swap (ie 'ETH-USD-SWAP') * * @param instrument * @return */ public static CurrencyPair toPair(String instrument) { String[] split = instrument.split("-"); if (split == null || split.length < 2) { throw new ExchangeException("Not supported instrument: " + instrument); } return new CurrencyPair(split[0], split[1]); } public static Ticker convert(OkexSpotTicker i) { return new Ticker.Builder() .currencyPair(toPair(i.getInstrumentId())) .last(i.getLast()) .bid(i.getBid()) .ask(i.getAsk()) .volume(i.getBaseVolume24h()) .quoteVolume(i.getQuoteVolume24h()) .timestamp(i.getTimestamp()) .build(); } public static LimitOrder convert(OkexOpenOrder o) { return new LimitOrder.Builder( o.getSide() == Side.sell ? OrderType.ASK : OrderType.BID, toPair(o.getInstrumentId())) .id(o.getOrderId()) .limitPrice(o.getPrice()) .originalAmount(o.getSize()) .timestamp(o.getCreatedAt()) .build(); } public static FundingRecord adaptFundingRecord(OkexWithdrawalRecord r) { return new FundingRecord.Builder() .setAddress(r.getTo()) .setAmount(r.getAmount()) .setCurrency(Currency.getInstance(r.getCurrency())) .setDate(r.getTimestamp()) .setInternalId(r.getWithdrawalId()) .setStatus(convertWithdrawalStatus(r.getStatus())) .setBlockchainTransactionHash(r.getTxid()) .setType(Type.WITHDRAWAL) .build(); } /** * -3:pending cancel; -2: cancelled; -1: failed; 0 :pending; 1 :sending; 2:sent; 3 :email * confirmation; 4 :manual confirmation; 5:awaiting identity confirmation */ private static Status convertWithdrawalStatus(String status) { switch (status) { case "-3": case "-2": return Status.CANCELLED; case "-1": return Status.FAILED; case "0": case "1": case "3": case "4": case "5": return Status.PROCESSING; case "2": return Status.COMPLETE; default: throw new ExchangeException("Unknown withdrawal status: " + status); } } public static FundingRecord adaptFundingRecord(OkexDepositRecord r) { return new FundingRecord.Builder() .setAddress(r.getTo()) .setAmount(r.getAmount()) .setCurrency(Currency.getInstance(r.getCurrency())) .setDate(r.getTimestamp()) .setStatus(convertDepositStatus(r.getStatus())) .setBlockchainTransactionHash(r.getTxid()) .setType(Type.DEPOSIT) .build(); } /** * The status of deposits (0: waiting for confirmation; 1: confirmation account; 2: recharge * success); */ private static Status convertDepositStatus(String status) { switch (status) { case "0": case "1": case "6": return Status.PROCESSING; case "2": return Status.COMPLETE; default: throw new ExchangeException("Unknown deposit status: " + status); } } public static OrderBook convertOrderBook(OkexOrderBook book, CurrencyPair currencyPair) { List<LimitOrder> asks = toLimitOrderList(book.getAsks(), OrderType.ASK, currencyPair); List<LimitOrder> bids = toLimitOrderList(book.getBids(), OrderType.BID, currencyPair); return new OrderBook(null, asks, bids); } private static List<LimitOrder> toLimitOrderList( OkexOrderBookEntry[] levels, OrderType orderType, CurrencyPair currencyPair) { List<LimitOrder> allLevels = new ArrayList<>(); if (levels != null) { for (int i = 0; i < levels.length; i++) { OkexOrderBookEntry ask = levels[i]; allLevels.add( new LimitOrder(orderType, ask.getVolume(), currencyPair, "0", null, ask.getPrice())); } } return allLevels; } }
package nl.b3p.viewer.config.services; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import javax.persistence.*; import nl.b3p.viewer.config.ClobElement; import nl.b3p.web.WaitPageStatus; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.data.ServiceInfo; import org.geotools.data.ows.HTTPClient; import org.geotools.data.ows.LayerDescription; import org.geotools.data.ows.SimpleHttpClient; import org.geotools.data.ows.Specification; import org.geotools.data.wfs.WFSDataStoreFactory; import org.geotools.data.wms.*; import org.geotools.data.wms.request.DescribeLayerRequest; import org.geotools.data.wms.response.DescribeLayerResponse; import org.geotools.ows.ServiceException; import org.stripesstuff.stripersist.Stripersist; /** * Entity for saving WMS service metadata. Enables the administration module to * easily work with WMS service entities and the viewer to quickly marshall the * metadata without having to do a GetCapabilities request each time the viewer * starts. * <p> * This requires an option to update the metadata should the service change, so * this class implements Updatable. * <p> * @author Matthijs Laan */ @Entity @DiscriminatorValue(WMSService.PROTOCOL) public class WMSService extends GeoService implements Updatable { private static final Log log = LogFactory.getLog(WMSService.class); /** * JPA DiscriminatorValue for this class. */ public static final String PROTOCOL = "wms"; /** * Parameter to specify the value for #getOverrideUrl(). */ public static final String PARAM_OVERRIDE_URL = "overrideUrl"; /** * HTTP Basic authentication username to use with pre-emptive authentication. */ public static final String PARAM_USERNAME = "username"; /** * HTTP Basic authentication password to use with pre-emptive authentication. */ public static final String PARAM_PASSWORD = "password"; /** * Additional persistent property for this subclass, so type must be nullable. */ private Boolean overrideUrl; /** * Whether to use the original URL the Capabilities was loaded with or the * URL the WMS reports it is at in the Capabilities. Sometimes the URL reported * by the WMS is outdated, but it can also be used to migrate the service * to another URL or load Capabilities from a static XML Capabilities document * on a simple HTTP server. According to the standard the URL in the Capabilities * should be used, so set this to false by default except if the user requests * an override. */ public Boolean getOverrideUrl() { return overrideUrl; } public void setOverrideUrl(Boolean overrideUrl) { this.overrideUrl = overrideUrl; } @Override public String toString() { return String.format("WMS service \"%s\" at %s", getName(), getUrl()); } //<editor-fold desc="Loading from WMS URL"> /** * Load WMS metadata from URL or only check if the service is online when * PARAM_ONLINE_CHECK_ONLY is true. * @param url The location of the WMS. * @param params Map containing parameters, keys are finals in this class. * @param status For reporting progress. */ @Override public WMSService loadFromUrl(String url, Map params, WaitPageStatus status) throws Exception { try { status.setCurrentAction("Ophalen informatie..."); WMSService wmsService = new WMSService(); wmsService.setUsername((String)params.get(PARAM_USERNAME)); wmsService.setPassword((String)params.get(PARAM_PASSWORD)); wmsService.setUrl(url); wmsService.setOverrideUrl(Boolean.TRUE.equals(params.get(PARAM_OVERRIDE_URL))); WebMapServer wms = wmsService.getWebMapServer(); if(Boolean.TRUE.equals(params.get(GeoService.PARAM_ONLINE_CHECK_ONLY))) { return null; } wmsService.load(wms, params, status); // Set unique Feature Source names FeatureSource.setUniqueNames(getAutomaticallyLinkedFeatureSources(wmsService.getTopLayer())); return wmsService; } finally { status.setProgress(100); status.setCurrentAction("Service ingeladen"); status.setFinished(true); } } /** * Do the actual loading work. */ protected void load(WebMapServer wms, Map params, WaitPageStatus status) throws IOException, MalformedURLException, ServiceException { ServiceInfo si = wms.getInfo(); setName(si.getTitle()); String serviceUrl = si.getSource().toString(); if(getOverrideUrl() &&!getUrl().equals(serviceUrl)) { getDetails().put(GeoService.DETAIL_OVERRIDDEN_URL, new ClobElement(serviceUrl)); } else { setUrl(serviceUrl); } getKeywords().addAll(si.getKeywords()); status.setCurrentAction("Inladen layers..."); boolean supportsDescribeLayer = wms.getCapabilities().getRequest().getDescribeLayer() != null; status.setProgress(supportsDescribeLayer ? 40 : 90); org.geotools.data.ows.Layer rl = wms.getCapabilities().getLayer(); setTopLayer(new Layer(rl, this)); if(supportsDescribeLayer) { status.setProgress(60); status.setCurrentAction("Gerelateerde WFS bronnen opzoeken..."); Map<String,List<LayerDescription>> layerDescByWfs = getDescribeLayerPerWFS(wms); if(layerDescByWfs != null) { status.setProgress(80); String action = "Gerelateerde WFS bron inladen..."; String[] wfses = (String[])layerDescByWfs.keySet().toArray(new String[] {}); for(int i = 0; i < wfses.length; i++) { String wfsUrl = wfses[i]; String wfsAction = action + (wfses.length > 1 ? " (" + (i+1) + " van " + wfses.length + ")" : ""); status.setCurrentAction(wfsAction); List<LayerDescription> layerDescriptions = layerDescByWfs.get(wfsUrl); loadLayerFeatureTypes(wfsUrl, layerDescriptions); } } } } /** * Construct the GeoTools WebMapServer metadata object. */ protected WebMapServer getWebMapServer() throws IOException, MalformedURLException, ServiceException { HTTPClient client = new SimpleHttpClient(); client.setUser(getUsername()); client.setPassword(getPassword()); return new WebMapServer(new URL(getUrl()), client) { @Override protected void setupSpecifications() { specs = new Specification[] { new WMS1_0_0(), new WMS1_1_0(), new WMS1_1_1() // No WMS 1.3.0, GeoTools GetCaps parser cannot handle // ExtendedCapabilities such as inspire_common:MetadataUrl, // for example PDOK. See: }; } }; } //</editor-fold> // <editor-fold desc="Updating"> /** * Reload the WMS capabilities metadata and update this entity if it is * changed. If {@link #getOverrideUrl()} is false, will pickup URL changes * from the service. */ @Override public UpdateResult update() { initLayerCollectionsForUpdate(); final UpdateResult result = new UpdateResult(this); try { Map params = new HashMap(); params.put(PARAM_OVERRIDE_URL, getOverrideUrl()); params.put(PARAM_USERNAME, getUsername()); params.put(PARAM_PASSWORD, getPassword()); WMSService update = loadFromUrl(getUrl(), params, result.getWaitPageStatus().subtask("", 80)); if(!getUrl().equals(update.getUrl())) { this.setUrl(update.getUrl()); result.changed(); } // XXX does this lead to update(), needs equals() guards? if(Boolean.TRUE.equals(getOverrideUrl())) { getDetails().put(DETAIL_OVERRIDDEN_URL, update.getDetails().get(DETAIL_OVERRIDDEN_URL)); } else { getDetails().remove(DETAIL_OVERRIDDEN_URL); } if(!getDetails().containsKey(DETAIL_ORIGINAL_NAME)) { getDetails().put(DETAIL_ORIGINAL_NAME, new ClobElement(update.getName())); } else { setName(update.getName()); } if(!getKeywords().equals(update.getKeywords())) { getKeywords().clear(); getKeywords().addAll(update.getKeywords()); } // Find auto-linked FeatureSource (manually linked feature sources // not updated automatically) Set<FeatureSource> linkedFS = getAutomaticallyLinkedFeatureSources(getTopLayer()); Map<String,WFSFeatureSource> linkedFSByURL = createFeatureSourceMapByURL(linkedFS); List<SimpleFeatureType> typesToRemove = new ArrayList(); updateWFS(update, linkedFSByURL, typesToRemove, result); updateLayers(update, linkedFSByURL, result); updateLayerTree(update, result); removeOrphanLayersAfterUpdate(result); removeFeatureTypes(typesToRemove, result); // WFSFeatureSources which are no longer used are not updated // Maybe remove these result.setStatus(UpdateResult.Status.UPDATED); } catch(Exception e) { result.failedWithException(e); } return result; } private Map<String, WFSFeatureSource> createFeatureSourceMapByURL(Collection<FeatureSource> fsCollection) { Map<String, WFSFeatureSource> map = new HashMap(); for(FeatureSource fs: fsCollection) { map.put(fs.getUrl(), (WFSFeatureSource)fs); } return map; } private void removeFeatureTypes(Collection<SimpleFeatureType> typesToRemove, UpdateResult result) { if(typesToRemove.isEmpty()) { return; } SimpleFeatureType.clearReferences(typesToRemove); for(SimpleFeatureType typeToRemove: typesToRemove) { typeToRemove.getFeatureSource().getFeatureTypes().remove(typeToRemove); Stripersist.getEntityManager().remove(typeToRemove); } } private static Set<FeatureSource> getAutomaticallyLinkedFeatureSources(Layer top) { final GeoService service = top.getService(); final Set<FeatureSource> featureSources = new HashSet(); top.accept(new Layer.Visitor() { @Override public boolean visit(Layer l) { if(l.getFeatureType() != null) { FeatureSource fs = l.getFeatureType().getFeatureSource(); // Do not include manually linked feature sources if(fs.getLinkedService() == service) { featureSources.add((WFSFeatureSource)fs); } } return true; } }); return featureSources; } private void updateWFS(final WMSService updateWMS, final Map<String,WFSFeatureSource> linkedFSesByURL, Collection<SimpleFeatureType> outTypesToRemove, final UpdateResult result) { final Set<FeatureSource> updateFSes = getAutomaticallyLinkedFeatureSources(updateWMS.getTopLayer()); for(FeatureSource fs: updateFSes) { WFSFeatureSource oldFS = linkedFSesByURL.get(fs.getUrl()); if(oldFS == null) { log.info("Found new WFS with URL " + fs.getUrl() + " linked to WMS"); // Make available for updating layers in map, will be persisted // by cascade from Layer linkedFSesByURL.put(fs.getUrl(), (WFSFeatureSource)fs); fs.setLinkedService(this); } else { log.info("Updating WFS with URL " + fs.getUrl() + " linked to WMS"); // Update or add all feature types from updated FS for(SimpleFeatureType updateFT: fs.getFeatureTypes()) { boolean isNew = updateFT == oldFS.addOrUpdateFeatureType(updateFT.getTypeName(), updateFT); if(isNew) { log.info("New feature type in WFS: " + updateFT.getTypeName()); } } // Find feature types which do not exist in updated FS // Remove these later on- Set<SimpleFeatureType> typesToRemove = new HashSet(); for(SimpleFeatureType oldFT: oldFS.getFeatureTypes()) { if(fs.getFeatureType(oldFT.getTypeName()) == null) { // Don'tnot modify list which we are iterating on typesToRemove.add(oldFT); log.info("Feature type " + oldFT.getTypeName() + " does no longer exist"); } } outTypesToRemove.addAll(typesToRemove); } } } /** * Internal update method for layers. Update result.layerStatus() which * currently has all layers set to MISSING. New layers are set to NEW, with * a clone plucked from the updated service tree. Existing layers are set to * UNMODIFIED or UPDATED (Layer entities modified) * <p> * Duplicate layers are not updated (will be removed later). * <p> * Grouping layers (no name) are ignored. */ private void updateLayers(final WMSService update, final Map<String,WFSFeatureSource> linkedFSesByURL, final UpdateResult result) { final WMSService updatingWMSService = this; update.getTopLayer().accept(new Layer.Visitor() { @Override public boolean visit(Layer l) { if(l.getName() == null) { // Grouping layer only return true; } MutablePair<Layer,UpdateResult.Status> layerStatus = result.getLayerStatus().get(l.getName()); if(layerStatus == null) { // New layer, pluck a copy from the tree that will be made // persistent. // Plucking a clone is necessary because the children // and parent will be set on this instance later on and we // need the original children to traverse the updated service // tree while doing that l = l.pluckCopy(); result.getLayerStatus().put(l.getName(), new MutablePair(l, UpdateResult.Status.NEW)); if(l.getFeatureType() != null) { // We may already have an updated previously persistent // FeatureType / FeatureSource // New FeatureSources were added to the linkedFSesByURL // map in updateWFS() WFSFeatureSource fs = linkedFSesByURL.get(l.getFeatureType().getFeatureSource().getUrl()); l.setFeatureType(fs.getFeatureType(l.getFeatureType().getTypeName())); } } else { if(layerStatus.getRight() != UpdateResult.Status.MISSING) { // Already processed, ignore duplicate layer return true; } Layer old = layerStatus.getLeft(); // Pluck from old tree old.setParent(null); old.getChildren().clear(); // The layer properties are ignored for update status, only // its featuretype determines changed boolean old.update(l); layerStatus.setRight(UpdateResult.Status.UNMODIFIED); // Only update feature type if not manually set to feature // this service (has linkedService set to updatingWMSService) if(old.getFeatureType() == null || old.getFeatureType().getFeatureSource().getLinkedService() == updatingWMSService) { // FeatureType instance may be the same (already updated in // updateWFS(), or a new FeatureType (put in linkedFSesByURL // map by the same method) if(l.getFeatureType() != null) { WFSFeatureSource fs = linkedFSesByURL.get(l.getFeatureType().getFeatureSource().getUrl()); old.setFeatureType(fs.getFeatureType(l.getFeatureType().getTypeName())); } else { old.setFeatureType(null); } } // XXX set UPDATED status if different } return true; } }); } /** * Update the tree structure of Layers by following the tree structure and * setting the parent and children accordingly. Reuses entities for layers * which are UNMODIFIED or UPDATED and inserts new entities for NEW layers. * <p> * Because virtual layers with null name cannot be updated, those are always * recreated and user set properties are lost, except those set on the top * layer which are preserved. * <p> * Interface should disallow setting user properties (especially authorizations) * on virtual layers. */ private void updateLayerTree(final WMSService update, final UpdateResult result) { Layer newTopLayer; String topLayerName = update.getTopLayer().getName(); if(topLayerName == null) { // Start with a new no name topLayer newTopLayer = update.getTopLayer().pluckCopy(); } else { // Old persistent top layer or new plucked copy from updated service newTopLayer = result.getLayerStatus().get(topLayerName).getLeft(); } // Copy user set stuff over from old toplayer, even if name was changed // or topLayer has no name newTopLayer.copyUserModifiedProperties(getTopLayer()); newTopLayer.setParent(null); newTopLayer.setService(this); newTopLayer.getChildren().clear(); setTopLayer(newTopLayer); // Do a breadth-first traversal to set the parent and fill the children // list of all layers. // For the breadth-first traversal save layers from updated service to // visit with their (possibly persistent) parent layers from this service // XXX why did we need BFS? Queue<Pair<Layer,Layer>> q = new LinkedList(); // Start at children of topLayer from updated service, topLayer handled // above for(Layer child: update.getTopLayer().getChildren()) { q.add(new ImmutablePair(child, newTopLayer)); } Set<String> visitedLayerNames = new HashSet(); do { // Remove from head of queue Pair<Layer,Layer> p = q.remove(); Layer updateLayer = p.getLeft(); // layer from updated service Layer parent = p.getRight(); // parent layer from this Layer thisLayer; String layerName = updateLayer.getName(); if(layerName == null) { // 'New' no name layer - we can't possibly guess if it is // the same as an already existing no name layer so always // new entity thisLayer = updateLayer.pluckCopy(); } else { if(visitedLayerNames.contains(layerName)) { // Duplicate layer in updated service -- ignore this one thisLayer = null; } else { // Find possibly already persistent updated layer // (depth first) - if new already a pluckCopy() thisLayer = result.getLayerStatus().get(layerName).getLeft(); visitedLayerNames.add(layerName); } } if(thisLayer != null) { thisLayer.setService(this); thisLayer.setParent(parent); parent.getChildren().add(thisLayer); } for(Layer child: updateLayer.getChildren()) { // Add add end of queue q.add(new ImmutablePair(child, thisLayer)); } } while(!q.isEmpty()); } private void removeOrphanLayersAfterUpdate(UpdateResult result) { // Remove old stuff: duplicate layers from old this service, old layers // with null name which are all replaced for(Layer l: result.getDuplicateOrNoNameLayers()) { Stripersist.getEntityManager().remove(l); } // Remove old layers from this service which are missing from updated // service for(Pair<Layer,UpdateResult.Status> p: result.getLayerStatus().values()) { if(p.getRight() == UpdateResult.Status.MISSING) { Stripersist.getEntityManager().remove(p.getLeft()); } } } //</editor-fold> //<editor-fold desc="DescribeLayer and WFS"> /** * Do a DescribeLayer request and put the response LayerDescription in a map * keyed by WFS URL * @param wms WebMapServer to get the DescribeLayer response from * @return A map keyed with the WFS URL containing LayerDescriptions for that WFS * or null if something went wrong (non-fatal - warning logged) */ private static Map<String,List<LayerDescription>> getDescribeLayerPerWFS(WebMapServer wms) { StringBuffer layers = new StringBuffer(); DescribeLayerResponse dlr = null; try { getAllNonVirtualLayers(layers, wms.getCapabilities().getLayer()); DescribeLayerRequest dlreq = wms.createDescribeLayerRequest(); dlreq.setProperty("VERSION", wms.getCapabilities().getVersion()); dlreq.setLayers(layers.toString()); log.debug("Issuing DescribeLayer request for WMS " + wms.getInfo().getSource().toString() + " with layers=" + layers); dlr = wms.issueRequest(dlreq); } catch(Exception e) { log.warn("DescribeLayer request failed for layers " + layers + " on service " + wms.getInfo().getSource().toString(), e); } if(dlr == null) { return null; } Map<String,List<LayerDescription>> layerDescByWfs = new HashMap<String,List<LayerDescription>>(); for(LayerDescription ld: dlr.getLayerDescs()) { log.debug(String.format("DescribeLayer response, name=%s, wfs=%s, typeNames=%s", ld.getName(), ld.getWfs(), Arrays.toString(ld.getQueries()) )); if(ld.getWfs() != null && ld.getQueries() != null && ld.getQueries().length != 0) { List<LayerDescription> lds = layerDescByWfs.get(ld.getWfs().toString()); if(lds == null) { lds = new ArrayList<LayerDescription>(); layerDescByWfs.put(ld.getWfs().toString(), lds); } lds.add(ld); } } return layerDescByWfs; } /** * Get all non-virtual layers for the DescribeLayer request (layer with a * name is non-virtual). * @param sb StringBuffer building the LAYERS parameter for DescribeLayer * @param l the top layer */ private static void getAllNonVirtualLayers(StringBuffer sb, org.geotools.data.ows.Layer l) { if(l.getName() != null) { if(sb.length() > 0) { sb.append(","); } sb.append(l.getName()); } for(org.geotools.data.ows.Layer child: l.getChildren()) { getAllNonVirtualLayers(sb, child); } } /** * Set feature types for layers in the WMSService from the given WFS according * to the DescribeLayer response. When errors occur these are logged but no * exception is thrown. Note: DescribeLayer may return multiple type names * for a layer, this is not supported - only the first one is used. * @param wfsUrl the WFS URL * @param layerDescriptions description of which feature types of the WFS are * used in layers of this service according to DescribeLayer */ public void loadLayerFeatureTypes(String wfsUrl, List<LayerDescription> layerDescriptions) { Map p = new HashMap(); p.put(WFSDataStoreFactory.URL.key, wfsUrl); p.put(WFSDataStoreFactory.USERNAME.key, getUsername()); p.put(WFSDataStoreFactory.PASSWORD.key, getPassword()); try { WFSFeatureSource wfsFs = new WFSFeatureSource(p); wfsFs.loadFeatureTypes(); boolean used = false; for(LayerDescription ld: layerDescriptions) { Layer l = getLayer(ld.getName()); if(l != null) { if(ld.getQueries().length != 1) { log.debug("Cannot handle multiple typeNames for this layer, only using the first"); } SimpleFeatureType sft = wfsFs.getFeatureType(ld.getQueries()[0]); if(sft != null) { l.setFeatureType(sft); log.debug("Feature type for layer " + l.getName() + " set to feature type " + sft.getTypeName()); used = true; } } } if(used) { log.debug("Type from WFSFeatureSource with url " + wfsUrl + " used by layer of WMS"); wfsFs.setLinkedService(this); log.debug("Unique name found for WFSFeatureSource: " + wfsFs.getName()); } else { log.debug("No type from WFSFeatureSource with url " + wfsUrl + " used!"); } } catch(Exception e) { log.error("Error loading WFS from url " + wfsUrl, e); } } //</editor-fold> }
package nl.sense_os.service.commonsense; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.telephony.TelephonyManager; import android.util.Log; import nl.sense_os.service.ISenseService; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensePrefs; import nl.sense_os.service.constants.SensePrefs.Auth; import nl.sense_os.service.constants.SensePrefs.Main.Advanced; import nl.sense_os.service.constants.SenseUrls; import nl.sense_os.service.constants.SensorData.SensorNames; import org.apache.http.conn.ssl.SSLSocketFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; public class SenseApi { /** * Application secrets that give an app access to the current CommonSense session ID. * * @see ISenseService#getSessionId(String) */ private static class AppSecrets { static final String SENSE = "]C@+[G1be,f)@3mz|2cj4gq~Jz(8WE&_$7g:,-KOI;v:iQt<r;1OQ@=mr}jmE8>!"; static final String ASK = "3$2Sp16096H*Rg!n*<G<411&8QlMvg!pMyN]q?m[5c|<N+$=/~Su{quv$/j5s`+6"; static final String RDAM_CS = "0$HTLi8e_}9^s7r#[_L~-ndz=t5z)e}I-ai#L22-?0+i7jfF2,~)oyi|H)q*GL$Y"; } private static final String TAG = "SenseApi"; private static final long CACHE_REFRESH = 1000l * 60 * 60; // 1 hour /** * @param context * Context for accessing phone details * @return The default device type, i.e. the phone's model String */ private static String getDefaultDeviceType(Context context) { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); return authPrefs.getString(Auth.DEVICE_TYPE, Build.MODEL); } /** * @param context * Context for accessing phone details * @return The default device UUID, i.e. the phone's IMEI String */ private static String getDefaultDeviceUuid(Context context) { return ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)) .getDeviceId(); } /** * Gets the device ID for use with CommonSense. The device ID is cached in the preferences if it * was fetched earlier. * * @param context * Context for getting preferences * @param uuid * (Optional) Device UUID. Set null to use the default device UUID for this phone * @return The device ID, or -1 if the device is not registered yet * @throws IOException * If the connection to CommonSense failed. * @throws JSONException * On unexpected response from CommonSense. */ public static int getDeviceId(Context context, String uuid) throws IOException, JSONException { SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); // append name and UUID to the preference keys String keyDeviceId = uuid == null ? Auth.DEVICE_ID : Auth.DEVICE_ID + uuid; String keyIdTime = uuid == null ? Auth.DEVICE_ID_TIME : Auth.DEVICE_ID_TIME + uuid; String keySensorList = uuid == null ? Auth.SENSOR_LIST : Auth.SENSOR_LIST + uuid; // try to get the device ID from the cache try { int cachedId = authPrefs.getInt(keyDeviceId, -1); long cacheTime = authPrefs.getLong(keyIdTime, 0); boolean isOutdated = System.currentTimeMillis() - cacheTime > CACHE_REFRESH; // return cached ID of it is still valid if (cachedId != -1 && false == isOutdated) { return cachedId; } } catch (Exception e) { // should not happen Log.e(TAG, "Failed to get device ID from cache! Exception while checking cache: ", e); } // if we make it here, the device ID was not in the cache // Log.v(TAG, "Device ID is missing or outdated, refreshing..."); // get phone IMEI, this is used as the device UUID at CommonSense if (uuid == null) { uuid = getDefaultDeviceUuid(context); } // get list of devices that are already registered at CommonSense for this user SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); if (devMode) Log.i(TAG, "Using developmentserver to get device ID"); String url = devMode ? SenseUrls.DEV_DEVICES : SenseUrls.DEVICES; String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); Map<String, String> response = SenseApi.request(context, url, null, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to get list of devices! Response code: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } // check if this device is in the list JSONObject content = new JSONObject(response.get("content")); JSONArray deviceList = content.getJSONArray("devices"); String entryUuid = ""; for (int x = 0; x < deviceList.length(); x++) { JSONObject device = deviceList.getJSONObject(x); entryUuid = device.getString("uuid"); // pad the UUID with leading zeros, CommonSense API removes them while (entryUuid.length() < uuid.length()) { entryUuid = "0" + entryUuid; } // Found the right device if UUID matches IMEI if (entryUuid.equalsIgnoreCase(uuid)) { // cache device ID in preferences int deviceId = Integer.parseInt(device.getString("id")); final Editor editor = authPrefs.edit(); editor.putString(Auth.DEVICE_TYPE, device.getString("type")); editor.putInt(keyDeviceId, deviceId); editor.putLong(keyIdTime, System.currentTimeMillis()); editor.remove(keySensorList); editor.commit(); return deviceId; } } // if we make it here, the device was not registered yet: return -1 Log.w(TAG, "This device is not registered at CommonSense yet"); return -1; } /** * Gets a list of all registered sensors for a device at the CommonSense API. Uses caching for * increased performance. * * @param context * Application context, used for getting preferences. * @param deviceUuid * (Optional) UUID of the device that the sensors should be connected to. Set null to * use the default device. * @return The list of sensors (can be empty) * @throws IOException * In case of communication failure to CommonSense * @throws JSONException * In case of unparseable response from CommonSense */ public static JSONArray getRegisteredSensors(Context context, String deviceUuid) throws IOException, JSONException { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); // try to get list of sensors from the cache String keySensorList = null, keyTime = null; try { keySensorList = deviceUuid == null ? Auth.SENSOR_LIST : Auth.SENSOR_LIST + deviceUuid; keyTime = deviceUuid == null ? Auth.SENSOR_LIST_TIME : Auth.SENSOR_LIST_TIME + deviceUuid; String cachedSensors = authPrefs.getString(keySensorList, null); long cacheTime = authPrefs.getLong(keyTime, 0); boolean isOutdated = System.currentTimeMillis() - cacheTime > CACHE_REFRESH; // return cached list of it is still valid if (false == isOutdated && null != cachedSensors) { return new JSONArray(cachedSensors); } } catch (Exception e) { // should not happen, we are only using stuff that was previously cached Log.e(TAG, "Failed to get list of sensors from cache!", e); } // if we make it here, the list was not in the cache // Log.v(TAG, "List of sensor IDs is missing or outdated, refreshing..."); // get device ID to use in communication with CommonSense int deviceId = getDeviceId(context, deviceUuid); // get the list of sensors for this device JSONArray sensorList = null; if (deviceId == -1) { // device is not yet registered, so the sensor list is empty Log.w(TAG, "The list of sensors is empty: device is not registered yet."); sensorList = new JSONArray("[]"); } else { // request fresh list of sensors for this device from CommonSense String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); if (devMode) Log.i(TAG, "Using developmentserver to get registered sensors"); String url = devMode ? SenseUrls.DEV_SENSORS : SenseUrls.SENSORS; url = url.replaceFirst("<id>", "" + deviceId); Map<String, String> response = SenseApi.request(context, url, null, cookie); String responseCode = response.get("http response code"); if (!"200".equals(responseCode)) { Log.w(TAG, "Failed to get list of sensors! Response code: " + responseCode); throw new IOException("Incorrect response from CommonSense: " + responseCode); } // parse response and store the list JSONObject content = new JSONObject(response.get("content")); sensorList = content.getJSONArray("sensors"); } // store the new sensor list Editor authEditor = authPrefs.edit(); authEditor.putString(keySensorList, sensorList.toString()); authEditor.putLong(keyTime, System.currentTimeMillis()); authEditor.commit(); return sensorList; } /** * Gets the sensor ID at CommonSense , which can be used to modify the sensor information and * data. * * @param context * Context for getting preferences * @param name * Sensor name, to match with registered sensors. * @param description * Sensor description (previously 'device_type'), to match with registered sensors. * @param dataType * Sensor data type, to match with registered sensors. * @param deviceUuid * (Optional) UUID of the device that holds the sensor. Set null to use the default * device. * @return String with the sensor's ID, or null if the sensor does not exist at CommonSense * (yet). * @throws IOException * If the request to CommonSense failed. * @throws JSONException * If the response from CommonSense could not be parsed. */ public static String getSensorId(Context context, String name, String description, String dataType, String deviceUuid) throws IOException, JSONException { // get list of all registered sensors for this device JSONArray sensors = getRegisteredSensors(context, deviceUuid); // check sensors with similar names and descriptions in the list for (int i = 0; i < sensors.length(); i++) { JSONObject sensor = (JSONObject) sensors.get(i); if (sensor.getString("name").equalsIgnoreCase(name) && sensor.getString("device_type").equalsIgnoreCase(description) && sensor.getString("data_type").equalsIgnoreCase(dataType)) { return sensor.getString("id"); } else if (name.equals(SensorNames.ACCELEROMETER) || name.equals(SensorNames.ORIENT) || name.equals(SensorNames.GYRO) || name.equals(SensorNames.LIN_ACCELERATION) || name.equals(SensorNames.MAGNET_FIELD)) { // special case to take care of changed motion sensor descriptions since Gingerbread if (name.equals(sensor.getString("name"))) { Log.w(TAG, "Using inexact match for '" + name + "' sensor ID..."); return sensor.getString("id"); } } } // if we make it here, the sensor does not exist (yet) return null; } /** * Gets the URL at CommonSense to which the data must be sent. * * @param context * Context for getting preferences * @param name * Sensor name, to match with registered sensors. * @param description * Sensor description (previously 'device_type'), to match with registered sensors. * @param dataType * Sensor data type, to match with registered sensors. * @param deviceUuid * (Optional) UUID of the device that holds the sensor. Set null to use the default * device. * @return String with the sensor's URL, or null if sensor does not have an ID (yet) * @throws JSONException * If there was unexpected response getting the sensor ID. * @throws IOException * If there was a problem during communication with CommonSense. */ public static String getSensorUrl(Context context, String name, String description, String dataType, String deviceUuid) throws IOException, JSONException { String id = getSensorId(context, name, description, dataType, deviceUuid); if (id == null) { Log.e(TAG, "Failed to get URL for sensor '" + name + "': sensor ID is not available"); return null; } SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); // found the right sensor if (dataType.equals(SenseDataTypes.FILE)) { String url = devMode ? SenseUrls.DEV_SENSOR_FILE : SenseUrls.SENSOR_FILE; return url.replaceFirst("<id>", id); } else { String url = devMode ? SenseUrls.DEV_SENSOR_DATA : SenseUrls.SENSOR_DATA; return url.replaceFirst("<id>", id); } } public static String getSessionId(Context context, String appId) throws IllegalAccessException { SharedPreferences prefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); if (AppSecrets.ASK.equals(appId)) { // Log.v(TAG, "An ASK app accessed the CommonSense session ID"); return prefs.getString(Auth.LOGIN_COOKIE, null); } else if (AppSecrets.RDAM_CS.equals(appId)) { // Log.v(TAG, "A Rotterdam CS app accessed the CommonSense session ID"); return prefs.getString(Auth.LOGIN_COOKIE, null); } else if (AppSecrets.SENSE.equals(appId)) { // Log.v(TAG, "A Sense app accessed the CommonSense session ID"); return prefs.getString(Auth.LOGIN_COOKIE, null); } else { Log.e(TAG, "App is not allowed access to the CommonSense session!"); throw new IllegalAccessException( "App is not allowed access to the CommonSense session!"); } } /** * @param hashMe * "clear" password String to be hashed before sending it to CommonSense * @return Hashed String */ public static String hashPassword(String hashMe) { final byte[] unhashedBytes = hashMe.getBytes(); try { final MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(unhashedBytes); final byte[] hashedBytes = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (final byte element : hashedBytes) { final String hex = Integer.toHexString(0xFF & element); if (hex.length() == 1) { hexString.append(0); } hexString.append(hex); } return hexString.toString(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * Tries to log in at CommonSense using the supplied username and password. After login, the * cookie containing the session ID is stored in the preferences. * * @param context * Context for getting preferences * @param username * Username for authentication * @param password * Hashed password for authentication * @return 0 if login completed successfully, -2 if login was forbidden, and -1 for any other * errors. * @throws JSONException * In case of unparseable response from CommonSense * @throws IOException * In case of communication failure to CommonSense */ public static int login(Context context, String username, String password) throws JSONException, IOException { // preferences final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); final Editor authEditor = authPrefs.edit(); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); if (devMode) Log.i(TAG, "Using developmentserver to log in"); final String url = devMode ? SenseUrls.DEV_LOGIN : SenseUrls.LOGIN; final JSONObject user = new JSONObject(); user.put("username", username); user.put("password", password); // perform actual request Map<String, String> response = request(context, url, user, null); // if response code is not 200 (OK), the login was incorrect String responseCode = response.get("http response code"); int result = -1; if ("403".equalsIgnoreCase(responseCode)) { Log.w(TAG, "CommonSense login refused! Response: forbidden!"); result = -2; } else if (!"200".equalsIgnoreCase(responseCode)) { Log.w(TAG, "CommonSense login failed! Response: " + responseCode); result = -1; } else { // received 200 response result = 0; } // get the cookie from the response String cookie = response.get("set-cookie"); if (result == 0 && response.get("set-cookie") == null) { // something went horribly wrong Log.w(TAG, "CommonSense login failed: no cookie received?!"); result = -1; } // handle result switch (result) { case 0: // logged in authEditor.putString(Auth.LOGIN_COOKIE, cookie); authEditor.commit(); break; case -1: // error break; case -2: // unauthorized authEditor.remove(Auth.LOGIN_COOKIE); authEditor.commit(); break; default: Log.e(TAG, "Unexpected login result: " + result); } return result; } /** * Registers a new sensor for this device at CommonSense. Also connects the sensor to this * device. * * @param context * The application context, used to retrieve preferences. * @param name * The name of the sensor. * @param displayName * The sensor's pretty display name. * @param description * The sensor description (previously "device_type"). * @param dataType * The sensor data type. * @param value * An example sensor value, used to determine the data structure for JSON type * sensors. * @param deviceType * (Optional) Type of the device that holds the sensor. Set null to use the default * device. * @param deviceUuid * (Optional) UUID of the device that holds the sensor. Set null to use the default * device. * @return The new sensor ID at CommonSense, or <code>null</code> if the registration failed. * @throws JSONException * In case of invalid sensor details or if the request returned unparseable * response. * @throws IOException * In case of communication failure during creation of the sensor. */ public static String registerSensor(Context context, String name, String displayName, String description, String dataType, String value, String deviceType, String deviceUuid) throws JSONException, IOException { final SharedPreferences authPrefs = context.getSharedPreferences(SensePrefs.AUTH_PREFS, Context.MODE_PRIVATE); String cookie = authPrefs.getString(Auth.LOGIN_COOKIE, null); SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); // prepare request to create new sensor String url = devMode ? SenseUrls.DEV_CREATE_SENSOR : SenseUrls.CREATE_SENSOR; JSONObject postData = new JSONObject(); JSONObject sensor = new JSONObject(); sensor.put("name", name); sensor.put("device_type", description); sensor.put("display_name", displayName); sensor.put("pager_type", ""); sensor.put("data_type", dataType); if (dataType.compareToIgnoreCase("json") == 0) { JSONObject dataStructJSon = new JSONObject(value); JSONArray fieldNames = dataStructJSon.names(); for (int x = 0; x < fieldNames.length(); x++) { String fieldName = fieldNames.getString(x); int start = dataStructJSon.get(fieldName).getClass().getName().lastIndexOf("."); dataStructJSon.put(fieldName, dataStructJSon.get(fieldName).getClass().getName() .substring(start + 1)); } sensor.put("data_structure", dataStructJSon.toString().replaceAll("\"", "\\\"")); } postData.put("sensor", sensor); // perform actual request Map<String, String> response = request(context, url, postData, cookie); // check response code String code = response.get("http response code"); if (!"201".equals(code)) { Log.e(TAG, "Failed to register sensor at CommonSense! Response code: " + code); throw new IOException("Incorrect response from CommonSense: " + code); } // retrieve the newly created sensor ID String content = response.get("content"); JSONObject responseJson = new JSONObject(content); JSONObject JSONSensor = responseJson.getJSONObject("sensor"); final String id = (String) JSONSensor.get("id"); // store the new sensor in the preferences JSONArray sensors = getRegisteredSensors(context, deviceUuid); sensors.put(JSONSensor); Editor authEditor = authPrefs.edit(); String keySensorList = deviceUuid == null ? Auth.SENSOR_LIST : Auth.SENSOR_LIST + deviceUuid; authEditor.putString(keySensorList, sensors.toString()); authEditor.commit(); // get device properties from preferences, so it matches the properties in CommonSense if (null == deviceUuid) { deviceUuid = getDefaultDeviceUuid(context); deviceType = getDefaultDeviceType(context); } // Add sensor to this device at CommonSense url = devMode ? SenseUrls.DEV_ADD_SENSOR_TO_DEVICE : SenseUrls.ADD_SENSOR_TO_DEVICE; url = url.replaceFirst("<id>", id); postData = new JSONObject(); JSONObject device = new JSONObject(); device.put("type", deviceType); device.put("uuid", deviceUuid); postData.put("device", device); response = request(context, url, postData, cookie); // check response code code = response.get("http response code"); if (!"201".equals(code)) { Log.e(TAG, "Failed to add sensor to device at CommonSense! Response code: " + code); throw new IOException("Incorrect response from CommonSense: " + code); } // Log.v(TAG, "Created sensor: '" + name + "' for device: '" + deviceType + "'"); // return the new sensor ID return id; } /** * Tries to register a new user at CommonSense. Discards private data of any previous users. * * @param context * Context for getting preferences * @param username * Username to register * @param password * Hashed password for the new user * @return 0 if registration completed successfully, -2 if the user already exists, and -1 for * any other unexpected responses. * @throws JSONException * In case of unparseable response from CommonSense * @throws IOException * In case of communication failure to CommonSense */ public static int registerUser(Context context, String username, String password, String name, String surname, String email, String mobile) throws JSONException, IOException { SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean devMode = prefs.getBoolean(Advanced.DEV_MODE, false); final String url = devMode ? SenseUrls.DEV_REG : SenseUrls.REG; // create JSON object to POST final JSONObject data = new JSONObject(); final JSONObject user = new JSONObject(); user.put("username", username); user.put("password", password); if (null != name) { user.put("name", name); } if (null != surname) { user.put("surname", surname); } if (null != email) { user.put("email", email); } if (null != mobile) { user.put("mobile", mobile); } data.put("user", user); // perform actual request Map<String, String> response = SenseApi.request(context, url, data, null); String responseCode = response.get("http response code"); int result = -1; if ("201".equalsIgnoreCase(responseCode)) { result = 0; } else if ("409".equalsIgnoreCase(responseCode)) { Log.e(TAG, "Error registering new user! User already exists"); result = -2; } else { Log.e(TAG, "Error registering new user! Response code: " + responseCode); result = -1; } return result; } /** * Performs request at CommonSense API. Returns the response code, content, and headers. * * @param context * Application context, used to read preferences. * @param urlString * Complete URL to perform request to. * @param content * (Optional) Content for the request. If the content is not null, the request method * is automatically POST. The default method is GET. * @param cookie * (Optional) Cookie header for the request. * @return Map with "content" and "http response code" fields, plus fields for all response * headers. * @throws IOException */ public static Map<String, String> request(Context context, String urlString, JSONObject content, String cookie) throws IOException { HttpURLConnection urlConnection = null; HashMap<String, String> result = new HashMap<String, String>(); try { // Log.d(TAG, "API request: " + (content == null ? "GET" : "POST") + " " + urlString // + " cookie:" + cookie); // get compression preference final SharedPreferences mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); final boolean compress = mainPrefs.getBoolean(Advanced.COMPRESS, true); // open new URL connection channel. URL url = new URL(urlString); if ("https".equals(url.getProtocol().toLowerCase())) { trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); urlConnection = https; } else { urlConnection = (HttpURLConnection) url.openConnection(); } // some parameters urlConnection.setUseCaches(false); urlConnection.setInstanceFollowRedirects(false); // set cookie (if available) if (null != cookie) { urlConnection.setRequestProperty("Cookie", cookie); } // send content (if available) if (null != content) { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); // send content DataOutputStream printout; if (compress) { // do not set content size urlConnection.setRequestProperty("Transfer-Encoding", "chunked"); urlConnection.setRequestProperty("Content-Encoding", "gzip"); GZIPOutputStream zipStream = new GZIPOutputStream( urlConnection.getOutputStream()); printout = new DataOutputStream(zipStream); } else { // set content size urlConnection.setFixedLengthStreamingMode(content.toString().length()); urlConnection.setRequestProperty("Content-Length", "" + content.toString().length()); printout = new DataOutputStream(urlConnection.getOutputStream()); } printout.writeBytes(content.toString()); printout.flush(); printout.close(); } // get response, or read error message InputStream inputStream; try { inputStream = urlConnection.getInputStream(); } catch (IOException e) { inputStream = urlConnection.getErrorStream(); } if (null == inputStream) { throw new IOException("could not get InputStream"); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 1024); String line; StringBuffer responseContent = new StringBuffer(); while ((line = reader.readLine()) != null) { responseContent.append(line); responseContent.append('\r'); } reader.close(); result.put("content", responseContent.toString()); result.put("http response code", "" + urlConnection.getResponseCode()); // get headers Map<String, List<String>> headerFields = urlConnection.getHeaderFields(); for (Entry<String, List<String>> entry : headerFields.entrySet()) { String key = entry.getKey(); List<String> value = entry.getValue(); if (null != key && null != value) { key = key.toLowerCase(); String valueString = value.toString(); valueString = valueString.substring(1, valueString.length() - 1); // Log.d(TAG, "Header field '" + key + "': '" + valueString + "'"); result.put(key, valueString); } else { // Log.d(TAG, "Skipped header field '" + key + "': '" + value + "'"); } } return result; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } } /** * Trust every server - do not check for any certificate */ // TODO Solve issue with security certificate for HTTPS. private static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } }
package no.nordicsemi.android.dfu; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Locale; import java.util.UUID; import no.nordicsemi.android.dfu.exception.DeviceDisconnectedException; import no.nordicsemi.android.dfu.exception.DfuException; import no.nordicsemi.android.dfu.exception.HexFileValidationException; import no.nordicsemi.android.dfu.exception.RemoteDfuException; import no.nordicsemi.android.dfu.exception.UnknownResponseException; import no.nordicsemi.android.dfu.exception.UploadAbortedException; import no.nordicsemi.android.error.GattError; import no.nordicsemi.android.log.ILogSession; import no.nordicsemi.android.log.LogContract; import no.nordicsemi.android.log.LogContract.Log.Level; import no.nordicsemi.android.log.Logger; import android.app.Activity; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.SystemClock; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; /** * The DFU Service provides full support for Over-the-Air (OTA) Device Firmware Update by Nordic Semiconductor.<br /> * With the Soft Device 7.0.0+ it allows to upload a new Soft Device, new Bootloader and a new Application. For older soft devices only the Application update is supported. * <p> * To run the service to your application inherit it and overwrite the missing method. Remember to it to the AndroidManifest.xml file. Start the service with the following parameters: * * <pre> * final Intent service = new Intent(this, YourDfuService.class); * service.putExtra(DfuService.EXTRA_DEVICE_ADDRESS, mSelectedDevice.getAddress()); * service.putExtra(DfuService.EXTRA_DEVICE_NAME, mSelectedDevice.getName()); * service.putExtra(DfuService.EXTRA_FILE_MIME_TYPE, mFileType == DfuService.TYPE_AUTO ? YourDfuService.MIME_TYPE_ZIP : YourDfuService.MIME_TYPE_OCTET_STREAM); * service.putExtra(DfuService.EXTRA_FILE_TYPE, mFileType); * service.putExtra(DfuService.EXTRA_FILE_PATH, mFilePath); * service.putExtra(DfuService.EXTRA_FILE_URI, mFileStreamUri); * startService(service); * </pre> * * The {@link #EXTRA_FILE_MIME_TYPE} and {@link #EXTRA_FILE_TYPE} parameters are optional. If not provided the application upload from HEX/BIN file is assumed. The service API is compatible with * previous versions. * </p> * <p> * The service will show its progress in the notifications bar and will send local broadcasts the the application. * </p> */ public abstract class DfuBaseService extends IntentService { private static final String TAG = "DfuService"; private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); /** A key for {@link SharedPreferences} entry that keeps information whether the upload is currently in progress. This may be used to get this information during activity creation. */ public static final String DFU_IN_PROGRESS = "no.nordicsemi.android.dfu.PREFS_DFU_IN_PROGRESS"; public static final String EXTRA_DEVICE_ADDRESS = "no.nordicsemi.android.dfu.extra.EXTRA_DEVICE_ADDRESS"; public static final String EXTRA_DEVICE_NAME = "no.nordicsemi.android.dfu.extra.EXTRA_DEVICE_NAME"; public static final String EXTRA_LOG_URI = "no.nordicsemi.android.dfu.extra.EXTRA_LOG_URI"; public static final String EXTRA_FILE_PATH = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_PATH"; public static final String EXTRA_FILE_URI = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_URI"; /** * The Init packet URI. This file is required if Extended Init Packet is required. Must point to a 'dat' file corresponding with the selected firmware. The Init packet may contain just the CRC * (in case of older versions of DFU) or the Extended Init Packet in binary format. */ public static final String EXTRA_INIT_FILE_PATH = "no.nordicsemi.android.dfu.extra.EXTRA_INIT_FILE_PATH"; /** * The Init packet path. This file is required if Extended Init Packet is required. Must point to a 'dat' file corresponding with the selected firmware. The Init packet may contain just the CRC * (in case of older versions of DFU) or the Extended Init Packet in binary format. */ public static final String EXTRA_INIT_FILE_URI = "no.nordicsemi.android.dfu.extra.EXTRA_INIT_FILE_URI"; /** * The input file mime-type. Currently only "application/zip" (ZIP) or "application/octet-stream" (HEX or BIN) are supported. If this parameter is empty the "application/octet-stream" is assumed. */ public static final String EXTRA_FILE_MIME_TYPE = "no.nordicsemi.android.dfu.extra.EXTRA_MIME_TYPE"; /** * This optional extra parameter may contain a file type. Currently supported are: * <ul> * <li>{@link #TYPE_SOFT_DEVICE} - only Soft Device update</li> * <li>{@link #TYPE_BOOTLOADER} - only Bootloader update</li> * <li>{@link #TYPE_APPLICATION} - only application update</li> * <li>{@link #TYPE_AUTO} -the file is a ZIP file that may contain more than one HEX. The ZIP file MAY contain only the following files: <b>softdevice.hex</b>, <b>bootloader.hex</b>, * <b>application.hex</b> to determine the type based on its name. At lease one of them MUST be present.</li> * </ul> * If this parameter is not provided the type is assumed as follows: * <ol> * <li>If the {@link #EXTRA_FILE_MIME_TYPE} field is <code>null</code> or is equal to {@value #MIME_TYPE_OCTET_STREAM} - the {@link #TYPE_APPLICATION} is assumed.</li> * <li>If the {@link #EXTRA_FILE_MIME_TYPE} field is equal to {@value #MIME_TYPE_ZIP} - the {@link #TYPE_AUTO} is assumed.</li> * </ol> */ public static final String EXTRA_FILE_TYPE = "no.nordicsemi.android.dfu.extra.EXTRA_FILE_TYPE"; /** * <p> * The file contains a new version of Soft Device. * </p> * <p> * Since DFU Library 7.0 all firmware may contain an Init packet. The Init packet is required if Extended Init Packet is used by the DFU bootloader. The Init packet for the Soft Device must be * placed in the [firmware name].dat file as binary file (in the same location). * </p> * * @see #EXTRA_FILE_TYPE */ public static final int TYPE_SOFT_DEVICE = 0x01; /** * <p> * The file contains a new version of Bootloader. * </p> * <p> * Since DFU Library 7.0 all firmware may contain an Init packet. The Init packet is required if Extended Init Packet is used by the DFU bootloader. The Init packet for the bootloader must be * placed in the [firmware name].dat file as binary file (in the same location). * </p> * * @see #EXTRA_FILE_TYPE */ public static final int TYPE_BOOTLOADER = 0x02; /** * <p> * The file contains a new version of Application. * </p> * <p> * Since DFU Library 7.0 all firmware may contain an Init packet. The Init packet is required if Extended Init Packet is used by the DFU bootloader. The Init packet for the application must be * placed in the [firmware name].dat file as binary file (in the same location). * </p> * * @see #EXTRA_FILE_TYPE */ public static final int TYPE_APPLICATION = 0x04; /** * <p> * A ZIP file that combines more than 1 HEX file. The names of files in the ZIP must be: <b>softdevice.hex</b> (or .bin), <b>bootloader.hex</b> (or .bin), <b>application.hex</b> (or .bin) in order * to be read correctly. In the DFU version 2 the Soft Device and Bootloader may be sent together. In case of additional application file included, the service will try to send Soft Device, * Bootloader and Application together (not supported by DFU v.2) and if it fails, send first SD+BL, reconnect and send application. * </p> * <p> * Since the DFU Library 7.0 all firmware may contain an Init packet. The Init packet is required if Extended Init Packet is used by the DFU bootloader. The Init packet for the Soft Device and * Bootloader must be in 'system.dat' file while for the application in the 'application.dat' file (included in the ZIP). The CRC in the 'system.dat' must be a CRC of both BIN contents if both a * Soft Device and a Bootloader is present. * </p> * * @see #EXTRA_FILE_TYPE */ public static final int TYPE_AUTO = 0x00; /** Extra to send progress and error broadcast events. */ public static final String EXTRA_DATA = "no.nordicsemi.android.dfu.extra.EXTRA_DATA"; /** * Extra to send progress or error information in the DFU notification. The value may contain: * <ul> * <li>Value 0 - 100 - percentage progress value</li> * <li>One of the following status constants: * <ul> * <li>{@link #PROGRESS_CONNECTING}</li> * <li>{@link #PROGRESS_STARTING}</li> * <li>{@link #PROGRESS_VALIDATING}</li> * <li>{@link #PROGRESS_DISCONNECTING}</li> * <li>{@link #PROGRESS_COMPLETED}</li> * <li>{@link #PROGRESS_ABORTED}</li> * </ul> * </li> * <li>An error code with {@link #ERROR_MASK} if initialization error occurred</li> * <li>An error code with {@link #ERROR_REMOTE_MASK} if remote DFU target returned an error</li> * <li>An error code with {@link #ERROR_CONNECTION_MASK} if connection error occurred (f.e. Gatt error (133) or Internal Gatt Error (129))</li> * </ul> * To check if error occurred use:<br /> * {@code boolean error = progressValue >= DfuBaseService.ERROR_MASK;} */ public static final String EXTRA_PROGRESS = "no.nordicsemi.android.dfu.extra.EXTRA_PROGRESS"; /** * The number of currently transferred part. The SoftDevice and Bootloader may be send together as one part. If user wants to upload them together with an application it has to be sent * in another connection as the second part. * * @see DfuBaseService#EXTRA_PARTS_TOTAL */ public static final String EXTRA_PART_CURRENT = "no.nordicsemi.android.dfu.extra.EXTRA_PART_CURRENT"; /** * Number of parts in total. * * @see DfuBaseService#EXTRA_PART_CURRENT */ public static final String EXTRA_PARTS_TOTAL = "no.nordicsemi.android.dfu.extra.EXTRA_PARTS_TOTAL"; /** The current upload speed in bytes/millisecond. */ public static final String EXTRA_SPEED_B_PER_MS = "no.nordicsemi.android.dfu.extra.EXTRA_SPEED_B_PER_MS"; /** The average upload speed in bytes/millisecond for the current part. */ public static final String EXTRA_AVG_SPEED_B_PER_MS = "no.nordicsemi.android.dfu.extra.EXTRA_AVG_SPEED_B_PER_MS"; /** * The broadcast message contains the following extras: * <ul> * <li>{@link #EXTRA_DATA} - the progress value (percentage 0-100) or: * <ul> * <li>{@link #PROGRESS_CONNECTING}</li> * <li>{@link #PROGRESS_STARTING}</li> * <li>{@link #PROGRESS_VALIDATING}</li> * <li>{@link #PROGRESS_DISCONNECTING}</li> * <li>{@link #PROGRESS_COMPLETED}</li> * <li>{@link #PROGRESS_ABORTED}</li> * </ul> * </li> * <li>{@link #EXTRA_DEVICE_ADDRESS} - the target device address</li> * <li>{@link #EXTRA_PART_CURRENT} - the number of currently transmitted part</li> * <li>{@link #EXTRA_PARTS_TOTAL} - number number of parts to send, f.e. a SoftDevice and Bootloader may be send together as one part, then application as the second part.</li> * </ul> */ public static final String BROADCAST_PROGRESS = "no.nordicsemi.android.dfu.broadcast.BROADCAST_PROGRESS"; /** Service is connecting to the remote DFU target. */ public static final int PROGRESS_CONNECTING = -1; /** Service is enabling notifications and starting transmission. */ public static final int PROGRESS_STARTING = -2; /** Service is sending validation request to the remote DFU target. */ public static final int PROGRESS_VALIDATING = -4; /** Service is disconnecting from the DFU target. */ public static final int PROGRESS_DISCONNECTING = -5; /** The connection is successful. */ public static final int PROGRESS_COMPLETED = -6; /** The upload has been aborted. Previous software version will be restored on the target. */ public static final int PROGRESS_ABORTED = -7; /** * The broadcast error message contains the following extras: * <ul> * <li>{@link #EXTRA_DATA} - the error number. Use {@link GattError#parse(int)} to get String representation</li> * <li>{@link #EXTRA_DEVICE_ADDRESS} - the target device address</li> * </ul> */ public static final String BROADCAST_ERROR = "no.nordicsemi.android.dfu.broadcast.BROADCAST_ERROR"; /** * If this bit is set than the progress value indicates an error. Use {@link GattError#parse(int)} to obtain error name. */ public static final int ERROR_MASK = 0x1000; // When user tries to connect to more than 6 devices on Nexus devices (Android 4.4.4) the 0x101 error is thrown. Mask changed 0x0100 -> 0x1000 to avoid collision. public static final int ERROR_DEVICE_DISCONNECTED = ERROR_MASK | 0x00; public static final int ERROR_FILE_NOT_FOUND = ERROR_MASK | 0x01; /** Thrown if service was unable to open the file ({@link IOException} has been thrown). */ public static final int ERROR_FILE_ERROR = ERROR_MASK | 0x02; /** Thrown then input file is not a valid HEX or ZIP file. */ public static final int ERROR_FILE_INVALID = ERROR_MASK | 0x03; /** Thrown when {@link IOException} occurred when reading from file. */ public static final int ERROR_FILE_IO_EXCEPTION = ERROR_MASK | 0x04; /** Error thrown then {@code gatt.discoverServices();} returns false. */ public static final int ERROR_SERVICE_DISCOVERY_NOT_STARTED = ERROR_MASK | 0x05; /** Thrown when the service discovery has finished but the DFU service has not been found. The device does not support DFU of is not in DFU mode. */ public static final int ERROR_SERVICE_NOT_FOUND = ERROR_MASK | 0x06; /** Thrown when the required DFU service has been found but at least one of the DFU characteristics is absent. */ public static final int ERROR_CHARACTERISTICS_NOT_FOUND = ERROR_MASK | 0x07; /** Thrown when unknown response has been obtained from the target. The DFU target must follow specification. */ public static final int ERROR_INVALID_RESPONSE = ERROR_MASK | 0x08; /** Thrown when the the service does not support given type or mime-type. */ public static final int ERROR_FILE_TYPE_UNSUPPORTED = ERROR_MASK | 0x09; /** Flag set then the DFU target returned a DFU error. Look for DFU specification to get error codes. */ public static final int ERROR_REMOTE_MASK = 0x2000; /** The flag set when one of {@link BluetoothGattCallback} methods was called with status other than {@link BluetoothGatt#GATT_SUCCESS}. */ public static final int ERROR_CONNECTION_MASK = 0x4000; /** * The log events are only broadcasted when there is no nRF Logger installed. The broadcast contains 2 extras: * <ul> * <li>{@link #EXTRA_LOG_LEVEL} - The log level: one of {@link LogContract.Log.Level#DEBUG}, {@link LogContract.Log.Level#VERBOSE}, {@link LogContract.Log.Level#INFO}, * {@link LogContract.Log.Level#WARNING}, {@link LogContract.Log.Level#ERROR}</li> * <li>{@link #EXTRA_LOG_MESSAGE}</li> * </ul> */ public static final String BROADCAST_LOG = "no.nordicsemi.android.dfu.broadcast.BROADCAST_LOG"; public static final String EXTRA_LOG_MESSAGE = "no.nordicsemi.android.dfu.extra.EXTRA_LOG_INFO"; public static final String EXTRA_LOG_LEVEL = "no.nordicsemi.android.dfu.extra.EXTRA_LOG_LEVEL"; /** Activity may broadcast this broadcast in order to pause, resume or abort DFU process. */ public static final String BROADCAST_ACTION = "no.nordicsemi.android.dfu.broadcast.BROADCAST_ACTION"; public static final String EXTRA_ACTION = "no.nordicsemi.android.dfu.extra.EXTRA_ACTION"; public static final int ACTION_PAUSE = 0; public static final int ACTION_RESUME = 1; public static final int ACTION_ABORT = 2; public static final int NOTIFICATION_ID = 283; // a random number private BluetoothAdapter mBluetoothAdapter; private String mDeviceAddress; private String mDeviceName; private ILogSession mLogSession; /** Lock used in synchronization purposes */ private final Object mLock = new Object(); /** The number of the last error that has occurred or 0 if there was no error */ private int mErrorState; /** The current connection state. If its value is > 0 than an error has occurred. Error number is a negative value of mConnectionState */ private int mConnectionState; private final static int STATE_DISCONNECTED = 0; private final static int STATE_CONNECTING = -1; private final static int STATE_CONNECTED = -2; private final static int STATE_CONNECTED_AND_READY = -3; // indicates that services were discovered private final static int STATE_DISCONNECTING = -4; private final static int STATE_CLOSED = -5; /** Flag set when we got confirmation from the device that notifications are enabled. */ private boolean mNotificationsEnabled; /** Flag set when we got confirmation from the device that Service Changed indications are enabled. */ private boolean mServiceChangedIndicationsEnabled; private final static int MAX_PACKET_SIZE = 20; // the maximum number of bytes in one packet is 20. May be less. /** The number of packets of firmware data to be send before receiving a new Packets receipt notification. 0 disables the packets notifications */ private int mPacketsBeforeNotification = 10; private byte[] mBuffer = new byte[MAX_PACKET_SIZE]; private InputStream mInputStream; /** Size of BIN content of all hex files that are going to be transmitted. */ private int mImageSizeInBytes; /** Number of bytes transmitted. */ private int mBytesSent; /** Number of bytes confirmed by the notification. */ @SuppressWarnings("unused") private int mBytesConfirmed; private int mPacketsSentSinceNotification; /** This value is used to calculate the current transfer speed. */ private int mLastBytesSent; /** * Firmware update may require two connections: one for Soft Device and/or Bootloader upload and second for Application. This fields contains the current part number. */ private int mPartCurrent; /** Total number of parts. */ private int mPartsTotal; private int mFileType; private boolean mPaused; private boolean mAborted; private boolean mResetRequestSent; private long mLastProgressTime, mStartTime; /** Flag indicating whether the image size has been already transfered or not */ private boolean mImageSizeSent; /** Flag indicating whether the init packet has been already transfered or not */ private boolean mInitPacketSent; /** Flag indicating whether the request was completed or not */ private boolean mRequestCompleted; /** Latest data received from device using notification. */ private byte[] mReceivedData = null; private static final int OP_CODE_START_DFU_KEY = 0x01; private static final int OP_CODE_INIT_DFU_PARAMS_KEY = 0x02; private static final int OP_CODE_RECEIVE_FIRMWARE_IMAGE_KEY = 0x03; private static final int OP_CODE_VALIDATE_KEY = 0x04; private static final int OP_CODE_ACTIVATE_AND_RESET_KEY = 0x05; private static final int OP_CODE_RESET_KEY = 0x06; // private static final int OP_CODE_PACKET_REPORT_RECEIVED_IMAGE_SIZE_KEY = 0x07; // 7 private static final int OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY = 0x08; private static final int OP_CODE_RESPONSE_CODE_KEY = 0x10; private static final int OP_CODE_PACKET_RECEIPT_NOTIF_KEY = 0x11; private static final byte[] OP_CODE_START_DFU = new byte[] { OP_CODE_START_DFU_KEY, 0x00 }; private static final byte[] OP_CODE_INIT_DFU_PARAMS_START = new byte[] { OP_CODE_INIT_DFU_PARAMS_KEY, 0x00 }; private static final byte[] OP_CODE_INIT_DFU_PARAMS_COMPLETE = new byte[] { OP_CODE_INIT_DFU_PARAMS_KEY, 0x01 }; private static final byte[] OP_CODE_RECEIVE_FIRMWARE_IMAGE = new byte[] { OP_CODE_RECEIVE_FIRMWARE_IMAGE_KEY }; private static final byte[] OP_CODE_VALIDATE = new byte[] { OP_CODE_VALIDATE_KEY }; private static final byte[] OP_CODE_ACTIVATE_AND_RESET = new byte[] { OP_CODE_ACTIVATE_AND_RESET_KEY }; private static final byte[] OP_CODE_RESET = new byte[] { OP_CODE_RESET_KEY }; // private static final byte[] OP_CODE_REPORT_RECEIVED_IMAGE_SIZE = new byte[] { OP_CODE_PACKET_REPORT_RECEIVED_IMAGE_SIZE_KEY }; private static final byte[] OP_CODE_PACKET_RECEIPT_NOTIF_REQ = new byte[] { OP_CODE_PACKET_RECEIPT_NOTIF_REQ_KEY, 0x00, 0x00 }; public static final int DFU_STATUS_SUCCESS = 1; public static final int DFU_STATUS_INVALID_STATE = 2; public static final int DFU_STATUS_NOT_SUPPORTED = 3; public static final int DFU_STATUS_DATA_SIZE_EXCEEDS_LIMIT = 4; public static final int DFU_STATUS_CRC_ERROR = 5; public static final int DFU_STATUS_OPERATION_FAILED = 6; private static final UUID GENERIC_ATTRIBUTE_SERVICE_UUID = new UUID(0x0000180100001000l, 0x800000805F9B34FBl); private static final UUID SERVICE_CHANGED_UUID = new UUID(0x00002A0500001000l, 0x800000805F9B34FBl); private static final UUID DFU_SERVICE_UUID = new UUID(0x000015301212EFDEl, 0x1523785FEABCD123l); private static final UUID DFU_CONTROL_POINT_UUID = new UUID(0x000015311212EFDEl, 0x1523785FEABCD123l); private static final UUID DFU_PACKET_UUID = new UUID(0x000015321212EFDEl, 0x1523785FEABCD123l); private static final UUID DFU_VERSION = new UUID(0x000015341212EFDEl, 0x1523785FEABCD123l); private static final UUID CLIENT_CHARACTERISTIC_CONFIG = new UUID(0x0000290200001000l, 0x800000805f9b34fbl); private static final int NOTIFICATIONS = 1; private static final int INDICATIONS = 2; // Since the DFU Library version 7.0 both HEX and BIN files are supported. As both files have the same MIME TYPE the distinction is made based on the file extension. public static final String MIME_TYPE_OCTET_STREAM = "application/octet-stream"; public static final String MIME_TYPE_ZIP = "application/zip"; private final BroadcastReceiver mDfuActionReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final int action = intent.getIntExtra(EXTRA_ACTION, 0); switch (action) { case ACTION_PAUSE: mPaused = true; break; case ACTION_RESUME: mPaused = false; // notify waiting thread synchronized (mLock) { mLock.notifyAll(); } break; case ACTION_ABORT: mPaused = false; mAborted = true; // notify waiting thread synchronized (mLock) { mLock.notifyAll(); } break; } } }; private final BroadcastReceiver mConnectionStateBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { // obtain the device and check it this is the one that we are connected to final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (!device.getAddress().equals(mDeviceAddress)) return; final String action = intent.getAction(); logi("Action received: " + action); mConnectionState = STATE_DISCONNECTED; // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } } }; private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) { // check whether an error occurred if (status == BluetoothGatt.GATT_SUCCESS) { if (newState == BluetoothGatt.STATE_CONNECTED) { logi("Connected to GATT server"); mConnectionState = STATE_CONNECTED; /* * The onConnectionStateChange callback is called just after establishing connection and before sending Encryption Request BLE event in case of a paired device. * In that case and when the Service Changed CCCD is enabled we will get the indication after initializing the encryption, about 1600 milliseconds later. * If we discover services right after connecting, the onServicesDiscovered callback will be called immediately, before receiving the indication and the following * service discovery and we may end up with old, application's services instead. * * This is to support the buttonless switch from application to bootloader mode where the DFU bootloader notifies the master about service change. * Tested on Nexus 4 (Android 4.4.4 and 5), Nexus 5 (Android 5), Samsung Note 2 (Android 4.4.2). The time after connection to end of service discovery is about 1.6s * on Samsung Note 2. * * NOTE: We are doing this to avoid the hack with calling the hidden gatt.refresh() method, at least for bonded devices. */ if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) { try { synchronized (this) { logd("Waiting 1600 ms for a possible Service Changed indication..."); wait(1600); // After 1.6s the services are already discovered so the following gatt.discoverServices() finishes almost immediately. // NOTE: This also works with shorted waiting time. The gatt.discoverServices() must be called after the indication is received which is // about 600ms after establishing connection. Values 600 - 1600ms should be OK. } } catch (InterruptedException e) { // do nothing } } // Attempts to discover services after successful connection. // NOTE: do not refresh the gatt device here! final boolean success = gatt.discoverServices(); logi("Attempting to start service discovery... " + (success ? "succeed" : "failed")); if (!success) { mErrorState = ERROR_SERVICE_DISCOVERY_NOT_STARTED; } else { // just return here, lock will be notified when service discovery finishes return; } } else if (newState == BluetoothGatt.STATE_DISCONNECTED) { logi("Disconnected from GATT server"); mPaused = false; mConnectionState = STATE_DISCONNECTED; } } else { loge("Connection state change error: " + status + " newState: " + newState); mPaused = false; mErrorState = ERROR_CONNECTION_MASK | status; } // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } } @Override public void onServicesDiscovered(final BluetoothGatt gatt, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { logi("Services discovered"); mConnectionState = STATE_CONNECTED_AND_READY; } else { loge("Service discovery error: " + status); mErrorState = ERROR_CONNECTION_MASK | status; } // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } } @Override public void onDescriptorWrite(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { if (CLIENT_CHARACTERISTIC_CONFIG.equals(descriptor.getUuid())) { if (SERVICE_CHANGED_UUID.equals(descriptor.getCharacteristic().getUuid())) { // we have enabled notifications for the Service Changed characteristic mServiceChangedIndicationsEnabled = descriptor.getValue()[0] == 2; } else { // we have enabled notifications for this characteristic mNotificationsEnabled = descriptor.getValue()[0] == 1; } } } else { loge("Descriptor write error: " + status); mErrorState = ERROR_CONNECTION_MASK | status; } // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } }; @Override public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { /* * This method is called when either a CONTROL POINT or PACKET characteristic has been written. * If it is the CONTROL POINT characteristic, just set the flag to true. * If the PACKET characteristic was written we must: * - if the image size was written in DFU Start procedure, just set flag to true * - else * - send the next packet, if notification is not required at that moment * - do nothing, because we have to wait for the notification to confirm the data received */ if (DFU_PACKET_UUID.equals(characteristic.getUuid())) { if (mImageSizeSent && mInitPacketSent) { // if the PACKET characteristic was written with image data, update counters mBytesSent += characteristic.getValue().length; mPacketsSentSinceNotification++; // if a packet receipt notification is expected, or the last packet was sent, do nothing. There onCharacteristicChanged listener will catch either // a packet confirmation (if there are more bytes to send) or the image received notification (it upload process was completed) final boolean notificationExpected = mPacketsBeforeNotification > 0 && mPacketsSentSinceNotification == mPacketsBeforeNotification; final boolean lastPacketTransfered = mBytesSent == mImageSizeInBytes; if (notificationExpected || lastPacketTransfered) return; // when neither of them is true, send the next packet try { waitIfPaused(); if (mAborted) { // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } } final byte[] buffer = mBuffer; final int size = mInputStream.read(buffer); writePacket(gatt, characteristic, buffer, size); updateProgressNotification(); return; } catch (final HexFileValidationException e) { loge("Invalid HEX file"); mErrorState = ERROR_FILE_INVALID; } catch (final IOException e) { loge("Error while reading the input stream", e); mErrorState = ERROR_FILE_IO_EXCEPTION; } } else if (!mImageSizeSent) { // we've got confirmation that the image size was sent sendLogBroadcast(Level.INFO, "Data written to " + characteristic.getUuid() + ", value (0x): " + parse(characteristic)); mImageSizeSent = true; } else if (!mInitPacketSent) { // we've got confirmation that the init packet was sent sendLogBroadcast(Level.INFO, "Data written to " + characteristic.getUuid() + ", value (0x): " + parse(characteristic)); mInitPacketSent = true; } } else { // if the CONTROL POINT characteristic was written just set the flag to true sendLogBroadcast(Level.INFO, "Data written to " + characteristic.getUuid() + ", value (0x): " + parse(characteristic)); mRequestCompleted = true; } } else { /* * If a Reset (Op Code = 6) or Activate and Reset (Op Code = 5) commands are sent the DFU target resets and sometimes does it so quickly that does not manage to send * any ACK to the controller and error 133 is thrown here. */ if (mResetRequestSent) mRequestCompleted = true; else { loge("Characteristic write error: " + status); mErrorState = ERROR_CONNECTION_MASK | status; } } // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } }; @Override public void onCharacteristicRead(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) { if (status == BluetoothGatt.GATT_SUCCESS) { /* * This method is called when the DFU Version characteristic has been read. */ mReceivedData = characteristic.getValue(); mRequestCompleted = true; } else { loge("Characteristic read error: " + status); mErrorState = ERROR_CONNECTION_MASK | status; } // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } }; @Override public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { final int responseType = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0); switch (responseType) { case OP_CODE_PACKET_RECEIPT_NOTIF_KEY: final BluetoothGattCharacteristic packetCharacteristic = gatt.getService(DFU_SERVICE_UUID).getCharacteristic(DFU_PACKET_UUID); try { mBytesConfirmed = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT32, 1); mPacketsSentSinceNotification = 0; waitIfPaused(); if (mAborted) break; final byte[] buffer = mBuffer; final int size = mInputStream.read(buffer); writePacket(gatt, packetCharacteristic, buffer, size); updateProgressNotification(); return; } catch (final HexFileValidationException e) { loge("Invalid HEX file"); mErrorState = ERROR_FILE_INVALID; } catch (final IOException e) { loge("Error while reading the input stream", e); mErrorState = ERROR_FILE_IO_EXCEPTION; } break; default: sendLogBroadcast(Level.INFO, "Received Read Response from " + characteristic.getUuid() + ", value (0x): " + parse(characteristic)); mReceivedData = characteristic.getValue(); break; } // notify waiting thread synchronized (mLock) { mLock.notifyAll(); return; } }; public String parse(final BluetoothGattCharacteristic characteristic) { final byte[] data = characteristic.getValue(); if (data == null) return ""; final int length = data.length; if (length == 0) return ""; final char[] out = new char[length * 3 - 1]; for (int j = 0; j < length; j++) { int v = data[j] & 0xFF; out[j * 3] = HEX_ARRAY[v >>> 4]; out[j * 3 + 1] = HEX_ARRAY[v & 0x0F]; if (j != length - 1) out[j * 3 + 2] = '-'; } return new String(out); } }; public DfuBaseService() { super(TAG); } @Override public void onCreate() { super.onCreate(); initialize(); final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); final IntentFilter actionFilter = makeDfuActionIntentFilter(); manager.registerReceiver(mDfuActionReceiver, actionFilter); // We must register this as a non-local receiver to get broadcasts from the notification action registerReceiver(mDfuActionReceiver, actionFilter); final IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(mConnectionStateBroadcastReceiver, filter); } @Override public void onDestroy() { super.onDestroy(); final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); manager.unregisterReceiver(mDfuActionReceiver); unregisterReceiver(mDfuActionReceiver); unregisterReceiver(mConnectionStateBroadcastReceiver); } @Override protected void onHandleIntent(final Intent intent) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // In order to let DfuActivity know whether DFU is in progress, we have to use Shared Preferences final SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(DFU_IN_PROGRESS, true); editor.commit(); // Read input parameters final String deviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); final String deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME); final String filePath = intent.getStringExtra(EXTRA_FILE_PATH); final Uri fileUri = intent.getParcelableExtra(EXTRA_FILE_URI); final String initFilePath = intent.getStringExtra(EXTRA_INIT_FILE_PATH); final Uri initFileUri = intent.getParcelableExtra(EXTRA_INIT_FILE_URI); final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI); int fileType = intent.getIntExtra(EXTRA_FILE_TYPE, TYPE_AUTO); if (filePath != null && fileType == TYPE_AUTO) fileType = filePath.toLowerCase(Locale.US).endsWith("zip") ? TYPE_AUTO : TYPE_APPLICATION; String mimeType = intent.getStringExtra(EXTRA_FILE_MIME_TYPE); mimeType = mimeType != null ? mimeType : (fileType == TYPE_AUTO ? MIME_TYPE_ZIP : MIME_TYPE_OCTET_STREAM); mLogSession = Logger.openSession(this, logUri); mPartCurrent = intent.getIntExtra(EXTRA_PART_CURRENT, 1); mPartsTotal = intent.getIntExtra(EXTRA_PARTS_TOTAL, 1); // Check file type and mime-type if ((fileType & ~(TYPE_SOFT_DEVICE | TYPE_BOOTLOADER | TYPE_APPLICATION)) > 0 || !(MIME_TYPE_ZIP.equals(mimeType) || MIME_TYPE_OCTET_STREAM.equals(mimeType))) { logw("File type or file mime-type not supported"); sendLogBroadcast(Level.WARNING, "File type or file mime-type not supported"); sendErrorBroadcast(ERROR_FILE_TYPE_UNSUPPORTED); return; } if (MIME_TYPE_OCTET_STREAM.equals(mimeType) && fileType != TYPE_SOFT_DEVICE && fileType != TYPE_BOOTLOADER && fileType != TYPE_APPLICATION) { logw("Unable to determine file type"); sendLogBroadcast(Level.WARNING, "Unable to determine file type"); sendErrorBroadcast(ERROR_FILE_TYPE_UNSUPPORTED); return; } mDeviceAddress = deviceAddress; mDeviceName = deviceName; mConnectionState = STATE_DISCONNECTED; mBytesSent = 0; mBytesConfirmed = 0; mPacketsSentSinceNotification = 0; mErrorState = 0; mAborted = false; mPaused = false; mNotificationsEnabled = false; mResetRequestSent = false; mRequestCompleted = false; mImageSizeSent = false; // read preferences final boolean packetReceiptNotificationEnabled = preferences.getBoolean(DfuSettingsConstants.SETTINGS_PACKET_RECEIPT_NOTIFICATION_ENABLED, true); String value = preferences.getString(DfuSettingsConstants.SETTINGS_NUMBER_OF_PACKETS, String.valueOf(DfuSettingsConstants.SETTINGS_NUMBER_OF_PACKETS_DEFAULT)); int numberOfPackets = DfuSettingsConstants.SETTINGS_NUMBER_OF_PACKETS_DEFAULT; try { numberOfPackets = Integer.parseInt(value); if (numberOfPackets < 0 || numberOfPackets > 0xFFFF) numberOfPackets = DfuSettingsConstants.SETTINGS_NUMBER_OF_PACKETS_DEFAULT; } catch (final NumberFormatException e) { numberOfPackets = DfuSettingsConstants.SETTINGS_NUMBER_OF_PACKETS_DEFAULT; } if (!packetReceiptNotificationEnabled) numberOfPackets = 0; mPacketsBeforeNotification = numberOfPackets; // The Soft Device starts where MBR ends (by default from the address 0x1000). Before there is a MBR section, which should not be transmitted over DFU. // Applications and bootloader starts from bigger address. However, in custom DFU implementations, user may want to transmit the whole whole data, even from address 0x0000. value = preferences.getString(DfuSettingsConstants.SETTINGS_MBR_SIZE, String.valueOf(DfuSettingsConstants.SETTINGS_DEFAULT_MBR_SIZE)); int mbrSize = DfuSettingsConstants.SETTINGS_DEFAULT_MBR_SIZE; try { mbrSize = Integer.parseInt(value); if (mbrSize < 0) mbrSize = 0; } catch (final NumberFormatException e) { mbrSize = DfuSettingsConstants.SETTINGS_DEFAULT_MBR_SIZE; } sendLogBroadcast(Level.VERBOSE, "Starting DFU service"); InputStream is = null; InputStream initIs = null; int imageSizeInBytes; try { // Prepare data to send, calculate stream size try { sendLogBroadcast(Level.VERBOSE, "Opening file..."); if (fileUri != null) { is = openInputStream(fileUri, mimeType, mbrSize, fileType); } else { is = openInputStream(filePath, mimeType, mbrSize, fileType); } if (initFileUri != null) { // Try to read the Init Packet file from URI initIs = getContentResolver().openInputStream(initFileUri); } else if (initFilePath != null) { // Try to read the Init Packet file from path initIs = new FileInputStream(initFilePath); } mInputStream = is; imageSizeInBytes = mImageSizeInBytes = is.available(); // Update the file type bit field basing on the ZIP content if (fileType == TYPE_AUTO && MIME_TYPE_ZIP.equals(mimeType)) { final ZipHexInputStream zhis = (ZipHexInputStream) is; fileType = zhis.getContentType(); } mFileType = fileType; // Set the Init packet stream in case of a ZIP file if (MIME_TYPE_ZIP.equals(mimeType)) { final ZipHexInputStream zhis = (ZipHexInputStream) is; if (fileType == TYPE_APPLICATION) { if (zhis.getApplicationInit() != null) initIs = new ByteArrayInputStream(zhis.getApplicationInit()); } else { if (zhis.getSystemInit() != null) initIs = new ByteArrayInputStream(zhis.getSystemInit()); } } sendLogBroadcast(Level.INFO, "Image file opened (" + mImageSizeInBytes + " bytes in total)"); } catch (final FileNotFoundException e) { initIs = null; loge("An exception occured while opening file", e); sendErrorBroadcast(ERROR_FILE_NOT_FOUND); return; } catch (final IOException e) { initIs = null; loge("An exception occured while calculating file size", e); sendErrorBroadcast(ERROR_FILE_ERROR); return; } // Let's connect to the device sendLogBroadcast(Level.VERBOSE, "Connecting to DFU target..."); updateProgressNotification(PROGRESS_CONNECTING); final BluetoothGatt gatt = connect(deviceAddress); // Are we connected? if (mErrorState > 0) { // error occurred final int error = mErrorState & ~ERROR_CONNECTION_MASK; loge("An error occurred while connecting to the device:" + error); sendLogBroadcast(Level.ERROR, String.format("Connection failed (0x%02X): %s", error, GattError.parse(error))); terminateConnection(gatt, mErrorState); return; } if (mAborted) { logi("Upload aborted"); sendLogBroadcast(Level.WARNING, "Upload aborted"); terminateConnection(gatt, PROGRESS_ABORTED); return; } // We have connected to DFU device and services are discoverer final BluetoothGattService dfuService = gatt.getService(DFU_SERVICE_UUID); // there was a case when the service was null. I don't know why if (dfuService == null) { loge("DFU service does not exists on the device"); sendLogBroadcast(Level.WARNING, "Connected. DFU Service not found"); terminateConnection(gatt, ERROR_SERVICE_NOT_FOUND); return; } final BluetoothGattCharacteristic controlPointCharacteristic = dfuService.getCharacteristic(DFU_CONTROL_POINT_UUID); final BluetoothGattCharacteristic packetCharacteristic = dfuService.getCharacteristic(DFU_PACKET_UUID); if (controlPointCharacteristic == null || packetCharacteristic == null) { loge("DFU characteristics not found in the DFU service"); sendLogBroadcast(Level.WARNING, "Connected. DFU Characteristics not found"); terminateConnection(gatt, ERROR_CHARACTERISTICS_NOT_FOUND); return; } /* * The DFU Version characteristic has been added in SDK 7.0. * * It may return version number in 2 bytes (f.e. 0x05-00), where the first one is the minor version and the second one is the major version. * In case of 0x05-00 the DFU has the version 0.5. * * Currently the following version numbers are supported: * * - 0.1 (0x01-00) - Device is connected to the application, not to the Bootloader. The application supports Long Term Key (LTK) sharing and buttonless update. * Enable notifications on the DFU Control Point characteristic and write 0x01-04 into it to jump to the Bootloader. * Check the Bootloader version again for more info about the Bootloader version. * * - 0.5 (0x05-00) - Device is in OTA-DFU Bootloader. The Bootloader supports LTK sharing and required the Extended Init Packet. It supports * a SoftDevice, Bootloader or an Application update. SoftDevice and a Bootloader may be sent together. * */ final BluetoothGattCharacteristic versionCharacteristic = dfuService.getCharacteristic(DFU_VERSION); // this may be null for older versions of the Bootloader sendLogBroadcast(Level.INFO, "Connected. Services discovered"); try { updateProgressNotification(PROGRESS_STARTING); // read the version number if available int version = 0; if (versionCharacteristic != null) { version = readVersion(gatt, versionCharacteristic); final int minor = (version & 0x0F); final int major = (version >> 8); sendLogBroadcast(Level.APPLICATION, "Version number read: " + major + "." + minor); } /* * Check if we are in the DFU Bootloader or in the Application that supports the buttonless update. * * In the DFU from SDK 6.1, which was also supporting the buttonless update, there was no DFU Version characteristic. In that case we may find out whether * we are in the bootloader or application by simply checking the number of characteristics. */ if (version == 1 || dfuService.getCharacteristics().size() > 3 /* Generic Access, Generic Attribute, DFU Service */) { // the service is connected to the application, not to the bootloader logi("Application with buttonless update found"); sendLogBroadcast(Level.WARNING, "Application with buttonless update found"); // if we are bonded we may want to enable Service Changed characteristic indications if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) { final BluetoothGattService genericAttributeService = gatt.getService(GENERIC_ATTRIBUTE_SERVICE_UUID); if (genericAttributeService != null) { final BluetoothGattCharacteristic serviceChangedCharacteristic = genericAttributeService.getCharacteristic(SERVICE_CHANGED_UUID); if (serviceChangedCharacteristic != null) { enableCCCD(gatt, serviceChangedCharacteristic, INDICATIONS); sendLogBroadcast(Level.APPLICATION, "Service Changed indications enabled"); } } } sendLogBroadcast(Level.VERBOSE, "Jumping to the DFU Bootloader..."); // enable notifications enableCCCD(gatt, controlPointCharacteristic, NOTIFICATIONS); sendLogBroadcast(Level.APPLICATION, "Notifications enabled"); // send 'jump to bootloader command' (Start DFU) updateProgressNotification(PROGRESS_DISCONNECTING); OP_CODE_START_DFU[1] = 0x04; logi("Sending Start DFU command (Op Code = 1, Upload Mode = 4)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_START_DFU, true); sendLogBroadcast(Level.APPLICATION, "Jump to bootloader sent (Op Code = 1, Upload Mode = 4)"); // The device will reset so we don't have to send Disconnect signal. waitUntilDisconnected(); sendLogBroadcast(Level.INFO, "Disconnected by the remote device"); // Close the device refreshDeviceCache(gatt, false); close(gatt); logi("Starting service that will connect to the DFU bootloader"); final Intent newIntent = new Intent(); newIntent.fillIn(intent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_PACKAGE); startService(newIntent); return; } // enable notifications enableCCCD(gatt, controlPointCharacteristic, NOTIFICATIONS); sendLogBroadcast(Level.APPLICATION, "Notifications enabled"); try { // set up the temporary variable that will hold the responses byte[] response = null; int status = 0; // obtain size of image(s) int softDeviceImageSize = (fileType & TYPE_SOFT_DEVICE) > 0 ? imageSizeInBytes : 0; int bootloaderImageSize = (fileType & TYPE_BOOTLOADER) > 0 ? imageSizeInBytes : 0; int appImageSize = (fileType & TYPE_APPLICATION) > 0 ? imageSizeInBytes : 0; // the sizes above may be overwritten if a ZIP file was passed if (MIME_TYPE_ZIP.equals(mimeType)) { final ZipHexInputStream zhis = (ZipHexInputStream) is; softDeviceImageSize = zhis.softDeviceImageSize(); bootloaderImageSize = zhis.bootloaderImageSize(); appImageSize = zhis.applicationImageSize(); } try { OP_CODE_START_DFU[1] = (byte) fileType; // send Start DFU command to Control Point logi("Sending Start DFU command (Op Code = 1, Upload Mode = " + fileType + ")"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_START_DFU); sendLogBroadcast(Level.APPLICATION, "DFU Start sent (Op Code = 1, Upload Mode = " + fileType + ")"); // send image size in bytes to DFU Packet logi("Sending image size array to DFU Packet (" + softDeviceImageSize + "b, " + bootloaderImageSize + "b, " + appImageSize + "b)"); writeImageSize(gatt, packetCharacteristic, softDeviceImageSize, bootloaderImageSize, appImageSize); sendLogBroadcast(Level.APPLICATION, "Firmware image size sent (" + softDeviceImageSize + "b, " + bootloaderImageSize + "b, " + appImageSize + "b)"); // a notification will come with confirmation. Let's wait for it a bit response = readNotificationResponse(); status = getStatusCode(response, OP_CODE_START_DFU_KEY); sendLogBroadcast(Level.APPLICATION, "Responce received (Op Code = " + response[1] + " Status = " + status + ")"); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Starting DFU failed", status); } catch (final RemoteDfuException e) { try { if (e.getErrorNumber() != DFU_STATUS_NOT_SUPPORTED) throw e; // If user wants to send soft device and/or bootloader + application we may try to send the Soft Device/Bootloader files first, // and then reconnect and send the application if ((fileType & TYPE_APPLICATION) > 0 && (fileType & (TYPE_SOFT_DEVICE | TYPE_BOOTLOADER)) > 0) { logw("DFU target does not support (SD/BL)+App update"); sendLogBroadcast(Level.WARNING, "DFU target does not support (SD/BL)+App update"); fileType &= ~TYPE_APPLICATION; // clear application bit mFileType = fileType; OP_CODE_START_DFU[1] = (byte) fileType; mPartsTotal = 2; // set new content type in the ZIP Input Stream and update sizes of images final ZipHexInputStream zhis = (ZipHexInputStream) is; zhis.setContentType(fileType); try { appImageSize = 0; mImageSizeInBytes = is.available(); } catch (final IOException e1) { // never happen } // send Start DFU command to Control Point sendLogBroadcast(Level.VERBOSE, "Sending only SD/BL"); logi("Resending Start DFU command (Op Code = 1, Upload Mode = " + fileType + ")"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_START_DFU); sendLogBroadcast(Level.APPLICATION, "DFU Start sent (Op Code = 1, Upload Mode = " + fileType + ")"); // send image size in bytes to DFU Packet logi("Sending image size array to DFU Packet: [" + softDeviceImageSize + "b, " + bootloaderImageSize + "b, " + appImageSize + "b]"); writeImageSize(gatt, packetCharacteristic, softDeviceImageSize, bootloaderImageSize, appImageSize); sendLogBroadcast(Level.APPLICATION, "Firmware image size sent [" + softDeviceImageSize + "b, " + bootloaderImageSize + "b, " + appImageSize + "b]"); // a notification will come with confirmation. Let's wait for it a bit response = readNotificationResponse(); status = getStatusCode(response, OP_CODE_START_DFU_KEY); sendLogBroadcast(Level.APPLICATION, "Responce received (Op Code = " + response[1] + " Status = " + status + ")"); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Starting DFU failed", status); } else throw e; } catch (final RemoteDfuException e1) { if (e1.getErrorNumber() != DFU_STATUS_NOT_SUPPORTED) throw e1; // If operation is not supported by DFU target we may try to upload application with legacy mode, using DFU v.1 if (fileType == TYPE_APPLICATION) { // The DFU target does not support DFU v.2 protocol logw("DFU target does not support DFU v.2"); sendLogBroadcast(Level.WARNING, "DFU target does not support DFU v.2"); // send Start DFU command to Control Point sendLogBroadcast(Level.VERBOSE, "Switching to DFU v.1"); logi("Resending Start DFU command (Op Code = 1)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_START_DFU); // If has 2 bytes, but the second one is ignored sendLogBroadcast(Level.APPLICATION, "DFU Start sent (Op Code = 1)"); // send image size in bytes to DFU Packet logi("Sending application image size to DFU Packet: " + imageSizeInBytes + " bytes"); writeImageSize(gatt, packetCharacteristic, mImageSizeInBytes); sendLogBroadcast(Level.APPLICATION, "Firmware image size sent (" + imageSizeInBytes + " bytes)"); // a notification will come with confirmation. Let's wait for it a bit response = readNotificationResponse(); status = getStatusCode(response, OP_CODE_START_DFU_KEY); sendLogBroadcast(Level.APPLICATION, "Responce received (Op Code = " + response[1] + ", Status = " + status + ")"); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Starting DFU failed", status); } else throw e1; } } // Since SDK 6.1 this delay is no longer required as the Receive Start DFU notification is postponed until the memory is clear. // if ((fileType & TYPE_SOFT_DEVICE) > 0) { // // In the experimental version of bootloader (SDK 6.0.0) we must wait some time until we can proceed with Soft Device update. Bootloader must prepare the RAM for the new firmware. // // Most likely this step will not be needed in the future as the notification received a moment before will be postponed until Bootloader is ready. // synchronized (this) { // try { // wait(6000); // } catch (final InterruptedException e) { // // do nothing // Send DFU Init Packet if (initIs != null) { sendLogBroadcast(Level.APPLICATION, "Writing Initialize DFU Parameters..."); logi("Sending the Initialize DFU Parameters START (Op Code = 2, Value = 0)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_INIT_DFU_PARAMS_START); try { byte[] data = new byte[20]; int size = 0; while ((size = initIs.read(data, 0, data.length)) != -1) { writeInitPacket(gatt, packetCharacteristic, data, size); } } catch (final IOException e) { loge("Error while reading Init packet file"); throw new DfuException("Error while reading Init packet file", ERROR_FILE_ERROR); } logi("Sending the Initialize DFU Parameters COMPLETE (Op Code = 2, Value = 1)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_INIT_DFU_PARAMS_COMPLETE); // a notification will come with confirmation. Let's wait for it a bit response = readNotificationResponse(); status = getStatusCode(response, OP_CODE_INIT_DFU_PARAMS_KEY); sendLogBroadcast(Level.APPLICATION, "Responce received (Op Code = " + response[1] + ", Status = " + status + ")"); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Device returned error after sending init packet", status); sendLogBroadcast(Level.APPLICATION, "Initialize DFU Parameters completed"); } else mInitPacketSent = true; // Send the number of packets of firmware before receiving a receipt notification final int numberOfPacketsBeforeNotification = mPacketsBeforeNotification; if (numberOfPacketsBeforeNotification > 0) { logi("Sending the number of packets before notifications (Op Code = 8, Value = " + numberOfPacketsBeforeNotification + ")"); setNumberOfPackets(OP_CODE_PACKET_RECEIPT_NOTIF_REQ, numberOfPacketsBeforeNotification); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_PACKET_RECEIPT_NOTIF_REQ); sendLogBroadcast(Level.APPLICATION, "Packet Receipt Notif Req (Op Code = 8) sent (Value = " + numberOfPacketsBeforeNotification + ")"); } // Initialize firmware upload logi("Sending Receive Firmware Image request (Op Code = 3)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_RECEIVE_FIRMWARE_IMAGE); sendLogBroadcast(Level.APPLICATION, "Receive Firmware Image request sent"); // This allow us to calculate upload time final long startTime = mLastProgressTime = mStartTime = SystemClock.elapsedRealtime(); updateProgressNotification(); try { sendLogBroadcast(Level.APPLICATION, "Starting upload..."); response = uploadFirmwareImage(gatt, packetCharacteristic, is); } catch (final DeviceDisconnectedException e) { loge("Disconnected while sending data"); throw e; // TODO reconnect? } final long endTime = SystemClock.elapsedRealtime(); logi("Transfer of " + mBytesSent + " bytes has taken " + (endTime - startTime) + " ms"); sendLogBroadcast(Level.APPLICATION, "Upload completed in " + (endTime - startTime) + " ms"); // Check the result of the operation status = getStatusCode(response, OP_CODE_RECEIVE_FIRMWARE_IMAGE_KEY); logi("Response received. Op Code: " + response[0] + " Req Op Code = " + response[1] + ", Status = " + response[2]); sendLogBroadcast(Level.APPLICATION, "Responce received (Op Code = " + response[1] + ", Status = " + status + ")"); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Device returned error after sending file", status); // Send Validate request logi("Sending Validate request (Op Code = 4)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_VALIDATE); sendLogBroadcast(Level.APPLICATION, "Validate request sent"); // A notification will come with status code. Let's wait for it a bit. response = readNotificationResponse(); status = getStatusCode(response, OP_CODE_VALIDATE_KEY); logi("Response received. Op Code: " + response[0] + " Req Op Code = " + response[1] + ", Status = " + response[2]); sendLogBroadcast(Level.APPLICATION, "Responce received (Op Code = " + response[1] + ", Status = " + status + ")"); if (status != DFU_STATUS_SUCCESS) throw new RemoteDfuException("Device returned validation error", status); // Disable notifications locally updateProgressNotification(PROGRESS_DISCONNECTING); gatt.setCharacteristicNotification(controlPointCharacteristic, false); // Send Activate and Reset signal. logi("Sending Activate and Reset request (Op Code = 5)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_ACTIVATE_AND_RESET); sendLogBroadcast(Level.APPLICATION, "Activate and Reset request sent"); // The device will reset so we don't have to send Disconnect signal. waitUntilDisconnected(); sendLogBroadcast(Level.INFO, "Disconnected by the remote device"); // Close the device refreshDeviceCache(gatt, true); // The new application may have lost bonding information (if there was bonding). Force refresh it just for sure. close(gatt); /* * We need to send PROGRESS_COMPLETED message only when all files has been transmitted. * In case user wants to send Soft Device and/or Bootloader and Application service will be started twice: one to send SD+BL, * second time to send Application using the new Bootloader. In the first case we do not send PROGRESS_COMPLETED notification. */ if (mPartCurrent == mPartsTotal) { updateProgressNotification(PROGRESS_COMPLETED); } else { /* * The current service handle will try to upload Soft Device and/or Bootloader. * We need to enqueue another Intent that will try to send application only. */ logi("Starting service that will upload application"); final Intent newIntent = new Intent(); newIntent.fillIn(intent, Intent.FILL_IN_COMPONENT | Intent.FILL_IN_PACKAGE); newIntent.putExtra(EXTRA_FILE_TYPE, TYPE_APPLICATION); newIntent.putExtra(EXTRA_PART_CURRENT, mPartCurrent + 1); newIntent.putExtra(EXTRA_PARTS_TOTAL, mPartsTotal); startService(newIntent); } } catch (final UnknownResponseException e) { final int error = ERROR_INVALID_RESPONSE; loge(e.getMessage()); sendLogBroadcast(Level.ERROR, e.getMessage()); logi("Sending Reset command (Op Code = 6)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_RESET); sendLogBroadcast(Level.APPLICATION, "Reset request sent"); terminateConnection(gatt, error); } catch (final RemoteDfuException e) { final int error = ERROR_REMOTE_MASK | e.getErrorNumber(); loge(e.getMessage()); sendLogBroadcast(Level.ERROR, String.format("Remote DFU error: %s", GattError.parse(error))); logi("Sending Reset command (Op Code = 6)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_RESET); sendLogBroadcast(Level.APPLICATION, "Reset request sent"); terminateConnection(gatt, error); } } catch (final UploadAbortedException e) { logi("Upload aborted"); sendLogBroadcast(Level.WARNING, "Upload aborted"); if (mConnectionState == STATE_CONNECTED_AND_READY) try { mAborted = false; logi("Sending Reset command (Op Code = 6)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_RESET); sendLogBroadcast(Level.APPLICATION, "Reset request sent"); } catch (final Exception e1) { // do nothing } terminateConnection(gatt, PROGRESS_ABORTED); } catch (final DeviceDisconnectedException e) { sendLogBroadcast(Level.ERROR, "Device has disconneted"); // TODO reconnect n times? loge(e.getMessage()); if (mNotificationsEnabled) gatt.setCharacteristicNotification(controlPointCharacteristic, false); close(gatt); updateProgressNotification(ERROR_DEVICE_DISCONNECTED); } catch (final DfuException e) { final int error = e.getErrorNumber() & ~ERROR_CONNECTION_MASK; sendLogBroadcast(Level.ERROR, String.format("Error (0x%02X): %s", error, GattError.parse(error))); loge(e.getMessage()); if (mConnectionState == STATE_CONNECTED_AND_READY) try { logi("Sending Reset command (Op Code = 6)"); writeOpCode(gatt, controlPointCharacteristic, OP_CODE_RESET); sendLogBroadcast(Level.APPLICATION, "Reset request sent"); } catch (final Exception e1) { // do nothing } terminateConnection(gatt, e.getErrorNumber()); } } finally { try { // upload has finished (success of fail) editor.putBoolean(DFU_IN_PROGRESS, false); editor.commit(); // ensure that input stream is always closed mInputStream = null; if (is != null) is.close(); is = null; } catch (final IOException e) { // do nothing } } } /** * Sets number of data packets that will be send before the notification will be received. * * @param data * control point data packet * @param value * number of packets before receiving notification. If this value is 0, then the notification of packet receipt will be disabled by the DFU target. */ private void setNumberOfPackets(final byte[] data, final int value) { data[1] = (byte) (value & 0xFF); data[2] = (byte) ((value >> 8) & 0xFF); } /** * Opens the binary input stream that returns the firmware image content. A Path to the file is given. * * @param filePath * the path to the HEX or BIN file * @param mimeType * the file type * @param mbrSize * the size of MBR, by default 0x1000 * @param types * the content files types in ZIP * @return the input stream with binary image content */ private InputStream openInputStream(final String filePath, final String mimeType, final int mbrSize, final int types) throws FileNotFoundException, IOException { final InputStream is = new FileInputStream(filePath); if (MIME_TYPE_ZIP.equals(mimeType)) return new ZipHexInputStream(is, mbrSize, types); if (filePath.toString().toLowerCase(Locale.US).endsWith("hex")) return new HexInputStream(is, mbrSize); return is; } /** * Opens the binary input stream. A Uri to the stream is given. * * @param stream * the Uri to the stream * @param mimeType * the file type * @param mbrSize * the size of MBR, by default 0x1000 * @param types * the content files types in ZIP * @return the input stream with binary image content */ private InputStream openInputStream(final Uri stream, final String mimeType, final int mbrSize, final int types) throws FileNotFoundException, IOException { final InputStream is = getContentResolver().openInputStream(stream); if (MIME_TYPE_ZIP.equals(mimeType)) return new ZipHexInputStream(is, mbrSize, types); if (stream.toString().toLowerCase(Locale.US).endsWith("hex")) return new HexInputStream(is, mbrSize); return is; } /** * Connects to the BLE device with given address. This method is SYNCHRONOUS, it wait until the connection status change from {@link #STATE_CONNECTING} to {@link #STATE_CONNECTED_AND_READY} or an * error occurs. * * @param address * the device address * @return the GATT device */ private BluetoothGatt connect(final String address) { mConnectionState = STATE_CONNECTING; logi("Connecting to the device..."); final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); final BluetoothGatt gatt = device.connectGatt(this, false, mGattCallback); // We have to wait until the device is connected and services are discovered // Connection error may occur as well. try { synchronized (mLock) { while (((mConnectionState == STATE_CONNECTING || mConnectionState == STATE_CONNECTED) && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } return gatt; } /** * Disconnects from the device and cleans local variables in case of error. This method is SYNCHRONOUS and wait until the disconnecting process will be completed. * * @param gatt * the GATT device to be disconnected * @param error * error number */ private void terminateConnection(final BluetoothGatt gatt, final int error) { if (mConnectionState != STATE_DISCONNECTED) { updateProgressNotification(PROGRESS_DISCONNECTING); // No need to disable notifications // Disconnect from the device disconnect(gatt); sendLogBroadcast(Level.INFO, "Disconnected"); } // Close the device refreshDeviceCache(gatt, false); close(gatt); updateProgressNotification(error); } /** * Disconnects from the device. This is SYNCHRONOUS method and waits until the callback returns new state. Terminates immediately if device is already disconnected. Do not call this method * directly, use {@link #terminateConnection(BluetoothGatt, int)} instead. * * @param gatt * the GATT device that has to be disconnected */ private void disconnect(final BluetoothGatt gatt) { if (mConnectionState == STATE_DISCONNECTED) return; mConnectionState = STATE_DISCONNECTING; logi("Disconnecting from the device..."); gatt.disconnect(); // We have to wait until device gets disconnected or an error occur waitUntilDisconnected(); } /** * Wait until the connection state will change to {@link #STATE_DISCONNECTED} or until an error occurs. */ private void waitUntilDisconnected() { try { synchronized (mLock) { while (mConnectionState != STATE_DISCONNECTED && mErrorState == 0) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } } /** * Closes the GATT device and cleans up. * * @param gatt * the GATT device to be closed */ private void close(final BluetoothGatt gatt) { logi("Cleaning up..."); sendLogBroadcast(Level.DEBUG, "gatt.close()"); gatt.close(); mConnectionState = STATE_CLOSED; } /** * Clears the device cache. After uploading new firmware the DFU target will have other services than before. * * @param gatt * the GATT device to be refreshed * @param force * <code>true</code> to force the refresh */ private void refreshDeviceCache(final BluetoothGatt gatt, final boolean force) { /* * If the device is bonded this is up to the Service Changed characteristic to notify Android that the services has changed. * There is no need for this trick in that case. * If not bonded the Android is unable to get the information about changing services. The hidden refresh method may be used to force refreshing the device cache. */ if (force || gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) { sendLogBroadcast(Level.DEBUG, "gatt.refresh()"); /* * There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections. */ try { final Method refresh = gatt.getClass().getMethod("refresh"); if (refresh != null) { final boolean success = (Boolean) refresh.invoke(gatt); logi("Refreshing result: " + success); } } catch (Exception e) { loge("An exception occured while refreshing device", e); sendLogBroadcast(Level.WARNING, "Refreshing failed"); } } } /** * Checks whether the response received is valid and returns the status code. * * @param response * the response received from the DFU device. * @param request * the expected Op Code * @return the status code * @throws UnknownResponseException * if response was not valid */ private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException { if (response == null || response.length != 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request || response[2] < 1 || response[2] > 6) throw new UnknownResponseException("Invalid response received", response, request); return response[2]; } /** * Reads the DFU Version characteristic if such exists. Otherwise it returns 0. * * @param gatt * the GATT device * @param characteristic * the characteristic to read * @return a version number or 0 if not present on the bootloader * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private int readVersion(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) throws DeviceDisconnectedException, DfuException, UploadAbortedException { if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to read version number", mConnectionState); // If the DFU Version characteristic is not available we return 0. if (characteristic == null) return 0; mErrorState = 0; logi("Reading DFU version number..."); sendLogBroadcast(Level.VERBOSE, "Reading DFU version number..."); gatt.readCharacteristic(characteristic); // We have to wait until device gets disconnected or an error occur try { synchronized (mLock) { while ((mRequestCompleted == false && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Unable to read version number", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to read version number", mConnectionState); // The version is a 16-bit UINT return characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, 0); } /** * Enables or disables the notifications for given characteristic. This method is SYNCHRONOUS and wait until the * {@link BluetoothGattCallback#onDescriptorWrite(BluetoothGatt, BluetoothGattDescriptor, int)} will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. If * connection state will change, or an error will occur, an exception will be thrown. * * @param gatt * the GATT device * @param characteristic * the characteristic to enable or disable notifications for * @param enable * <code>true</code> to enable notifications, <code>false</code> to disable them * @throws DfuException * @throws UploadAbortedException */ private void enableCCCD(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int type) throws DeviceDisconnectedException, DfuException, UploadAbortedException { final String debugString = type == NOTIFICATIONS ? "notifications" : "indications"; if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState); mErrorState = 0; if ((type == NOTIFICATIONS && mNotificationsEnabled) || (type == INDICATIONS && mServiceChangedIndicationsEnabled)) return; logi("Enabling " + debugString + "..."); sendLogBroadcast(Level.VERBOSE, "Enabling " + debugString + " for " + characteristic.getUuid()); // enable notifications locally gatt.setCharacteristicNotification(characteristic, true); // enable notifications on the device final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG); descriptor.setValue(type == NOTIFICATIONS ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); sendLogBroadcast(Level.DEBUG, "gatt.writeDescriptor(" + descriptor.getUuid() + (type == NOTIFICATIONS ? ", value=0x01-00)" : ", value=0x02-00)")); gatt.writeDescriptor(descriptor); // We have to wait until device gets disconnected or an error occur try { synchronized (mLock) { while ((((type == NOTIFICATIONS && !mNotificationsEnabled) || (type == INDICATIONS && !mServiceChangedIndicationsEnabled)) && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Unable to set " + debugString + " state", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState); } /** * Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the * {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)} will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. * If connection state will change, or an error will occur, an exception will be thrown. * * @param gatt * the GATT device * @param characteristic * the characteristic to write to. Should be the DFU CONTROL POINT * @param value * the value to write to the characteristic * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private void writeOpCode(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] value) throws DeviceDisconnectedException, DfuException, UploadAbortedException { final boolean reset = value[0] == OP_CODE_RESET_KEY || value[0] == OP_CODE_ACTIVATE_AND_RESET_KEY; writeOpCode(gatt, characteristic, value, reset); } /** * Writes the operation code to the characteristic. This method is SYNCHRONOUS and wait until the * {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)} will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. * If connection state will change, or an error will occur, an exception will be thrown. * * @param gatt * the GATT device * @param characteristic * the characteristic to write to. Should be the DFU CONTROL POINT * @param value * the value to write to the characteristic * @param reset * whether the command trigger restarting the device * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private void writeOpCode(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] value, final boolean reset) throws DeviceDisconnectedException, DfuException, UploadAbortedException { mReceivedData = null; mErrorState = 0; mRequestCompleted = false; /* * Sending a command that will make the DFU target to reboot may cause an error 133 (0x85 - Gatt Error). If so, with this flag set, the error will not be shown to the user * as the peripheral is disconnected anyway. See: mGattCallback#onCharacteristicWrite(...) method */ mResetRequestSent = reset; characteristic.setValue(value); sendLogBroadcast(Level.VERBOSE, "Writing to characteristic " + characteristic.getUuid()); sendLogBroadcast(Level.DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); gatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((mRequestCompleted == false && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (!mResetRequestSent && mErrorState != 0) throw new DfuException("Unable to write Op Code " + value[0], mErrorState); if (!mResetRequestSent && mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to write Op Code " + value[0], mConnectionState); } /** * Writes the image size to the characteristic. This method is SYNCHRONOUS and wait until the {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)} * will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown. * * @param gatt * the GATT device * @param characteristic * the characteristic to write to. Should be the DFU PACKET * @param imageSize * the image size in bytes * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private void writeImageSize(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int imageSize) throws DeviceDisconnectedException, DfuException, UploadAbortedException { mReceivedData = null; mErrorState = 0; mImageSizeSent = false; characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); characteristic.setValue(new byte[4]); characteristic.setValue(imageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 0); sendLogBroadcast(Level.VERBOSE, "Writing to characteristic " + characteristic.getUuid()); sendLogBroadcast(Level.DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); gatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((mImageSizeSent == false && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Unable to write Image Size", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to write Image Size", mConnectionState); } /** * <p> * Writes the Soft Device, Bootloader and Application image sizes to the characteristic. Soft Device and Bootloader update was added in DFU v.2. Sizes of SD, BL and App are uploaded as 3x UINT32 * even though some of them may be 0s. F.e. if only App is being updated the data will be <0x00000000, 0x00000000, [App size]> * </p> * <p> * This method is SYNCHRONOUS and wait until the {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)} will be called or the connection state will * change from {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown. * </p> * * @param gatt * the GATT device * @param characteristic * the characteristic to write to. Should be the DFU PACKET * @param softDeviceImageSize * the Soft Device image size in bytes * @param bootloaderImageSize * the Bootloader image size in bytes * @param appImageSize * the Application image size in bytes * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private void writeImageSize(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int softDeviceImageSize, final int bootloaderImageSize, final int appImageSize) throws DeviceDisconnectedException, DfuException, UploadAbortedException { mReceivedData = null; mErrorState = 0; mImageSizeSent = false; characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); characteristic.setValue(new byte[12]); characteristic.setValue(softDeviceImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 0); characteristic.setValue(bootloaderImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 4); characteristic.setValue(appImageSize, BluetoothGattCharacteristic.FORMAT_UINT32, 8); sendLogBroadcast(Level.VERBOSE, "Writing to characteristic " + characteristic.getUuid()); sendLogBroadcast(Level.DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); gatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((mImageSizeSent == false && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Unable to write Image Sizes", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to write Image Sizes", mConnectionState); } /** * Writes the Init packet to the characteristic. This method is SYNCHRONOUS and wait until the {@link BluetoothGattCallback#onCharacteristicWrite(BluetoothGatt, BluetoothGattCharacteristic, int)} * will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown. * * @param gatt * the GATT device * @param characteristic * the characteristic to write to. Should be the DFU PACKET * @param initPacket * the init packet as a byte array. This must be shorter or equal to 20 bytes (TODO check this restriction). * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private void writeInitPacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) throws DeviceDisconnectedException, DfuException, UploadAbortedException { byte[] locBuffer = buffer; if (buffer.length != size) { locBuffer = new byte[size]; System.arraycopy(buffer, 0, locBuffer, 0, size); } mErrorState = 0; mInitPacketSent = false; characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); characteristic.setValue(locBuffer); logi("Sending init packet (Value = " + parse(locBuffer) + ")"); sendLogBroadcast(Level.VERBOSE, "Writing to characteristic " + characteristic.getUuid()); sendLogBroadcast(Level.DEBUG, "gatt.writeCharacteristic(" + characteristic.getUuid() + ")"); gatt.writeCharacteristic(characteristic); // We have to wait for confirmation try { synchronized (mLock) { while ((mInitPacketSent == false && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Unable to write Init DFU Parameters", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to write Init DFU Parameters", mConnectionState); } /** * Starts sending the data. This method is SYNCHRONOUS and terminates when the whole file will be uploaded or the connection status will change from {@link #STATE_CONNECTED_AND_READY}. If * connection state will change, or an error will occur, an exception will be thrown. * * @param gatt * the GATT device (DFU target) * @param packetCharacteristic * the characteristic to write file content to. Must be the DFU PACKET * @return The response value received from notification with Op Code = 3 when all bytes will be uploaded successfully. * @throws DeviceDisconnectedException * Thrown when the device will disconnect in the middle of the transmission. The error core will be saved in {@link #mConnectionState}. * @throws DfuException * Thrown if DFU error occur * @throws UploadAbortedException */ private byte[] uploadFirmwareImage(final BluetoothGatt gatt, final BluetoothGattCharacteristic packetCharacteristic, final InputStream inputStream) throws DeviceDisconnectedException, DfuException, UploadAbortedException { mReceivedData = null; mErrorState = 0; final byte[] buffer = mBuffer; try { final int size = inputStream.read(buffer); sendLogBroadcast(Level.VERBOSE, "Sending firmware to characteristic " + packetCharacteristic.getUuid() + "..."); writePacket(gatt, packetCharacteristic, buffer, size); } catch (final HexFileValidationException e) { throw new DfuException("HEX file not valid", ERROR_FILE_INVALID); } catch (final IOException e) { throw new DfuException("Error while reading file", ERROR_FILE_IO_EXCEPTION); } try { synchronized (mLock) { while ((mReceivedData == null && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Uploading Fimrware Image failed", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Uploading Fimrware Image failed: device disconnected", mConnectionState); return mReceivedData; } /** * Writes the buffer to the characteristic. The maximum size of the buffer is 20 bytes. This method is ASYNCHRONOUS and returns immediately after adding the data to TX queue. * * @param gatt * the GATT device * @param characteristic * the characteristic to write to. Should be the DFU PACKET * @param buffer * the buffer with 1-20 bytes * @param size * the number of bytes from the buffer to send */ private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) { byte[] locBuffer = buffer; if (buffer.length != size) { locBuffer = new byte[size]; System.arraycopy(buffer, 0, locBuffer, 0, size); } characteristic.setValue(locBuffer); gatt.writeCharacteristic(characteristic); // FIXME BLE buffer overflow // after writing to the device with WRITE_NO_RESPONSE property the onCharacteristicWrite callback is received immediately after writing data to a buffer. // The real sending is much slower than adding to the buffer. This method does not return false if writing didn't succeed.. just the callback is not invoked. // More info: this works fine on Nexus 5 (Andorid 4.4) (4.3 seconds) and on Samsung S4 (Android 4.3) (20 seconds) so this is a driver issue. // Nexus 4 and 7 uses Qualcomm chip, Nexus 5 and Samsung uses Broadcom chips. } private void waitIfPaused() { synchronized (mLock) { try { while (mPaused) mLock.wait(); } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } } } /** * Waits until the notification will arrive. Returns the data returned by the notification. This method will block the thread if response is not ready or connection state will change from * {@link #STATE_CONNECTED_AND_READY}. If connection state will change, or an error will occur, an exception will be thrown. * * @return the value returned by the Control Point notification * @throws DeviceDisconnectedException * @throws DfuException * @throws UploadAbortedException */ private byte[] readNotificationResponse() throws DeviceDisconnectedException, DfuException, UploadAbortedException { mErrorState = 0; try { synchronized (mLock) { while ((mReceivedData == null && mConnectionState == STATE_CONNECTED_AND_READY && mErrorState == 0 && !mAborted) || mPaused) mLock.wait(); } } catch (final InterruptedException e) { loge("Sleeping interrupted", e); } if (mAborted) throw new UploadAbortedException(); if (mErrorState != 0) throw new DfuException("Unable to write Op Code", mErrorState); if (mConnectionState != STATE_CONNECTED_AND_READY) throw new DeviceDisconnectedException("Unable to write Op Code", mConnectionState); return mReceivedData; } /** Stores the last progress percent. Used to lower number of calls of {@link #updateProgressNotification(int)}. */ private int mLastProgress = -1; /** * Creates or updates the notification in the Notification Manager. Sends broadcast with current progress to the activity. */ private void updateProgressNotification() { final int progress = (int) (100.0f * mBytesSent / mImageSizeInBytes); if (mLastProgress == progress) return; mLastProgress = progress; updateProgressNotification(progress); } /** * Creates or updates the notification in the Notification Manager. Sends broadcast with given progress or error state to the activity. * * @param progress * the current progress state or an error number, can be one of {@link #PROGRESS_CONNECTING}, {@link #PROGRESS_STARTING}, {@link #PROGRESS_VALIDATING}, {@link #PROGRESS_DISCONNECTING}, * {@link #PROGRESS_COMPLETED} or {@link #ERROR_FILE_ERROR}, {@link #ERROR_FILE_INVALID} , etc */ private void updateProgressNotification(final int progress) { final String deviceAddress = mDeviceAddress; final String deviceName = mDeviceName != null ? mDeviceName : getString(R.string.dfu_unknown_name); final Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notify_dfu); final NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(android.R.drawable.stat_sys_upload).setOnlyAlertOnce(true);//.setLargeIcon(largeIcon); switch (progress) { case PROGRESS_CONNECTING: builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_connecting)).setContentText(getString(R.string.dfu_status_connecting_msg, deviceName)).setProgress(100, 0, true); break; case PROGRESS_STARTING: builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_starting)).setContentText(getString(R.string.dfu_status_starting_msg, deviceName)).setProgress(100, 0, true); break; case PROGRESS_VALIDATING: builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_validating)).setContentText(getString(R.string.dfu_status_validating_msg, deviceName)).setProgress(100, 0, true); break; case PROGRESS_DISCONNECTING: builder.setOngoing(true).setContentTitle(getString(R.string.dfu_status_disconnecting)).setContentText(getString(R.string.dfu_status_disconnecting_msg, deviceName)) .setProgress(100, 0, true); break; case PROGRESS_COMPLETED: builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_completed)).setContentText(getString(R.string.dfu_status_completed_msg)).setAutoCancel(true); break; case PROGRESS_ABORTED: builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_aborted)).setContentText(getString(R.string.dfu_status_aborted_msg)).setAutoCancel(true); break; default: if (progress >= ERROR_MASK) { // progress is an error number builder.setOngoing(false).setContentTitle(getString(R.string.dfu_status_error)).setContentText(getString(R.string.dfu_status_error_msg)).setAutoCancel(true); } else { // progress is in percents final String title = mPartsTotal == 1 ? getString(R.string.dfu_status_uploading) : getString(R.string.dfu_status_uploading_part, mPartCurrent, mPartsTotal); final String text = (mFileType & TYPE_APPLICATION) > 0 ? getString(R.string.dfu_status_uploading_msg, deviceName) : getString(R.string.dfu_status_uploading_components_msg, deviceName); builder.setOngoing(true).setContentTitle(title).setContentText(text).setProgress(100, progress, false); } } // send progress or error broadcast if (progress < ERROR_MASK) sendProgressBroadcast(progress); else sendErrorBroadcast(progress); // update the notification final Intent intent = new Intent(this, getNotificationTarget()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(EXTRA_DEVICE_ADDRESS, deviceAddress); intent.putExtra(EXTRA_DEVICE_NAME, deviceName); intent.putExtra(EXTRA_PROGRESS, progress); // this may contains ERROR_CONNECTION_MASK bit! if (mLogSession != null) intent.putExtra(EXTRA_LOG_URI, mLogSession.getSessionUri()); final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); // Android 5 builder.setColor(Color.GRAY); // Add Abort action to the notification if (progress != PROGRESS_ABORTED && progress != PROGRESS_COMPLETED) { final Intent abortIntent = new Intent(BROADCAST_ACTION); abortIntent.putExtra(EXTRA_ACTION, ACTION_ABORT); final PendingIntent pendingAbortIntent = PendingIntent.getBroadcast(this, 1, abortIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(R.drawable.ic_action_notify_cancel, getString(R.string.dfu_action_abort), pendingAbortIntent); } final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, builder.build()); } protected abstract Class<? extends Activity> getNotificationTarget(); private void sendProgressBroadcast(final int progress) { final long now = SystemClock.elapsedRealtime(); final float speed = (float) (mBytesSent - mLastBytesSent) / (float) (now - mLastProgressTime); final float avgSpeed = (float) mBytesSent / (float) (now - mStartTime); mLastProgressTime = now; mLastBytesSent = mBytesSent; final Intent broadcast = new Intent(BROADCAST_PROGRESS); broadcast.putExtra(EXTRA_DATA, progress); broadcast.putExtra(EXTRA_DEVICE_ADDRESS, mDeviceAddress); broadcast.putExtra(EXTRA_PART_CURRENT, mPartCurrent); broadcast.putExtra(EXTRA_PARTS_TOTAL, mPartsTotal); broadcast.putExtra(EXTRA_SPEED_B_PER_MS, speed); broadcast.putExtra(EXTRA_AVG_SPEED_B_PER_MS, avgSpeed); if (mLogSession != null) broadcast.putExtra(EXTRA_LOG_URI, mLogSession.getSessionUri()); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); } private void sendErrorBroadcast(final int error) { final Intent broadcast = new Intent(BROADCAST_ERROR); broadcast.putExtra(EXTRA_DATA, error & ~ERROR_CONNECTION_MASK); broadcast.putExtra(EXTRA_DEVICE_ADDRESS, mDeviceAddress); if (mLogSession != null) broadcast.putExtra(EXTRA_LOG_URI, mLogSession.getSessionUri()); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); } private void sendLogBroadcast(final int level, final String message) { final ILogSession session = mLogSession; final String fullMessage = "[DFU] " + message; if (session == null) { // the log provider is not installed, use broadcast action final Intent broadcast = new Intent(BROADCAST_LOG); broadcast.putExtra(EXTRA_LOG_MESSAGE, fullMessage); broadcast.putExtra(EXTRA_LOG_LEVEL, level); broadcast.putExtra(EXTRA_DEVICE_ADDRESS, mDeviceAddress); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast); } else { // the log provider is installed, we can use logger Logger.log(session, level, fullMessage); } } /** * Initializes bluetooth adapter * * @return <code>true</code> if initialization was successful */ private boolean initialize() { // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { loge("Unable to initialize BluetoothManager."); return false; } mBluetoothAdapter = bluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { loge("Unable to obtain a BluetoothAdapter."); return false; } return true; } private static IntentFilter makeDfuActionIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(DfuBaseService.BROADCAST_ACTION); return intentFilter; } private void loge(final String message) { if (BuildConfig.DEBUG) Log.e(TAG, message); } private void loge(final String message, final Throwable e) { if (BuildConfig.DEBUG) Log.e(TAG, message, e); } private void logw(final String message) { if (BuildConfig.DEBUG) Log.w(TAG, message); } private void logi(final String message) { if (BuildConfig.DEBUG) Log.i(TAG, message); } private void logd(final String message) { if (BuildConfig.DEBUG) Log.d(TAG, message); } public String parse(final byte[] data) { if (data == null) return ""; final int length = data.length; if (length == 0) return ""; final char[] out = new char[length * 3 - 1]; for (int j = 0; j < length; j++) { int v = data[j] & 0xFF; out[j * 3] = HEX_ARRAY[v >>> 4]; out[j * 3 + 1] = HEX_ARRAY[v & 0x0F]; if (j != length - 1) out[j * 3 + 2] = '-'; } return new String(out); } }
package org.biojava.bio.program.phred; import java.io.BufferedReader; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.biojava.bio.BioError; import org.biojava.bio.BioException; import org.biojava.bio.dist.Distribution; import org.biojava.bio.dist.DistributionFactory; import org.biojava.bio.dist.DistributionTools; import org.biojava.bio.dist.DistributionTrainerContext; import org.biojava.bio.dist.SimpleDistributionTrainerContext; import org.biojava.bio.seq.DNATools; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.SequenceIterator; import org.biojava.bio.seq.db.HashSequenceDB; import org.biojava.bio.seq.db.IDMaker; import org.biojava.bio.seq.db.SequenceDB; import org.biojava.bio.seq.impl.SimpleSequence; import org.biojava.bio.seq.io.FastaDescriptionLineParser; import org.biojava.bio.seq.io.FastaFormat; import org.biojava.bio.seq.io.SeqIOTools; import org.biojava.bio.seq.io.SequenceBuilderFactory; import org.biojava.bio.seq.io.SimpleSequenceBuilder; import org.biojava.bio.seq.io.StreamReader; import org.biojava.bio.seq.io.StreamWriter; import org.biojava.bio.seq.io.SymbolTokenization; import org.biojava.bio.symbol.Alignment; import org.biojava.bio.symbol.Alphabet; import org.biojava.bio.symbol.AlphabetManager; import org.biojava.bio.symbol.AtomicSymbol; import org.biojava.bio.symbol.BasisSymbol; import org.biojava.bio.symbol.FiniteAlphabet; import org.biojava.bio.symbol.IllegalAlphabetException; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.bio.symbol.IntegerAlphabet; import org.biojava.bio.symbol.SimpleSymbolList; import org.biojava.bio.symbol.Symbol; import org.biojava.bio.symbol.SymbolList; import org.biojava.utils.AssertionFailure; import org.biojava.utils.ChangeVetoException; import org.biojava.utils.ListTools; public final class PhredTools { static{ try { List l = new ArrayList(2); l.add(DNATools.getDNA()); l.add(IntegerAlphabet.getSubAlphabet(0,99)); AlphabetManager.getCrossProductAlphabet(l, "PHRED"); } catch (IllegalAlphabetException iae) { throw new BioError( "Could not create the Phred alphabet", iae); } } /** * Retrieves the PHRED alphabet from the AlphabetManager. The Phred alphabet * is a cross product of a subset of the IntegerAlphabet from 0...99 and the * DNA alphabet. The Phred alphabet is finite. * * The Phred Alphabet contains 400 BasisSymbols named, for example, (guanine 47). * The BasisSymbols can be fragmented into their component AtomicSymbols using * the <code>getSymbols()</code> method of BasisSymbol. */ public static final FiniteAlphabet getPhredAlphabet(){ return (FiniteAlphabet)AlphabetManager.alphabetForName("PHRED"); } public static final Symbol dnaSymbolFromPhred(Symbol phredSym) throws IllegalSymbolException{ //validate the symbol getPhredAlphabet().validate(phredSym); //get the DNA component of the Phred Symbol List l = ((BasisSymbol)phredSym).getSymbols(); //the first symbol should be DNA return (Symbol) l.get(0); } public static final IntegerAlphabet.IntegerSymbol integerSymbolFromPhred(Symbol phredSym) throws IllegalSymbolException{ //validate the symbol getPhredAlphabet().validate(phredSym); //get the IntegerSymbol component of the Phred Symbol List l = ((BasisSymbol)phredSym).getSymbols(); //the second symbol should be the IntegerSymbol return (IntegerAlphabet.IntegerSymbol)(l.get(1)); } public static SymbolList createPhred(SymbolList dna, SymbolList quality) throws IllegalArgumentException, IllegalAlphabetException, IllegalSymbolException{ //perform initial checks if(dna.length() != quality.length()){ throw new IllegalArgumentException("SymbolLists must be of equal length "+ dna.length()+" : "+quality.length()); } if(dna.getAlphabet() != DNATools.getDNA()){ throw new IllegalAlphabetException( "Expecting SymbolList 'dna' to use the DNA alphabet, uses " +dna.getAlphabet().getName()); } Alphabet subint = IntegerAlphabet.getSubAlphabet(0,99); if(quality.getAlphabet() != subint && quality.getAlphabet() != IntegerAlphabet.getInstance()){ throw new IllegalAlphabetException( "Expecting SymbolList quality to use the "+subint.getName()+" alphabet"+ "or IntegerAlphabet instead uses "+ quality.getAlphabet().getName()); } //build the symbollist SimpleSymbolList sl = new SimpleSymbolList(getPhredAlphabet()); for(int i = 1; i <= dna.length(); i++){ Symbol d = dna.symbolAt(i); Symbol q = quality.symbolAt(i); try{ sl.addSymbol(getPhredSymbol(d,q)); }catch(ChangeVetoException e){ throw new AssertionFailure(e); } } return sl; } public static final Symbol getPhredSymbol(Symbol dna, Symbol integer) throws IllegalSymbolException{ return getPhredAlphabet().getSymbol(new ListTools.Doublet(dna, integer)); } /** * Writes Phred quality data in a Fasta type format. * @param db a bunch of PhredSequence objects * @param qual the OutputStream to write the quality data to. * @param seq the OutputStream to write the sequence data to. * @since 1.2 */ public static void writePhredQuality(OutputStream qual, OutputStream seq, SequenceDB db) throws IOException, BioException{ StreamWriter qualw = new StreamWriter(qual,new PhredFormat()); StreamWriter seqw = new StreamWriter(seq, new FastaFormat()); SequenceDB qualDB = new HashSequenceDB(IDMaker.byName); //Get the quality SymbolLists and add them to a SeqDB for(SequenceIterator i = db.sequenceIterator(); i.hasNext();){ Sequence p = i.nextSequence(); if(p instanceof PhredSequence){ PhredSequence ps = (PhredSequence)p; SymbolList ql = ps.getQuality(); try{ qualDB.addSequence( new SimpleSequence(ql,p.getURN(),p.getName(),p.getAnnotation())); }catch(ChangeVetoException cve){ throw new AssertionFailure("Cannot Add Quality Sequences to Database", cve); } } else{ throw new BioException("Expecting PhredSequence, got " + p.getClass().getName()); } } qualw.writeStream(qualDB.sequenceIterator()); seqw.writeStream(db.sequenceIterator());//this works as sequence methods act on the underlying SimpleSequence } /** * Constructs a StreamReader to read in Phred quality data in FASTA format. * The data is converted into sequences consisting of Symbols from the IntegerAlphabet. */ public static StreamReader readPhredQuality(BufferedReader br){ return new StreamReader(br, new PhredFormat(), getQualityParser(), getFastaBuilderFactory()); } /** * Calls SeqIOTools.readFastaDNA(br), added here for convinience. */ public static StreamReader readPhredSequence(BufferedReader br){ return (StreamReader)SeqIOTools.readFastaDNA(br); } private static SequenceBuilderFactory _fastaBuilderFactory; /** * Get a default SequenceBuilderFactory for handling FASTA * files. */ private static SequenceBuilderFactory getFastaBuilderFactory() { if (_fastaBuilderFactory == null) { _fastaBuilderFactory = new FastaDescriptionLineParser.Factory(SimpleSequenceBuilder.FACTORY); } return _fastaBuilderFactory; } /** * returns the IntegerAlphabet parser */ private static SymbolTokenization getQualityParser() { return IntegerAlphabet.getInstance().getTokenization("token"); } /** * The quality value is related to the base call error probability * by the formula QV = - 10 * log_10( P_e ) * where P_e is the probability that the base call is an error. * @return a <code>double</code> value, note that for most Phred scores this will be rounded * to the nearest <code>int</code> */ public static double qualityFromP(double probOfError){ return (-10 * (Math.log(probOfError)/Math.log(10.0))); } /** * Calculates the probability of an error from the quality score via the formula * P_e = 10**(QV/-10) */ public static double pFromQuality(double quality){ return Math.pow(10.0,(quality/-10.0)); } /** * Calculates the probability of an error from the quality score via the formula * P_e = 10**(QV/-10) */ public static double pFromQuality(int quality){ return pFromQuality((double)quality); } /** * Calculates the probability of an error from the quality score via the formula * P_e = 10**(QV/-10) */ public static double pFromQuality(IntegerAlphabet.IntegerSymbol quality){ return pFromQuality(quality.intValue()); } /** * Converts a Phred sequence to an array of distributions. Essentially a fuzzy sequence * Assumes that all of the non called bases are equiprobable */ public static Distribution[] phredToDistArray(PhredSequence s){ Distribution[] pos = new Distribution[s.length()]; DistributionTrainerContext dtc = new SimpleDistributionTrainerContext(); for (int i = 0; i < s.length(); i++) {// for each symbol in the phred sequence Symbol qual = s.getQualityAt(i); Symbol base = s.getDNAAt(i); double pBase = pFromQuality((IntegerAlphabet.IntegerSymbol)qual); double pOthers = (1.0 - pBase)/3; try{ pos[i] = DistributionFactory.DEFAULT.createDistribution(DNATools.getDNA()); dtc.registerDistribution(pos[i]); for(Iterator iter = (DNATools.getDNA().iterator()); iter.hasNext();){ Symbol sym = (Symbol)iter.next(); if(sym.equals(base)) pos[i].setWeight(sym,pBase); else pos[i].setWeight(sym,pOthers); } dtc.train(); }catch(IllegalAlphabetException iae){ throw new AssertionFailure("Sequence "+s.getName()+" contains an illegal alphabet", iae); }catch(ChangeVetoException cve){ throw new AssertionFailure("The Distribution has become locked", cve); }catch(IllegalSymbolException ise){ throw new AssertionFailure("Sequence "+s.getName()+" contains an illegal symbol", ise); } } return pos; } /** * converts an Alignment of PhredSequences to a Distribution[] where each position is the average * distribution of the underlying column of the alignment. * @throws ClassCastException if the sequences in the alignment are not instances of PhredSequence */ public static Distribution[] phredAlignmentToDistArray(Alignment a){ List labels = a.getLabels(); int depth = labels.size(); Distribution [] average = new Distribution[a.length()]; Distribution[][] matrix = new Distribution[labels.size()][]; for(int y = 0; y < a.length(); y++){// for eaxh position for(Iterator i = labels.iterator(); i.hasNext();){ SymbolList sl = a.symbolListForLabel(i.next()); matrix[y] = phredToDistArray((PhredSequence)sl); } average[y] = DistributionTools.average(matrix[y]); } return average; } }
package org.broad.igv.feature; import org.apache.log4j.Logger; import org.broad.tribble.readers.AsciiLineReader; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; /** * Class description * * @author Enter your name here... * @version Enter version here..., 08/10/16 */ public class CytoBandFileParser { private static Logger logger = Logger.getLogger(CytoBandFileParser.class); /** * Validate cytoband file * * @param reader * @param filename * @return */ public static boolean isValid(AsciiLineReader reader, String filename) { if (reader == null) { return false; } try { String nextLine; while ((nextLine = reader.readLine()) != null) { String[] tokens = nextLine.split("\t"); String chr = tokens[0].trim(); Cytoband cytoData = new Cytoband(chr); parseData(tokens, cytoData); } return true; } catch (Exception e) { logger.error("Invalid Cytoband file data : file=" + filename, e); return false; } } /** * Method description * * @param reader * @return */ public static LinkedHashMap<String, List<Cytoband>> loadData(BufferedReader reader) { LinkedHashMap<String, List<Cytoband>> dataMap = new LinkedHashMap<String, List<Cytoband>>(); try { String nextLine; while ((nextLine = reader.readLine()) != null && (nextLine.trim().length() > 0)) { String[] data = nextLine.split("\t"); String chr = data[0].trim(); List<Cytoband> cytobands = dataMap.get(chr); if (cytobands == null) { cytobands = new ArrayList<Cytoband>(); dataMap.put(chr, cytobands); } Cytoband cytoData = new Cytoband(chr); parseData(data, cytoData); cytobands.add(cytoData); } reader.close(); } catch (IOException e) { e.printStackTrace(); } return dataMap; } private static void parseData(String[] tokens, Cytoband cytoData) { cytoData.setStart(Integer.parseInt(tokens[1].trim())); cytoData.setEnd(Integer.parseInt(tokens[2].trim())); if (tokens.length > 3) { cytoData.setName(tokens[3]); } if (tokens.length > 4) { if (tokens[4].equals("acen")) { cytoData.setType('c'); } else { cytoData.setType(tokens[4].charAt(1)); if (cytoData.getType() == 'p') { String stainString = tokens[4].substring(4).trim(); short stain = stainString.length() == 0 ? 100 : Short.parseShort(stainString); cytoData.setStain(stain); } } } } private static String parseChromosome(String[] data) { String chr = data[0].substring(3); int underscore = chr.indexOf('_'); if (underscore > 0) { chr = chr.substring(0, underscore); } return chr; } }
package uk.ac.ebi.pride.proteinidentificationindex.search.service.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.solr.core.query.result.FacetPage; import org.springframework.data.solr.core.query.result.HighlightPage; import org.springframework.data.solr.repository.Facet; import org.springframework.data.solr.repository.Highlight; import org.springframework.data.solr.repository.Query; import org.springframework.data.solr.repository.SolrCrudRepository; import uk.ac.ebi.pride.proteinidentificationindex.search.model.ProteinIdentification; import uk.ac.ebi.pride.proteinidentificationindex.search.model.ProteinIdentificationSummary; import java.util.Collection; import java.util.List; import static org.springframework.data.solr.core.query.Query.Operator.*; /** * @author Jose A. Dianes * @version $Id$ * * Note: using the Query annotation allows wildcards to go straight into the query */ public interface SolrProteinIdentificationRepository extends SolrCrudRepository<ProteinIdentification, String> { public static final String HIGHLIGHT_PRE_FRAGMENT = "<span class='search-hit'>"; public static final String HIGHLIGHT_POST_FRAGMENT = "</span>"; // Id query methods @Query("id:?0") List<ProteinIdentification> findById(String id); @Query("id:(?0)") List<ProteinIdentification> findByIdIn(Collection<String> id); // Accession query methods @Query("accession:?0") List<ProteinIdentification> findByAccession(String accession); @Query("accession:(?0)") List<ProteinIdentification> findByAccessionIn(Collection<String> accession); // Synonym query methods @Query("synonyms:?0 AND project_accession:?1") List<ProteinIdentification> findBySynonymAndProjectAccession(String synonym, String projectAccession); // Project accession query methods Long countByProjectAccession(String projectAccession); @Query("project_accession:?0") List<ProteinIdentification> findByProjectAccession(String projectAccession); @Query("project_accession:(?0)") List<ProteinIdentification> findByProjectAccessionIn(Collection<String> projectAccessions); @Query("project_accession:?0") Page<ProteinIdentification> findByProjectAccession(String projectAccession, Pageable pageable); @Query("project_accession:(?0)") Page<ProteinIdentification> findByProjectAccessionIn(Collection<String> projectAccessions, Pageable pageable); @Query(value = "project_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) Page<ProteinIdentification> findByProjectAccessionAndFilterModNames(String projectAccessions, List<String> modNameFilters, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"submitted_accession, accession, ambiguity_group"}) @Query(value = "project_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") HighlightPage<ProteinIdentification> findByProjectAccessionHighlights(String projectAccessions, String term, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"submitted_accession, accession, ambiguity_group"}) @Query(value = "project_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) HighlightPage<ProteinIdentification> findByProjectAccessionHighlightsAndFilterModNames(String projectAccessions, String term, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0") FacetPage<ProteinIdentification> findByProjectAccessionFacetModNames(String projectAccessions, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") FacetPage<ProteinIdentification> findByProjectAccessionFacetModNames(String projectAccessions, String term, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) FacetPage<ProteinIdentification> findByProjectAccessionFacetModNamesAndFilterModNames(String projectAccessions, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "project_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) FacetPage<ProteinIdentification> findByProjectAccessionFacetModNamesAndFilterModNames(String projectAccessions, String term, List<String> modNameFilters, Pageable pageable); // Assay accession query methods Long countByAssayAccession(String assayAccession); @Query("assay_accession:?0") List<ProteinIdentification> findByAssayAccession(String assayAccession); @Query("assay_accession:(?0)") List<ProteinIdentification> findByAssayAccessionIn(Collection<String> assayAccessions); @Query("assay_accession:?0") Page<ProteinIdentification> findByAssayAccession(String assayAccession, Pageable pageable); @Query("assay_accession:(?0)") Page<ProteinIdentification> findByAssayAccessionIn(Collection<String> assayAccessions, Pageable pageable); @Query(value = "assay_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) Page<ProteinIdentification> findByAssayAccessionAndFilterModNames(String assayAccession, List<String> modNameFilters, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"submitted_accession, accession, ambiguity_group"}) @Query(value = "assay_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") HighlightPage<ProteinIdentification> findByAssayAccessionHighlights(String assayAccession, String term, Pageable pageable); @Highlight(prefix = HIGHLIGHT_PRE_FRAGMENT, postfix = HIGHLIGHT_POST_FRAGMENT, fields = {"submitted_accession, accession, ambiguity_group"}) @Query(value = "assay_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) HighlightPage<ProteinIdentification> findByAssayAccessionHighlightsAndFilterModNames(String assayAccession, String term, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)") FacetPage<ProteinIdentification> findByAssayAccessionFacetModNames(String assayAccession, String term, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0") FacetPage<ProteinIdentification> findByAssayAccessionFacetModNames(String assayAccession, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0", filters = "mod_names:(?1)", defaultOperator = AND) FacetPage<ProteinIdentification> findByAssayAccessionFacetModNamesAndFilterModNames(String assayAccession, List<String> modNameFilters, Pageable pageable); @Facet(fields = {"mod_names"}, limit = 100) @Query(value = "assay_accession:?0 AND (submitted_accession:?1 OR accession:?1 OR ambiguity_group:?1)", filters = "mod_names:(?2)", defaultOperator = AND) FacetPage<ProteinIdentification> findByAssayAccessionFacetModNamesAndFilterModNames(String assayAccession, String term, List<String> modNameFilters, Pageable pageable); // Submitted accession query methods @Query("submitted_accession:?0 AND assay_accession:?1") List<ProteinIdentification> findBySubmittedAccessionAndAssayAccession(String submittedAccession, String assayAccession); // Queries with Projections @Query(value = "project_accession:?0", fields = { "accession" }) List<ProteinIdentificationSummary> findSummaryByProjectAccession(String projectAccession); @Query(value = "assay_accession:?0", fields = { "accession" }) List<ProteinIdentificationSummary> findSummaryByAssayAccession(String assayAccession); }
package org.eclipse.imp.pdb.facts; import java.util.Collections; import java.util.Iterator; import java.util.Map; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.impl.AbstractDefaultAnnotatable; import org.eclipse.imp.pdb.facts.impl.AbstractDefaultWithKeywordParameters; import org.eclipse.imp.pdb.facts.impl.AnnotatedConstructorFacade; import org.eclipse.imp.pdb.facts.impl.ConstructorWithKeywordParametersFacade; import org.eclipse.imp.pdb.facts.type.ExternalType; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.eclipse.imp.pdb.facts.util.AbstractSpecialisedImmutableMap; import org.eclipse.imp.pdb.facts.util.ImmutableMap; import org.eclipse.imp.pdb.facts.visitors.IValueVisitor; /** * IExternalValue, together with {@link ExternalType} offer a limited form of extensibility * to the PDB's value and type system. The IExternalValue interface is used to tag extensions, * such as 'function values' that are not part of the PDB fact exchange and manipulation * interfaces but do need to integrate with them. * <br> * Note that implementations of IExternalValues are obliged to have a type that subclasses * ExternalType and that they all implement encodeAsConstructor. * If you do not do this, (de)serialization will not work. * <br> * Note that NORMAL USE OF THE PDB DOES NOT REQUIRE IMPLEMENTING THIS INTERFACE */ public interface IExternalValue extends IValue { @Override /** * @return an ExternalType */ Type getType(); @Override default boolean isEqual(IValue other) { return equals(other); } default IConstructor encodeAsConstructor() { return new IConstructor() { @Override public Type getConstructorType() { return TypeFactory.getInstance().constructor(new TypeStore(), getType(), getName(), new Type[0]); } @Override public Type getType() { return ((ExternalType) getType()).asAbstractDataType(); } @Override public String getName() { return IExternalValue.this.getClass().getSimpleName().toLowerCase(); } @Override public Type getUninstantiatedConstructorType() { return getConstructorType(); } @Override public IValue get(String label) { return null; } @Override public IConstructor set(String label, IValue newChild) throws FactTypeUseException { return this; } @Override public boolean has(String label) { return false; } @Override public IConstructor set(int index, IValue newChild) { return this; } @Override public Type getChildrenTypes() { return TypeFactory.getInstance().voidType(); } @Override public boolean declaresAnnotation(TypeStore store, String label) { return false; } @Override public <T, E extends Throwable> T accept(IValueVisitor<T, E> v) throws E { return v.visitConstructor(this); } @Override public boolean isEqual(IValue other) { return equals(other); } @Override public boolean isAnnotatable() { return true; } @Override public boolean mayHaveKeywordParameters() { return true; } @Override public INode replace(int first, int second, int end, IList repl) throws FactTypeUseException, IndexOutOfBoundsException { return this; } @Override public int arity() { return 0; } @Override public IValue get(int i) throws IndexOutOfBoundsException { return null; } @Override public Iterable<IValue> getChildren() { return Collections.emptyList(); } @Override public Iterator<IValue> iterator() { return Collections.emptyIterator(); } @Override public IAnnotatable<? extends IConstructor> asAnnotatable() { return new AbstractDefaultAnnotatable<IConstructor>(this) { @Override protected IConstructor wrap(IConstructor content, ImmutableMap<String, IValue> annotations) { return new AnnotatedConstructorFacade(content, annotations); } }; } @Override public IWithKeywordParameters<IConstructor> asWithKeywordParameters() { return new AbstractDefaultWithKeywordParameters<IConstructor>(this, AbstractSpecialisedImmutableMap.<String,IValue>mapOf()) { @Override protected IConstructor wrap(IConstructor content, ImmutableMap<String, IValue> parameters) { return new ConstructorWithKeywordParametersFacade(content, parameters); } @Override public boolean hasParameters() { return false; } @Override public java.util.Set<String> getParameterNames() { return Collections.emptySet(); } @Override public Map<String, IValue> getParameters() { return Collections.unmodifiableMap(parameters); } }; } }; } @Override default boolean isAnnotatable() { return false; } @Override default IAnnotatable<? extends IValue> asAnnotatable() { throw new UnsupportedOperationException(); } @Override default boolean mayHaveKeywordParameters() { return false; } @Override default IWithKeywordParameters<? extends IValue> asWithKeywordParameters() { throw new UnsupportedOperationException(); } @Override default <T, E extends Throwable> T accept(IValueVisitor<T, E> v) throws E { return v.visitExternal(this); } }
package org.eclipse.imp.pdb.facts.type; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.exceptions.FactTypeDeclarationException; import org.eclipse.imp.pdb.facts.exceptions.FactTypeRedeclaredException; import org.eclipse.imp.pdb.facts.exceptions.FactTypeUseException; import org.eclipse.imp.pdb.facts.exceptions.IllegalAnnotationDeclaration; import org.eclipse.imp.pdb.facts.exceptions.IllegalIdentifierException; import org.eclipse.imp.pdb.facts.exceptions.RedeclaredAnnotationException; import org.eclipse.imp.pdb.facts.exceptions.RedeclaredConstructorException; import org.eclipse.imp.pdb.facts.exceptions.RedeclaredFieldNameException; import org.eclipse.imp.pdb.facts.exceptions.UndeclaredAbstractDataTypeException; /** * This class manages type declarations. It stores declarations of annotations, * type aliases and abstract data-type constructors. * TypeStores can import others, but the imports are not transitive. * Cyclic imports are allowed. * <p> * @see {@link TypeFactory}, {@link Type} and {@link IValueFactory} for more information. */ public class TypeStore { private static final Type NODE_TYPE = TypeFactory.getInstance().nodeType(); private final TypeFactory factory = TypeFactory.getInstance(); private final Map<String, Type> fAliases= new HashMap<String, Type>(); private final Map<String, Type> fADTs= new HashMap<String, Type>(); private final Map<Type, Set<Type>> fConstructors = new HashMap<Type, Set<Type>>(); private final Map<Type, Map<String, Type>> fAnnotations = new HashMap<Type, Map<String, Type>>(); private final Set<TypeStore> fImports = new HashSet<TypeStore>(); /** * A type store that is initially empty and imports the given TypeStores. * Note that imports are not transitive. */ public TypeStore(TypeStore... imports) { importStore(imports); } /** * Retrieves all ADT's declared in this TypeStore. Note that it does * not return the ADT's of imported TypeStores. */ public Collection<Type> getAbstractDataTypes() { return Collections.unmodifiableCollection(fADTs.values()); } /** * Retrieves all aliases declared in this TypeStore. Note that it does * not return the aliases of imported TypeStores. */ public Collection<Type> getAliases() { return Collections.unmodifiableCollection(fAliases.values()); } /** * Retrieves all annotations declared in this TypeStore. Note that it does * not return the annotations of imported TypeStores. * * @return a map of types for which annotations are declared to a map of names of these * annotations to the types of the values that give access to these annotations. */ public Map<Type, Map<String, Type>> getAnnotations() { Map<Type, Map<String,Type>> unmodifiableMap = new HashMap<Type,Map<String,Type>>(); for (Type key : fAnnotations.keySet()) { unmodifiableMap.put(key, Collections.unmodifiableMap(fAnnotations.get(key))); } return unmodifiableMap; } /** * Retrieves all constructors declared in this TypeStore. Note that it does * not return the constructors of imported TypeStores. */ public Collection<Type> getConstructors() { Set<Type> result = new HashSet<Type>(); for (Set<Type> adt : fConstructors.values()) { result.addAll(adt); } return Collections.unmodifiableCollection(result); } /** * Retrieves all imports declared in this TypeStore. Note that it does * not return the imports of imported TypeStores. */ public Collection<TypeStore> getImports() { return Collections.unmodifiableCollection(fImports); } /** * Add other stores to the set of imported stores. * Note that imports are not transitive. * * @param stores */ public void importStore(TypeStore... stores) { synchronized(fImports) { for (TypeStore s : stores) { doImport(s); } } } /** * Removes a number of stores from the imported stores. The stores to be removed must be reference-equal to some of * the stores imported by the receiver. * * @param stores to be removed */ public void unimportStores(TypeStore... stores) { synchronized (fImports) { fImports.removeAll(Arrays.asList(stores)); } } private void doImport(TypeStore s) { checkOverlappingAliases(s); checkConstructorOverloading(s); fImports.add(s); } /** * Blindly copy all declaration of the other store into the receiver. */ public void extendStore(TypeStore other) { synchronized (fAliases) { fAliases.putAll(other.fAliases); } synchronized (fADTs) { fADTs.putAll(other.fADTs); } synchronized (fConstructors) { for (Type type : other.fConstructors.keySet()) { Set<Type> set = fConstructors.get(type); if (set == null) { set = new HashSet<Type>(); } set.addAll(other.fConstructors.get(type)); fConstructors.put(type, set); } } synchronized (fAnnotations) { fAnnotations.putAll(other.fAnnotations); } synchronized (fImports) { fImports.addAll(other.fImports); } } private void checkConstructorOverloading(TypeStore s) { for (Type type : fADTs.values()) { Type other = s.fADTs.get(type.getName()); if (other != null && other == type) { Set<Type> signature1 = fConstructors.get(type); Set<Type> signature2 = s.fConstructors.get(type); for (Type alt : signature2) { Type children = alt.getFieldTypes(); checkOverloading(signature1, alt.getName(), children); try { checkFieldNames(signature1, children); } catch (RedeclaredFieldNameException e) { throw new RedeclaredFieldNameException(e.getFieldName(), e.getFirstType(), e.getSecondType(), type); } } } } } private void checkOverlappingAliases(TypeStore s) { synchronized (fAliases) { for (Type alias : fAliases.values()) { Type other = s.fAliases.get(alias.getName()); if (other != null && !other.comparable(alias)) { throw new FactTypeRedeclaredException(alias.getName(), other); } } } } /** * @return the singleton instance of the {@link TypeFactory} */ public TypeFactory getFactory() { return factory; } /** * Declare an alias type. The alias may be parameterized to make an abstract alias. * Each ParameterType embedded in the aliased type should occur in the list of parameters. * * @param alias the alias to declare in this store * @throws FactTypeRedeclaredException */ public void declareAlias(Type alias) throws FactTypeDeclarationException { synchronized (fADTs) { synchronized (fAliases) { String name = alias.getName(); Type oldAdt = lookupAbstractDataType(name); if (oldAdt != null) { throw new FactTypeRedeclaredException(name, oldAdt); } Type oldAlias = lookupAlias(name); if (oldAlias != null) { if (alias.isSubtypeOf(oldAlias)) { // instantiating can be ignored. return; } throw new FactTypeRedeclaredException(name, oldAlias); } fAliases.put(name, alias); } } } /** * Declare a @{link AbstractDataType}, which is a kind of tree node. Each kind of tree node * may have different alternatives, which are ConstructorTypes. A @{link ConstructorType} is always a * sub-type of a AbstractDataType. A AbstractDataType is always a sub type of value. * * @param adt the abstract data-type to declare in this store * @throws FactTypeRedeclaredException */ public void declareAbstractDataType(Type adt) throws FactTypeDeclarationException { synchronized (fADTs) { synchronized (fAliases) { synchronized (fConstructors) { String name = adt.getName(); Type oldAdt = lookupAbstractDataType(name); if (oldAdt != null) { if (adt.comparable(oldAdt)) { return; // paramaterized ADT got instantiated, don't store. } throw new FactTypeRedeclaredException(name, oldAdt); } Type oldAlias = lookupAlias(name); if (oldAlias != null) { throw new FactTypeRedeclaredException(name, oldAlias); } fADTs.put(name, adt); if (fConstructors.get(adt) == null) { fConstructors.put(adt, new HashSet<Type>()); } } } } } /** * Declare a new constructor type. A constructor type extends an abstract data type such * that it represents more values. * * @param constructor a constructor type * @throws UndeclaredAbstractDataTypeException, RedeclaredFieldNameException, RedeclaredConstructorException */ public void declareConstructor(Type constructor) throws FactTypeDeclarationException { synchronized (fADTs) { synchronized(fConstructors) { Type adt = constructor.getAbstractDataType(); Type other = lookupAbstractDataType(adt.getName()); if (other == null) { throw new UndeclaredAbstractDataTypeException(adt); } Set<Type> signature = lookupAlternatives(adt); if (signature == null) { throw new UndeclaredAbstractDataTypeException(adt); } checkOverloading(signature, constructor.getName(), constructor.getFieldTypes()); try { checkFieldNames(signature, constructor.getFieldTypes()); } catch (RedeclaredFieldNameException e) { throw new RedeclaredFieldNameException(e.getFieldName(), e.getFirstType(), e.getSecondType(), adt); } Set<Type> localSignature = fConstructors.get(adt); if (localSignature == null) { localSignature = new HashSet<Type>(); fConstructors.put(adt, localSignature); if (!fADTs.containsKey(adt.getName())) { fADTs.put(adt.getName(), adt); } } localSignature.add(constructor); } } } private void checkFieldNames(Set<Type> signature, Type tupleType) { if (!tupleType.hasFieldNames()) { return; } for (Type alt : signature) { Type altArgs = alt.getFieldTypes(); if (!altArgs.hasFieldNames()) { continue; } for (int i = tupleType.getArity() - 1; i >= 0; i Type type = tupleType.getFieldType(i); String label = tupleType.getFieldName(i); for (int j = altArgs.getArity() - 1; j >= 0; j if (altArgs.getFieldName(j).equals(label)) { if (!altArgs.getFieldType(j).equivalent(type)) { throw new RedeclaredFieldNameException(label, type, altArgs.getFieldType(j), tupleType); } } } } } } private void checkOverloading(Set<Type> signature, String name, Type tupleType) throws FactTypeDeclarationException { for (Type alt : signature) { if (alt.isConstructorType() && alt.getName().equals(name)) { Type fieldTypes = alt.getFieldTypes(); if (fieldTypes != tupleType && fieldTypes.comparable(tupleType)) { throw new RedeclaredConstructorException(name, fieldTypes, tupleType); } } } } /** * Lookup a AliasType that was declared before by name * @param name the name of the type to lookup * @return the AliasType */ public Type lookupAlias(final String name) { synchronized (fAliases) { synchronized (fImports) { Type result = fAliases.get(name); if (result == null) { for (TypeStore i : fImports) { result = i.fAliases.get(name); if (result != null) { return result; } } } return result; } } } /** * Returns all alternative ways of constructing a certain abstract data type. * * @param adt * @return all types that construct the given type */ public Set<Type> lookupAlternatives(Type adt) { synchronized (fConstructors) { synchronized (fImports) { while (adt.isAliasType()) { adt = adt.getAliased(); } Set<Type> result = fConstructors.get(adt); if (result == null) { result = new HashSet<Type>(); } for (TypeStore s : fImports) { if (s != this) { Set<Type> imported = s.fConstructors.get(adt); if (imported != null) { result.addAll(imported); } } } return result; } } } /** * Lookup a ConstructorType by name, and in the context of a certain AbstractDataType * @param adt the AbstractDataType context * @param constructorName the name of the ConstructorType * @return a ConstructorType if it was declared before * @throws a FactTypeError if the type was not declared before */ public Set<Type> lookupConstructor(Type adt, String constructorName) throws FactTypeUseException { synchronized (fConstructors) { synchronized (fImports) { while (adt.isAliasType()) { adt = adt.getAliased(); } Type parameterizedADT = fADTs.get(adt.getName()); Set<Type> local = parameterizedADT != null ? fConstructors.get(parameterizedADT) : null; Set<Type> result = new HashSet<Type>(); if (local != null) { for (Type cand : local) { if (cand.getName().equals(constructorName)) { result.add(cand); } } } for (TypeStore i : fImports) { local = i.fConstructors.get(adt); if (local != null) { for (Type cand : local) { if (cand.getName().equals(constructorName)) { result.add(cand); } } } } return result; } } } /** * Lookup a ConstructorType by name, across all AbstractDataTypes and for * a certain list of argument types. * * @param constructorName the name of the ConstructorType * @param args a tuple type defining the arguments of the constructor * @return the first constructor that matches * @throws a FactTypeError if the type was not declared before */ public Type lookupFirstConstructor(final String cons, final Type args) { Collection<Type> adts = allAbstractDataTypes(); for (Type adt : adts) { Type cand = lookupConstructor(adt, cons, args); if (cand != null) { return cand; } } return null; } private Set<Type> allAbstractDataTypes() { synchronized (fADTs) { synchronized (fImports) { Set<Type> result = new HashSet<Type>(); result.addAll(fADTs.values()); for (TypeStore s : fImports) { result.addAll(s.fADTs.values()); } return result; } } } /** * Lookup a ConstructorType by name, and in the context of a certain AbstractDataType * for a specific list of argument types. * * @param adt the AbstractDataType context * @param constructorName the name of the ConstructorType * @return a ConstructorType if it was declared before * @throws a FactTypeError if the type was not declared before */ public Type lookupConstructor(Type adt, String cons, Type args) { Set<Type> sig = lookupConstructor(adt, cons); if (sig != null) { for (Type cand : sig) { if (args.isSubtypeOf(cand.getFieldTypes())) { return cand; } } } return null; } /** * Retrieve all tree node types for a given constructor name, * regardless of abstract data-type. * * @param constructName the name of the tree node */ public Set<Type> lookupConstructors(String constructorName) { synchronized (fConstructors) { synchronized (fImports) { Set<Type> result = new HashSet<Type>(); for (Set<Type> adt : fConstructors.values()) { for (Type cand : adt) { String name = cand.getName(); if (name.equals(constructorName)) { result.add(cand); } } } for (TypeStore i : fImports) { if (i != this) { for (Set<Type> adt : i.fConstructors.values()) { for (Type cand : adt) { String name = cand.getName(); if (name.equals(constructorName)) { result.add(cand); } } } } } return result; } } } /** * See if a certain abstract data-type was declared * @param name the supposed name of the abstract data-type * @return null if such type does not exist, or the type if it was declared earlier */ public Type lookupAbstractDataType(String name) { synchronized (fADTs) { synchronized (fImports) { Type result = fADTs.get(name); if (result != null) { return result; } for (TypeStore s : fImports) { result = s.fADTs.get(name); if (result != null) { return result; } } return result; } } } /** * Declare that certain tree node types may have an annotation with a certain * label. The annotation with that label will have a specific type. * * @param onType the type of values that carry this annotation * @param key the label of the annotation * @param valueType the type of values that represent the annotation * @throws FactTypeDeclarationException when an attempt is made to define annotations for anything * but NamedTreeTypes orTreeNodeTypes. */ public void declareAnnotation(Type onType, String key, Type valueType) { if (!onType.isSubtypeOf(NODE_TYPE)) { throw new IllegalAnnotationDeclaration(onType); } synchronized (fAnnotations) { Map<String, Type> annotationsForType = fAnnotations.get(onType); if (!factory.isIdentifier(key)) { throw new IllegalIdentifierException(key); } if (annotationsForType == null) { annotationsForType = new HashMap<String, Type>(); fAnnotations.put(onType, annotationsForType); } Map<String, Type> declaredEarlier = getAnnotations(onType); if (!declaredEarlier.containsKey(key)) { annotationsForType.put(key, valueType); } else if (!declaredEarlier.get(key).equivalent(valueType)) { throw new RedeclaredAnnotationException(key, declaredEarlier.get(key)); } // otherwise its a safe re-declaration and we do nothing } } /** * Locates all declared annotations for a type, including the annotations declared * for all the node type. * * @param onType * @return a map of all annotations declared for onType */ public Map<String, Type> getAnnotations(Type onType) { if (!onType.isSubtypeOf(NODE_TYPE)) { return Collections.<String,Type>emptyMap(); } synchronized(fAnnotations) { synchronized (fImports) { Map<String, Type> result = new HashMap<String,Type>(); if (onType != NODE_TYPE) { Map<String, Type> local = fAnnotations.get(onType); if (local != null) { result.putAll(local); } } Map<String, Type> onNode = fAnnotations.get(NODE_TYPE); if (onNode != null) { result.putAll(onNode); } for (TypeStore s : fImports) { Map<String, Type> local = s.fAnnotations.get(onType); if (local != null) { result.putAll(local); } onNode = s.fAnnotations.get(NODE_TYPE); if (onNode != null) { result.putAll(onNode); } } return result; } } } /** * Retrieve the type of values that are declared to be valid for a certain kind of * annotations on certain kinds of values * @param onType the type of values that this annotation can be found on * @param key the label of the annotation to find the corresponding type of * @return the type of the requested annotation value or null if none exists */ public Type getAnnotationType(Type onType, String key) { Map<String, Type> annotationsFor = getAnnotations(onType); Type result = annotationsFor.get(key); if (result != null) { return result; } return null; } public Type getAlias(String name) { synchronized (fAliases) { synchronized (fImports) { Type result = fAliases.get(name); if (result != null) { return result; } for (TypeStore s : fImports) { result = s.fAliases.get(name); if (result != null) { return result; } } return null; } } } }
package org.knowm.xchange.independentreserve.service; import java.io.IOException; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.FundingRecord; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.independentreserve.IndependentReserveAdapters; import org.knowm.xchange.independentreserve.dto.IndependentReserveHttpStatusException; import org.knowm.xchange.independentreserve.dto.account.IndependentReserveBalance; import org.knowm.xchange.independentreserve.dto.trade.IndependentReserveTransaction; import org.knowm.xchange.service.account.AccountService; import org.knowm.xchange.service.trade.params.DefaultTradeHistoryParamPaging; import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams; import org.knowm.xchange.service.trade.params.MoneroWithdrawFundsParams; import org.knowm.xchange.service.trade.params.RippleWithdrawFundsParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrency; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan; import org.knowm.xchange.service.trade.params.WithdrawFundsParams; public class IndependentReserveAccountService extends IndependentReserveAccountServiceRaw implements AccountService { /** * Constructor * * @param exchange */ public IndependentReserveAccountService(Exchange exchange) { super(exchange); } @Override public AccountInfo getAccountInfo() throws IOException { return new AccountInfo( exchange.getExchangeSpecification().getUserName(), IndependentReserveAdapters.adaptWallet(getIndependentReserveBalance())); } @Override public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { withdrawDigitalCurrency(amount, address, "", currency.getCurrencyCode(), null); return null; } @Override public String withdrawFunds(WithdrawFundsParams params) throws IOException { if (!(params instanceof DefaultWithdrawFundsParams)) { throw new IllegalStateException("Don't know how to withdraw: " + params); } String destinationTag = null; if (params instanceof RippleWithdrawFundsParams) { destinationTag = ((RippleWithdrawFundsParams) params).getTag(); } if (destinationTag == null && params instanceof MoneroWithdrawFundsParams) { destinationTag = ((MoneroWithdrawFundsParams) params).getPaymentId(); } DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; withdrawDigitalCurrency( defaultParams.getAmount(), defaultParams.getAddress(), "", defaultParams.getCurrency().getCurrencyCode(), destinationTag); return null; } @Override public TradeHistoryParams createFundingHistoryParams() { return new IndependentReserveTradeHistoryParams(); } @Override public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException { if (!(params instanceof IndependentReserveTradeHistoryParams)) { throw new IllegalArgumentException( "Invalid TradeHistoryParams used as argument of getFundingHistory"); } IndependentReserveTradeHistoryParams historyParams = (IndependentReserveTradeHistoryParams) params; final IndependentReserveBalance bal = getIndependentReserveBalance(); final Currency currency = historyParams.getCurrency(); return bal.getIndependentReserveAccounts().stream() .filter(acc -> currency == null || currency.getCurrencyCode().equalsIgnoreCase(acc.getCurrencyCode())) .map( acc -> { try { return getTransactions( acc.getAccountGuid(), historyParams.startTime, historyParams.endTime, historyParams.transactionTypes, historyParams.getPageNumber(), historyParams.getPageLength()) .getIndependentReserveTranasactions() .stream() .map(IndependentReserveAdapters::adaptTransaction); } catch (IndependentReserveHttpStatusException | IOException e) { throw new ExchangeException(e); } }) .flatMap(Function.identity()) .collect(Collectors.toList()); } public static class IndependentReserveTradeHistoryParams extends DefaultTradeHistoryParamPaging implements TradeHistoryParams, TradeHistoryParamCurrency, TradeHistoryParamsTimeSpan { private Currency currency; private Date startTime; private Date endTime; private IndependentReserveTransaction.Type[] transactionTypes; public IndependentReserveTradeHistoryParams() { transactionTypes = new IndependentReserveTransaction.Type[] { IndependentReserveTransaction.Type.Brokerage, IndependentReserveTransaction.Type.Deposit, IndependentReserveTransaction.Type.Withdrawal, IndependentReserveTransaction.Type.Trade }; setPageLength(50); setPageNumber(1); } @Override public Currency getCurrency() { return currency; } @Override public void setCurrency(Currency currency) { this.currency = currency; } @Override public Date getStartTime() { return startTime; } @Override public void setStartTime(Date startTime) { this.startTime = startTime; } @Override public Date getEndTime() { return endTime; } @Override public void setEndTime(Date endTime) { this.endTime = endTime; } public IndependentReserveTransaction.Type[] getTransactionTypes() { return transactionTypes; } public void setTransactionTypes(IndependentReserveTransaction.Type[] transactionTypes) { this.transactionTypes = transactionTypes; } } }
package fundamentals.tree.traversal.level.lc116_populatingnextrightpointersineachnode; import fundamentals.tree.TreeLinkNode; import java.util.LinkedList; import java.util.Queue; /** * Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. * Initially, all next pointers are set to NULL. * Note: You may only use constant extra space. You may assume that it is a perfect binary tree * (ie, all leaves are at the same level, and every parent has two children). */ public class Solution { public static void main(String[] args) { TreeLinkNode root = new TreeLinkNode(1); root.left = new TreeLinkNode(2); root.right = new TreeLinkNode(3); root.left.left = new TreeLinkNode(4); root.left.right = new TreeLinkNode(5); root.right.left = new TreeLinkNode(6); root.right.right = new TreeLinkNode(7); root.left.left.left = new TreeLinkNode(8); root.left.left.right = new TreeLinkNode(9); root.left.right.left = new TreeLinkNode(10); root.left.right.right = new TreeLinkNode(11); root.right.left.left = new TreeLinkNode(12); root.right.left.right = new TreeLinkNode(13); root.right.right.left = new TreeLinkNode(14); root.right.right.right = new TreeLinkNode(15); new Solution().connect(root); System.out.println(root.val + " next: " + root.next); System.out.println(root.left.val + " next: " + root.left.next); System.out.println(root.right.val + " next: " + root.right.next); System.out.println(root.left.left.val + " next: " + root.left.left.next); System.out.println(root.left.right.val + " next: " + root.left.right.next); System.out.println(root.right.left.val + " next: " + root.right.left.next); System.out.println(root.right.right.val + " next: " + root.right.right.next); } // O(N) time, O(1) space: key is to use "next" too! public void connect(TreeLinkNode root) { if (root == null) { return; } while (root.left != null) { TreeLinkNode first = root; // error1: don't forget save first node, since we always move root while (root.next != null) { // error2: if you stop here, don't forget the children of last node root.left.next = root.right; root.right.next = root.next.left; root = root.next; // error3: don't forget move pointer in inner of nested loop } root.left.next = root.right; root = first.left; } } // DFS: key is to use "next". but DFS needs O(h) extra space. public void connect2(TreeLinkNode root) { if (root == null) { return; } // 1.Connect children for lower level use if (root.left != null) { // Assume perfect binary tree, but left is null for leaves root.left.next = root.right; } // 2.Higher level must be handled already, so connect to sibling if (root.right != null && root.next != null) { root.right.next = root.next.left; } connect(root.left); connect(root.right); } // My 1st public void connect1(TreeLinkNode root) { if (root == null) { return; } Queue<TreeLinkNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeLinkNode last = null; int sizeOfLevel = queue.size(); while (sizeOfLevel TreeLinkNode node = queue.poll(); // Put children if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } // Link to sibling if (last == null) { last = node; } else { last.next = node; last = node; } } } } }
package org.myrobotlab.service; import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import org.myrobotlab.control.ServoOrchestratorGUI_middlemiddle_panel; import org.myrobotlab.framework.Service; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.ServiceInterface; import org.slf4j.Logger; /** * based on _TemplateService * "Clock-Code" modified from "Clock-Service" */ /** * * @author LunDev (github), Ma. Vo. (MyRobotlab) */ public class ServoOrchestrator extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory .getLogger(ServoOrchestrator.class); org.myrobotlab.control.ServoOrchestratorGUI sogui_ref; // TODO - don't define size (or at least make it bigger) // rework, that it could be made bigger int sizex = 5; int sizey = 5; SettingsItemHolder[] settingsitemholder; Servo[] servos; public boolean isClockRunning; public int interval = 1; public transient ClockThread myClock = null; int middleright_shownitem; boolean click_play = true; int pos1; int pos2; int pos3; public ServoOrchestrator(String n) { super(n); // intializing variables settingsitemholder = new SettingsItemHolder[sizey]; servos = new Servo[sizey]; for (int i = 0; i < settingsitemholder.length; i++) { SettingsItemHolder sih = new SettingsItemHolder(); sih.name = "Channel " + (i + 1); sih.min = 0; sih.max = 180; sih.startvalue = (sih.min + sih.max) / 2; sih.arduinopos = 0; sih.pinpos = 0; sih.attached = false; settingsitemholder[i] = sih; } pos1 = 1; pos2 = 1; pos3 = 000; } @Override public void startService() { super.startService(); } @Override public void stopService() { super.stopService(); } @Override public String getDescription() { return "organize your Servo-movements"; } public void setsoguireference( org.myrobotlab.control.ServoOrchestratorGUI so_ref) { sogui_ref = so_ref; } public void setmiddlemiddlesize() { sogui_ref.sizex = sizex; sogui_ref.sizey = sizey; } public void set_middleright_arduino_list_items() { List<ServiceInterface> services = Runtime.getServices(); ArrayList<String> arduinolist = new ArrayList<String>(); for (ServiceInterface service : services) { String type = service.getType(); String typ = type.substring(23); if (typ.equals("Arduino")) { String name = service.getName(); arduinolist.add(name); } } String[] arduinoarray = new String[arduinolist.size() + 2]; arduinoarray[0] = " "; arduinoarray[1] = "refresh"; for (int i = 0; i < arduinolist.size(); i++) { arduinoarray[i + 2] = arduinolist.get(i); } sogui_ref.middleright_arduino_list.setListData(arduinoarray); } public void middleright_update_button() { settingsitemholder[middleright_shownitem].name = sogui_ref.middleright_name_textfield .getText(); settingsitemholder[middleright_shownitem].min = Integer .parseInt(sogui_ref.middleright_min_textfield.getText()); settingsitemholder[middleright_shownitem].max = Integer .parseInt(sogui_ref.middleright_max_textfield.getText()); settingsitemholder[middleright_shownitem].startvalue = Integer .parseInt(sogui_ref.middleright_startvalue_textfield.getText()); } public void middleright_attach_button() { if (!settingsitemholder[middleright_shownitem].attached) { settingsitemholder[middleright_shownitem].arduinopos = sogui_ref.middleright_arduino_list .getSelectedIndex(); settingsitemholder[middleright_shownitem].pinpos = sogui_ref.middleright_pin_list .getSelectedIndex(); String arduino = (String) sogui_ref.middleright_arduino_list .getSelectedValue(); int pin = Integer.parseInt((String) sogui_ref.middleright_pin_list .getSelectedValue()); servos[middleright_shownitem] = (Servo) Runtime.start("so." + middleright_shownitem, "Servo"); servos[middleright_shownitem].attach(arduino, pin); servos[middleright_shownitem].attach(); sogui_ref.middleright_attach_button.setText("Detach"); settingsitemholder[middleright_shownitem].attached = true; } else { servos[middleright_shownitem].detach(); servos[middleright_shownitem] = null; sogui_ref.middleright_attach_button.setText("Attach"); settingsitemholder[middleright_shownitem].attached = false; } } public void bottommiddlerighttop_update_button() { pos1 = Integer.parseInt(sogui_ref.bottommiddlerighttop_textfield_1 .getText()); pos2 = Integer.parseInt(sogui_ref.bottommiddlerighttop_textfield_2 .getText()); pos3 = Integer.parseInt(sogui_ref.bottommiddlerighttop_textfield_3 .getText()); play_updatetime(true, true, true); play_updatepanels(pos1); } public void bottommiddlerightbottom_button_1() { play_go_ba(); } public void bottommiddlerightbottom_button_2() { play_go_fa(); } public void bottommiddlerightbottom_button_3() { play_go_b1(); } public void bottommiddlerightbottom_button_4() { play_go_f1(); } public void bottommiddlerightbottom_button_5() { // TODO - add functionality } public void bottommiddlerightbottom_button_6() { play_go_stop(); } public void bottommiddlerightbottom_button_7() { play_go_start(); } public void bottommiddlerightbottom_button_8() { // TODO - add functionality } public void bottomright_click_checkbox() { click_play = sogui_ref.bottomright_click_checkbox.isSelected(); } public void middleright_arduino_list() { String selvalue = (String) sogui_ref.middleright_arduino_list .getSelectedValue(); if (selvalue == null) { } else if (selvalue.equals(" ")) { } else if (selvalue.equals("refresh")) { set_middleright_arduino_list_items(); } else { } } public void externalcall_loadsettings(int pos) { middleright_shownitem = pos; sogui_ref.middleright_name_textfield .setText(settingsitemholder[pos].name); sogui_ref.middleright_min_textfield.setText(settingsitemholder[pos].min + ""); sogui_ref.middleright_max_textfield.setText(settingsitemholder[pos].max + ""); sogui_ref.middleright_startvalue_textfield .setText(settingsitemholder[pos].startvalue + ""); sogui_ref.middleright_arduino_list .setSelectedIndex(settingsitemholder[middleright_shownitem].arduinopos); sogui_ref.middleright_pin_list .setSelectedIndex(settingsitemholder[middleright_shownitem].pinpos); if (!settingsitemholder[middleright_shownitem].attached) { sogui_ref.middleright_attach_button.setText("Attach"); } else { sogui_ref.middleright_attach_button.setText("Detach"); } } public void play_go_start() { sogui_ref.bottommiddlerightbottom_button_6.setEnabled(true); sogui_ref.bottommiddlerightbottom_button_7.setEnabled(false); startClock(); } public void play_go_stop() { sogui_ref.bottommiddlerightbottom_button_6.setEnabled(false); sogui_ref.bottommiddlerightbottom_button_7.setEnabled(true); stopClock(); } public void play_go_f1() { pos1++; play_updatetime(true, false, false); play_updatepanels(pos1); } public void play_go_b1() { pos1 play_updatetime(true, false, false); play_updatepanels(pos1); } public void play_go_fa() { pos1 = sogui_ref.middlemiddle_ref.getRandomDragAndDropPanels()[0].length; pos2 = 4; pos3 = 999; play_updatetime(true, true, true); play_updatepanels(pos1); } public void play_go_ba() { pos1 = 1; pos2 = 1; pos3 = 0; play_updatetime(true, true, true); play_updatepanels(pos1); } public void play_play_1_1() { pos1++; if (pos1 > sizex) { play_go_stop(); } play_updatetime(true, false, false); play_playreally(pos1); } public void play_play_2_1() { pos2++; if (pos2 > 4) { play_play_1_1(); pos2 -= 4; } play_updatetime(false, true, false); } public void play_play_3_1() { pos3++; if (pos3 > 999) { play_play_2_1(); pos3 -= 999; } play_updatetime(false, false, true); } public void play_checktime() { if (pos1 > sogui_ref.middlemiddle_ref.getRandomDragAndDropPanels()[0].length) { pos1 = sogui_ref.middlemiddle_ref.getRandomDragAndDropPanels()[0].length; } else if (pos1 < 1) { pos1 = 1; } if (pos2 > 4) { pos2 = 4; } else if (pos2 < 1) { pos2 = 1; } if (pos3 > 999) { pos3 = 999; } else if (pos3 < 0) { pos3 = 0; } } public void play_updatetime(boolean t1, boolean t2, boolean t3) { play_checktime(); if (t1) { sogui_ref.bottommiddlerighttop_textfield_1.setText(pos1 + ""); } if (t2) { sogui_ref.bottommiddlerighttop_textfield_2.setText(pos2 + ""); } if (t3) { sogui_ref.bottommiddlerighttop_textfield_3.setText(pos3 + ""); } } public void play_updatepanels(int pos) { for (int i = 0; i < sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[0].length; i++) { sogui_ref.middlemiddle_ref.prep[sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[0].length + i] .setBackground(Color.green); } sogui_ref.middlemiddle_ref.prep[sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[0].length + pos - 1] .setBackground(Color.red); sogui_ref.middlemiddle_ref.relayout(); } public void play_playreally(int pos) { play_updatepanels(pos); if (click_play) { play_playclick(); } if (pos <= sizex) { play_searchblocks(pos); } } public void play_playclick() { try { AudioInputStream audioInputStream = AudioSystem .getAudioInputStream(new File( "C:\\Users\\Marvin\\Desktop\\temp\\click.wav") .getAbsoluteFile()); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) { e.printStackTrace(); } } public void play_searchblocks(int pos) { for (int i = 0; i < sizey; i++) { ServoOrchestratorGUI_middlemiddle_panel panels11 = sogui_ref.middlemiddle_ref .getRandomDragAndDropPanels()[pos][i]; if (panels11 != null) { play_playblock(i, panels11); } } } public void play_playblock(int channel, ServoOrchestratorGUI_middlemiddle_panel block) { switch (block.type) { case "timesection": break; case "channel": break; case "servo": if (servos[channel] != null) { int movetopos = Integer.parseInt(block.servo_goal.getText()); servos[channel].moveTo(movetopos); } break; } } public class SettingsItemHolder { String name; int min; int max; int startvalue; int arduinopos; int pinpos; boolean attached; } public class ClockThread implements Runnable { public Thread thread = null; ClockThread() { thread = new Thread(this, getName() + "_ticking_thread"); thread.start(); } public void run() { try { while (isClockRunning == true) { play_play_3_1(); Thread.sleep(interval); } } catch (InterruptedException e) { isClockRunning = false; } } } public void startClock() { if (myClock == null) { isClockRunning = true; myClock = new ClockThread(); } } public void stopClock() { if (myClock != null) { isClockRunning = false; myClock.thread.interrupt(); myClock.thread = null; myClock = null; } isClockRunning = false; } public static void main(String[] args) throws InterruptedException { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.INFO); try { Runtime.start("gui", "GUIService"); Runtime.start("servoorchestrator", "ServoOrchestrator"); } catch (Exception e) { Logging.logException(e); } } }
package org.openhab.binding.fronius.handler; import java.io.IOException; import org.apache.commons.lang.StringUtils; 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.io.net.http.HttpUtil; import org.openhab.binding.fronius.FroniusBaseDeviceConfiguration; import org.openhab.binding.fronius.FroniusBindingConstants; import org.openhab.binding.fronius.FroniusBridgeConfiguration; import org.openhab.binding.fronius.internal.api.InverterRealtimeResponse; import org.openhab.binding.fronius.internal.api.PowerFlowRealtimeResponse; import org.openhab.binding.fronius.internal.api.ValueUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; /** * The {@link FroniusSymoInverterHandler} is responsible for updating the data, which are * sent to one of the channels. * * @author Thomas Rokohl - Initial contribution */ public class FroniusSymoInverterHandler extends FroniusBaseThingHandler { private final Logger logger = LoggerFactory.getLogger(FroniusSymoInverterHandler.class); private InverterRealtimeResponse inverterRealtimeResponse; private PowerFlowRealtimeResponse powerFlowResponse; private FroniusBaseDeviceConfiguration config; private static final int API_TIMEOUT = 5000; private Gson gson; public FroniusSymoInverterHandler(Thing thing) { super(thing); gson = new Gson(); } @Override protected String getDescription() { return "Fronius Symo Inverter"; } @Override public void refresh(FroniusBridgeConfiguration bridgeConfiguration) { updateData(bridgeConfiguration, config); updateChannels(); } @Override public void initialize() { config = getConfigAs(FroniusBaseDeviceConfiguration.class); super.initialize(); } /** * Update the channel from the last data retrieved * * @param channelId the id identifying the channel to be updated * @return the last retrieved data */ @Override protected Object getValue(String channelId) { String[] fields = StringUtils.split(channelId, " if (inverterRealtimeResponse == null || inverterRealtimeResponse.getBody() == null || inverterRealtimeResponse.getBody().getData() == null) { return null; } String fieldName = fields[0]; switch (fieldName) { case FroniusBindingConstants.InverterDataChannelDayEnergy: ValueUnit day = inverterRealtimeResponse.getBody().getData().getDayEnergy(); day.setUnit("kWh"); return day; case FroniusBindingConstants.InverterDataChannelPac: return inverterRealtimeResponse.getBody().getData().getPac(); case FroniusBindingConstants.InverterDataChannelTotal: ValueUnit total = inverterRealtimeResponse.getBody().getData().getTotalEnergy(); total.setUnit("MWh"); return total; case FroniusBindingConstants.InverterDataChannelYear: ValueUnit year = inverterRealtimeResponse.getBody().getData().getYearEnergy(); year.setUnit("MWh"); return year; case FroniusBindingConstants.InverterDataChannelFac: return inverterRealtimeResponse.getBody().getData().getFac(); case FroniusBindingConstants.InverterDataChannelIac: return inverterRealtimeResponse.getBody().getData().getIac(); case FroniusBindingConstants.InverterDataChannelIdc: return inverterRealtimeResponse.getBody().getData().getIdc(); case FroniusBindingConstants.InverterDataChannelUac: return inverterRealtimeResponse.getBody().getData().getUac(); case FroniusBindingConstants.InverterDataChannelUdc: return inverterRealtimeResponse.getBody().getData().getUdc(); } if (powerFlowResponse == null || powerFlowResponse.getBody() == null || powerFlowResponse.getBody().getData() == null || powerFlowResponse.getBody().getData().getSite() == null) { return null; } switch (fieldName) { case FroniusBindingConstants.PowerFlowpGrid: return powerFlowResponse.getBody().getData().getSite().getPgrid(); case FroniusBindingConstants.PowerFlowpLoad: return powerFlowResponse.getBody().getData().getSite().getPload(); case FroniusBindingConstants.PowerFlowpAkku: return powerFlowResponse.getBody().getData().getSite().getPakku(); } return null; } /** * Get new data */ private void updateData(FroniusBridgeConfiguration bridgeConfiguration, FroniusBaseDeviceConfiguration config) { inverterRealtimeResponse = getRealtimeData(bridgeConfiguration.hostname, config.deviceId); powerFlowResponse = getPowerFlowRealtime(bridgeConfiguration.hostname); } /** * Make the PowerFlowRealtimeDataRequest * * @param ip address of the device * @return {PowerFlowRealtimeResponse} the object representation of the json response */ private PowerFlowRealtimeResponse getPowerFlowRealtime(String ip) { PowerFlowRealtimeResponse result = null; boolean resultOk = false; String errorMsg = null; try { String location = FroniusBindingConstants.POWERFLOW_REALTIME_DATA.replace("%IP%", StringUtils.trimToEmpty(ip)); logger.debug("URL = {}", location); String response = HttpUtil.executeUrl("GET", location, API_TIMEOUT); if (response != null) { logger.debug("aqiResponse = {}", response); result = gson.fromJson(response, PowerFlowRealtimeResponse.class); } if (result == null) { errorMsg = "no data returned"; } else if (result.getBody() != null) { resultOk = true; } else { errorMsg = "missing data sub-object"; } if (!resultOk) { logger.debug("Error in fronius response: {}", errorMsg); } } catch (JsonSyntaxException e) { errorMsg = "Configuration is incorrect"; logger.debug("Error running fronius request: {}", errorMsg); } catch (IOException | IllegalStateException e) { logger.debug("Error running fronius request: {}", e.getMessage()); } return resultOk ? result : null; } /** * Make the InverterRealtimeDataRequest * * @param ip address of the device * @return {InverterRealtimeResponse} the object representation of the json response */ private InverterRealtimeResponse getRealtimeData(String ip, int deviceId) { InverterRealtimeResponse result = null; boolean resultOk = false; String errorMsg = null; try { String location = FroniusBindingConstants.INVERTER_REALTIME_DATA_URL.replace("%IP%", StringUtils.trimToEmpty(ip)); location = location.replace("%DEVICEID%", Integer.toString(deviceId)); logger.debug("URL = {}", location); String response = HttpUtil.executeUrl("GET", location, API_TIMEOUT); if (response != null) { logger.debug("aqiResponse = {}", response); result = gson.fromJson(response, InverterRealtimeResponse.class); } if (result == null) { errorMsg = "no data returned"; } else if (result.getBody() != null) { resultOk = true; } else { errorMsg = "missing data sub-object"; } if (!resultOk) { logger.debug("Error in fronius response: {}", errorMsg); } } catch (JsonSyntaxException e) { errorMsg = "Configuration is incorrect"; logger.debug("Error running fronius request: {}", e.getMessage()); } catch (IOException | IllegalStateException e) { errorMsg = "Connection failed"; logger.debug("Error running fronius request: {}", e.getMessage()); } // Update the thing status if (resultOk) { updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, errorMsg); } return resultOk ? result : null; } }
package org.csstudio.alarm.table.preferences; import org.csstudio.alarm.table.JmsLogsPlugin; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.jface.preference.IPreferenceStore; /** * Class used to initialize default preference values. */ public class AlarmViewerPreferenceInitializer extends AbstractPreferenceInitializer { /* * (non-Javadoc) * * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences() */ public void initializeDefaultPreferences() { IPreferenceStore store = JmsLogsPlugin.getDefault() .getPreferenceStore(); store.setDefault(AlarmViewerPreferenceConstants.P_STRINGAlarm, "TYPE,100" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "EVENTTIME,100" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "NAME,100" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "SEVERITY" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "STATUS" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "VALUE" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "TEXT" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "USER" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "HOST" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "APPLICATION-ID" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "PROCESS-ID" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "CLASS" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "DOMAIN" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "FACILITY" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "LOCATION" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "VALUE" + ";" + //$NON-NLS-1$ //$NON-NLS-2$ "DESTINATION" //$NON-NLS-1$ ); store.setDefault(AlarmViewerPreferenceConstants.MAX, 200); store.setDefault(AlarmViewerPreferenceConstants.REMOVE, 10); store.setDefault( AlarmViewerPreferenceConstants.INITIAL_PRIMARY_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); //$NON-NLS-1$ store .setDefault( AlarmViewerPreferenceConstants.PRIMARY_URL, "failover:(tcp://krykjmsb.desy.de:64616)?maxReconnectDelay=5000"); //$NON-NLS-1$ store .setDefault( AlarmViewerPreferenceConstants.INITIAL_SECONDARY_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); //$NON-NLS-1$ store .setDefault( AlarmViewerPreferenceConstants.SECONDARY_URL, "failover:(tcp://krykjmsa.desy.de:62616)?maxReconnectDelay=5000"); //$NON-NLS-1$ store.setDefault(AlarmViewerPreferenceConstants.QUEUE, "ALARM,ACK"); //$NON-NLS-1$ store .setDefault( AlarmViewerPreferenceConstants.SENDER_URL, "failover:(tcp://krykjmsb.desy.de:64616,tcp://krykjmsa.desy.de:62616)?maxReconnectDelay=5000"); //$NON-NLS-1$ store .setDefault( AlarmViewerPreferenceConstants.LOG_ALARM_SOUND_FILE, "..\\beep.mp3"); //$NON-NLS-1$ } }
package org.csstudio.domain.desy.collection.immutable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; /** * Immutable collection. * * @param <T> Type of contained elements * @see java.util.ArrayList * @author Bastian Knerr (bastian.knerr@desy.de) */ public class ImmutableArrayList<T> extends ArrayList<T> implements IImmutableList<T> { private static final long serialVersionUID = 450475645815625237L; public static final IImmutableList<?> EMPTY_LIST = new ImmutableArrayList<Object>(0); public ImmutableArrayList(@Nonnull final Collection<? extends T> c) { super(c); } public ImmutableArrayList(@Nonnull final Iterable<? extends T> i) { final Iterator<? extends T> it = i.iterator(); while (it.hasNext()) { final T type = it.next(); add(type); } } private ImmutableArrayList() { super(); } ImmutableArrayList(final int i) { super(i); } /** * {@inheritDoc} */ @Override @Nonnull public ImmutableIterator<T> iterator() { return new ImmutableIterator<T>(super.iterator()); } /** * {@inheritDoc} */ @Override @Nonnull public ImmutableListIterator<T> listIterator() { return new ImmutableListIterator<T>(super.listIterator()); } /** * {@inheritDoc} */ @Override @Nonnull public ImmutableListIterator<T> listIterator(final int index) { return new ImmutableListIterator<T>(super.listIterator(index)); } /** * {@inheritDoc} */ @Override public boolean containsAll(@Nonnull final IImmutableCollection<? extends T> c) { for (final T t : c) { if (!contains(t)) { return false; } } return true; } // private void addAll(@Nonnull final IImmutableCollection<? extends T> elements) { // for (final T e : elements) { // add(e); /** * {@inheritDoc} */ @Override @CheckForNull public T pollFirst() { return isEmpty() ? null : get(0); } /** * {@inheritDoc} */ @Nonnull @Override public IImmutableList<T> filter(@Nonnull final Filter<T> filter) { if (isEmpty()) { return ImmutableCollections.emptyList(); } final ImmutableArrayList<T> result = new ImmutableArrayList<T>(); for (final T item : this) { if (filter.filter(item)) { result.add(item); } } return result; } /** * {@inheritDoc} */ @Override @Nonnull public List<T> toList() { return new ArrayList<T>(this); } }
import java.util.Date; import java.text.SimpleDateFormat; import java.lang.Exception; import java.sql.*; public class Address { public static final String tableName = "address"; // fields private int id = 0; private String name; private String christianname; private String addressform; private String email; private String phone; private String mobile; private String street; private int number; private String city; private String postcode; private String country; private Date birthday; public int getId() { return this.id; } public String getName() { return this.name; } public String getChristianname() { return this.christianname; } public String getAddressform() { return this.addressform; } public String getEmail() { return this.email; } public String getPhone() { return this.phone; } public String getMobile() { return this.mobile; } public String getStreet() { return this.street; } public int getNumber() { return this.number; } public String getCity() { return this.city; } public String getPostcode() { return this.postcode; } public String getCountry() { return this.country; } public Date getBirthday() { return this.birthday; } private void setId (int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setChristianname(String christianname) { this.christianname = christianname; } public void setAddressform(String addressform) { this.addressform = addressform; } public void setEmail(String email) { this.email = email; } public void setPhone(String phone) { this.phone = phone; } public void setMobile(String mobile) { this.mobile = mobile; } public void setStreet(String street) { this.street = street; } public void setNumber(int number) { this.number = number; } public void setCity(String city) { this.city = city; } public void setPostcode(String postcode) { this.postcode = postcode; } public void setCountry(String country) { this.country = country; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Address () { } public void save () throws Exception { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/addressbook?user=addressbook&password=addressbook"); PreparedStatement statement; if (this.id == 0) { // insert statement = connection.prepareStatement("INSERT INTO " + this.tableName + " (name, christianname, addressform, email, phone, mobile, street, number, city, postcode, country, birthday) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS); } else { // update statement = connection.prepareStatement("UPDATE " + this.tableName + " SET name=?, christianname=?, addressform=?, email=?, phone=?, mobile=?, street=?, number=?, city=?, postcode=?, country=?, birthday=? WHERE id=" + Integer.toString(this.id) + ";"); } statement.setString(1, this.name); statement.setString(2, this.christianname); statement.setString(3, this.addressform); statement.setString(4, this.email); statement.setString(5, this.phone); statement.setString(6, this.mobile); statement.setString(7, this.street); statement.setString(8, Integer.toString(this.number)); statement.setString(9, this.city); statement.setString(10, this.postcode); statement.setString(11, this.country); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); statement.setString(12, formatter.format(this.birthday)); int affectedRows = statement.executeUpdate(); // set the id if (this.id == 0) { if (affectedRows == 0) { throw new SQLException("Insert failed, no rows affected."); } ResultSet generatedKeys = statement.getGeneratedKeys(); if (generatedKeys.next()) { this.setId(generatedKeys.getInt(1)); } else { throw new SQLException("Insert failed, no ID obtained."); } } statement.close(); connection.close(); } public void fill (ResultSet resultSet) { } }
package org.ovirt.engine.ui.uicommonweb.models.hosts; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.ovirt.engine.core.common.action.AddBondParameters; import org.ovirt.engine.core.common.action.AttachNetworkToVdsParameters; import org.ovirt.engine.core.common.action.UpdateNetworkToVdsParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.comparators.NameableComparator; import org.ovirt.engine.core.common.businessentities.network.Bond; import org.ovirt.engine.core.common.businessentities.network.Network; import org.ovirt.engine.core.common.businessentities.network.NetworkBootProtocol; import org.ovirt.engine.core.common.businessentities.network.Nic; import org.ovirt.engine.core.common.businessentities.network.VdsNetworkInterface; import org.ovirt.engine.core.common.businessentities.network.Vlan; import org.ovirt.engine.core.common.queries.ConfigurationValues; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryReturnValue; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.KeyValuePairCompat; import org.ovirt.engine.core.compat.RefObject; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.ui.frontend.AsyncQuery; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.frontend.INewAsyncCallback; import org.ovirt.engine.ui.uicommonweb.Linq; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider; import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.Model; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.Event; import org.ovirt.engine.ui.uicompat.EventArgs; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs; import org.ovirt.engine.ui.uicompat.ProvidePropertyChangedEvent; @SuppressWarnings("unused") public class HostInterfaceListModel extends SearchableListModel { public static final String ENGINE_NETWORK_NAME = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.ManagementNetwork); private UICommand privateEditCommand; @Override public UICommand getEditCommand() { return privateEditCommand; } private void setEditCommand(UICommand value) { privateEditCommand = value; } private UICommand privateEditManagementNetworkCommand; public UICommand getEditManagementNetworkCommand() { return privateEditManagementNetworkCommand; } private void setEditManagementNetworkCommand(UICommand value) { privateEditManagementNetworkCommand = value; } private UICommand privateBondCommand; public UICommand getBondCommand() { return privateBondCommand; } private void setBondCommand(UICommand value) { privateBondCommand = value; } private UICommand privateDetachCommand; public UICommand getDetachCommand() { return privateDetachCommand; } private void setDetachCommand(UICommand value) { privateDetachCommand = value; } private UICommand privateSaveNetworkConfigCommand; public UICommand getSaveNetworkConfigCommand() { return privateSaveNetworkConfigCommand; } private void setSaveNetworkConfigCommand(UICommand value) { privateSaveNetworkConfigCommand = value; } private UICommand privateSetupNetworksCommand; public UICommand getSetupNetworksCommand() { return privateSetupNetworksCommand; } private void setSetupNetworksCommand(UICommand value) { privateSetupNetworksCommand = value; } private ArrayList<VdsNetworkInterface> privateOriginalItems; public ArrayList<VdsNetworkInterface> getOriginalItems() { return privateOriginalItems; } public void setOriginalItems(ArrayList<VdsNetworkInterface> value) { privateOriginalItems = value; } private boolean isSelectionAvailable; public boolean getIsSelectionAvailable() { return isSelectionAvailable; } public void setSelectionAvailable(boolean value) { if (isSelectionAvailable != value) { isSelectionAvailable = value; onPropertyChanged(new PropertyChangedEventArgs("isSelectionAvailable")); //$NON-NLS-1$ } } @Override public Iterable getItems() { return super.items; } @Override public void setItems(Iterable value) { if (items != value) { itemsChanging(value, items); items = value; itemsChanged(); getItemsChangedEvent().raise(this, EventArgs.Empty); onPropertyChanged(new PropertyChangedEventArgs("Items")); //$NON-NLS-1$ } } @Override public VDS getEntity() { return (VDS) super.getEntity(); } public void setEntity(VDS value) { if (super.getEntity() != null) { VDS currentItem = ((VDS) super.getEntity()); VDS newItem = value; Guid currentItemId = currentItem.getId(); Guid newItemId = newItem.getId(); if (currentItemId.equals(newItemId)) { setEntity(value, false); updateActionAvailability(); return; } } super.setEntity(value); } private ArrayList<VdsNetworkInterface> getSelectedItems(boolean withVlans) { ArrayList<VdsNetworkInterface> list = new ArrayList<VdsNetworkInterface>(); if (getItems() != null) { boolean isModelSelected; for (Object item : getItems()) { isModelSelected = false; HostInterfaceLineModel model = (HostInterfaceLineModel) item; if (model.getIsBonded()) { if (model.getIsSelected()) { isModelSelected = true; list.add(model.getInterface()); } } else { for (HostInterface hostInterface : model.getInterfaces()) { if (hostInterface.getIsSelected()) { isModelSelected = true; list.add(hostInterface.getInterface()); } } } for (HostVLan vLan : model.getVLans()) { if (vLan.getIsSelected() || (withVlans && isModelSelected)) { list.add(vLan.getInterface()); } } } } return list; } @Override public ArrayList<VdsNetworkInterface> getSelectedItems() { return getSelectedItems(false); } public ArrayList<VdsNetworkInterface> getSelectedItemsWithVlans() { return getSelectedItems(true); } private ArrayList<VdsNetworkInterface> getInterfaceItems() { ArrayList<VdsNetworkInterface> list = new ArrayList<VdsNetworkInterface>(); if (getItems() != null) { for (Object item : getItems()) { HostInterfaceLineModel model = (HostInterfaceLineModel) item; for (HostInterface hostInterface : model.getInterfaces()) { list.add(hostInterface.getInterface()); } } } return list; } private ArrayList<VdsNetworkInterface> getAllItems() { ArrayList<VdsNetworkInterface> list = new ArrayList<VdsNetworkInterface>(); for (Object a : getItems()) { HostInterfaceLineModel item = (HostInterfaceLineModel) a; if (item.getIsBonded()) { list.add(item.getInterface()); } for (HostInterface hostInterface : item.getInterfaces()) { list.add(hostInterface.getInterface()); } for (HostVLan vLan : item.getVLans()) { list.add(vLan.getInterface()); } } return list; } /** * Gets a boolean value indicating whether a detach confirmation is needed (cuurently happens when attempting to * change the Management Interface's network to 'None'). */ // TODO: Suspect this property is obsolete. private boolean detachConfirmationNeeded; public boolean getDetachConfirmationNeeded() { return detachConfirmationNeeded; } private void setDetachConfirmationNeeded(boolean value) { if (detachConfirmationNeeded != value) { detachConfirmationNeeded = value; onPropertyChanged(new PropertyChangedEventArgs("DetachConfirmationNeeded")); //$NON-NLS-1$ } } private Model privatecurrentModel; public Model getcurrentModel() { return privatecurrentModel; } public void setcurrentModel(Model value) { privatecurrentModel = value; } public HostInterfaceListModel() { setTitle(ConstantsManager.getInstance().getConstants().networkInterfacesTitle()); setHashName("network_interfaces"); //$NON-NLS-1$ setEditCommand(new UICommand("Edit", this)); //$NON-NLS-1$ setEditManagementNetworkCommand(new UICommand("EditManagementNetwork", this)); //$NON-NLS-1$ setBondCommand(new UICommand("Bond", this)); //$NON-NLS-1$ setDetachCommand(new UICommand("Detach", this)); //$NON-NLS-1$ setSaveNetworkConfigCommand(new UICommand("SaveNetworkConfig", this)); //$NON-NLS-1$ setSetupNetworksCommand(new UICommand("SetupNetworks", this)); //$NON-NLS-1$ updateActionAvailability(); } @Override public void search() { if (getEntity() != null) { super.search(); } } @Override protected void onEntityChanged() { super.onEntityChanged(); getSearchCommand().execute(); updateActionAvailability(); } // protected override void OnSelectedItemChanged() // base.OnSelectedItemChanged(); // UpdateActionAvailability(); // protected override void SelectedItemsChanged() // base.SelectedItemsChanged(); // UpdateActionAvailability(); @Override protected void entityPropertyChanged(Object sender, PropertyChangedEventArgs e) { super.entityPropertyChanged(sender, e); if (e.PropertyName.equals("status") || e.PropertyName.equals("net_config_dirty")) //$NON-NLS-1$ //$NON-NLS-2$ { updateActionAvailability(); } } @Override protected void syncSearch() { super.syncSearch(); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { HostInterfaceListModel interfaceModel = (HostInterfaceListModel) model; Iterable iVdcQueryableItems = (Iterable) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); ArrayList<VdsNetworkInterface> items = new ArrayList<VdsNetworkInterface>(); Iterator networkInterfacesIterator = iVdcQueryableItems.iterator(); while (networkInterfacesIterator.hasNext()) { items.add((VdsNetworkInterface) networkInterfacesIterator.next()); } interfaceModel.updateItems(items); } }; IdQueryParameters tempVar = new IdQueryParameters(getEntity().getId()); tempVar.setRefresh(getIsQueryFirstTime()); Frontend.RunQuery(VdcQueryType.GetVdsInterfacesByVdsId, tempVar, _asyncQuery); // VdcQueryReturnValue returnValue = Frontend.RunQuery(VdcQueryType.GetVdsInterfacesByVdsId, // new GetVdsByVdsIdParameters(Entity.vds_id) { Refresh = IsQueryFirstTime }); // if (returnValue != null && returnValue.Succeeded) // List<VdsNetworkInterface> items = new List<VdsNetworkInterface>(); // foreach (IVdcQueryable item in ((List<IVdcQueryable>)returnValue.ReturnValue)) // VdsNetworkInterface i = (VdsNetworkInterface)item; // items.Add(i); // UpdateItems(items); // else // UpdateItems(new List<VdsNetworkInterface>()); } private void updateItems(Iterable<VdsNetworkInterface> source) { ArrayList<HostInterfaceLineModel> items = new ArrayList<HostInterfaceLineModel>(); setOriginalItems((ArrayList<VdsNetworkInterface>) source); List<Bond> nonEmptyBonds = new ArrayList<Bond>(); List<Nic> independentNics = new ArrayList<Nic>(); Map<String, List<Nic>> bondToNics = new HashMap<String, List<Nic>>(); Map<String, List<Vlan>> nicToVlans = new HashMap<String, List<Vlan>>(); sortNics(); classifyNics(nonEmptyBonds, independentNics, bondToNics, nicToVlans); // create all bond models for (Bond bond : nonEmptyBonds) { HostInterfaceLineModel model = lineModelFromBond(bond); items.add(model); // add contained interface models - should exist, but check just in case if (bondToNics.containsKey(bond.getName())) { for (Nic nic : bondToNics.get(bond.getName())) { model.getInterfaces().add(hostInterfaceFromNic(nic)); } } // add any corresponding VLAN bridge models model.getVLans().addAll(gatherVlans(bond, nicToVlans)); } // create all independent NIC models for (Nic nic : independentNics) { HostInterfaceLineModel model = lineModelFromInterface(nic); model.getInterfaces().add(hostInterfaceFromNic(nic)); items.add(model); // add any corresponding VLAN bridge models model.getVLans().addAll(gatherVlans(nic, nicToVlans)); } setItems(items); updateActionAvailability(); } private List<HostVLan> gatherVlans(VdsNetworkInterface nic, Map<String, List<Vlan>> nicToVlans) { List<HostVLan> hostVlanList = new ArrayList<HostVLan>(); if (nicToVlans.containsKey(nic.getName())) { for (Vlan vlan : nicToVlans.get(nic.getName())) { hostVlanList.add(hostVlanFromNic(vlan)); } } return hostVlanList; } private void sortNics() { Collections.sort(getOriginalItems(), new Linq.InterfaceComparator()); } private void classifyNics(List<Bond> nonEmptyBonds, List<Nic> independentNics, Map<String, List<Nic>> bondToNics, Map<String, List<Vlan>> nicToVlans) { for (VdsNetworkInterface nic : getOriginalItems()) { if (nic instanceof Bond) { nonEmptyBonds.add((Bond) nic); } else if (nic instanceof Nic) { if (nic.getBondName() == null) { independentNics.add((Nic) nic); } else { if (bondToNics.containsKey(nic.getBondName())) { bondToNics.get(nic.getBondName()).add((Nic) nic); } else { List<Nic> nicList = new ArrayList<Nic>(); nicList.add((Nic) nic); bondToNics.put(nic.getBondName(), nicList); } } } else if (nic instanceof Vlan) { String nameWithoutVlan = nic.getName().substring(0, nic.getName().lastIndexOf('.')); if (nicToVlans.containsKey(nameWithoutVlan)) { nicToVlans.get(nameWithoutVlan).add((Vlan) nic); } else { List<Vlan> vlanList = new ArrayList<Vlan>(); vlanList.add((Vlan) nic); nicToVlans.put(nameWithoutVlan, vlanList); } } } } private HostInterfaceLineModel lineModelFromInterface(VdsNetworkInterface nic) { HostInterfaceLineModel model = new HostInterfaceLineModel(); model.setInterfaces(new ArrayList<HostInterface>()); model.setVLans(new ArrayList<HostVLan>()); model.setNetworkName(nic.getNetworkName()); model.setIsManagement(nic.getIsManagement()); return model; } private HostInterfaceLineModel lineModelFromBond(VdsNetworkInterface nic) { HostInterfaceLineModel model = lineModelFromInterface(nic); model.setInterface(nic); model.setIsBonded(true); model.setBondName(nic.getName()); model.setAddress(nic.getAddress()); return model; } private HostInterface hostInterfaceFromNic(VdsNetworkInterface nic) { HostInterface hi = new HostInterface(); hi.setInterface(nic); hi.setName(nic.getName()); hi.setAddress(nic.getAddress()); hi.setMAC(nic.getMacAddress()); hi.setSpeed(nic.getSpeed()); hi.setRxRate(nic.getStatistics().getReceiveRate()); hi.setRxDrop(nic.getStatistics().getReceiveDropRate()); hi.setTxRate(nic.getStatistics().getTransmitRate()); hi.setTxDrop(nic.getStatistics().getTransmitDropRate()); hi.setStatus(nic.getStatistics().getStatus()); hi.getPropertyChangedEvent().addListener(this); return hi; } private HostVLan hostVlanFromNic(VdsNetworkInterface nic) { HostVLan hv = new HostVLan(); hv.setInterface(nic); hv.setName(nic.getName()); hv.setNetworkName(nic.getNetworkName()); hv.setAddress(nic.getAddress()); hv.getPropertyChangedEvent().addListener(this); return hv; } @Override public void eventRaised(Event ev, Object sender, EventArgs args) { super.eventRaised(ev, sender, args); if (ev.matchesDefinition(ProvidePropertyChangedEvent.Definition)) { model_PropertyChanged(sender, (PropertyChangedEventArgs) args); } else if (sender instanceof Model && StringHelper.stringsEqual(((Model) sender).getTitle(), "InterfaceList")) //$NON-NLS-1$ { HostManagementNetworkModel managementNetworkModel = ((HostManagementNetworkModel) getWindow()); VdsNetworkInterface vdsNetworkInterface = (VdsNetworkInterface) managementNetworkModel.getInterface().getSelectedItem(); if (vdsNetworkInterface.getBonded() != null && vdsNetworkInterface.getBonded().equals(true)) { managementNetworkModel.getBondingOptions().setIsChangable(true); } else { managementNetworkModel.getBondingOptions().setIsChangable(false); } } } private void model_PropertyChanged(Object sender, PropertyChangedEventArgs args) { if (!args.PropertyName.equals("IsSelected")) //$NON-NLS-1$ { return; } if (sender instanceof HostInterfaceLineModel) { HostInterfaceLineModel model = (HostInterfaceLineModel) sender; for (HostInterface hostInterface : model.getInterfaces()) { hostInterface.getPropertyChangedEvent().removeListener(this); hostInterface.setIsSelected(model.getIsSelected()); hostInterface.getPropertyChangedEvent().addListener(this); } for (HostVLan vLan : model.getVLans()) { vLan.getPropertyChangedEvent().removeListener(this); vLan.setIsSelected(false); vLan.getPropertyChangedEvent().addListener(this); } if (model.getIsSelected()) { if (model.getIsBonded()) { setSelectedItem(model.getInterface()); } else { setSelectedItem(model.getInterfaces().get(0).getInterface()); } } } else if (sender instanceof HostInterface) { HostInterface model = (HostInterface) sender; Object selectItem = null; if (model.getIsSelected()) { selectItem = model.getInterface(); } for (Object a : getItems()) { HostInterfaceLineModel item = (HostInterfaceLineModel) a; boolean found = false; for (HostInterface hostInterface : item.getInterfaces()) { if (hostInterface == model) { item.getPropertyChangedEvent().removeListener(this); item.setIsSelected(model.getIsSelected()); item.getPropertyChangedEvent().addListener(this); if (item.getIsBonded() && item.getIsSelected()) { selectItem = item.getInterface(); } for (HostVLan vLan : item.getVLans()) { vLan.getPropertyChangedEvent().removeListener(this); vLan.setIsSelected(false); vLan.getPropertyChangedEvent().addListener(this); } found = true; break; } } if (found) { for (HostInterface hostInterface : item.getInterfaces()) { hostInterface.getPropertyChangedEvent().removeListener(this); hostInterface.setIsSelected(model.getIsSelected()); hostInterface.getPropertyChangedEvent().addListener(this); } } } if (selectItem != null) { setSelectedItem(selectItem); } } else if (sender instanceof HostVLan) { HostVLan model = (HostVLan) sender; for (Object a : getItems()) { HostInterfaceLineModel item = (HostInterfaceLineModel) a; for (HostVLan vLan : item.getVLans()) { if (vLan == model) { for (HostInterface hostInterface : item.getInterfaces()) { hostInterface.getPropertyChangedEvent().removeListener(this); hostInterface.setIsSelected(false); hostInterface.getPropertyChangedEvent().addListener(this); } item.getPropertyChangedEvent().removeListener(this); item.setIsSelected(false); item.getPropertyChangedEvent().addListener(this); break; } } } if (model.getIsSelected()) { setSelectedItem(model.getInterface()); } } if (getSelectedItems().isEmpty()) { setSelectedItem(null); } else { // Check whether the SelectedItem is still a one from SelectedItems. If not, choose the first one. boolean found = false; for (VdsNetworkInterface item : getSelectedItems()) { if (item == getSelectedItem()) { found = true; break; } } if (!found) { setSelectedItem(Linq.firstOrDefault(getSelectedItems())); } } updateActionAvailability(); } private ArrayList<String> getSelectedNicsNetworks(RefObject<Boolean> isVlanSelected, RefObject<Boolean> isManagementSelected) { ArrayList<VdsNetworkInterface> selectedItems = getSelectedItemsWithVlans(); ArrayList<String> list = new ArrayList<String>(); isVlanSelected.argvalue = false; isManagementSelected.argvalue = false; for (VdsNetworkInterface nic : selectedItems) { if (!StringHelper.isNullOrEmpty(nic.getNetworkName())) { if (nic.getIsManagement()) { isManagementSelected.argvalue = true; } list.add(nic.getNetworkName()); if (!isVlanSelected.argvalue && nic.getVlanId() != null) { isVlanSelected.argvalue = true; } } } return list; } public void edit() { if (getWindow() != null) { return; } AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) model; ArrayList<Network> networksByCluster = (ArrayList<Network>) ReturnValue; VdsNetworkInterface item = (VdsNetworkInterface) hostInterfaceListModel.getSelectedItem(); ArrayList<Network> networksToAdd = new ArrayList<Network>(); Network selectedNetwork = null; if (item.getVlanId() != null) { for (Network network : networksByCluster) { if (StringHelper.stringsEqual(network.getName(), item.getNetworkName())) { networksToAdd.add(network); if (selectedNetwork == null) { selectedNetwork = network; } } } } else { // creating dictionary of networks by name HashMap<String, Network> networkDictionary = new HashMap<String, Network>(); for (Network network : networksByCluster) { networkDictionary.put(network.getName(), network); } // creating list of attached networks. ArrayList<Network> attachedNetworks = new ArrayList<Network>(); for (VdsNetworkInterface nic : hostInterfaceListModel.getAllItems()) { if (nic.getNetworkName() != null && networkDictionary.containsKey(nic.getNetworkName())) { attachedNetworks.add(networkDictionary.get(nic.getNetworkName())); } } ArrayList<Network> unAttachedNetworks = Linq.except(networksByCluster, attachedNetworks); // adding selected network names to list. boolean isVlanSelected = false; boolean isManagementSelected = false; ArrayList<VdsNetworkInterface> selectedItems = hostInterfaceListModel.getSelectedItemsWithVlans(); ArrayList<String> selectedNicsNetworks = new ArrayList<String>(); for (VdsNetworkInterface nic : selectedItems) { if (!StringHelper.isNullOrEmpty(nic.getNetworkName())) { if (nic.getIsManagement()) { isManagementSelected = true; } selectedNicsNetworks.add(nic.getNetworkName()); if (!isVlanSelected && nic.getVlanId() != null) { isVlanSelected = true; } } } for (String selectedNetworkName : selectedNicsNetworks) { if (networkDictionary.containsKey(selectedNetworkName)) { Network network = networkDictionary.get(selectedNetworkName); networksToAdd.add(network); attachedNetworks.remove(network); if (selectedNetwork == null) { selectedNetwork = network; } } } if (!isManagementSelected || isVlanSelected) { for (Network unAttachedNetwork : unAttachedNetworks) { if (isVlanSelected) { if (unAttachedNetwork.getVlanId() != null) { networksToAdd.add(unAttachedNetwork); } } else { networksToAdd.add(unAttachedNetwork); } } } } Collections.sort(networksToAdd, new NameableComparator()); // Add a 'none' option to networks. if (!StringHelper.isNullOrEmpty(item.getNetworkName())) { Network tempVar = new Network(); tempVar.setId(Guid.Empty); tempVar.setName("None"); //$NON-NLS-1$ networksToAdd.add(0, tempVar); } HostInterfaceModel hostInterfaceModel = new HostInterfaceModel(); hostInterfaceListModel.setWindow(hostInterfaceModel); hostInterfaceModel.setEntity(item.getName()); hostInterfaceModel.setTitle(ConstantsManager.getInstance().getConstants().editNetworkInterfaceTitle()); hostInterfaceModel.setHashName("edit_network_interface_hosts"); //$NON-NLS-1$ hostInterfaceModel.setNetworks(hostInterfaceListModel.getSelectedItemsWithVlans()); hostInterfaceModel.setNoneBootProtocolAvailable(!item.getIsManagement()); hostInterfaceModel.setBootProtocol(!hostInterfaceModel.getNoneBootProtocolAvailable() && item.getBootProtocol() == NetworkBootProtocol.NONE ? NetworkBootProtocol.DHCP : item.getBootProtocol()); hostInterfaceModel.getAddress().setEntity(item.getAddress()); hostInterfaceModel.getSubnet().setEntity(item.getSubnet()); hostInterfaceModel.getNetwork().setItems(networksToAdd); hostInterfaceModel.getName().setEntity(item.getName()); hostInterfaceModel.getBondingOptions().setIsAvailable(false); if (item.getBonded() != null && item.getBonded().equals(true)) { hostInterfaceModel.getBondingOptions().setIsAvailable(true); Map.Entry<String, EntityModel> defaultItem = null; RefObject<Map.Entry<String, EntityModel>> tempRef_defaultItem = new RefObject<Map.Entry<String, EntityModel>>(defaultItem); ArrayList<Map.Entry<String, EntityModel>> list = AsyncDataProvider.getBondingOptionList(tempRef_defaultItem); defaultItem = tempRef_defaultItem.argvalue; Map.Entry<String, EntityModel> selectBondingOpt = new KeyValuePairCompat<String, EntityModel>(); boolean containsSelectBondingOpt = false; hostInterfaceModel.getBondingOptions().setItems(list); for (int i = 0; i < list.size(); i++) { if (StringHelper.stringsEqual(list.get(i).getKey(), item.getBondOptions())) { selectBondingOpt = list.get(i); containsSelectBondingOpt = true; break; } } if (containsSelectBondingOpt == false) { if (StringHelper.stringsEqual(item.getBondOptions(), AsyncDataProvider.getDefaultBondingOption())) { selectBondingOpt = defaultItem; } else { selectBondingOpt = list.get(list.size() - 1); EntityModel entityModel = selectBondingOpt.getValue(); entityModel.setEntity(item.getBondOptions()); } } hostInterfaceModel.getBondingOptions().setSelectedItem(selectBondingOpt); } if (selectedNetwork == null && networksToAdd.size() > 0) { selectedNetwork = networksToAdd.get(0); } hostInterfaceModel.getNetwork().setSelectedItem(selectedNetwork); hostInterfaceModel.getCheckConnectivity() .setIsAvailable(!StringHelper.isNullOrEmpty(item.getNetworkName()) && item.getIsManagement()); hostInterfaceModel.getCheckConnectivity() .setIsChangable(!StringHelper.isNullOrEmpty(item.getNetworkName()) && item.getIsManagement()); hostInterfaceModel.getCheckConnectivity().setEntity(item.getIsManagement()); if (networksToAdd.isEmpty()) { hostInterfaceModel.setMessage(ConstantsManager.getInstance() .getConstants() .thereAreNoNetworksAvailablePleaseAddAdditionalNetworksMsg()); UICommand tempVar2 = new UICommand("Cancel", hostInterfaceListModel); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().close()); tempVar2.setIsDefault(true); tempVar2.setIsCancel(true); hostInterfaceModel.getCommands().add(tempVar2); } else { UICommand tempVar3 = new UICommand("OnSave", hostInterfaceListModel); //$NON-NLS-1$ tempVar3.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar3.setIsDefault(true); hostInterfaceModel.getCommands().add(tempVar3); UICommand tempVar4 = new UICommand("Cancel", hostInterfaceListModel); //$NON-NLS-1$ tempVar4.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar4.setIsCancel(true); hostInterfaceModel.getCommands().add(tempVar4); } } }; AsyncDataProvider.getClusterNetworkList(_asyncQuery, getEntity().getVdsGroupId()); } public void editManagementNetwork() { if (getWindow() != null) { return; } HostManagementNetworkModel managementNicModel = new HostManagementNetworkModel(); setWindow(managementNicModel); managementNicModel.setTitle(ConstantsManager.getInstance().getConstants().editManagementNetworkTitle()); managementNicModel.setHashName("edit_management_network"); //$NON-NLS-1$ AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { final HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) model; ArrayList<Network> clusterNetworks = (ArrayList<Network>) ReturnValue; final VdsNetworkInterface item = (VdsNetworkInterface) hostInterfaceListModel.getSelectedItem(); final HostManagementNetworkModel managementModel = (HostManagementNetworkModel) hostInterfaceListModel.getWindow(); Network networkToEdit = Linq.findNetworkByName(clusterNetworks, item.getNetworkName()); managementModel.setEntity(networkToEdit); managementModel.setNoneBootProtocolAvailable(!item.getIsManagement()); managementModel.setBootProtocol(!managementModel.getNoneBootProtocolAvailable() && item.getBootProtocol() == NetworkBootProtocol.NONE ? NetworkBootProtocol.DHCP : item.getBootProtocol()); managementModel.getAddress().setEntity(item.getAddress()); managementModel.getSubnet().setEntity(item.getSubnet()); managementModel.getGateway().setEntity(item.getGateway()); final StringBuilder tmpDefaultInterfaceName = new StringBuilder(); AsyncDataProvider.getInterfaceOptionsForEditNetwork(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { ArrayList<VdsNetworkInterface> interfaces = (ArrayList<VdsNetworkInterface>) returnValue; String defaultInterfaceName = tmpDefaultInterfaceName.toString(); managementModel.getInterface().setItems(interfaces); managementModel.getInterface() .setSelectedItem(Linq.findInterfaceByName(interfaces, defaultInterfaceName)); if (item.getBonded() != null && item.getBonded().equals(true)) { managementModel.getInterface().setTitle(ConstantsManager.getInstance() .getConstants() .interfaceListTitle()); managementModel.getInterface() .getSelectedItemChangedEvent() .addListener(hostInterfaceListModel); } managementModel.getCheckConnectivity().setIsAvailable(true); managementModel.getCheckConnectivity().setIsChangable(true); managementModel.getCheckConnectivity().setEntity(item.getIsManagement()); // currently, always // should be // true managementModel.getBondingOptions().setIsAvailable(false); if (item.getBonded() != null && item.getBonded().equals(true)) { managementModel.getBondingOptions().setIsAvailable(true); Map.Entry<String, EntityModel> defaultItem = null; RefObject<Map.Entry<String, EntityModel>> tempRef_defaultItem = new RefObject<Map.Entry<String, EntityModel>>(defaultItem); ArrayList<Map.Entry<String, EntityModel>> list = AsyncDataProvider.getBondingOptionList(tempRef_defaultItem); defaultItem = tempRef_defaultItem.argvalue; Map.Entry<String, EntityModel> selectBondingOpt = new KeyValuePairCompat<String, EntityModel>(); boolean containsSelectBondingOpt = false; managementModel.getBondingOptions().setItems(list); for (int i = 0; i < list.size(); i++) { if (StringHelper.stringsEqual(list.get(i).getKey(), item.getBondOptions())) { selectBondingOpt = list.get(i); containsSelectBondingOpt = true; break; } } if (containsSelectBondingOpt == false) { if (StringHelper.stringsEqual(item.getBondOptions(), AsyncDataProvider.getDefaultBondingOption())) { selectBondingOpt = defaultItem; } else { selectBondingOpt = list.get(list.size() - 1); EntityModel entityModel = selectBondingOpt.getValue(); entityModel.setEntity(item.getBondOptions()); } } managementModel.getBondingOptions().setSelectedItem(selectBondingOpt); } UICommand tempVar = new UICommand("OnEditManagementNetworkConfirmation", hostInterfaceListModel); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); managementModel.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", hostInterfaceListModel); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); managementModel.getCommands().add(tempVar2); } }), getOriginalItems(), item, networkToEdit, getEntity().getId(), tmpDefaultInterfaceName); } }; AsyncDataProvider.getClusterNetworkList(_asyncQuery, getEntity().getVdsGroupId()); } public void onEditManagementNetworkConfirmation(boolean isBond) { if (!isBond) { HostManagementNetworkModel model = (HostManagementNetworkModel) getWindow(); if (!model.validate()) { return; } if ((Boolean) model.getCheckConnectivity().getEntity() == true) { onEditManagementNetwork(); return; } } else { HostBondInterfaceModel model = (HostBondInterfaceModel) getWindow(); if (!model.validate()) { return; } if ((Boolean) model.getCheckConnectivity().getEntity() == true) { onBond(); return; } } ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(ConstantsManager.getInstance().getConstants().confirmTitle()); confirmModel.getLatch().setEntity(true); confirmModel.getLatch().setIsAvailable(true); confirmModel.getLatch().setIsChangable(true); if (!isBond) { UICommand tempVar = new UICommand("OnEditManagementNetwork", this); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); confirmModel.getCommands().add(tempVar); } else { UICommand tempVar2 = new UICommand("OnBond", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar2.setIsDefault(true); confirmModel.getCommands().add(tempVar2); } UICommand tempVar3 = new UICommand("CancelConfirm", this); //$NON-NLS-1$ tempVar3.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar3.setIsCancel(true); confirmModel.getCommands().add(tempVar3); } public void onEditManagementNetwork() { HostManagementNetworkModel model = (HostManagementNetworkModel) getWindow(); if (getConfirmWindow() != null) { ConfirmationModel confirmModel = (ConfirmationModel) getConfirmWindow(); if ((Boolean) confirmModel.getLatch().getEntity() == true) { model.getCheckConnectivity().setEntity(true); } } if (model.getProgress() != null) { return; } if (!model.validate()) { return; } VdsNetworkInterface nic = (VdsNetworkInterface) model.getInterface().getSelectedItem(); Network network = model.getEntity(); VdcActionType actionType = VdcActionType.UpdateNetworkToVdsInterface; UpdateNetworkToVdsParameters parameters = new UpdateNetworkToVdsParameters(getEntity().getId(), network, new ArrayList<VdsNetworkInterface>(Arrays.asList(new VdsNetworkInterface[] { nic }))); Map.Entry<String, EntityModel> bondingOption; if (model.getBondingOptions().getSelectedItem() != null) { bondingOption = (Map.Entry<String, EntityModel>) model.getBondingOptions().getSelectedItem(); if (!bondingOption.getKey().equals("custom")) //$NON-NLS-1$ { parameters.setBondingOptions((StringHelper.isNullOrEmpty(bondingOption.getKey()) ? null : bondingOption.getKey())); } else { EntityModel entityModel = bondingOption.getValue(); if (entityModel.getEntity() != null) { parameters.setBondingOptions(entityModel.getEntity().toString()); } } } if (nic.getBonded() == null || nic.getBonded() == false) { parameters.setBondingOptions(null); } if (network != null) { parameters.setOldNetworkName(network.getName()); } parameters.setCheckConnectivity((Boolean) model.getCheckConnectivity().getEntity()); parameters.setBootProtocol(model.getBootProtocol()); if (model.getIsStaticAddress()) { parameters.setAddress((String) model.getAddress().getEntity()); parameters.setSubnet((String) model.getSubnet().getEntity()); parameters.setGateway((String) model.getGateway().getEntity()); } model.startProgress(null); setcurrentModel(model); Frontend.RunAction(actionType, parameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostManagementNetworkModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, hostInterfaceListModel.getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); } } }, this); cancelConfirm(); } public void bond() { if (getWindow() != null) { return; } HostBondInterfaceModel bondModel = new HostBondInterfaceModel(); setWindow(bondModel); bondModel.setTitle(ConstantsManager.getInstance().getConstants().bondNetworkInterfacesTitle()); bondModel.setHashName("bond_network_interfaces"); //$NON-NLS-1$ AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) model; ArrayList<Network> networksByCluster = (ArrayList<Network>) ReturnValue; HostBondInterfaceModel innerBondModel = (HostBondInterfaceModel) hostInterfaceListModel.getWindow(); Network selectedNetwork = null; VDS host = hostInterfaceListModel.getEntity(); // Allow change gateway if there one of the selected interfaces connected to engine network. boolean isAnyManagement = false; for (VdsNetworkInterface innerItem : hostInterfaceListModel.getSelectedItemsWithVlans()) { if (innerItem.getIsManagement()) { isAnyManagement = true; break; } } ArrayList<Network> networksToAdd = new ArrayList<Network>(); // creating dictionary of networks by name HashMap<String, Network> networkDictionary = new HashMap<String, Network>(); for (Network network : networksByCluster) { networkDictionary.put(network.getName(), network); } // creating list of attached networks. ArrayList<Network> attachedNetworks = new ArrayList<Network>(); for (VdsNetworkInterface nic : hostInterfaceListModel.getAllItems()) { if (nic.getNetworkName() != null && networkDictionary.containsKey(nic.getNetworkName())) { attachedNetworks.add(networkDictionary.get(nic.getNetworkName())); } } ArrayList<Network> unAttachedNetworks = Linq.except(networksByCluster, attachedNetworks); // adding selected network names to list. boolean isVlanSelected = false; boolean isManagement = false; RefObject<Boolean> tempRef_isVlanSelected = new RefObject<Boolean>(isVlanSelected); RefObject<Boolean> tempRef_isManagement = new RefObject<Boolean>(isManagement); ArrayList<String> selectedNicsNetworks = hostInterfaceListModel.getSelectedNicsNetworks(tempRef_isVlanSelected, tempRef_isManagement); isVlanSelected = tempRef_isVlanSelected.argvalue; isManagement = tempRef_isManagement.argvalue; for (String selectedNetworkName : selectedNicsNetworks) { if (networkDictionary.containsKey(selectedNetworkName)) { Network network = networkDictionary.get(selectedNetworkName); networksToAdd.add(network); attachedNetworks.remove(network); if (selectedNetwork == null) { selectedNetwork = network; } } } if (!isManagement) { for (Network unAttachedNetwork : unAttachedNetworks) { if (isVlanSelected) { if (unAttachedNetwork.getVlanId() != null) { networksToAdd.add(unAttachedNetwork); } } else { networksToAdd.add(unAttachedNetwork); } } innerBondModel.getNetwork().setItems(networksToAdd); } else { innerBondModel.getNetwork().setItems(new ArrayList<Network>(Arrays.asList(selectedNetwork))); } if (selectedNetwork == null && networksToAdd.size() > 0) { selectedNetwork = networksToAdd.get(0); } innerBondModel.getNetwork().setSelectedItem(selectedNetwork); // Interface bond = selectedItems.FirstOrDefault(a => a.is_bond.HasValue && a.is_bond.Value); VdsNetworkInterface bond = Linq.findInterfaceByIsBond(getSelectedItems()); if (bond != null) // one of the bond items is a bond itself -> don't // allocate a new bond name, edit the existing one: { innerBondModel.getBond() .setItems(new ArrayList<String>(Arrays.asList(new String[] { bond.getName() }))); innerBondModel.getBond().setSelectedItem(bond.getName()); innerBondModel.getBond().setIsChangable(false); hostInterfaceListModel.postBond(hostInterfaceListModel, innerBondModel, networksToAdd, isAnyManagement); } else { AsyncQuery _asyncQuery1 = new AsyncQuery(); _asyncQuery1.setModel(hostInterfaceListModel); _asyncQuery1.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model1, Object ReturnValue1) { HostInterfaceListModel innerHostInterfaceListModel = (HostInterfaceListModel) model1; HostBondInterfaceModel bModel = (HostBondInterfaceModel) innerHostInterfaceListModel.getWindow(); List<VdsNetworkInterface> bonds = (List<VdsNetworkInterface>) ((VdcQueryReturnValue) ReturnValue1).getReturnValue(); List<String> bondNames = new ArrayList<String>(); for (VdsNetworkInterface bond : bonds) { bondNames.add(bond.getName()); } bModel.getBond().setItems(bondNames); // ((List<Interface>)model.Bond.Options).Sort(a => a.name); bModel.getBond().setSelectedItem(Linq.firstOrDefault(bondNames)); boolean hasManagement = false; for (VdsNetworkInterface innerItem : innerHostInterfaceListModel.getSelectedItemsWithVlans()) { if (innerItem.getIsManagement()) { hasManagement = true; break; } } innerHostInterfaceListModel.postBond(innerHostInterfaceListModel, bModel, bModel.getNetwork().getItems() != null ? (ArrayList<Network>) bModel.getNetwork() .getItems() : new ArrayList<Network>(), hasManagement); } }; Frontend.RunQuery(VdcQueryType.GetVdsFreeBondsByVdsId, new IdQueryParameters(host.getId()), _asyncQuery1); } } }; AsyncDataProvider.getClusterNetworkList(_asyncQuery, getEntity().getVdsGroupId()); } public void postBond(HostInterfaceListModel hostInterfaceListModel, HostBondInterfaceModel innerBondModel, ArrayList<Network> networksToAdd, boolean isAnyManagement) { VdsNetworkInterface interfaceWithNetwork = Linq.findInterfaceNetworkNameNotEmpty(getSelectedItemsWithVlans()); innerBondModel.getCheckConnectivity().setIsChangable(interfaceWithNetwork != null); innerBondModel.getCheckConnectivity().setIsAvailable(interfaceWithNetwork != null && interfaceWithNetwork.getIsManagement()); innerBondModel.getCheckConnectivity().setEntity(interfaceWithNetwork != null && interfaceWithNetwork.getIsManagement()); innerBondModel.setNoneBootProtocolAvailable(!(interfaceWithNetwork != null && interfaceWithNetwork.getIsManagement())); if (interfaceWithNetwork != null) { innerBondModel.setBootProtocol(!innerBondModel.getNoneBootProtocolAvailable() && interfaceWithNetwork.getBootProtocol() == NetworkBootProtocol.NONE ? NetworkBootProtocol.DHCP : interfaceWithNetwork.getBootProtocol()); innerBondModel.getAddress().setEntity(interfaceWithNetwork.getAddress()); innerBondModel.getSubnet().setEntity(interfaceWithNetwork.getSubnet()); innerBondModel.getGateway().setEntity(interfaceWithNetwork.getGateway()); } else { innerBondModel.setBootProtocol(NetworkBootProtocol.NONE); } innerBondModel.getGateway().setIsAvailable(isAnyManagement); if (networksToAdd.isEmpty()) { innerBondModel.setMessage(ConstantsManager.getInstance() .getConstants() .thereAreNoNetworksAvailablePleaseAddAdditionalNetworksMsg()); UICommand tempVar = new UICommand("Cancel", hostInterfaceListModel); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().close()); tempVar.setIsDefault(true); tempVar.setIsCancel(true); innerBondModel.getCommands().add(tempVar); } else { if (interfaceWithNetwork != null && interfaceWithNetwork.getIsManagement()) { UICommand tempVar2 = new UICommand("OnEditManagementNetworkConfirmation_Bond", hostInterfaceListModel); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar2.setIsDefault(true); innerBondModel.getCommands().add(tempVar2); UICommand tempVar3 = new UICommand("Cancel", hostInterfaceListModel); //$NON-NLS-1$ tempVar3.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar3.setIsCancel(true); innerBondModel.getCommands().add(tempVar3); } else { UICommand tempVar4 = new UICommand("OnBond", hostInterfaceListModel); //$NON-NLS-1$ tempVar4.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar4.setIsDefault(true); innerBondModel.getCommands().add(tempVar4); UICommand tempVar5 = new UICommand("Cancel", hostInterfaceListModel); //$NON-NLS-1$ tempVar5.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar5.setIsCancel(true); innerBondModel.getCommands().add(tempVar5); } } } public void onBond() { HostBondInterfaceModel model = (HostBondInterfaceModel) getWindow(); if (getConfirmWindow() != null) { ConfirmationModel confirmModel = (ConfirmationModel) getConfirmWindow(); if ((Boolean) confirmModel.getLatch().getEntity() == true) { model.getCheckConnectivity().setEntity(true); } cancelConfirm(); } if (model.getProgress() != null) { return; } if (!model.validate()) { return; } VDS host = getEntity(); ArrayList<VdsNetworkInterface> selectedItems = getSelectedItems(); Network net = (Network) model.getNetwork().getSelectedItem(); // Interface interfaceWithNetwork = items.FirstOrDefault(a => !string.IsNullOrEmpty(a.network_name)); VdsNetworkInterface interfaceWithNetwork = Linq.findInterfaceNetworkNameNotEmpty(selectedItems); // look for lines with vlans ArrayList<HostInterfaceLineModel> itemList = (ArrayList<HostInterfaceLineModel>) getItems(); for (HostInterfaceLineModel lineModel : itemList) { if (lineModel.getIsSelected() && lineModel.getVlanSize() == 1) { interfaceWithNetwork = lineModel.getVLans().get(0).getInterface(); // bond action is only enabled if there is one vlaned interface break; } } if (interfaceWithNetwork != null) { UpdateNetworkToVdsParameters parameters = new UpdateNetworkToVdsParameters(host.getId(), net, selectedItems); parameters.setCheckConnectivity((Boolean) model.getCheckConnectivity().getEntity()); parameters.setOldNetworkName(interfaceWithNetwork.getNetworkName()); Map.Entry<String, EntityModel> bondingOption; if (model.getBondingOptions().getSelectedItem() != null) { bondingOption = (Map.Entry<String, EntityModel>) model.getBondingOptions().getSelectedItem(); if (!bondingOption.getKey().equals("custom")) //$NON-NLS-1$ { parameters.setBondingOptions((StringHelper.isNullOrEmpty(bondingOption.getKey()) ? null : bondingOption.getKey())); } else { EntityModel entityModel = bondingOption.getValue(); if (entityModel.getEntity() != null) { parameters.setBondingOptions(entityModel.getEntity().toString()); } } } parameters.setBootProtocol(model.getBootProtocol()); parameters.setBondName((String) model.getBond().getSelectedItem()); if (model.getIsStaticAddress()) { parameters.setAddress((String) model.getAddress().getEntity()); parameters.setSubnet((String) model.getSubnet().getEntity()); if (interfaceWithNetwork.getIsManagement()) { parameters.setGateway((String) model.getGateway().getEntity()); } } model.startProgress(null); setcurrentModel(model); Frontend.RunAction(VdcActionType.UpdateNetworkToVdsInterface, parameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostBondInterfaceModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, hostInterfaceListModel.getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); } } }, this); } else { String[] nics = new String[selectedItems.size()]; for (int i = 0; i < selectedItems.size(); i++) { nics[i] = selectedItems.get(i).getName(); } // var parameters = new AddBondParameters( // host.vds_id, // model.Bond.ValueAs<Interface>().name, // net, // items.Select(a => a.name).ToArray()) // BondingOptions = model.BondingOptions.ValueAs<string>(), // BootProtocol = model.BootProtocol AddBondParameters parameters = new AddBondParameters(host.getId(), (String) model.getBond().getSelectedItem(), net, nics); Map.Entry<String, EntityModel> bondingOption; if (model.getBondingOptions().getSelectedItem() != null) { bondingOption = (Map.Entry<String, EntityModel>) model.getBondingOptions().getSelectedItem(); if (!bondingOption.getKey().equals("custom")) //$NON-NLS-1$ { parameters.setBondingOptions((StringHelper.isNullOrEmpty(bondingOption.getKey()) ? null : bondingOption.getKey())); } else { EntityModel entityModel = bondingOption.getValue(); if (entityModel.getEntity() != null) { parameters.setBondingOptions(entityModel.getEntity().toString()); } } } parameters.setBootProtocol(model.getBootProtocol()); if (model.getIsStaticAddress()) { parameters.setAddress((String) model.getAddress().getEntity()); parameters.setSubnet((String) model.getSubnet().getEntity()); parameters.setGateway((String) model.getGateway().getEntity()); } model.startProgress(null); setcurrentModel(model); Frontend.RunAction(VdcActionType.AddBond, parameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostBondInterfaceModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, hostInterfaceListModel.getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); } } }, this); } } public void detach() { if (getWindow() != null) { return; } HostInterfaceModel model = new HostInterfaceModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().detachNetworkInterfacesTitle()); model.setHashName("detach_network_interfaces"); //$NON-NLS-1$ VdsNetworkInterface nic = (VdsNetworkInterface) getSelectedItem(); model.getName().setEntity(nic.getName()); UICommand tempVar = new UICommand("OnDetach", this); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } public void onDetach() { HostInterfaceModel model = (HostInterfaceModel) getWindow(); if (model.getProgress() != null) { return; } setcurrentModel(model); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) model; ArrayList<Network> networks = (ArrayList<Network>) ReturnValue; Network defaultNetwork = new Network(); VdsNetworkInterface nic = (VdsNetworkInterface) getSelectedItem(); defaultNetwork.setName(nic.getNetworkName()); Network tempVar = Linq.findNetworkByName(networks, nic.getNetworkName()); Network net = (tempVar != null) ? tempVar : defaultNetwork; hostInterfaceListModel.startProgress(null); Frontend.RunAction(VdcActionType.DetachNetworkFromVdsInterface, new AttachNetworkToVdsParameters(getEntity().getId(), net, nic), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostInterfaceModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); } } }, hostInterfaceListModel); } }; AsyncDataProvider.getClusterNetworkList(_asyncQuery, getEntity().getVdsGroupId()); } public void onSave() { HostInterfaceModel model = (HostInterfaceModel) getWindow(); if (!model.validate()) { return; } String nicName = (String) model.getEntity(); final VdsNetworkInterface nic = (VdsNetworkInterface) Linq.findInterfaceByName(getAllItems(), nicName); if (nic == null) { cancel(); return; } Network network = (Network) model.getNetwork().getSelectedItem(); // Save changes. if (network.getId().equals(Guid.Empty)) { if (nic.getIsManagement()) { // We are trying to disconnect the management interface from its // network -> ask for the user's confirmation before doing that. ConfirmationModel confirmModel = new ConfirmationModel(); setConfirmWindow(confirmModel); confirmModel.setTitle(ConstantsManager.getInstance() .getConstants() .editManagementNetworkInterfaceTitle()); confirmModel.setHashName("edit_management_network_interface"); //$NON-NLS-1$ confirmModel.setMessage(ConstantsManager.getInstance() .getMessages() .youAreAboutToDisconnectHostInterfaceMsg(nic.getName())); UICommand tempVar = new UICommand("OnConfirmManagementDetach", this); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); confirmModel.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); confirmModel.getCommands().add(tempVar2); } else { if (model.getProgress() != null) { return; } AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { final HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) model; HostInterfaceModel hostInterfaceModel = (HostInterfaceModel) hostInterfaceListModel.getWindow(); ArrayList<Network> networks = (ArrayList<Network>) ReturnValue; Network defaultNetwork = new Network(); defaultNetwork.setName(nic.getNetworkName()); Network tempVar3 = Linq.findNetworkByName(networks, nic.getNetworkName()); Network net = (tempVar3 != null) ? tempVar3 : defaultNetwork; hostInterfaceModel.startProgress(null); setcurrentModel(hostInterfaceModel); Frontend.RunAction(VdcActionType.DetachNetworkFromVdsInterface, new AttachNetworkToVdsParameters(getEntity().getId(), net, nic), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostInterfaceModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); } } }, hostInterfaceListModel); } }; AsyncDataProvider.getClusterNetworkList(_asyncQuery, getEntity().getVdsGroupId()); } } else { if (model.getProgress() != null) { return; } AttachNetworkToVdsParameters parameters; VdcActionType actionType; boolean vLanAttached = false; boolean bondWithVlans = false; boolean isUpdateVlan = false; if (nic.getBonded() != null && nic.getBonded()) { for (HostInterfaceLineModel item : (ArrayList<HostInterfaceLineModel>) getItems()) { if (item.getInterface() != null && item.getInterface().getId().equals(nic.getId())) { if (item.getVLans() != null && item.getVLans().size() > 0) { bondWithVlans = true; for (HostVLan vLan : item.getVLans()) { if (StringHelper.stringsEqual(network.getName(), vLan.getNetworkName())) { vLanAttached = true; break; } } } break; } } } else { for (VdsNetworkInterface item : getSelectedItemsWithVlans()) { if (item.getVlanId() != null && StringHelper.stringsEqual(item.getNetworkName(), network.getName())) { isUpdateVlan = true; break; } } } // If the selected item is a non-attached or attached to vlan eth (over bond or not), // and the selected network in the dialog is a new vlan, attach selected network. if ((StringHelper.isNullOrEmpty(nic.getNetworkName()) && (nic.getBonded() == null || !nic.getBonded()) && !isUpdateVlan) || (bondWithVlans && (!vLanAttached && network.getVlanId() != null))) { parameters = new AttachNetworkToVdsParameters(getEntity().getId(), network, nic); actionType = VdcActionType.AttachNetworkToVdsInterface; } else { parameters = new UpdateNetworkToVdsParameters(getEntity().getId(), network, new ArrayList<VdsNetworkInterface>(Arrays.asList(new VdsNetworkInterface[] { nic }))); parameters.setOldNetworkName((nic.getNetworkName() != null ? nic.getNetworkName() : network.getName())); parameters.setCheckConnectivity((Boolean) model.getCheckConnectivity().getEntity()); actionType = VdcActionType.UpdateNetworkToVdsInterface; } Map.Entry<String, EntityModel> bondingOption; if (model.getBondingOptions().getSelectedItem() != null) { bondingOption = (Map.Entry<String, EntityModel>) model.getBondingOptions().getSelectedItem(); if (!bondingOption.getKey().equals("custom")) //$NON-NLS-1$ { parameters.setBondingOptions((StringHelper.isNullOrEmpty(bondingOption.getKey()) ? null : bondingOption.getKey())); } else { EntityModel entityModel = bondingOption.getValue(); if (entityModel.getEntity() != null) { parameters.setBondingOptions(entityModel.getEntity().toString()); } } } parameters.setBootProtocol(model.getBootProtocol()); if (model.getIsStaticAddress()) { parameters.setAddress((String) model.getAddress().getEntity()); parameters.setSubnet((String) model.getSubnet().getEntity()); } model.startProgress(null); setcurrentModel(model); Frontend.RunAction(actionType, parameters, new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostInterfaceModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, hostInterfaceListModel.getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); } } }, this); } } public void saveNetworkConfig() { if (getWindow() != null) { return; } ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().saveNetworkConfigurationTitle()); model.setHashName("save_network_configuration"); //$NON-NLS-1$ model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantToMakeTheChangesPersistentMsg()); UICommand tempVar = new UICommand("OnSaveNetworkConfig", this); //$NON-NLS-1$ tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok()); tempVar.setIsDefault(true); model.getCommands().add(tempVar); UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$ tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel()); tempVar2.setIsCancel(true); model.getCommands().add(tempVar2); } public void onSaveNetworkConfig() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(null); setcurrentModel(model); new SaveNetworkConfigAction(this, model, getEntity()).execute(); } public void onConfirmManagementDetach() { HostInterfaceModel model = (HostInterfaceModel) getWindow(); if (model.getProgress() != null) { return; } String nicName = (String) model.getEntity(); final VdsNetworkInterface nic = (VdsNetworkInterface) Linq.findInterfaceByName(getInterfaceItems(), nicName); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) model; ArrayList<Network> networks = (ArrayList<Network>) ReturnValue; Network defaultNetwork = new Network(); defaultNetwork.setName(nic.getNetworkName()); Network tempVar = Linq.findNetworkByName(networks, nic.getNetworkName()); Network net = (tempVar != null) ? tempVar : defaultNetwork; hostInterfaceListModel.startProgress(null); setcurrentModel(hostInterfaceListModel); Frontend.RunAction(VdcActionType.DetachNetworkFromVdsInterface, new AttachNetworkToVdsParameters(getEntity().getId(), net, nic), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { HostInterfaceListModel hostInterfaceListModel = (HostInterfaceListModel) result.getState(); VdcReturnValueBase returnValueBase = result.getReturnValue(); if (returnValueBase != null && returnValueBase.getSucceeded()) { EntityModel commitChanges = ((HostInterfaceModel) hostInterfaceListModel.getcurrentModel()).getCommitChanges(); if ((Boolean) commitChanges.getEntity()) { new SaveNetworkConfigAction(HostInterfaceListModel.this, hostInterfaceListModel.getcurrentModel(), getEntity()).execute(); } else { hostInterfaceListModel.getcurrentModel().stopProgress(); hostInterfaceListModel.cancel(); hostInterfaceListModel.search(); } } else { hostInterfaceListModel.getcurrentModel().stopProgress(); } } }, hostInterfaceListModel); } }; AsyncDataProvider.getClusterNetworkList(_asyncQuery, getEntity().getVdsGroupId()); } public void cancel() { setConfirmWindow(null); setWindow(null); } public void cancelConfirm() { setConfirmWindow(null); } public void setupNetworks() { if (getWindow() != null) { return; } HostSetupNetworksModel setupNetworksWindowModel = new HostSetupNetworksModel(this); setWindow(setupNetworksWindowModel); // set entity setupNetworksWindowModel.setEntity(getEntity()); } private void updateActionAvailability() { VDS host = getEntity(); VdsNetworkInterface selectedItem = (VdsNetworkInterface) getSelectedItem(); ArrayList<VdsNetworkInterface> selectedItems = getSelectedItems(); getEditCommand().setIsExecutionAllowed(host != null && host.getStatus() != VDSStatus.NonResponsive && selectedItem != null && selectedItems.size() == 1 && StringHelper.isNullOrEmpty(selectedItem.getBondName()) && !selectedItem.getIsManagement()); getBondCommand().setIsExecutionAllowed(host != null && host.getStatus() != VDSStatus.NonResponsive && selectedItems.size() >= 2 && !isAnyBond(selectedItems) && Linq.findAllInterfaceNetworkNameNotEmpty(selectedItems).size() <= 1 && Linq.findAllInterfaceBondNameIsEmpty(selectedItems).size() == selectedItems.size() && Linq.findAllInterfaceVlanIdIsEmpty(selectedItems).size() == selectedItems.size()); // to bond, selected lines must not have more that 1 networks (vlan or not) if (getItems() != null) { ArrayList<HostInterfaceLineModel> itemList = (ArrayList<HostInterfaceLineModel>) getItems(); // total network count cannot be more than 1 int totalNetworkCount = 0; for (HostInterfaceLineModel lineModel : itemList) { if (lineModel.getIsSelected()) { int lineNetworkCount = lineModel.getVlanSize() + (lineModel.getNetworkName() != null ? 1 : 0); if (lineNetworkCount > 1) { // bailout getBondCommand().setIsExecutionAllowed(false); break; } totalNetworkCount += lineNetworkCount; if (totalNetworkCount > 1) { // bailout getBondCommand().setIsExecutionAllowed(false); break; } } } } getDetachCommand().setIsExecutionAllowed(host != null && host.getStatus() != VDSStatus.NonResponsive && selectedItems.size() == 1 && selectedItem != null && !StringHelper.isNullOrEmpty(selectedItem.getNetworkName()) && !selectedItem.getIsManagement()); getSaveNetworkConfigCommand().setIsExecutionAllowed(host != null && (host.getNetConfigDirty() == null ? false : host.getNetConfigDirty())); getEditManagementNetworkCommand().setIsExecutionAllowed(host != null && host.getStatus() != VDSStatus.NonResponsive && selectedItems.size() == 1 && selectedItem != null && selectedItem.getIsManagement()); // Setup Networks is only available on 3.1 Clusters, all the other commands (except save network configuration) // available only on less than 3.1 Clusters if (host != null) { Version v31 = new Version(3, 1); boolean isLessThan31 = host.getVdsGroupCompatibilityVersion().compareTo(v31) < 0; getSetupNetworksCommand().setIsAvailable(!isLessThan31); getSaveNetworkConfigCommand().setIsAvailable(true); getEditCommand().setIsAvailable(isLessThan31); getBondCommand().setIsAvailable(isLessThan31); getDetachCommand().setIsAvailable(isLessThan31); getEditManagementNetworkCommand().setIsAvailable(isLessThan31); setSelectionAvailable(isLessThan31); } } private boolean isAnyBond(Iterable<VdsNetworkInterface> items) { for (VdsNetworkInterface item : items) { if ((item.getBonded() == null ? false : item.getBonded())) { return true; } } return false; } @Override public void executeCommand(UICommand command) { executeCommand(command, new Object[0]); } @Override public void executeCommand(UICommand command, Object... parameters) { super.executeCommand(command); if (command == getEditCommand()) { edit(); } else if (command == getEditManagementNetworkCommand()) { editManagementNetwork(); } else if (command == getSetupNetworksCommand()) { setupNetworks(); } else if (command == getBondCommand()) { bond(); } else if (command == getDetachCommand()) { detach(); } else if (command == getSaveNetworkConfigCommand()) { saveNetworkConfig(); } else if (StringHelper.stringsEqual(command.getName(), "OnSave")) //$NON-NLS-1$ { onSave(); } else if (StringHelper.stringsEqual(command.getName(), "OnEditManagementNetwork")) //$NON-NLS-1$ { onEditManagementNetwork(); } else if (StringHelper.stringsEqual(command.getName(), "OnEditManagementNetworkConfirmation")) //$NON-NLS-1$ { onEditManagementNetworkConfirmation(false); } else if (StringHelper.stringsEqual(command.getName(), "OnEditManagementNetworkConfirmation_Bond")) //$NON-NLS-1$ { onEditManagementNetworkConfirmation(true); } else if (StringHelper.stringsEqual(command.getName(), "OnBond")) //$NON-NLS-1$ { onBond(); } else if (StringHelper.stringsEqual(command.getName(), "OnDetach")) //$NON-NLS-1$ { onDetach(); } else if (StringHelper.stringsEqual(command.getName(), "OnConfirmManagementDetach")) //$NON-NLS-1$ { onConfirmManagementDetach(); } else if (StringHelper.stringsEqual(command.getName(), "Cancel")) //$NON-NLS-1$ { cancel(); } else if (StringHelper.stringsEqual(command.getName(), "CancelConfirm")) //$NON-NLS-1$ { cancelConfirm(); } else if (StringHelper.stringsEqual(command.getName(), "OnSaveNetworkConfig")) //$NON-NLS-1$ { onSaveNetworkConfig(); } } @Override protected String getListName() { return "HostInterfaceListModel"; //$NON-NLS-1$ } }
package org.hswebframework.web.authorization.basic.web; import org.hswebframework.web.authorization.listener.event.AuthorizationSuccessEvent; import org.hswebframework.web.authorization.token.UserToken; import org.hswebframework.web.authorization.token.UserTokenHolder; import org.hswebframework.web.authorization.token.UserTokenManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import java.util.ArrayList; import java.util.List; /** * ,,token{@link UserTokenManager} * * @author zhouhao * @see org.springframework.context.ApplicationEvent * @see org.hswebframework.web.authorization.listener.event.AuthorizationEvent * @see UserTokenManager * @see UserTokenGenerator * @since 3.0 */ public class UserOnSignIn implements ApplicationListener<AuthorizationSuccessEvent> { /** * * @see UserToken#getType() * @see SessionIdUserTokenGenerator#getSupportTokenType() */ private String defaultTokenType = "sessionId"; private UserTokenManager userTokenManager; private List<UserTokenGenerator> userTokenGenerators = new ArrayList<>(); public UserOnSignIn(UserTokenManager userTokenManager) { this.userTokenManager = userTokenManager; } public void setDefaultTokenType(String defaultTokenType) { this.defaultTokenType = defaultTokenType; } @Autowired(required = false) public void setUserTokenGenerators(List<UserTokenGenerator> userTokenGenerators) { this.userTokenGenerators = userTokenGenerators; } @Override public void onApplicationEvent(AuthorizationSuccessEvent event) { UserToken token = UserTokenHolder.currentToken(); String tokenType = (String) event.getParameter("token_type").orElse(defaultTokenType); if (token != null) { userTokenManager.signOutByToken(token.getToken()); } //token GeneratedToken newToken = userTokenGenerators.stream() .filter(generator -> generator.getSupportTokenType().equals(tokenType)) .findFirst() .orElseThrow(() -> new UnsupportedOperationException(tokenType)) .generate(event.getAuthentication()); userTokenManager.signIn(newToken.getToken(), newToken.getType(), event.getAuthentication().getUser().getId(), newToken.getTimeout()); event.getResult().putAll(newToken.getResponse()); } }
package org.innovateuk.ifs.registration.controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.innovateuk.ifs.commons.exception.ObjectNotFoundException; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.security.SecuredBySpring; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.controller.ValidationHandler; import org.innovateuk.ifs.exception.InviteAlreadyAcceptedException; import org.innovateuk.ifs.filter.CookieFlashMessageFilter; import org.innovateuk.ifs.invite.constant.InviteStatus; import org.innovateuk.ifs.invite.resource.ApplicationInviteResource; import org.innovateuk.ifs.invite.service.InviteRestService; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.project.invite.resource.SentProjectPartnerInviteResource; import org.innovateuk.ifs.project.invite.service.ProjectPartnerInviteRestService; import org.innovateuk.ifs.registration.form.InviteAndIdCookie; import org.innovateuk.ifs.registration.form.RegistrationForm; import org.innovateuk.ifs.registration.form.ResendEmailVerificationForm; import org.innovateuk.ifs.registration.service.RegistrationCookieService; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.service.OrganisationRestService; import org.innovateuk.ifs.user.service.UserRestService; import org.innovateuk.ifs.user.service.UserService; import org.innovateuk.ifs.util.EncryptedCookieService; import org.innovateuk.ifs.util.NavigationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.util.Optional; import static java.util.Collections.emptyList; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.controller.ErrorToObjectErrorConverterFactory.*; @Controller @RequestMapping("/registration") @SecuredBySpring(value = "Controller", description = "TODO", securedType = RegistrationController.class) @PreAuthorize("permitAll") public class RegistrationController { public static final String BASE_URL = "/registration/register"; public void setValidator(Validator validator) { this.validator = validator; } @Autowired @Qualifier("mvcValidator") private Validator validator; @Autowired private UserService userService; @Autowired private UserRestService userRestService; @Autowired private RegistrationCookieService registrationCookieService; @Autowired private EncryptedCookieService cookieUtil; @Autowired private OrganisationRestService organisationRestService; @Autowired private InviteRestService inviteRestService; @Autowired protected CookieFlashMessageFilter cookieFlashMessageFilter; @Autowired private NavigationUtils navigationUtils; @Autowired private ProjectPartnerInviteRestService projectPartnerInviteRestService; private static final Log LOG = LogFactory.getLog(RegistrationController.class); private final static String EMAIL_FIELD_NAME = "email"; @GetMapping("/success") public String registrationSuccessful(Model model, @RequestHeader(value = "referer", required = false) final String referer, final HttpServletRequest request, HttpServletResponse response) { model.addAttribute("isApplicantJourney", registrationCookieService.isApplicantJourney(request)); registrationCookieService.deleteInviteHashCookie(response); registrationCookieService.deleteProjectInviteHashCookie(response); if (referer == null || !referer.contains(request.getServerName() + "/registration/register")) { throw new ObjectNotFoundException("Attempt to access registration page directly...", emptyList()); } return "registration/successful"; } @GetMapping("/verified") public String verificationSuccessful(final HttpServletRequest request, final HttpServletResponse response) { if (!hasVerifiedCookieSet(request)) { throw new ObjectNotFoundException("Attempt to access registration page directly...", emptyList()); } else { cookieFlashMessageFilter.removeFlashMessage(response); return "registration/verified"; } } @GetMapping("/verify-email/{hash}") public String verifyEmailAddress(@PathVariable("hash") final String hash, final HttpServletResponse response) { userRestService.verifyEmail(hash).getSuccess(); cookieFlashMessageFilter.setFlashMessage(response, "verificationSuccessful"); return "redirect:/registration/verified"; } @GetMapping("/register") public String registerForm(@ModelAttribute("registrationForm") RegistrationForm registrationForm, Model model, UserResource user, HttpServletRequest request, HttpServletResponse response) { if (user != null) { return navigationUtils.getRedirectToLandingPageUrl(request); } if (getOrganisationId(request) == null) { return navigationUtils.getRedirectToLandingPageUrl(request); } try { addRegistrationFormToModel(registrationForm, model, request, response); } catch (InviteAlreadyAcceptedException e) { LOG.info("invite already accepted", e); cookieFlashMessageFilter.setFlashMessage(response, "inviteAlreadyAccepted"); return "redirect:/login"; } String destination = "registration/register"; if (!processOrganisation(request, model)) { destination = "redirect:/"; } return destination; } private boolean processOrganisation(HttpServletRequest request, Model model) { RestResult<OrganisationResource> result = organisationRestService.getOrganisationByIdForAnonymousUserFlow(getOrganisationId(request)); if (result.isSuccess()) { addOrganisationNameToModel(model, result.getSuccess()); return true; } return false; } private void addRegistrationFormToModel(RegistrationForm registrationForm, Model model, HttpServletRequest request, HttpServletResponse response) { setOrganisationIdCookie(request, response); setInviteeEmailAddress(registrationForm, request, model); model.addAttribute("registrationForm", registrationForm); } /** * When the current user is an invitee, use the invited email address in the registration flow. */ private boolean setInviteeEmailAddress(RegistrationForm registrationForm, HttpServletRequest request, Model model) { Optional<String> inviteHash = registrationCookieService.getInviteHashCookieValue(request); if (inviteHash.isPresent()) { RestResult<ApplicationInviteResource> invite = inviteRestService.getInviteByHash(inviteHash.get()); if (invite.isSuccess() && InviteStatus.SENT.equals(invite.getSuccess().getStatus())) { ApplicationInviteResource inviteResource = invite.getSuccess(); registrationForm.setEmail(inviteResource.getEmail()); model.addAttribute("invitee", true); return true; } else { LOG.debug("Invite already accepted."); throw new InviteAlreadyAcceptedException(); } } Optional<InviteAndIdCookie> projectInvite = registrationCookieService.getProjectInviteHashCookieValue(request); if (projectInvite.isPresent()) { RestResult<SentProjectPartnerInviteResource> invite = projectPartnerInviteRestService.getInviteByHash(projectInvite.get().getId(), projectInvite.get().getHash()); if (invite.isSuccess() && InviteStatus.SENT.equals(invite.getSuccess().getStatus())) { SentProjectPartnerInviteResource inviteResource = invite.getSuccess(); registrationForm.setEmail(inviteResource.getEmail()); model.addAttribute("invitee", true); return true; } else { LOG.debug("Invite already accepted."); throw new InviteAlreadyAcceptedException(); } } return false; } @PostMapping("/register") public String registerFormSubmit(@Valid @ModelAttribute("registrationForm") RegistrationForm registrationForm, BindingResult bindingResult, HttpServletResponse response, UserResource user, HttpServletRequest request, Model model) { try { if (setInviteeEmailAddress(registrationForm, request, model)) { bindingResult = new BeanPropertyBindingResult(registrationForm, "registrationForm"); validator.validate(registrationForm, bindingResult); } } catch (InviteAlreadyAcceptedException e) { LOG.info("invite already accepted", e); cookieFlashMessageFilter.setFlashMessage(response, "inviteAlreadyAccepted"); return "redirect:/login"; } checkForExistingEmail(registrationForm.getEmail(), bindingResult); model.addAttribute(BindingResult.MODEL_KEY_PREFIX + "registrationForm", bindingResult); ValidationHandler validationHandler = ValidationHandler.newBindingResultHandler(bindingResult); return validationHandler.failNowOrSucceedWith( () -> registerForm(registrationForm, model, user, request, response), () -> createUser(registrationForm, getOrganisationId(request), getCompetitionId(request)).handleSuccessOrFailure( failure -> { validationHandler.addAnyErrors(failure, fieldErrorsToFieldErrors( e -> newFieldError(e, e.getFieldName(), e.getFieldRejectedValue(), "registration." + e.getErrorKey()) ), asGlobalErrors() ); return registerForm(registrationForm, model, user, request, response); }, userResource -> acceptInvite(request, userResource).handleSuccessOrFailure( failure -> { removeCompetitionIdCookie(response); registrationCookieService.deleteOrganisationIdCookie(response); if (failure.getErrors().stream().anyMatch( error -> error.getErrorKey().equals("ORGANISATION_ALREADY_EXISTS_FOR_PROJECT"))) { return "redirect:/registration/duplicate-project-organisation"; } validationHandler.addAnyErrors(failure, fieldErrorsToFieldErrors( e -> newFieldError(e, e.getFieldName(), e.getFieldRejectedValue(), "registration." + e.getErrorKey()) ), asGlobalErrors() ); return registerForm(registrationForm, model, user, request, response); }, success -> { removeCompetitionIdCookie(response); registrationCookieService.deleteOrganisationIdCookie(response); return "redirect:/registration/success"; }))); } @GetMapping("/duplicate-project-organisation") public String displayErrorPage(HttpServletRequest request, Model model) { InviteAndIdCookie projectInvite = registrationCookieService.getProjectInviteHashCookieValue(request).get(); SentProjectPartnerInviteResource invite = projectPartnerInviteRestService.getInviteByHash(projectInvite.getId(), projectInvite.getHash()).getSuccess(); model.addAttribute("model", invite); return "registration/duplicate-organisation-error"; } @GetMapping("/resend-email-verification") public String resendEmailVerification(final ResendEmailVerificationForm resendEmailVerificationForm, final Model model) { model.addAttribute("resendEmailVerificationForm", resendEmailVerificationForm); return "registration/resend-email-verification"; } @PostMapping("/resend-email-verification") public String resendEmailVerification(@Valid final ResendEmailVerificationForm resendEmailVerificationForm, final BindingResult bindingResult, final Model model) { if (bindingResult.hasErrors()) { model.addAttribute("resendEmailVerificationForm", resendEmailVerificationForm); return "registration/resend-email-verification"; } userService.resendEmailVerificationNotification(resendEmailVerificationForm.getEmail()); return "registration/resend-email-verification-send"; } private void removeCompetitionIdCookie(HttpServletResponse response) { registrationCookieService.deleteCompetitionIdCookie(response); } private Long getCompetitionId(HttpServletRequest request) { return registrationCookieService.getCompetitionIdCookieValue(request).orElse(null); } private ServiceResult<Void> acceptInvite(HttpServletRequest request, UserResource userResource) { Optional<String> inviteHash = registrationCookieService.getInviteHashCookieValue(request); if (inviteHash.isPresent()) { Optional<Long> organisationId = registrationCookieService.getOrganisationIdCookieValue(request); return inviteRestService.acceptInvite(inviteHash.get(), userResource.getId(), organisationId.get()).toServiceResult(); } Optional<InviteAndIdCookie> projectInvite = registrationCookieService.getProjectInviteHashCookieValue(request); if (projectInvite.isPresent()) { SentProjectPartnerInviteResource invite = projectPartnerInviteRestService.getInviteByHash(projectInvite.get().getId(), projectInvite.get().getHash()).getSuccess(); Optional<Long> organisationId = registrationCookieService.getOrganisationIdCookieValue(request); return projectPartnerInviteRestService.acceptInvite(projectInvite.get().getId(), invite.getId(), organisationId.get()).toServiceResult(); } return serviceSuccess(); } private void checkForExistingEmail(String email, BindingResult bindingResult) { if (!bindingResult.hasFieldErrors(EMAIL_FIELD_NAME) && StringUtils.hasText(email)) { Optional<UserResource> existingUserSearch = userService.findUserByEmail(email); if (existingUserSearch.isPresent()) { bindingResult.rejectValue(EMAIL_FIELD_NAME, "validation.standard.email.exists"); } } } private ServiceResult<UserResource> createUser(RegistrationForm registrationForm, Long organisationId, Long competitionId) { return userService.createLeadApplicantForOrganisationWithCompetitionId( registrationForm.getFirstName(), registrationForm.getLastName(), registrationForm.getPassword(), registrationForm.getEmail(), registrationForm.getTitle(), registrationForm.getPhoneNumber(), organisationId, competitionId, registrationForm.getAllowMarketingEmails()); } private void addOrganisationNameToModel(Model model, OrganisationResource organisation) { model.addAttribute("organisationName", organisation.getName()); } private Long getOrganisationId(HttpServletRequest request) { return registrationCookieService.getOrganisationIdCookieValue(request).orElse(null); } private void setOrganisationIdCookie(HttpServletRequest request, HttpServletResponse response) { Long organisationId = getOrganisationId(request); if (organisationId != null) { registrationCookieService.saveToOrganisationIdCookie(organisationId, response); } } private boolean hasVerifiedCookieSet(final HttpServletRequest request) { final Optional<Cookie> cookie = cookieUtil.getCookie(request, CookieFlashMessageFilter.COOKIE_NAME); return cookie.isPresent() && cookieUtil.getCookieValue(request, CookieFlashMessageFilter.COOKIE_NAME).equals("verificationSuccessful"); } }
package com.googlecode.mp4parser.boxes.mp4.samplegrouping; import com.coremedia.iso.boxes.Box; import com.googlecode.mp4parser.boxes.BoxRoundtripTest; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.UUID; public class CencSampleEncryptionInformationGroupEntryTest extends BoxRoundtripTest { public CencSampleEncryptionInformationGroupEntryTest(Box boxUnderTest, Map.Entry<String, Object>... properties) { super(boxUnderTest, properties); } @Parameterized.Parameters public static Collection<Object[]> data() { CencSampleEncryptionInformationGroupEntry seig1 = new CencSampleEncryptionInformationGroupEntry(); seig1.setEncrypted(true); seig1.setKid(UUID.randomUUID()); seig1.setIvSize(8); CencSampleEncryptionInformationGroupEntry seig2 = new CencSampleEncryptionInformationGroupEntry(); seig2.setEncrypted(false); seig2.setKid(UUID.fromString("00000000-0000-0000-0000-000000000000")); return Arrays.asList( new Object[]{new SampleGroupDescriptionBox(), new Map.Entry[]{ new E("groupEntries", Arrays.asList(seig1))}}, new Object[]{new SampleGroupDescriptionBox(), new Map.Entry[]{ new E("groupEntries", Arrays.asList(seig1, seig2)) }}, new Object[]{new SampleGroupDescriptionBox(), new Map.Entry[]{ new E("groupEntries", Arrays.asList(seig2))}}); } }
package io.subutai.core.hubmanager.impl; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.net.util.SubnetUtils; import com.google.common.collect.Sets; import io.subutai.common.command.CommandResult; import io.subutai.common.command.CommandUtil; import io.subutai.common.command.RequestBuilder; import io.subutai.common.environment.CreateEnvironmentContainerGroupRequest; import io.subutai.common.environment.CreateEnvironmentContainerResponseCollector; import io.subutai.common.environment.Node; import io.subutai.common.environment.PrepareTemplatesResponseCollector; import io.subutai.common.host.HostArchitecture; import io.subutai.common.host.HostInterface; import io.subutai.common.host.HostInterfaceModel; import io.subutai.common.network.Gateway; import io.subutai.common.network.Gateways; import io.subutai.common.network.Vni; import io.subutai.common.network.Vnis; import io.subutai.common.peer.ContainerSize; import io.subutai.common.peer.EnvironmentId; import io.subutai.common.peer.Host; import io.subutai.common.peer.HostNotFoundException; import io.subutai.common.peer.LocalPeer; import io.subutai.common.peer.Peer; import io.subutai.common.peer.PeerException; import io.subutai.common.protocol.P2PConfig; import io.subutai.common.settings.Common; import io.subutai.common.task.CloneRequest; import io.subutai.common.task.CloneResponse; import io.subutai.common.util.P2PUtil; import io.subutai.core.environment.api.EnvironmentManager; import io.subutai.core.environment.api.exception.EnvironmentManagerException; import io.subutai.core.identity.api.IdentityManager; import io.subutai.core.network.api.NetworkManager; import io.subutai.core.peer.api.PeerManager; import io.subutai.core.security.api.SecurityManager; import io.subutai.hub.share.dto.PublicKeyContainer; import io.subutai.hub.share.dto.environment.ContainerStateDto; import io.subutai.hub.share.dto.environment.EnvironmentDto; import io.subutai.hub.share.dto.environment.EnvironmentInfoDto; import io.subutai.hub.share.dto.environment.EnvironmentNodeDto; import io.subutai.hub.share.dto.environment.EnvironmentNodesDto; import io.subutai.hub.share.dto.environment.EnvironmentPeerDto; import io.subutai.hub.share.dto.environment.SSHKeyDto; public class HubEnvironmentManager { private static final Logger LOG = LoggerFactory.getLogger( HubEnvironmentManager.class.getName() ); private static final String MANAGEMENT_HOST_NETWORK_BINDING = "subutai management_network"; private static final String MANAGEMENT_PROXY_BINDING = "subutai proxy"; private static final String SSH_FOLDER = "/root/.ssh"; private static final String SSH_FILE = String.format( "%s/authorized_keys", SSH_FOLDER ); protected CommandUtil commandUtil = new CommandUtil(); private SecurityManager securityManager; private PeerManager peerManager; private ConfigManager configManager; private IdentityManager identityManager; private EnvironmentManager environmentManager; private NetworkManager networkManager; public HubEnvironmentManager( final EnvironmentManager environmentManager, final ConfigManager hConfigManager, final PeerManager peerManager, final IdentityManager identityManager, final NetworkManager networkManager ) { this.environmentManager = environmentManager; this.configManager = hConfigManager; this.peerManager = peerManager; this.identityManager = identityManager; this.networkManager = networkManager; } public Set<Long> getReservedVnis() { Set<Long> vniDtos = new HashSet<>(); try { Vnis vnis = peerManager.getLocalPeer().getReservedVnis(); for ( Vni vni : vnis.list() ) { vniDtos.add( vni.getVni() ); } return vniDtos; } catch ( PeerException e ) { LOG.error( "Could not get local peer reserved vnis" ); } return null; } public Set<String> getTunnelNetworks() { Set<String> usedInterfaces = new HashSet<>(); try { Set<HostInterfaceModel> r = peerManager.getLocalPeer().getInterfaces().filterByIp( P2PUtil.P2P_INTERFACE_IP_PATTERN ); Collection tunnels = CollectionUtils.collect( r, new Transformer() { @Override public Object transform( final Object o ) { HostInterface i = ( HostInterface ) o; SubnetUtils u = new SubnetUtils( i.getIp(), P2PUtil.P2P_SUBNET_MASK ); return u.getInfo().getNetworkAddress(); } } ); usedInterfaces.addAll( tunnels ); return usedInterfaces; } catch ( PeerException e ) { LOG.error( "Could not get local peer used interfaces" ); } return null; } public Set<String> getReservedGateways() { Set<String> gatewayDtos = new HashSet<>(); try { Gateways gateways = peerManager.getLocalPeer().getGateways(); for ( Gateway gateway : gateways.list() ) { gatewayDtos.add( gateway.getIp() ); } return gatewayDtos; } catch ( PeerException e ) { LOG.error( "Could not get local peer used interfaces" ); } return null; } public PublicKeyContainer createPeerEnvironmentKeyPair( EnvironmentId environmentId ) { try { io.subutai.common.security.PublicKeyContainer publicKeyContainer = peerManager.getLocalPeer().createPeerEnvironmentKeyPair( environmentId ); PublicKeyContainer keyContainer = new PublicKeyContainer(); keyContainer.setKey( publicKeyContainer.getKey() ); keyContainer.setHostId( publicKeyContainer.getHostId() ); keyContainer.setFingerprint( publicKeyContainer.getFingerprint() ); return keyContainer; } catch ( PeerException e ) { LOG.error( "Could not create local peer PEK" ); } return null; } public void setupVNI( EnvironmentPeerDto peerDto ) { try { Vni vni = new Vni( peerDto.getEnvironmentInfo().getVni(), peerDto.getEnvironmentInfo().getId() ); peerManager.getLocalPeer().reserveVni( vni ); } catch ( PeerException e ) { LOG.error( "Could not setup VNI", e.getMessage() ); } } public EnvironmentPeerDto setupP2P( EnvironmentPeerDto peerDto ) { LocalPeer localPeer = peerManager.getLocalPeer(); EnvironmentInfoDto env = peerDto.getEnvironmentInfo(); SubnetUtils.SubnetInfo subnetInfo = new SubnetUtils( peerDto.getEnvironmentInfo().getTunnelNetwork(), P2PUtil.P2P_SUBNET_MASK ).getInfo(); final String[] addresses = subnetInfo.getAllAddresses(); try { localPeer.setupInitialP2PConnection( new P2PConfig( localPeer.getId(), env.getId(), env.getP2pHash(), addresses[0], env.getP2pKey(), env.getP2pTTL() ) ); } catch ( PeerException e ) { LOG.error( "Could not setup initial p2p participant on local peer MH with explicit IP", e ); } ExecutorService p2pExecutor = Executors.newSingleThreadExecutor(); ExecutorCompletionService<P2PConfig> p2pCompletionService = new ExecutorCompletionService<>( p2pExecutor ); P2PConfig config = new P2PConfig( localPeer.getId(), env.getId(), env.getP2pHash(), addresses[1], env.getP2pKey(), env.getP2pTTL() ); p2pCompletionService.submit( new SetupP2PConnectionTask( localPeer, config ) ); try { final Future<P2PConfig> f = p2pCompletionService.take(); P2PConfig createdConfig = f.get(); p2pExecutor.shutdown(); peerDto.setTunnelAddress( createdConfig.getAddress() ); peerDto.setCommunityName( createdConfig.getHash() ); peerDto.setP2pSecretKey( createdConfig.getSecretKey() ); } catch ( ExecutionException | InterruptedException e ) { LOG.error( "Problems setting up p2p connection", e ); } return peerDto; } public void setupTunnel( EnvironmentDto environmentDto ) throws InterruptedException, ExecutionException { LocalPeer localPeer = peerManager.getLocalPeer(); Map<String, String> tunnels = new HashMap<>(); for ( EnvironmentPeerDto peerDto : environmentDto.getPeers() ) { if ( !peerDto.getPeerId().equals( localPeer.getId() ) ) { tunnels.put( peerDto.getPeerId(), peerDto.getTunnelAddress() ); } } if ( !tunnels.isEmpty() ) { ExecutorService tunnelExecutor = Executors.newSingleThreadExecutor(); ExecutorCompletionService<Integer> tunnelCompletionService = new ExecutorCompletionService<Integer>( tunnelExecutor ); tunnelCompletionService.submit( new SetupTunnelTask( localPeer, environmentDto.getId(), tunnels ) ); final Future<Integer> f = tunnelCompletionService.take(); f.get(); tunnelExecutor.shutdown(); } } public void prepareTemplates( EnvironmentPeerDto peerDto, EnvironmentNodesDto nodesDto ) { Set<Node> nodes = new HashSet<>(); for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() ) { ContainerSize contSize = ContainerSize.valueOf( ContainerSize.class, nodeDto.getContainerSize() ); Node node = new Node( nodeDto.getHostName(), nodeDto.getContainerName(), nodeDto.getTemplateName(), contSize, 0, 0, peerDto.getPeerId(), nodeDto.getHostId() ); nodes.add( node ); } ExecutorService taskExecutor = Executors.newSingleThreadExecutor(); CompletionService<PrepareTemplatesResponseCollector> taskCompletionService = getCompletionService( taskExecutor ); LOG.debug( String.format( "Preparing templates on peer %s", peerManager.getLocalPeer().getId() ) ); taskCompletionService.submit( new CreatePeerTemplatePrepareTask( peerManager.getLocalPeer(), nodes ) ); taskExecutor.shutdown(); try { Future<PrepareTemplatesResponseCollector> futures = taskCompletionService.take(); final PrepareTemplatesResponseCollector prepareTemplatesResponse = futures.get(); if ( !prepareTemplatesResponse.hasSucceeded() ) { LOG.error( "There were errors during preparation of templates on peer " + prepareTemplatesResponse .getPeerId() ); } } catch ( Exception e ) { LOG.error( "There were errors during preparation templates. Unexpected error.", e.getMessage() ); } } public EnvironmentNodesDto cloneContainers( EnvironmentPeerDto peerDto, EnvironmentNodesDto envNodes ) { try { CreateEnvironmentContainerGroupRequest containerGroupRequest = new CreateEnvironmentContainerGroupRequest( peerDto.getEnvironmentInfo().getId() ); for ( EnvironmentNodeDto nodeDto : envNodes.getNodes() ) { if ( nodeDto.getState().equals( ContainerStateDto.STARTING ) ) { ContainerSize contSize = ContainerSize.valueOf( ContainerSize.class, nodeDto.getContainerSize() ); try { CloneRequest cloneRequest = new CloneRequest( nodeDto.getHostId(), nodeDto.getHostName(), nodeDto.getContainerName(), nodeDto.getIp(), peerDto.getEnvironmentInfo().getId(), peerDto.getPeerId(), peerDto.getOwnerId(), nodeDto.getTemplateName(), HostArchitecture.AMD64, contSize ); containerGroupRequest.addRequest( cloneRequest ); } catch ( Exception e ) { LOG.error( "Could not create container clone request", e.getMessage() ); } } } final CreateEnvironmentContainerResponseCollector containerCollector = peerManager.getLocalPeer().createEnvironmentContainerGroup( containerGroupRequest ); List<CloneResponse> cloneResponseList = containerCollector.getResponses(); for ( CloneResponse cloneResponse : cloneResponseList ) { for ( EnvironmentNodeDto nodeDto : envNodes.getNodes() ) { if ( cloneResponse.getHostname().equals( nodeDto.getHostName() ) ) { nodeDto.setIp( cloneResponse.getIp() ); nodeDto.setTemplateArch( cloneResponse.getTemplateArch().name() ); nodeDto.setContainerId( cloneResponse.getContainerId() ); nodeDto.setElapsedTime( cloneResponse.getElapsedTime() ); } } } } catch ( PeerException e ) { LOG.error( "Could not clone containers" ); } return envNodes; } public void configureSsh( EnvironmentPeerDto peerDto, EnvironmentDto envDto ) throws EnvironmentManagerException { EnvironmentInfoDto env = peerDto.getEnvironmentInfo(); Set<String> sshKeys = new HashSet<>(); for ( SSHKeyDto sshKeyDto : env.getSshKeys() ) { sshKeys.add( sshKeyDto.getSshKey() ); } Set<Host> hosts = getLocalPeerHosts( envDto ); addSshKeys( hosts, sshKeys ); Set<Host> succeededHosts = Sets.newHashSet(); Set<Host> failedHosts = Sets.newHashSet( hosts ); Map<Host, CommandResult> results = commandUtil.executeParallelSilent( getConfigSSHCommand(), hosts ); for ( Map.Entry<Host, CommandResult> resultEntry : results.entrySet() ) { CommandResult result = resultEntry.getValue(); Host host = resultEntry.getKey(); if ( result.hasSucceeded() ) { succeededHosts.add( host ); } } failedHosts.removeAll( succeededHosts ); for ( Host failedHost : failedHosts ) { LOG.error( String.format( "Failed to configure ssh on host %s", failedHost.getHostname() ) ); } if ( !failedHosts.isEmpty() ) { throw new EnvironmentManagerException( "Failed to configure ssh on all hosts" ); } } public void configureHash( EnvironmentDto envDto ) throws EnvironmentManagerException { Set<Host> hosts = getLocalPeerHosts( envDto ); Map<Host, CommandResult> results = commandUtil .executeParallelSilent( getAddIpHostToEtcHostsCommand( Common.DEFAULT_DOMAIN_NAME, hosts ), hosts ); Set<Host> succeededHosts = Sets.newHashSet(); for ( Map.Entry<Host, CommandResult> resultEntry : results.entrySet() ) { CommandResult result = resultEntry.getValue(); Host host = resultEntry.getKey(); if ( result.hasSucceeded() ) { succeededHosts.add( host ); } else { LOG.debug( String.format( "Error: %s, Exit Code %d", result.getStdErr(), result.getExitCode() ) ); } } hosts.removeAll( succeededHosts ); for ( Host failedHost : hosts ) { LOG.error( String.format( "Host registration failed on host %s", failedHost.getHostname() ) ); } if ( !hosts.isEmpty() ) { throw new EnvironmentManagerException( "Failed to register all hosts" ); } } private Set<Host> getLocalPeerHosts( EnvironmentDto envDto ) { LocalPeer localPeer = peerManager.getLocalPeer(); Set<Host> hosts = Sets.newHashSet(); for ( EnvironmentNodesDto nodesDto : envDto.getNodes() ) { if ( nodesDto.getPeerId().equals( localPeer.getId() ) ) { for ( EnvironmentNodeDto nodeDto : nodesDto.getNodes() ) { try { hosts.add( localPeer.getContainerHostById( nodeDto.getHostId() ) ); } catch ( HostNotFoundException e ) { LOG.error( "Could not get Host: " + nodeDto.getHostId() ); } } } } return hosts; } protected void addSshKeys( Set<Host> hosts, Set<String> keys ) throws EnvironmentManagerException { //send key in portions, since all can not fit into one command, it fails int i = 0; StringBuilder keysString = new StringBuilder(); for ( String key : keys ) { keysString.append( key ); i++; //send next 5 keys if ( i % 5 == 0 || i == keys.size() ) { Set<Host> succeededHosts = Sets.newHashSet(); Set<Host> failedHosts = Sets.newHashSet( hosts ); Map<Host, CommandResult> results = commandUtil.executeParallelSilent( getAppendSshKeysCommand( keysString.toString() ), hosts ); keysString.setLength( 0 ); for ( Map.Entry<Host, CommandResult> resultEntry : results.entrySet() ) { CommandResult result = resultEntry.getValue(); Host host = resultEntry.getKey(); if ( result.hasSucceeded() ) { succeededHosts.add( host ); } } failedHosts.removeAll( succeededHosts ); for ( Host failedHost : failedHosts ) { LOG.error( String.format( "Failed to add ssh keys on host %s", failedHost.getHostname() ) ); } if ( !failedHosts.isEmpty() ) { throw new EnvironmentManagerException( "Failed to add ssh keys on all hosts" ); } } } } public RequestBuilder getAppendSshKeysCommand( String keys ) { return new RequestBuilder( String.format( "mkdir -p %1$s && " + "chmod 700 %1$s && " + "echo '%3$s' >> %2$s && " + "chmod 644 %2$s", Common.CONTAINER_SSH_FOLDER, Common.CONTAINER_SSH_FILE, keys ) ); } public RequestBuilder getConfigSSHCommand() { return new RequestBuilder( String.format( "echo 'Host *' > %1$s/config && " + "echo ' StrictHostKeyChecking no' >> %1$s/config && " + "chmod 644 %1$s/config", Common.CONTAINER_SSH_FOLDER ) ); } public RequestBuilder getAddIpHostToEtcHostsCommand( String domainName, Set<Host> containerHosts ) { StringBuilder cleanHosts = new StringBuilder( "localhost|127.0.0.1|" ); StringBuilder appendHosts = new StringBuilder(); for ( Host host : containerHosts ) { String ip = host.getInterfaceByName( Common.DEFAULT_CONTAINER_INTERFACE ).getIp(); String hostname = host.getHostname(); cleanHosts.append( ip ).append( "|" ).append( hostname ).append( "|" ); appendHosts.append( "/bin/echo '" ). append( ip ).append( " " ). append( hostname ).append( "." ).append( domainName ). append( " " ).append( hostname ). append( "' >> '/etc/hosts'; " ); } if ( cleanHosts.length() > 0 ) { //drop pipe | symbol cleanHosts.setLength( cleanHosts.length() - 1 ); cleanHosts.insert( 0, "egrep -v '" ); cleanHosts.append( "' /etc/hosts > etc-hosts-cleaned; mv etc-hosts-cleaned /etc/hosts;" ); appendHosts.insert( 0, cleanHosts ); } appendHosts.append( "/bin/echo '127.0.0.1 localhost " ).append( "' >> '/etc/hosts';" ); return new RequestBuilder( appendHosts.toString() ); } private class SetupP2PConnectionTask implements Callable<P2PConfig> { private Peer peer; private P2PConfig p2PConfig; public SetupP2PConnectionTask( final Peer peer, final P2PConfig config ) { this.peer = peer; this.p2PConfig = config; } @Override public P2PConfig call() throws Exception { p2PConfig.setAddress( peer.setupP2PConnection( p2PConfig ) ); return p2PConfig; } } private class SetupTunnelTask implements Callable<Integer> { private final Peer peer; private final String environmentId; private final Map<String, String> tunnels; public SetupTunnelTask( final Peer peer, final String environmentId, final Map<String, String> tunnels ) { this.peer = peer; this.environmentId = environmentId; this.tunnels = tunnels; } @Override public Integer call() throws Exception { return peer.setupTunnels( tunnels, environmentId ); } } protected CompletionService<PrepareTemplatesResponseCollector> getCompletionService( Executor executor ) { return new ExecutorCompletionService<>( executor ); } }
package org.opennms.netmgt.provision.service.dns; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.bind.JAXBException; import org.apache.commons.io.IOExceptionWithCause; import org.apache.commons.lang.StringUtils; import org.opennms.core.utils.LogUtils; import org.opennms.core.utils.ThreadCategory; import org.opennms.core.xml.JaxbUtils; import org.opennms.netmgt.provision.persist.requisition.Requisition; import org.opennms.netmgt.provision.persist.requisition.RequisitionInterface; import org.opennms.netmgt.provision.persist.requisition.RequisitionMonitoredService; import org.opennms.netmgt.provision.persist.requisition.RequisitionNode; import org.xbill.DNS.ARecord; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.TSIG; import org.xbill.DNS.Type; import org.xbill.DNS.ZoneTransferException; import org.xbill.DNS.ZoneTransferIn; /** * Implementation of <code>java.net.URLConnection</code> for handling * URLs specified in the Provisiond configuration requesting an import * requisition based on the A records of a zone transfer for a DNS server. * * @author <a href="mailto:david@opennms.org">David Hustace</a> * @version $Id: $ */ public class DnsRequisitionUrlConnection extends URLConnection { private static final String EXPRESSION_ARG = "expression"; private static final String SERVICES_ARG = "services"; private static final String QUERY_ARG_SEPARATOR = "&"; /** Constant <code>URL_SCHEME="dns://"</code> */ public static final String URL_SCHEME = "dns: /** Constant <code>PROTOCOL="dns"</code> */ public static final String PROTOCOL = "dns"; private String m_zone; //TODO implement this private Long m_serial; //TODO implement this private Boolean m_fallback; //TODO implement this private TSIG m_key; private URL m_url; private int m_port; private String m_foreignSource; private static Map<String, String> m_args; /** * <p>Constructor for DnsRequisitionUrlConnection.</p> * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected DnsRequisitionUrlConnection(URL url) throws MalformedURLException { super(url); m_args = getUrlArgs(url); validateDnsUrl(url); m_url = url; m_port = url.getPort() == -1 ? 53 : url.getPort(); m_zone = parseZone(url); m_foreignSource = parseForeignSource(url); if (m_zone == null) { throw new IllegalArgumentException("Specified Zone is null"); } m_serial = Long.valueOf(0L); m_fallback = Boolean.FALSE; m_key = null; } /** * {@inheritDoc} * * This is a no op. */ @Override public void connect() throws IOException { } /** * {@inheritDoc} * * Creates a ByteArrayInputStream implementation of InputStream of the XML marshaled version * of the Requisition class. Calling close on this stream is safe. */ @Override public InputStream getInputStream() throws IOException { InputStream stream = null; try { Requisition r = buildRequisitionFromZoneTransfer(); stream = new ByteArrayInputStream(jaxBMarshal(r).getBytes()); } catch (IOException e) { log().warn("getInputStream: Problem getting input stream: "+e, e); throw e; } catch (Throwable e) { String message = "Problem getting input stream: "+e; log().warn(message, e); throw new IOExceptionWithCause(message,e ); } return stream; } /** * Builds a Requisition based on the A records returned in a zone transfer from the * specified zone. * * @return an instance of the JaxB annotated Requistion class than can be marshaled * into the XML and streamed to the Provisioner * * @throws IOException * @throws ZoneTransferException */ private Requisition buildRequisitionFromZoneTransfer() throws IOException, ZoneTransferException { ZoneTransferIn xfer = null; List<Record> records = null; LogUtils.debugf(this, "connecting to host %s:%d", m_url.getHost(), m_port); try { xfer = ZoneTransferIn.newIXFR(new Name(m_zone), m_serial.longValue(), m_fallback.booleanValue(), m_url.getHost(), m_port, m_key); records = getRecords(xfer); } catch (ZoneTransferException e) // Fallbacking to AXFR { String message = "IXFR not supported trying AXFR: "+e; log().warn(message, e); xfer = ZoneTransferIn.newAXFR(new Name(m_zone), m_url.getHost(), m_key); records = getRecords(xfer); } Requisition r = null; if (records.size() > 0) { //for now, set the foreign source to the specified dns zone r = new Requisition(getForeignSource()); for (Record rec : records) { if (matchingRecord(rec)) { r.insertNode(createRequisitionNode(rec)); } } } return r; } @SuppressWarnings("unchecked") private List<Record> getRecords(ZoneTransferIn xfer) throws IOException, ZoneTransferException { return (List<Record>) xfer.run(); } /** * Creates an instance of the JaxB annotated RequisionNode class. * * @param rec * @return a populated RequisitionNode based on defaults and data from the * A record returned from a DNS zone transfer query. */ private RequisitionNode createRequisitionNode(Record rec) { ARecord arec = (ARecord)rec; String addr = StringUtils.stripStart(arec.getAddress().toString(), "/"); RequisitionNode n = new RequisitionNode(); String host = rec.getName().toString(); String nodeLabel = StringUtils.stripStart(host, "."); n.setBuilding(getForeignSource()); n.setForeignId(computeHashCode(nodeLabel)); n.setNodeLabel(nodeLabel); RequisitionInterface i = new RequisitionInterface(); i.setDescr("DNS-A"); i.setIpAddr(addr); i.setSnmpPrimary("P"); i.setManaged(Boolean.TRUE); i.setStatus(Integer.valueOf(1)); // TODO validate services against service table of database if (getArgs() != null && getArgs().get(SERVICES_ARG) != null) { String[] services = getArgs().get(SERVICES_ARG).split(","); for (String service : services) { service = service.trim(); i.insertMonitoredService(new RequisitionMonitoredService(service)); log().debug("Adding provisioned service " + service); } } else { i.insertMonitoredService(new RequisitionMonitoredService("ICMP")); i.insertMonitoredService(new RequisitionMonitoredService("SNMP")); log().debug("Adding default provisioned services ICMP and SNMP"); } n.putInterface(i); return n; } /** * Determines if the record is an A record and if the canonical name * matches the expression supplied in the URL, if one was supplied. * * @param rec * @return boolean if rec should be included in the import requisition */ private boolean matchingRecord(Record rec) { log().info("matchingRecord: checking rec: "+rec+" to see if it should be imported..."); boolean matches = false; if ("A".equals(Type.string(rec.getType()))) { log().debug("matchingRecord: record is a an A record, continuing..."); String expression = determineExpressionFromUrl(getUrl()); if (expression != null) { Pattern p = Pattern.compile(expression); Matcher m = p.matcher(rec.getName().toString()); // Try matching on host name only for backwards compatibility log().debug("matchingRecord: attempting to match hostname: ["+rec.getName().toString()+"] with expression: ["+expression+"]"); if (m.matches()) { matches = true; } else { // include the IP address and try again log().debug("matchingRecord: attempting to match record: ["+rec.getName().toString() +" "+rec.rdataToString()+"] with expression: ["+expression+"]"); m = p.matcher(rec.getName().toString() + " " + rec.rdataToString()); if (m.matches()) { matches = true; } } log().debug("matchingRecord: record matches expression: "+matches); } else { log().debug("matchingRecord: on expression for this zone, returning valid match for this A record..."); matches = true; } } log().info("matchingRecord: record: "+rec+" matches: "+matches); return matches; } /** * Created this in the case that we decide to every do something different with the hashing * to have a lesser likely hood of duplicate foreign ids * @param nodeLabel * @return */ private String computeHashCode(String nodeLabel) { String hash = String.valueOf(nodeLabel.hashCode()); return hash; } /** * Utility to marshal the Requisition class into XML. * * @param r * @return a String of XML encoding the Requisition class * * @throws JAXBException */ private String jaxBMarshal(Requisition r) throws JAXBException { return JaxbUtils.marshal(r); } /** * <p>getZone</p> * * @return a {@link java.lang.String} object. */ public String getZone() { return m_zone; } /** * <p>getSerial</p> * * @return a {@link java.lang.Long} object. */ public Long getSerial() { return m_serial; } /** * <p>setSerial</p> * * @param serial a {@link java.lang.Long} object. */ public void setSerial(Long serial) { m_serial = serial; } /** * <p>getFallback</p> * * @return a {@link java.lang.Boolean} object. */ public Boolean getFallback() { return m_fallback; } /** * <p>setFallback</p> * * @param fallback a {@link java.lang.Boolean} object. */ public void setFallback(Boolean fallback) { m_fallback = fallback; } /** * <p>getKey</p> * * @return a {@link org.xbill.DNS.TSIG} object. */ public TSIG getKey() { return m_key; } /** * <p>setKey</p> * * @param key a {@link org.xbill.DNS.TSIG} object. */ public void setKey(TSIG key) { m_key = key; } /** * <p>getDescription</p> * * @return a {@link java.lang.String} object. */ public String getDescription() { return m_url.toString(); } /** * <p>toString</p> * * @return a {@link java.lang.String} object. */ public String toString() { return getDescription(); } /** * <p>getUrl</p> * * @return a {@link java.net.URL} object. */ public URL getUrl() { return m_url; } public static Map<String, String> getArgs() { return m_args; } /** * <p>determineExpressionFromUrl</p> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String determineExpressionFromUrl(URL url) { log().info("determineExpressionFromUrl: finding regex as parameter in query string of URL: "+url); if(getUrlArgs(url) == null) { return null; } else { return getUrlArgs(url).get(EXPRESSION_ARG); } } private static List<String> tokenizeQueryArgs(String query) throws IllegalArgumentException { if (query == null) { throw new IllegalArgumentException("The URL query is null"); } List<String> queryArgs = Arrays.asList(StringUtils.split(query, QUERY_ARG_SEPARATOR)); return queryArgs; } /** * <p>decodeQueryString</p> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String decodeQueryString(URL url) { if (url == null || url.getQuery() == null) { throw new IllegalArgumentException("The URL or the URL query is null: "+url); } String query = null; try { query = URLDecoder.decode(url.getQuery(), "UTF-8"); } catch (UnsupportedEncodingException e) { log().error("decodeQueryString: "+e, e); } return query; } /** * Validate the format is: * dns://<host>/<zone>/?expression=<regex> * * there should be only one arguement in the path * there should only be one query parameter * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected static void validateDnsUrl(URL url) throws MalformedURLException { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); if (path == null || StringUtils.countMatches(path, "/") > 1) { throw new MalformedURLException("The specified DNS URL contains invalid path: "+url); } String query = url.getQuery(); if ((query != null) && (determineExpressionFromUrl(url) == null) && (getArgs().get(SERVICES_ARG) == null)) { throw new MalformedURLException("The specified DNS URL contains an invalid query string: "+url); } } /** * Zone should be the first path entity * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseZone(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String zone = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); zone = paths[0]; } return zone; } /** * Foreign Source should be the second path entity, if it exists, otherwise it is * set to the value of the zone. * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseForeignSource(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String foreignSource = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); foreignSource = paths[1]; } return foreignSource; } protected static Map<String, String> getUrlArgs(URL url) { if (url.getQuery() == null) { return null; } //TODO: need to throw exception if query is null String query = decodeQueryString(url); //TODO: need to handle exception List<String> queryArgs = tokenizeQueryArgs(query); Map<String, String> args = new HashMap<String, String>(); for (String queryArg : queryArgs) { String[] argTokens = StringUtils.split(queryArg, '='); if (argTokens.length < 2) { log().warn("getUrlArgs: syntax error in URL query string, missing '=' in query argument: "+queryArg); } else { log().debug("adding arg tokens " + argTokens[0].toLowerCase() + ", " + argTokens[1]); args.put(argTokens[0].toLowerCase(), argTokens[1]); } } return args; } private static ThreadCategory log() { return ThreadCategory.getInstance(DnsRequisitionUrlConnection.class); } /** * <p>setForeignSource</p> * * @param foreignSource a {@link java.lang.String} object. */ public void setForeignSource(String foreignSource) { m_foreignSource = foreignSource; } /** * <p>getForeignSource</p> * * @return a {@link java.lang.String} object. */ public String getForeignSource() { return m_foreignSource; } }
package org.csstudio.display.builder.representation.javafx; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.csstudio.display.builder.model.properties.ScriptInfo; import org.csstudio.display.builder.model.properties.ScriptPV; import javafx.beans.property.ReadOnlyStringWrapper; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn.CellDataFeatures; import javafx.scene.control.TableView; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.util.Callback; /** Dialog for editing {@link ScriptInfo}s * @author Kay Kasemir */ public class ScriptsDialog extends Dialog<List<ScriptInfo>> { /** Modifiable ScriptPV */ private static class PVItem { public String name; public boolean trigger; public PVItem(final String name, final boolean trigger) { this.name = name; this.trigger = trigger; } public static PVItem forPV(final ScriptPV info) { return new PVItem(info.getName(), info.isTrigger()); } public ScriptPV toScriptPV() { return new ScriptPV(name, trigger); } }; /** Modifiable ScriptInfo */ private static class ScriptItem { public String file, text; public List<PVItem> pvs; public ScriptItem() { this("", "", new ArrayList<>()); } public ScriptItem(final String file, final String text, final List<PVItem> pvs) { this.file = file; this.text = text; this.pvs = pvs; } public static ScriptItem forInfo(final ScriptInfo info) { final List<PVItem> pvs = new ArrayList<>(); info.getPVs().forEach(pv -> pvs.add(PVItem.forPV(pv))); return new ScriptItem(info.getFile(), info.getText(), pvs); } public ScriptInfo getScriptInfo() { final List<ScriptPV> spvs = new ArrayList<>(); pvs.forEach(pv -> spvs.add(pv.toScriptPV())); return new ScriptInfo(file, text, spvs); } }; /** Data that is linked to the table */ private final ObservableList<ScriptItem> script_items = FXCollections.observableArrayList(); private TableView<ScriptItem> scripts_table; /** @param scripts Scripts to show/edit in the dialog */ public ScriptsDialog(final List<ScriptInfo> scripts) { setTitle("Scripts"); setHeaderText("Edit scripts and their PVs"); scripts.forEach(script -> script_items.add(ScriptItem.forInfo(script))); fixupScripts(0); getDialogPane().setContent(createContent()); getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); setResizable(true); setResultConverter(button -> { if (button != ButtonType.OK) return null; final List<ScriptInfo> result = new ArrayList<>(); for (ScriptItem item : script_items) { if (!item.file.isEmpty()) result.add(item.getScriptInfo()); } return result; }); } private Node createContent() { final Node scripts = createScriptsTable(); // TODO Table/add/remove for PVs of current script scripts_table.getSelectionModel().selectedItemProperty().addListener((prop, old, selected) -> { // TODO Show in "pvs" table if (selected == null) System.out.println("Nothing selected"); else System.out.println("PVs: " + selected.pvs.stream().map(pv -> pv.name).collect(Collectors.joining(", "))); }); return new HBox(scripts); } /** @return Node for UI elements that edit the scripts */ private Node createScriptsTable() { final GridPane content = new GridPane(); content.setHgap(10); content.setVgap(10); content.setGridLinesVisible(true); // TODO For debugging // Create table with editable column final TableColumn<ScriptItem, String> name_col = new TableColumn<>("Script"); name_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ScriptItem,String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(final CellDataFeatures<ScriptItem, String> param) { final String name = param.getValue().file; if (name.isEmpty()) return new ReadOnlyStringWrapper("<enter name>"); return new ReadOnlyStringWrapper(name); } }); name_col.setCellFactory(TextFieldTableCell.<ScriptItem>forTableColumn()); name_col.setOnEditCommit(event -> { final int row = event.getTablePosition().getRow(); script_items.get(row).file = event.getNewValue(); fixupScripts(row); }); // TODO Table column to select file or set to ScriptInfo.EMBEDDED_PYTHON scripts_table = new TableView<>(script_items); scripts_table.getColumns().add(name_col); scripts_table.setEditable(true); scripts_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); scripts_table.setTooltip(new Tooltip("Edit scripts. Add new script in last row")); content.add(scripts_table, 0, 0, 1, 3); GridPane.setHgrow(scripts_table, Priority.ALWAYS); GridPane.setVgrow(scripts_table, Priority.ALWAYS); // Buttons final Button add = new Button(Messages.Add, JFXUtil.getIcon("add.png")); add.setMaxWidth(Double.MAX_VALUE); content.add(add, 1, 0); add.setOnAction(event -> { script_items.add(new ScriptItem()); }); final Button remove = new Button(Messages.Remove, JFXUtil.getIcon("delete.png")); remove.setMaxWidth(Double.MAX_VALUE); content.add(remove, 1, 1); remove.setOnAction(event -> { final int sel = scripts_table.getSelectionModel().getSelectedIndex(); if (sel >= 0) { script_items.remove(sel); fixupScripts(sel); } }); return content; } /** Fix scripts data: Delete empty rows in middle, but keep one empty final row * @param changed_row Row to check, and remove if it's empty */ private void fixupScripts(final int changed_row) { // Check if edited row is now empty and should be deleted if (changed_row < script_items.size()) { final ScriptItem item = script_items.get(changed_row); if (item.file.trim().isEmpty()) script_items.remove(changed_row); } // Assert one empty row at bottom final int len = script_items.size(); if (len <= 0 || script_items.get(len-1).file.trim().length() > 0) script_items.add(new ScriptItem()); } }
package bridlensis.env; public class DefaultNameGenerator implements NameGenerator { private char prefix; private short count; public DefaultNameGenerator() { prefix = 'b'; count = 1; } @Override public String generate() { if (count == Short.MAX_VALUE) { prefix++; count = 1; } StringBuilder name = new StringBuilder(6); name.append(prefix); name.append(String.format("%05d", count++)); return name.toString(); } }
package steamParser; import java.io.FileInputStream; import java.io.IOException; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import steamParser.Constants.Game; import com.google.gson.Gson; /** * @author Casper * */ public class GamesManager { private static final int NUM_OF_THREADS = 24; public static int i; public static class MyRunnable implements Runnable { private java.sql.Connection con; private PreparedStatement pst; private int appid; MyRunnable(int appid,java.sql.Connection con, PreparedStatement pst) { this.con = con; this.pst = pst; this.appid = appid; } @Override public void run() { Document doc = null; int retryCount = 0; while (doc == null && retryCount < Constants.MAX_RETRIES) { // if (retryCount > 0) { // System.out.println("Reconnecting " + "(" + retryCount + ") " + "to appid: " + appid); try { doc = Jsoup.connect(Constants.STEAM_APP_URL + appid).timeout(5*1000).get(); } catch (IOException e1) { // System.out.println("Error connecting to appid: " + appid); // e1.printStackTrace(); } retryCount++; } // if (retryCount != 1){ // System.out.println("RETRY COUNT = " + retryCount); if (retryCount == Constants.MAX_RETRIES){ System.out.println("Reached max retries. Unable to connect to appid: " + appid); } Elements nameEle = new Elements(); if (doc != null) { nameEle = doc.getElementsByClass("apphub_AppName"); // If name cannot be found, it means there is no app with that appid anymore, or the webpage requires age input. if (!(nameEle.size() > 0)) { if(doc.getElementsByClass("agecheck").size() > 0){ doc = null; retryCount = 0; // Auto fill age form with timeout of 5 seconds. while (doc == null && retryCount < Constants.MAX_RETRIES) { try { doc = Jsoup.connect("http://store.steampowered.com/agecheck/app/" + appid) .data("ageYear", "1990") .data("ageMonth", "January") .data("ageDay", "1") .timeout(5*1000) .post(); } catch (IOException e) { System.out.println("Error connecting to AGECHECK of appid: " + appid); // e.printStackTrace(); } retryCount++; } if (retryCount == Constants.MAX_RETRIES){ System.out.println("Reached max AGECHECK retries. Unable to connect to appid: " + appid); } } } if (doc != null) { nameEle = doc.getElementsByClass("apphub_AppName"); if (nameEle.size() > 0) { String name = nameEle.text(); int positive; int negative; BigDecimal rating; // System.out.println(i++ + ")"); // System.out.println("appid: "+ appid); Element positiveEle = doc.getElementById("ReviewsTab_positive"); Element negativeEle = doc.getElementById("ReviewsTab_negative"); if (positiveEle == null) { positive = 0; } else { String positiveStr = positiveEle.getElementsByClass("user_reviews_count").text() .replace("(", "") .replace(")", "") .replace(",", ""); positive = Integer.parseInt(positiveStr); } if (negativeEle == null) { negative = 0; } else { String negativeStr = negativeEle.getElementsByClass("user_reviews_count").text() .replace("(", "") .replace(")", "") .replace(",", ""); negative = Integer.parseInt(negativeStr); } if (positive == 0 && negative == 0) { rating = BigDecimal.valueOf(0); } else { rating = BigDecimal.valueOf((positive * 100.0) / (positive + negative)); } // System.out.println(name); // System.out.println("+ " + positive); // System.out.println("- " + negative); // System.out.println(rating + "%"); try { pst.setString(1, name); pst.setInt(2, positive); pst.setInt(3, negative); pst.setBigDecimal(4, rating); pst.setInt(5, appid); pst.setInt(6, appid); pst.setString(7, name); pst.setInt(8, positive); pst.setInt(9, negative); pst.setBigDecimal(10, rating); pst.setInt(11, appid); pst.executeUpdate(); con.commit(); } catch (SQLException e) { System.out.println("Error with appid: " + appid); e.printStackTrace(); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } } else { // System.out.println("appid: "+ appid); // System.out.println("No info found."); } } } else { System.out.println("appid: " + appid + " returns NULL"); } } } /** * Gets games list of user with steamid and insert/updates into database. * @param steamid * @throws Exception */ public static void loadGames(String steamid) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(NUM_OF_THREADS); Connection con = null; PreparedStatement pst = null; try { con = getConnection(); con.setAutoCommit(false); String sql = "UPDATE games SET name=?, positive=?, negative=?, rating=? WHERE appid=?;" + "INSERT INTO games (appid, name, positive, negative, rating)" + "SELECT ?, ?, ?, ?, ?" + "WHERE NOT EXISTS (SELECT 1 FROM games WHERE appid=?)"; pst = con.prepareStatement(sql); i = 1; System.out.println("Starting threads..."); List<Integer> appidList = getAppidList(steamid); long startTime = System.currentTimeMillis(); for (int appid : appidList) { Runnable worker = new MyRunnable(appid, con, pst); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } long finishTime = System.currentTimeMillis(); System.out.println("Finished all threads"); System.out.println("That took: " + (finishTime - startTime) + " ms."); System.out.println(" } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); con.rollback(); e.printStackTrace(); return; } finally { if (pst != null) { pst.close(); } if (con != null) { con.close(); } } } /** * Scrapes all steam pages for appid: 0-400k and insert/updates into database. * @throws SQLException */ public static void loadAllGames() throws SQLException { ExecutorService executor = Executors.newFixedThreadPool(NUM_OF_THREADS); Connection con = null; PreparedStatement pst = null; try { con = getConnection(); con.setAutoCommit(false); String sql = "UPDATE games SET name=?, positive=?, negative=?, rating=? WHERE appid=?;" + "INSERT INTO games (appid, name, positive, negative, rating)" + "SELECT ?, ?, ?, ?, ?" + "WHERE NOT EXISTS (SELECT 1 FROM games WHERE appid=?)"; pst = con.prepareStatement(sql); i = 1; System.out.println("Starting threads..."); long startTime = System.currentTimeMillis(); for (int appid = 0; appid < 400000; appid++) { // for(int x = 0; x < 1000; x++){ // int appid = 7796; Runnable worker = new MyRunnable(appid, con, pst); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } long finishTime = System.currentTimeMillis(); System.out.println("Finished all threads"); System.out.println("That took: " + (finishTime - startTime) + " ms."); System.out.println(" } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); con.rollback(); e.printStackTrace(); return; } finally { if (pst != null) { pst.close(); } if (con != null) { con.close(); } } } /** * Get list of appids from given steam ID. * @param steamid * @return List of appids * @throws Exception */ public static List<Integer> getAppidList(String steamid) { String json = null; try { json = SteamIdManager.readUrl("http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + Constants.STEAM_KEY + "&steamid=" + steamid + "&format=json"); } catch (Exception e) { e.printStackTrace(); } if (json == null) { return null; } else { Gson gson = new Gson(); Constants.Page page = gson.fromJson(json, Constants.Page.class); List<Integer> appids = new ArrayList<Integer>(); if (page.response.games != null) { for (Game game : page.response.games) { appids.add(Integer.parseInt(game.appid)); } } else { return null; } return appids; } } public static List<GameBean> getGames(String steamid) { List<GameBean> games = new ArrayList<GameBean>(); List<Integer> appidList = getAppidList(steamid); Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { con = getConnection(); pst = con.prepareStatement("SELECT * FROM games where appid=?"); if (appidList != null) { // int x = 1; for (int id : appidList) { pst.setInt(1, id); rs = pst.executeQuery(); while (rs.next()) { GameBean game = new GameBean(); game.setAppid(rs.getInt(1)); game.setName(rs.getString(2)); game.setPositive(rs.getInt(3)); game.setNegative(rs.getInt(4)); game.setRating(rs.getDouble(5)); games.add(game); // System.out.println(x++ + ")"); // System.out.println(game.getAppid()); // System.out.println(game.getName()); // System.out.println(game.getPositive() + "/" + game.getNegative()); // System.out.println(game.getRating() + "%"); } } } } catch (SQLException e) { e.printStackTrace(); return null; } finally { if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return games; } public static Connection getConnection() throws SQLException { Properties props = new Properties(); FileInputStream fis = null; try { // fis = new FileInputStream("db.properties"); // props.load(getServletContext().getResourceAsStream("/WEB-INF/db.properties")); props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties")); // props.load(fis); } catch (IOException e) { e.printStackTrace(); System.out.println("Unable to load db.properties file."); return null; } try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String url = props.getProperty("POSTGRES_DB_URL"); String user = props.getProperty("POSTGRES_DB_USERNAME"); String password = props.getProperty("POSTGRES_DB_PASSWORD"); Connection con = null; con = DriverManager.getConnection(url, user, password); return con; } }
package stray; import java.util.Iterator; import java.util.Map; import stray.blocks.Block; import stray.blocks.Blocks; import stray.util.AssetLogger; import stray.world.World; import com.badlogic.gdx.utils.Logger; public class AssetLoadingScreen extends MiscLoadingScreen { public AssetLoadingScreen(Main m) { super(m); m.manager.setLogger(output); } private AssetLogger output = new AssetLogger("assetoutput", Logger.DEBUG); private long startms = 0; @Override public void render(float delta) { main.manager.update(Math.round(1000f / Main.MAX_FPS)); if (main.manager.getProgress() >= 1f) { // finished for (String s : main.manager.getAssetNames()) { // System.out.println(s); } Iterator it = Blocks.instance().getAllBlocks(); while (it.hasNext()) { Block block = (Block) ((Map.Entry) it.next()).getValue(); block.postLoad(main); } Main.GAME.world = new World(main); Main.logger.info("Finished loading all managed assets, took " + (System.currentTimeMillis() - startms) + " ms"); main.setScreen(Main.MAINMENU); } super.render(delta); } @Override public void tickUpdate() { } @Override public void resize(int width, int height) { main.camera.setToOrtho(false, width, height); main.batch.setProjectionMatrix(main.camera.combined); } @Override public void show() { startms = System.currentTimeMillis(); } @Override public void hide() { } @Override public void pause() { } @Override public void resume() { } @Override public void dispose() { } @Override public void renderDebug(int starting) { } @Override public void renderUpdate() { } }
package unitTests; import java.io.File; import java.net.URL; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.junit.Test; import org.ow2.proactive.scheduler.common.SchedulerConstants; import org.ow2.proactive.scheduler.common.job.JobPriority; import org.ow2.proactive.scheduler.common.job.JobType; import org.ow2.proactive.scheduler.common.job.TaskFlowJob; import org.ow2.proactive.scheduler.common.job.factories.JobFactory; import org.ow2.proactive.scheduler.common.task.JavaTask; import org.ow2.proactive.scheduler.common.task.NativeTask; import org.ow2.proactive.scheduler.common.task.RestartMode; import org.ow2.proactive.scheduler.common.task.Task; import org.ow2.proactive.scheduler.common.task.dataspaces.InputAccessMode; import org.ow2.proactive.scheduler.common.task.dataspaces.OutputAccessMode; /** * This class will test the jobFactory. * It will parse job XML descriptors as exhaustively as possible to check that every features and insertions are managed. * * @author The ProActive Team * @since ProActive Scheduling 0.9.1 */ public class TestJobFactory { private static URL jobTaskFlowDescriptor = TestJobFactory.class .getResource("/unitTests/descriptors/Job_TaskFlow.xml"); private static URL jobMultiNodesDescriptor = TestJobFactory.class .getResource("/unitTests/descriptors/Job_MultiNodes.xml"); @Test public void run() throws Throwable { //test default behavior as well (null is STAX) log("TEST jobFactory STAX"); run_(null); } private void run_(String impl) throws Throwable { String URLbegin = System.getProperty("pa.scheduler.home") + "/"; System.setProperty("jobName", "Job_TaskFlow"); log("Test Job TASKFLOW"); TaskFlowJob tfJob = (TaskFlowJob) JobFactory.getFactory(impl).createJob( new File(jobTaskFlowDescriptor.toURI()).getAbsolutePath()); //Check job properties Assert.assertEquals(tfJob.getDescription(), "No paquit in its HostName."); Assert.assertEquals(tfJob.getName(), "Job_TaskFlow"); Assert.assertEquals(tfJob.getProjectName(), "My_project"); Assert.assertEquals(tfJob.getPriority(), JobPriority.NORMAL); Assert.assertEquals(tfJob.isCancelJobOnError(), true); Assert.assertEquals(tfJob.getMaxNumberOfExecution(), 2); Assert.assertEquals(tfJob.getRestartTaskOnError(), RestartMode.ELSEWHERE); Assert.assertEquals(tfJob.getType(), JobType.TASKSFLOW); Assert.assertEquals(tfJob.getTasks().size(), 4); Assert.assertEquals("input/space", tfJob.getInputSpace()); Assert.assertEquals("output/space", tfJob.getOutputSpace()); //Check task 1 properties Assert.assertEquals(tfJob.getTask("task1").getName(), "task1"); Assert.assertEquals(tfJob.getTask("task1").isCancelJobOnError(), false); Assert.assertEquals(tfJob.getTask("task1").isPreciousResult(), false); Assert.assertEquals(tfJob.getTask("task1").getRestartTaskOnError(), RestartMode.ANYWHERE); Assert.assertEquals(tfJob.getTask("task1").getMaxNumberOfExecution(), 1); Assert.assertEquals(tfJob.getTask("task1").getDescription(), "Parallel Tasks - Task 1"); Assert.assertEquals(2, tfJob.getTask("task1").getSelectionScripts().size()); Assert.assertEquals(false, tfJob.getTask("task1").getSelectionScripts().get(0).isDynamic()); Assert.assertTrue(tfJob.getTask("task1").getSelectionScripts().get(0).getScript() != null); Assert.assertEquals(1, tfJob.getTask("task1").getSelectionScripts().get(0).getParameters().length); Assert.assertEquals("paquit", tfJob.getTask("task1").getSelectionScripts().get(0).getParameters()[0]); Assert.assertEquals(true, tfJob.getTask("task1").getSelectionScripts().get(1).isDynamic()); Assert.assertTrue(tfJob.getTask("task1").getSelectionScripts().get(1).getScript() != null); Assert.assertEquals(2, tfJob.getTask("task1").getSelectionScripts().get(1).getParameters().length); Assert.assertEquals("test1", tfJob.getTask("task1").getSelectionScripts().get(1).getParameters()[0]); Assert.assertEquals("test2", tfJob.getTask("task1").getSelectionScripts().get(1).getParameters()[1]); Assert.assertTrue(tfJob.getTask("task1").getPreScript().getScript().contains( "Beginning of Pre-Script")); Assert.assertTrue(tfJob.getTask("task1").getPostScript().getScript().contains( "Content is equals to " + URLbegin + "samples/scripts/misc/unset.js")); Assert.assertEquals(tfJob.getTask("task1").getPostScript().getParameters(), null); Assert.assertTrue(tfJob.getTask("task1").getCleaningScript().getScript().contains( "Beginning of clean script")); Assert.assertEquals(tfJob.getTask("task1").getCleaningScript().getParameters(), null); Assert.assertEquals(tfJob.getTask("task1").getDependencesList(), null); Assert.assertEquals(tfJob.getTask("task1").getNumberOfNodesNeeded(), 1); Assert.assertEquals(tfJob.getTask("task1").getResultPreview(), null); Assert.assertEquals(tfJob.getTask("task1").getWallTime(), 12 * 1000); Assert.assertEquals(tfJob.getTask("task1").isWallTimeSet(), true); Assert.assertEquals(tfJob.getTask("task1").getGenericInformations().size(), 0); Assert.assertNull(tfJob.getTask("task1").getInputFilesList()); Assert.assertNull(tfJob.getTask("task1").getOutputFilesList()); Assert.assertEquals(((JavaTask) tfJob.getTask("task1")).getArgument("sleepTime"), "1"); Assert.assertEquals(((JavaTask) tfJob.getTask("task1")).getArgument("number"), "1"); Assert.assertEquals(((JavaTask) tfJob.getTask("task1")).getExecutableClassName(), "org.ow2.proactive.scheduler.examples.WaitAndPrint"); Assert.assertEquals(((JavaTask) tfJob.getTask("task1")).isFork(), true); Assert.assertEquals(((JavaTask) tfJob.getTask("task1")).getForkEnvironment(), null); //Check task 2 properties Assert.assertEquals(tfJob.getTask("task2").getName(), "task2"); //the following commented check fails, it is what we expect, because replacement is done in the internal factory. //it avoids complex changes during user job creation process. //this property is tested in the TestDatabaseCRUD //Assert.assertEquals(tfJob.getTask("task2").isCancelJobOnError(),true); Assert.assertEquals(tfJob.getTask("task2").isPreciousResult(), false); Assert.assertEquals(tfJob.getTask("task2").getRestartTaskOnError(), RestartMode.ELSEWHERE); Assert.assertEquals(tfJob.getTask("task2").getMaxNumberOfExecution(), 2); Assert.assertEquals(tfJob.getTask("task2").getDescription(), "Parallel Tasks - Task 2"); Assert.assertEquals(tfJob.getTask("task2").getSelectionScripts(), null); Assert.assertTrue(tfJob.getTask("task2").getPreScript().getScript().contains( "Beginning of Pre-Script")); Assert.assertEquals(tfJob.getTask("task2").getPostScript(), null); Assert.assertEquals(tfJob.getTask("task2").getCleaningScript(), null); Assert.assertEquals(tfJob.getTask("task2").getDependencesList(), null); Assert.assertEquals(tfJob.getTask("task2").getNumberOfNodesNeeded(), 1); Assert.assertEquals(tfJob.getTask("task2").getResultPreview(), null); Assert.assertEquals(tfJob.getTask("task2").getWallTime(), 0); Assert.assertEquals(tfJob.getTask("task2").isWallTimeSet(), false); Assert.assertEquals(tfJob.getTask("task2").getGenericInformations().size(), 0); Assert.assertEquals("tata*", tfJob.getTask("task2").getInputFilesList().get(0).getInputFiles() .getIncludes()[0]); Assert.assertEquals("tata*1", tfJob.getTask("task2").getInputFilesList().get(0).getInputFiles() .getExcludes()[0]); Assert.assertEquals(InputAccessMode.TransferFromInputSpace, tfJob.getTask("task2") .getInputFilesList().get(0).getMode()); Assert.assertEquals("toto*.txt", tfJob.getTask("task2").getInputFilesList().get(1).getInputFiles() .getIncludes()[0]); Assert.assertEquals("toto*2.txt", tfJob.getTask("task2").getInputFilesList().get(1).getInputFiles() .getExcludes()[0]); Assert.assertEquals(InputAccessMode.TransferFromOutputSpace, tfJob.getTask("task2") .getInputFilesList().get(1).getMode()); Assert.assertEquals("titi*", tfJob.getTask("task2").getOutputFilesList().get(0).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("titi*1", tfJob.getTask("task2").getOutputFilesList().get(0).getOutputFiles() .getExcludes()[0]); Assert.assertEquals(OutputAccessMode.TransferToOutputSpace, tfJob.getTask("task2") .getOutputFilesList().get(0).getMode()); Assert.assertEquals("titi*.txt", tfJob.getTask("task2").getOutputFilesList().get(1).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("titi*3.txt", tfJob.getTask("task2").getOutputFilesList().get(1).getOutputFiles() .getExcludes()[0]); Assert.assertEquals(OutputAccessMode.TransferToOutputSpace, tfJob.getTask("task2") .getOutputFilesList().get(1).getMode()); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).getArgument("sleepTime"), "12"); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).getArgument("number"), "21"); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).getArgument("test"), "/bin/java/jdk1.5"); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).getExecutableClassName(), "org.ow2.proactive.scheduler.examples.WaitAndPrint"); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).isFork(), true); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).isWallTimeSet(), false); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).getForkEnvironment().getJavaHome(), "/bin/java/jdk1.5"); Assert.assertEquals(((JavaTask) tfJob.getTask("task2")).getForkEnvironment().getWorkingDir(), "/bin/java/jdk1.5/toto"); Assert.assertEquals( ((JavaTask) tfJob.getTask("task2")).getForkEnvironment().getJVMArguments().get(0), "-dparam=12"); Assert.assertEquals( ((JavaTask) tfJob.getTask("task2")).getForkEnvironment().getJVMArguments().get(1), "-djhome=/bin/java/jdk1.5"); Map<String, String> props = ((JavaTask) tfJob.getTask("task2")).getForkEnvironment() .getSystemEnvironment(); Assert.assertEquals(3, props.size()); Assert.assertEquals("ioioio#123:456", props.get("toto")); Assert.assertEquals("456", props.get("tata")); Assert.assertEquals("123!456", props.get("titi")); Assert.assertEquals("ioioio#123:456", ((JavaTask) tfJob.getTask("task2")).getForkEnvironment() .getSystemEnvironmentVariable("toto")); Assert.assertEquals("456", ((JavaTask) tfJob.getTask("task2")).getForkEnvironment() .getSystemEnvironmentVariable("tata")); Assert.assertEquals("123!456", ((JavaTask) tfJob.getTask("task2")).getForkEnvironment() .getSystemEnvironmentVariable("titi")); List<String> addcp = ((JavaTask) tfJob.getTask("task2")).getForkEnvironment() .getAdditionalClasspath(); Assert.assertEquals(2, addcp.size()); Assert.assertEquals("a", addcp.get(0)); Assert.assertEquals("b", addcp.get(1)); Assert.assertNotNull(((JavaTask) tfJob.getTask("task2")).getForkEnvironment().getEnvScript()); //Check task 3 properties Assert.assertEquals(tfJob.getTask("task3").getName(), "task3"); //the following commented check fails, it is what we expect, because replacement is done in the internal factory. //it avoids complex changes during user job creation process. //this property is tested in the TestDatabaseCRUD //Assert.assertEquals(tfJob.getTask("task3").isCancelJobOnError(),true); Assert.assertEquals(tfJob.getTask("task3").isPreciousResult(), false); //the following commented check fails, it is what we expect, because replacement is done in the internal factory. //it avoids complex changes during user job creation process. //this property is tested in the TestDatabaseCRUD //Assert.assertEquals(tfJob.getTask("task3").getRestartTaskOnError(),RestartMode.ELSEWHERE); //the following commented check fails, it is what we expect, because replacement is done in the internal factory. //it avoids complex changes during user job creation process. //this property is tested in the TestDatabaseCRUD //Assert.assertEquals(tfJob.getTask("task3").getMaxNumberOfExecution(),2); Assert.assertEquals(tfJob.getTask("task3").getDescription(), "Dependent Tasks - Task 3"); Assert.assertEquals(tfJob.getTask("task3").getSelectionScripts(), null); Assert.assertEquals(tfJob.getTask("task3").getPreScript(), null); Assert.assertTrue(tfJob.getTask("task3").getPostScript().getScript().contains( "Unsetting system property user.property1")); Assert.assertEquals(tfJob.getTask("task3").getPostScript().getParameters(), null); Assert.assertEquals(tfJob.getTask("task3").getCleaningScript(), null); Assert.assertEquals(tfJob.getTask("task3").getDependencesList().size(), 2); Assert.assertEquals(tfJob.getTask("task3").getDependencesList().get(0).getName(), "task1"); Assert.assertEquals(tfJob.getTask("task3").getDependencesList().get(1).getName(), "task2"); Assert.assertEquals(tfJob.getTask("task3").getResultPreview(), null); Assert.assertEquals(tfJob.getTask("task3").getWallTime(), 10 * 60 * 1000 + 53 * 1000); Assert.assertEquals(tfJob.getTask("task3").isWallTimeSet(), true); Assert.assertEquals(tfJob.getTask("task3").getGenericInformations().size(), 0); Assert.assertEquals(1, tfJob.getTask("task3").getInputFilesList().size()); Assert.assertEquals("tata*", tfJob.getTask("task3").getInputFilesList().get(0).getInputFiles() .getIncludes()[0]); Assert.assertNull(tfJob.getTask("task3").getInputFilesList().get(0).getInputFiles().getExcludes()); Assert .assertEquals(InputAccessMode.none, tfJob.getTask("task3").getInputFilesList().get(0) .getMode()); Assert.assertNull(tfJob.getTask("task3").getOutputFilesList()); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getCommandLine().length, 5); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getCommandLine()[0], URLbegin + "samples/jobs_descriptors/job_native_linux/nativTask"); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getCommandLine()[1], "1"); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getCommandLine()[2], "2 2"); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getCommandLine()[3], "3"); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getCommandLine()[4], "12"); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getWorkingDir(), "task3workingDir"); Assert.assertEquals(((NativeTask) tfJob.getTask("task3")).getNumberOfNodesNeeded(), 3); //Check task 4 properties Assert.assertEquals(tfJob.getTask("task4").getName(), "task4"); Assert.assertEquals(tfJob.getTask("task4").isCancelJobOnError(), true); Assert.assertEquals(tfJob.getTask("task4").isPreciousResult(), true); Assert.assertEquals(tfJob.getTask("task4").getRestartTaskOnError(), RestartMode.ANYWHERE); Assert.assertEquals(tfJob.getTask("task4").getMaxNumberOfExecution(), 3); Assert.assertEquals(tfJob.getTask("task4").getDescription(), null); Assert.assertEquals(tfJob.getTask("task4").getSelectionScripts(), null); Assert.assertEquals(tfJob.getTask("task4").getPreScript(), null); Assert.assertEquals(tfJob.getTask("task4").getPostScript(), null); Assert.assertEquals(tfJob.getTask("task4").getCleaningScript(), null); Assert.assertEquals(tfJob.getTask("task4").getDependencesList().size(), 1); Assert.assertEquals(tfJob.getTask("task4").getDependencesList().get(0).getName(), "task3"); Assert.assertEquals(tfJob.getTask("task4").getResultPreview(), "tadzaam"); Assert.assertEquals(tfJob.getTask("task4").getWallTime(), 0); Assert.assertEquals(tfJob.getTask("task4").isWallTimeSet(), false); Assert.assertEquals(tfJob.getTask("task4").getGenericInformations().get("n11"), "v11"); Assert.assertEquals(tfJob.getTask("task4").getGenericInformations().get("n22"), "v22"); Assert.assertNull(tfJob.getTask("task4").getInputFilesList()); Assert.assertEquals(5, tfJob.getTask("task4").getOutputFilesList().size()); Assert.assertEquals("a", tfJob.getTask("task4").getOutputFilesList().get(0).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("b", tfJob.getTask("task4").getOutputFilesList().get(1).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("c", tfJob.getTask("task4").getOutputFilesList().get(2).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("d", tfJob.getTask("task4").getOutputFilesList().get(3).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("e", tfJob.getTask("task4").getOutputFilesList().get(4).getOutputFiles() .getIncludes()[0]); Assert.assertEquals("f", tfJob.getTask("task4").getOutputFilesList().get(0).getOutputFiles() .getExcludes()[0]); Assert.assertEquals("g", tfJob.getTask("task4").getOutputFilesList().get(1).getOutputFiles() .getExcludes()[0]); Assert.assertNull(tfJob.getTask("task4").getOutputFilesList().get(2).getOutputFiles().getExcludes()); Assert.assertEquals("h", tfJob.getTask("task4").getOutputFilesList().get(3).getOutputFiles() .getExcludes()[0]); Assert.assertEquals("i", tfJob.getTask("task4").getOutputFilesList().get(4).getOutputFiles() .getExcludes()[0]); Assert.assertEquals(OutputAccessMode.TransferToOutputSpace, tfJob.getTask("task4") .getOutputFilesList().get(0).getMode()); Assert.assertEquals(OutputAccessMode.none, tfJob.getTask("task4").getOutputFilesList().get(1) .getMode()); Assert.assertEquals(OutputAccessMode.none, tfJob.getTask("task4").getOutputFilesList().get(2) .getMode()); Assert.assertEquals(OutputAccessMode.TransferToOutputSpace, tfJob.getTask("task4") .getOutputFilesList().get(3).getMode()); Assert.assertEquals(OutputAccessMode.none, tfJob.getTask("task4").getOutputFilesList().get(4) .getMode()); Assert.assertEquals(((NativeTask) tfJob.getTask("task4")).getWorkingDir(), "task4workingDir"); Assert.assertEquals(((NativeTask) tfJob.getTask("task4")).getNumberOfNodesNeeded(), 10); Assert.assertEquals(((NativeTask) tfJob.getTask("task4")).getGenerationScript().getScript(), "command=args[0]+\" 12\";\n"); Assert.assertEquals(((NativeTask) tfJob.getTask("task4")).getGenerationScript().getParameters()[0], URLbegin + "samples/jobs_descriptors/job_native_linux/nativTask"); Assert.assertEquals(((NativeTask) tfJob.getTask("task4")).getGenerationScript().execute().getResult() , URLbegin + "samples/jobs_descriptors/job_native_linux/nativTask 12"); log("Test Job MULTI_NODES"); TaskFlowJob mnJob = (TaskFlowJob) JobFactory.getFactory().createJob( new File(jobMultiNodesDescriptor.toURI()).getAbsolutePath()); //Check job properties Assert.assertEquals(mnJob.getDescription(), "No description"); Assert.assertEquals(mnJob.getName(), "job_multiNodes"); Assert.assertEquals(mnJob.getPriority(), JobPriority.LOW); Assert.assertNotSame(mnJob.getEnvironment().getJobClasspath()[0], "one/two/"); Assert.assertTrue(mnJob.getEnvironment().getJobClasspath()[0].endsWith("one/two/")); Assert.assertNotSame(mnJob.getEnvironment().getJobClasspath()[1], "three"); Assert.assertTrue(mnJob.getEnvironment().getJobClasspath()[1].endsWith("three")); Assert.assertEquals(mnJob.isCancelJobOnError(), false); Assert.assertEquals(mnJob.getMaxNumberOfExecution(), 1); Assert.assertEquals(mnJob.getRestartTaskOnError(), RestartMode.ANYWHERE); Assert.assertEquals(mnJob.getType(), JobType.TASKSFLOW); Assert.assertEquals(mnJob.getGenericInformations().get("n1"), "v1"); Assert.assertEquals(mnJob.getGenericInformations().get("n2"), "v2"); //Check task properties JavaTask jt = (JavaTask) mnJob.getTask("Controller"); Assert.assertEquals(jt.getArgument("numberToFind"), "100"); Assert.assertEquals(jt.isCancelJobOnError(), false); Assert.assertEquals(jt.getCleaningScript(), null); Assert.assertEquals(jt.getDependencesList(), null); Assert .assertEquals(jt.getDescription(), "Will control the workers in order to find the prime number"); Assert.assertEquals(jt.getExecutableClassName(), "org.ow2.proactive.scheduler.examples.MultiNodeExample"); Assert.assertEquals(jt.getGenericInformations().get("n11"), "v11"); Assert.assertEquals(jt.getGenericInformations().get("n22"), "v22"); Assert.assertEquals(jt.getMaxNumberOfExecution(), 1); Assert.assertEquals(jt.getName(), "Controller"); Assert.assertEquals(jt.getNumberOfNodesNeeded(), 3); Assert.assertEquals(jt.getPreScript(), null); Assert.assertEquals(jt.getPostScript(), null); Assert.assertEquals(jt.getRestartTaskOnError(), RestartMode.ANYWHERE); Assert.assertEquals(jt.getResultPreview(), "path.to.package.class"); Assert.assertEquals(jt.getSelectionScripts(), null); Assert.assertTrue(jt.isPreciousResult()); log("Test generated task name"); TaskFlowJob job = new TaskFlowJob(); for (int i = 0; i < 4; i++) { Task t = new NativeTask(); job.addTask(t); } Task t1, t2, t3, t4; Assert.assertNull(job.getTask(SchedulerConstants.TASK_NAME_IFNOTSET + "0")); Assert.assertNotNull(t1 = job.getTask(SchedulerConstants.TASK_NAME_IFNOTSET + "1")); Assert.assertNotNull(t2 = job.getTask(SchedulerConstants.TASK_NAME_IFNOTSET + "2")); Assert.assertNotNull(t3 = job.getTask(SchedulerConstants.TASK_NAME_IFNOTSET + "3")); Assert.assertNotNull(t4 = job.getTask(SchedulerConstants.TASK_NAME_IFNOTSET + "4")); Assert.assertNull(job.getTask(SchedulerConstants.TASK_NAME_IFNOTSET + "5")); Assert.assertTrue(t1 != t2); Assert.assertTrue(t1 != t3); Assert.assertTrue(t1 != t4); Assert.assertTrue(t2 != t3); Assert.assertTrue(t2 != t4); Assert.assertTrue(t3 != t4); } private void log(String s) { System.out.println(" } }
// MemUtilTest.java package ed.util; import java.io.*; import java.util.*; import org.testng.annotations.Test; import ed.util.*; import static ed.util.MemUtil.*; public class MemUtilTest extends ed.TestCase { @Test public void testJavaIsGC(){ assertTrue( GCLine.isGCLine( "2369.623: [GC [PSYoungGen: 253491K->57715K(270720K)] 662375K->492170K(760896K), 0.1937260 secs] [Times: user=0.24 sys=0.00, real=0.20 secs] " ) ); assertTrue( GCLine.isGCLine( "2378.656: [GC [PSYoungGen: 259315K->53474K(271616K)] 693770K->491671K(761792K), 0.1463140 secs] [Times: user=0.16 sys=0.00, real=0.14 secs] " ) ); assertTrue( GCLine.isGCLine( "2388.453: [GC [PSYoungGen: 257442K->56577K(271616K)] 695639K->498343K(761792K), 0.1480230 secs] [Times: user=0.17 sys=0.00, real=0.14 secs] " ) ); assertTrue( GCLine.isGCLine( "2394.839: [GC [PSYoungGen: 260545K->52847K(272960K)] 702311K->509225K(763136K), 0.1738920 secs] [Times: user=0.19 sys=0.00, real=0.18 secs] " ) ); assertTrue( GCLine.isGCLine( "2395.013: [Full GC [PSYoungGen: 52847K->0K(272960K)] [PSOldGen: 456378K->287193K(508160K)] 509225K->287193K(781120K) [PSPermGen: 44209K->44209K(44992K)], 0.8087710 secs] [Times: user=0.81 sys=0.00, real=0.80 secs] " ) ); assertTrue( GCLine.isGCLine( "[GC [PSYoungGen: 260545K->52847K(272960K)] 702311K->509225K(763136K), 0.1738920 secs] [Times: user=0.19 sys=0.00, real=0.18 secs] " ) ); assertTrue( GCLine.isGCLine( "[Full GC [PSYoungGen: 52847K->0K(272960K)] [PSOldGen: 456378K->287193K(508160K)] 509225K->287193K(781120K) [PSPermGen: 44209K->44209K(44992K)], 0.8087710 secs] [Times: user=0.81 sys=0.00, real=0.80 secs] " ) ); assertTrue( GCLine.isGCLine( "46954.065: [Full GC [PSYoungGen: 100608K->100594K(225984K)] [PSOldGen: 819199K->819199K(819200K)] 919807K->919794K(1045184K) [PSPermGen: 46936K->46936K(47232K)], 1.8832360 secs]" ) ); assertTrue( GCLine.isGCLine( "105.350: [GC [PSYoungGen: 106006K->25000K(145024K)] 228802K->167810K(1874496K), 0.0308960 secs]" ) ); assertFalse( GCLine.isGCLine( "Asdasd" ) ); assertFalse( GCLine.isGCLine( "Exception in thread \"ThreadPool.MyThread:HttpServer-main:2\" java.lang.OutOfMemoryError: GC overhead limit exceeded\"" ) ); assertFalse( GCLine.isGCLine( "Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded" ) ); assertFalse( GCLine.isGCLine( "java.lang.OutOfMemoryError: GC overhead limit exceeded" ) ); assertFalse( GCLine.isGCLine( "java.lang.OutOfMemoryError: GC overhead limit exceeded" ) ); assertFalse( GCLine.isGCLine( "\"GC task thread#0 (ParallelGC)\" prio=10 tid=0x000000004011d800 nid=0x58c7 runnable " ) ); assertFalse( GCLine.isGCLine( "\"GC task thread#1 (ParallelGC)\" prio=10 tid=0x000000004011ec00 nid=0x58c8 runnable " ) ); assertFalse( GCLine.isGCLine( "[11/02/2008 01:53:30.475 EST] ThreadPool.MyThread:HttpServer-main:15 || clusterstock:www.slow INFO >> /Gannett-Co-GCI-stock-financial-analysis.html 2615ms" ) ); assertFalse( GCLine.isGCLine( "Exception in thread \"ThreadPool.MyThread:HttpServer-main:29\" java.lang.OutOfMemoryError: GC overhead limit exceeded" ) ); assertFalse( GCLine.isGCLine( "java.lang.OutOfMemoryError: GC overhead limit exceeded" ) ); } @Test public void testParse1(){ _testParse( "2394.839: [GC [PSYoungGen: 260545K->52847K(272960K)] 702311K->509225K(763136K), 0.1738920 secs] [Times: user=0.19 sys=0.00, real=0.18 secs] " , 2394839 , false , 180 ); _testParse( "[Full GC [PSYoungGen: 52847K->0K(272960K)] [PSOldGen: 456378K->287193K(508160K)] 509225K->287193K(781120K) [PSPermGen: 44209K->44209K(44992K)], 0.8087710 secs] [Times: user=0.81 sys=0.00, real=0.80 secs] " , -1 , true , 800 ); _testParse( "7.12: [Full GC [PSYoungGen: 52847K->0K(272960K)] [PSOldGen: 456378K->287193K(508160K)] 509225K->287193K(781120K) [PSPermGen: 44209K->44209K(44992K)], 0.8087710 secs] [Times: user=0.81 sys=0.00, real=0.80 secs] " , 7120 , true , 800 ); _testParse( "7.012: [Full GC [PSYoungGen: 52847K->0K(272960K)] [PSOldGen: 456378K->287193K(508160K)] 509225K->287193K(781120K) [PSPermGen: 44209K->44209K(44992K)], 0.8087710 secs] [Times: user=0.81 sys=0.00, real=0.80 secs] " , 7012 , true , 800 ); } @Test public void testParse2(){ _testParse( "[GC [PSYoungGen: 260545K->52847K(272960K)] 702311K->509225K(763136K), 0.1738920 secs] [Times: user=0.19 sys=0.00, real=0.18 secs] " , -1 , false , 180 ); } @Test public void test15parse(){ _testParse( "105.350: [GC [PSYoungGen: 106006K->25000K(145024K)] 228802K->167810K(1874496K), 0.0308960 secs]" , 105350 , false , 30); _testParse( "405.910: [Full GC [PSYoungGen: 34126K->0K(145920K)] [PSOldGen: 1740897K->1359078K(1751296K)] 1775023K->1359078K(1897216K) [PSPermGen: 22334K->22173K(45568K)], 3.4769290 secs]" , 405910 , true , 3476 ); } @Test public void testparse3(){ _testParse( "120.944: [Full GC [PSYoungGen: 482K->0K(80768K)] [PSOldGen: 199383K->184138K(204800K)] 199865K->184138K(285568K) [PSPermGen: 39425K->39425K(47168K)], 0.6940380 secs]" , 120944 , true , 694 ); } void _testParse( String line , long when , boolean full , long howLong ){ GCLine l = GCLine.parse( line ); assert( l != null ); assertEquals( when , l.when() ); assertEquals( full , l.full() ); assertEquals( howLong , l.howLong() ); } @Test public void testGCStream1(){ GCStream s = new GCStream(); assertEquals( 0.0 , s.fullGCPercentage() ); s.add( new GCLine( 0000 , false , 5 ) ); s.add( new GCLine( 1000 , false , 5 ) ); s.add( new GCLine( 2000 , false , 5 ) ); s.add( new GCLine( 3000 , false , 5 ) ); s.add( new GCLine( 4000 , false , 5 ) ); s.add( new GCLine( 5000 , false , 5 ) ); assertEquals( 0.0 , s.fullGCPercentage() ); } @Test public void testGCStream2(){ GCStream s = new GCStream(); assertEquals( 0.0 , s.fullGCPercentage() ); s.add( new GCLine( 0000 , true , 500 ) ); s.add( new GCLine( 1000 , true , 500 ) ); s.add( new GCLine( 2000 , true , 500 ) ); s.add( new GCLine( 3000 , true , 500 ) ); s.add( new GCLine( 4000 , true , 500 ) ); assertEquals( 0.0 , s.fullGCPercentage() , 0 ); s.add( new GCLine( 5000 , true , 500 ) ); assertEquals( .6 , s.fullGCPercentage() , 0 ); } @Test public void testGCStream3(){ GCStream s = new GCStream(); assertEquals( 0.0 , s.fullGCPercentage() ); s.add( new GCLine( 0000 , true , 500 ) ); s.add( new GCLine( 1000 , false , 500 ) ); s.add( new GCLine( 2000 , true , 500 ) ); s.add( new GCLine( 3000 , false , 500 ) ); s.add( new GCLine( 4000 , true , 500 ) ); assertEquals( 0.0 , s.fullGCPercentage() , 0 ); s.add( new GCLine( 5000 , true , 500 ) ); assertEquals( .4 , s.fullGCPercentage() , 0 ); } public static void main( String args[] ){ (new MemUtilTest()).runConsole(); } }
package com.akiban.sql.pg; import com.akiban.server.types.extract.ConverterTestUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.io.Writer; import java.sql.Connection; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; /** Test the {@code YamlTester} class. */ public class YamlTesterIT extends PostgresServerYamlITBase { static { ConverterTestUtils.setGlobalTimezone("UTC"); } /* Tests */ /* Test general syntax */ @Test public void testIncorrectYaml() throws Exception { testYamlFail("!!blah-blah"); } @Test public void testEmptyYaml() throws Exception { testYamlFail(""); } @Test public void testEmptyDocument() throws Exception { testYamlFail(" } @Test public void testNotSequence() throws Exception { testYamlFail("a: b\n"); } @Test public void testFirstElementNotMap() throws Exception { testYamlFail("- a\n"); } @Test public void testFirstElementKeyNumber() throws Exception { testYamlFail("- 1\n"); } @Test public void testFirstElementKeySequence() throws Exception { testYamlFail("- [a]\n"); } @Test public void testFirstElementKeyNotKnown() throws Exception { testYamlFail("- UnknownCommand:"); } /* Test !select-engine general syntax */ @Test public void testSelectEngineMissingValue() throws Exception { testYamlFail("- Statement: !select-engine"); } @Test public void testSelectEngineScalarValue() throws Exception { testYamlFail("- Statement: !select-engine foo"); } @Test public void testSelectEngineSequenceValue() throws Exception { testYamlFail("- Statement: !select-engine [foo, bar]"); } @Test public void testSelectEngineKeyNotScalar() throws Exception { testYamlFail("- Statement: !select-engine { [foo, bar]: baz }"); } @Test public void testSelectEngineMatch() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: !select-engine\n" + " { foo: bar,\n" + " it: INSERT INTO t VALUES (1) }\n" + "..."); } @Test public void testSelectEngineNoMatch() throws Exception { testYaml("- Statement: !select-engine { foo: bar }"); } @Test public void testSelectEngineKeyItOverAllPrecedence() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: !select-engine\n" + " { it: SELECT * FROM t, all: oops }"); } @Test public void testSelectEngineKeyItOverAllPrecedenceReversed() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: !select-engine\n" + " { all: oops, it: SELECT * FROM t }"); } @Test public void testSelectEngineKeyItOverAllPrecedenceNull() throws Exception { testYaml(" "- Statement: !select-engine { it: null, all: oops }"); testYaml(" "- Statement: !select-engine { all: oops, it: null }"); testYamlFail(" "- Statement: !select-engine { it: oops, all: null }"); testYamlFail(" "- Statement: !select-engine { all: null, it: oops }"); } @Test public void testSelectEngineKeyAll() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: !select-engine\n" + " { all: SELECT * FROM t, foo: oops }"); } @Test public void testSelectEngineKeyAllNull() throws Exception { testYaml(" "- Statement: !select-engine { all: null, foo: oops }"); testYaml(" "- Statement: !select-engine { foo: oops, all: null }"); } /* Test Include */ @Test public void testIncludeMissingValue() throws Exception { testYaml("- Include:"); } @Test public void testIncludeNullValue() throws Exception { testYaml("- Include: null"); } @Test public void testIncludeWrongTypeValue() throws Exception { testYamlFail("- Include: [a, b]"); } @Test public void testIncludeFileNotFound() throws Exception { testYamlFail("- Include: file-definitely-not-found"); } @Test public void testIncludeUnexpectedAttributes() throws Exception { testYamlFail("- Include: somefile\n" + "- foo: bar"); } @Test public void testIncludeRegexp() throws Exception { testYamlFail("- Include: !re foo.yaml"); } @Test public void testIncludeSimple() throws Exception { File include = File.createTempFile("include", null); include.deleteOnExit(); writeFile(include, " "- CreateTable: c (cid int)\n" + " "- Statement: INSERT INTO c VALUES (1), (2)\n"); testYaml(" "- Include: " + include + "\n" + " "- Statement: SELECT * FROM c\n" + "- output: [[1], [2]]\n"); } @Test public void testIncludeNested() throws Exception { File include1 = File.createTempFile("include1", null); include1.deleteOnExit(); File include2 = File.createTempFile("include2", null); include2.deleteOnExit(); writeFile(include1, " "- Include: " + include2 + "\n" + " "- Statement: INSERT INTO c VALUES (1), (2)\n"); writeFile(include2, " "- CreateTable: c (cid int)\n"); testYaml(" "- Include: " + include1 + "\n" + " "- Statement: SELECT * FROM c\n" + "- output: [[1], [2]]\n"); } @Test public void testIncludeNestedFileNotFound() throws Exception { File include = File.createTempFile("include", null); include.deleteOnExit(); writeFile(include, " "- Include: file-that-is-not-found"); testYamlFail(" "- Include: " + include); } @Test public void testIncludeNestedRelative() throws Exception { File include1 = File.createTempFile("include1", null); include1.deleteOnExit(); File include2 = File.createTempFile("include2", null); include2.deleteOnExit(); writeFile(include1, " "- Include: " + include2.getName() + "\n" + " "- Statement: INSERT INTO c VALUES (1), (2)\n"); writeFile(include2, " "- CreateTable: c (cid int)\n"); testYaml(" "- Include: " + include1 + "\n" + " "- Statement: SELECT * FROM c\n" + "- output: [[1], [2]]\n"); } @Test public void testIncludeHasError() throws Exception { File include = File.createTempFile("include", null); include.deleteOnExit(); writeFile(include, " "- Properties: all\n" + "- prop_b: prop_b_value\n" + " "- Statement: a b c\n" + "- unexpected_attribute: nope"); testYamlFail(" "- Properties: all\n" + "- prop_a: prop_a_value\n" + " "- Include: " + include); } @Test public void testIncludeSelectEngine() throws Exception { File includeFile = File.createTempFile("include", null); includeFile.deleteOnExit(); writeFile(includeFile, "- CreateTable: t (bigint_field bigint)\n"); /* * Double backslashes, to escape them in the YAML format. Note that * they need to be doubled for Java strings, and double again for * regexps. */ String include = includeFile.getPath().replaceAll("\\\\", "\\\\"); testYaml(" "- Include: !select-engine { foo: bar, it: '" + include + "' }\n" + " "- Statement: SELECT bigint_field FROM t\n" + "..."); } /* Test Properties */ @Test public void testPropertiesNoValue() throws Exception { testYamlFail(" "- Properties:\n"); } @Test public void testPropertiesNullValue() throws Exception { testYamlFail(" "- Properties: null\n"); } @Test public void testPropertiesValueNotString() throws Exception { testYamlFail(" "- Properties: 33\n"); } @Test public void testPropertiesValueUnknownEngine() throws Exception { testYaml(" "- Properties: gorp\n"); } @Test public void testPropertiesValueRegexp() throws Exception { testYamlFail(" "- Properties: !re all\n"); } @Test public void testPropertiesValueAttributesNotSequenceOfMaps() throws Exception { testYamlFail(" "- Properties: all\n" + "33\n"); } @Test public void testPropertiesValueSuppressedNoValue() throws Exception { testYamlFail(" "- Properties: all\n" + "- suppressed:\n"); } @Test public void testPropertiesValueSuppressedBadValue() throws Exception { testYamlFail(" "- Properties: all\n" + "- suppressed: gorp\n"); } @Test public void testPropertiesValueSuppressedAll() throws Exception { testYaml(" "- Properties: all\n" + "- suppressed: true\n" + " "- Never seen!\n"); } @Test public void testPropertiesValueSuppressedIt() throws Exception { testYaml(" "- Properties: it\n" + "- suppressed: true\n" + " "- Never seen!\n"); } /* Test CreateTable */ @Test public void testCreateTableNoValue() throws Exception { testYamlFail("- CreateTable:"); } @Test public void testCreateTableNullValue() throws Exception { testYamlFail("- CreateTable: null"); } @Test public void testCreateTableSequenceValue() throws Exception { testYamlFail("- CreateTable: [a, b, c]"); } @Test public void testCreateTableUnexpectedAttribute() throws Exception { testYamlFail("- CreateTable: foo (int_field int)\n" + "- unexpected_attribute: quux"); } @Test public void testCreateTableSuccess() throws Exception { testYaml("- CreateTable: foo (int_field int)"); } /* Test CreateTable error */ @Test public void testCreateTableErrorNoValue() throws Exception { testYamlFail( "- CreateTable: a b c\n" + "- error:"); } @Test public void testCreateTableErrorNotSequence() throws Exception { testYamlFail( "- CreateTable: a b c\n" + "- error: fooey"); } @Test public void testCreateTableErrorEmptySequence() throws Exception { testYamlFail( "- CreateTable: a b c\n" + "- error: []"); } @Test public void testCreateTableErrorRepeated() throws Exception { testYamlFail("- CreateTable: a (i int\n" + "- error: [42000]\n" + "- error: [42000]\n"); } @Test public void testCreateTableErrorSequenceTooLong() throws Exception { testYamlFail( " "- CreateTable: a b c\n" + "- error: [1, a, b]"); } @Test public void testCreateTableErrorCodeNotScalar() throws Exception { testYamlFail( " "- CreateTable: a b c\n" + "- error: [[x, y], a, b]"); } @Test public void testCreateTableErrorNotError() throws Exception { testYamlFail( " "- CreateTable: a (i int)\n" + "- error: [1]"); } @Test public void testCreateTableNotErrorError() throws Exception { testYamlFail("- CreateTable: a (int_field int"); } @Test public void testCreateTableErrorWrongError() throws Exception { testYamlFail( " "- CreateTable: a (i int\n" + "- error: [37]"); } @Test public void testCreateTableErrorRightError() throws Exception { testYaml( " "- CreateTable: a (i int\n" + "- error: [42000]"); } @Test public void testCreateTableErrorWrongErrorMessage() throws Exception { testYamlFail( " "- CreateTable: a (i int\n" + "- error: [42000, nope]"); } @Test public void testCreateTableErrorRightErrorMessage() throws Exception { testYaml( " "- CreateTable: a (i int\n" + "- error:\n" + " - 42000\n" + " - |\n" + " ERROR: Encountered \"<EOF>\" at line 1, column 21.\n" + " Was expecting one of:\n" + " \")\" ...\n" + " \",\" ...\n" + " \n" + " Position: 21"); } @Test public void testCreateTableErrorSelectEngine() throws Exception { testYaml( " "- CreateTable: a (i int\n" + "- error: !select-engine { it: [42000], sys-aksql: [33] }"); } /* Test Statement */ @Test public void testStatementNoValue() throws Exception { testYaml("- Statement:"); } @Test public void testStatementNullValue() throws Exception { testYaml("- Statement: null"); } @Test public void testStatementValueInteger() throws Exception { testYamlFail("- Statement: 3"); } @Test public void testStatementValueSequence() throws Exception { testYamlFail("- Statement: [a, b, c]"); } @Test public void testStatementUnknownAttribute() throws Exception { testYamlFail("- Statement: a b c\n" + "- unknown_attrib: x y z"); } @Test public void testStatementCreateTable() throws Exception { testYamlFail("- Statement: create TABLE foo (int_field int)"); } @Test public void testStatementSelectEngineMatch() throws Exception { testYaml("- Statement: !select-engine { it: MORP }\n" + "- error: [42000]"); } @Test public void testStatementSelectEngineMatchAll() throws Exception { testYaml("- Statement: !select-engine { all: MORP }\n" + "- error: [42000]"); } @Test public void testStatementSelectEngineNoMatch() throws Exception { testYaml("- Statement: !select-engine { sys: MORP }"); } /* Test Statement params */ @Test public void testStatementParamsNoValue() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: SELECT * FROM t\n" + "- params:"); } @Test public void testStatementParamsNullValue() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: SELECT * FROM t\n" + "- params: null"); } @Test public void testStatementParamsRepeated() throws Exception { testYamlFail(" "- CreateTable: t (i int)\n" + " "- Statement: SELECT * FROM t WHERE i = ?\n" + "- params: [[1]]\n" + "- params: [[2]]\n"); } @Test public void testStatementParamsNotSequence() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: 3"); } @Test public void testStatementParamsValueSequenceOfMaps() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: [a: b]"); } @Test public void testStatementParamsValueEmpty() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: []"); } @Test public void testStatementParamsValueEmptySequence() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: [[], []]"); } @Test public void testStatementParamsValueDifferentLengthParams() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: [[a, b], [c, d, e]]"); } /* Test Statement param_types */ @Test public void testStatementParamsTypesNoParams() throws Exception { testYamlFail("- Statement: a b c\n" + "- param_types: [CHAR]"); } @Test public void testStatementParamsTypesNoParamsNoValue() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: SELECT * FROM t\n" + "- param_types:"); } @Test public void testStatementParamsTypesNullParamsNullValue() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: SELECT * FROM t\n" + "- params: null\n" + "- param_types: null"); } @Test public void testStatementParamsTypesNoValue() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: SELECT * FROM t WHERE bigint_field = ?\n" + "- params: [[1]]\n" + "- param_types:"); } @Test public void testStatementParamsTypesNullValue() throws Exception { testYaml(" "- CreateTable: t (bigint_field bigint)\n" + " "- Statement: SELECT * FROM t WHERE bigint_field = ?\n" + "- params: [[1]]\n" + "- param_types: null"); } @Test public void testStatementParamsTypesUnknown() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: [[a, b]]\n" + "- param_types: [CHAR, WHATTYPE]"); } @Test public void testStatementParamsTypesEmpty() throws Exception { testYamlFail("- Statement: a b c\n" + "- param_types: []"); } @Test public void testStatementParamsTypesRepeated() throws Exception { testYamlFail(" "- CreateTable: t (i int)\n" + " "- Statement: SELECT * FROM t WHERE i = ?\n" + "- params: [[1]]\n" + "- param_types: [INTEGER]\n" + "- param_types: [INTEGER]\n"); } @Test public void testStatementParamsTypesTooMany() throws Exception { testYamlFail("- Statement: a b c\n" + "- param_types: [CHAR, INTEGER, BOOLEAN]\n" + "- params: [[a, b]]"); } @Test public void testStatementParamsTypesTooFew() throws Exception { testYamlFail("- Statement: a b c\n" + "- params: [[a, b]]\n" + "- param_types: [CHAR]"); } @Test public void testStatementParamTypesSuccess() throws Exception { testYaml( " "- CreateTable: c (cid int)\n" + " "- Statement: INSERT INTO c VALUES (1), (2)\n" + " "- Statement: SELECT * FROM c where cid = ?\n" + "- params: [[1]]\n" + "- param_types: [DECIMAL]\n" + "- output: [[1]]"); } @Test public void testStatementParamTypesSelectEngine() throws Exception { testYaml( " "- CreateTable: c (cid int)\n" + " "- Statement: INSERT INTO c VALUES (1), (2)\n" + " "- Statement: SELECT * FROM c where cid = ?\n" + "- params: [[1]]\n" + "- param_types: !select-engine { it: [DECIMAL], foo: bar }\n" + "- output: [[1]]"); } /* Test Statement output */ @Test public void testStatementOutputNoValue() throws Exception { testYaml(" "- CreateTable: t (id int)\n" + " "- Statement: SELECT * FROM t\n" + "- output:"); } @Test public void testStatementOutputRepeated() throws Exception { testYamlFail(" "- CreateTable: t (id int)\n" + " "- Statement: INSERT INTO t VALUES (1)\n" + " "- Statement: SELECT * FROM t\n" + "- output: [[1]]\n" + "- output: [[1]]\n"); } @Test public void testStatementOutputNullValue() throws Exception { testYaml(" "- CreateTable: t (id int)\n" + " "- Statement: SELECT * FROM t\n" + "- output: null"); } @Test public void testStatementOutputValueNotSequence() throws Exception { testYamlFail("- Statement: a b c\n" + "- output: 33"); } @Test public void testStatementOutputValueNotSequenceOfSequences() throws Exception { testYamlFail("- Statement: a b c\n" + "- output: [33]"); } @Test public void testStatementOutputValueNotSequenceOfSequencesOfScalars() throws Exception { testYamlFail("- Statement: a b c\n" + "- output: [[[33]]]"); } @Test public void testStatementOutputEmpty() throws Exception { testYamlFail("- Statement: a b c\n" + "- output: []"); } @Test public void testStatementOutputEmptyRow() throws Exception { testYamlFail("- Statement: a b c\n" + "- output: [[], []]"); } @Test public void testStatementOutputDifferentRowLengths() throws Exception { testYamlFail("- Statement: a b c\n" + "- output: [[a], [b], [c, d, e]]"); } @Test public void testStatementOutputWrongResults() throws Exception { testYamlFail( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [1, Smith]\n" + " - [2, Howard]\n"); } @Test public void testStatementOutputMissingRow() throws Exception { testYamlFail( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [1, Smith]"); } @Test public void testStatementOutputExtraRow() throws Exception { testYamlFail( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [1, Smith]\n" + " - [2, Jones]\n" + " - [2, Jones]\n"); } @Test public void testStatementOutputRightResults() throws Exception { testYaml( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [1, Smith]\n" + " - [2, Jones]\n"); } @Test public void testStatementOutputEmptyValue() throws Exception { testYaml( " "- CreateTable: t (x varchar(32), y varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('', 'abc')\n" + " "- Statement: SELECT * FROM t\n" + "- output:\n" + " - ['', 'abc']\n"); } @Test public void testStatementOutputDontCare() throws Exception { testYaml( " "- CreateTable: customers (cid int, name varchar(32))\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [!dc dc, Smith]\n" + " - [2, !dc dc]"); } @Test public void testStatementOutputDontCareMissingValue() throws Exception { testYamlFail( " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [!dc]\n"); } @Test public void testStatementOutputRegexp() throws Exception { testYaml( " "- CreateTable: t (name varchar(32))\n" + " "- Statement: INSERT INTO t VALUES\n" + " ('hubba-hubba'), ('abc123')\n" + " "- Statement: SELECT * FROM t\n" + "- output:\n" + " - [!re '([^-]*)-{1}']\n" + " - [!re '[a-z]+[0-9]+']\n"); } @Test public void testStatementOutputRegexpMissingValue() throws Exception { testYamlFail( " "- Statement: SELECT * FROM t\n" + "- output:\n" + " - [!re]\n"); } @Test public void testStatementOutputRegexpNonScalarValue() throws Exception { testYamlFail( " "- Statement: SELECT * FROM t\n" + "- output:\n" + " - [!re [a, b, c]]\n"); } @Test public void testStatementOutputRegexpSelectEngine() throws Exception { testYaml( " "- CreateTable: t (name varchar(32))\n" + " "- Statement: INSERT INTO t VALUES\n" + " ('abc'), ('123')\n" + " "- Statement: SELECT * FROM t\n" + "- output:\n" + " !select-engine\n" + " it: [[!re '[a-z]+'], [!re '[0-9]+']]\n" + " foo: bar\n"); } @Test public void testStatementOutputNullAndEmpty() throws Exception { testYaml( " "- CreateTable: customers (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO customers (name)\n" + " VALUES ('Smith'), (''), ('null')\n" + " "- Statement: INSERT INTO customers (cid) VALUES (1)\n" + " "- Statement: SELECT * FROM customers\n" + "- output:\n" + " - [null, Smith]\n" + " - [null, '']\n" + " - [null, 'null']\n" + " - [1, null]\n" + "..."); } @Test public void testStatementOutputParamsRightResults() throws Exception { testYaml( " "- CreateTable: customers (cid int, name varchar(32))\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + " "- Statement: SELECT * FROM customers WHERE name = ?\n" + "- params: [[Jones], [Smith], [Smith]]\n" + "- output:\n" + " - [2, Jones]\n" + " - [1, Smith]\n" + " - [1, Smith]"); } @Test public void testStatementOutputParamsExtraResultsOneCall() throws Exception { testYamlFail( " "- CreateTable: parts (part varchar(32), product varchar(32))\n" + " "- Statement:\n" + " INSERT INTO parts VALUES\n" + " ('a123', 'a'), ('a456', 'a'), ('b789', 'b'), ('b000', 'b'),\n" + " ('c246', 'c')\n" + " "- Statement: SELECT * FROM parts WHERE product = ?\n" + "- params: [[a], [b]]\n" + "- output:\n" + " - [a123, a]\n" + " - [a456, a]\n" + " - [b789, b]"); } @Test public void testStatementOutputParamsExtraResultsExtraCall() throws Exception { testYamlFail( " "- CreateTable: parts (part varchar(32), product varchar(32))\n" + " "- Statement:\n" + " INSERT INTO parts VALUES\n" + " ('a123', 'a'), ('a456', 'a'), ('b789', 'b'), ('b000', 'b'),\n" + " ('c246', 'c')\n" + " "- Statement: SELECT * FROM parts WHERE product = ?\n" + "- params: [[a], [b], [c]]\n" + "- output:\n" + " - [a123, a]\n" + " - [a456, a]\n" + " - [b789, b]\n" + " - [b000, b]"); } @Test public void testStatementOutputParamsExtraOutputOneCall() throws Exception { testYamlFail( " "- CreateTable: parts (part varchar(32), product varchar(32))\n" + " "- Statement:\n" + " INSERT INTO parts VALUES\n" + " ('a123', 'a'), ('a456', 'a'), ('b789', 'b'), ('b000', 'b'),\n" + " ('c246', 'c')\n" + " "- Statement: SELECT * FROM parts WHERE product = ?\n" + "- params: [[a], [b]\n" + "- output:\n" + " - [a123, a]\n" + " - [a456, a]\n" + " - [b789, b]\n" + " - [b000, b]\n" + " - [c246, c]"); } @Test public void testStatementOutputParamsWrongOutput() throws Exception { testYamlFail( " "- CreateTable: parts (part varchar(32), product varchar(32))\n" + " "- Statement:\n" + " INSERT INTO parts VALUES\n" + " ('a123', 'a'), ('a456', 'a'), ('b789', 'b'), ('b000', 'b'),\n" + " ('c246', 'c')\n" + " "- Statement: SELECT * FROM parts WHERE product = ?\n" + "- params: [[a], [b]\n" + "- output:\n" + " - [a123, a]\n" + " - [a456, a]\n" + " - [b789, b]\n" + " - [bxyz, b]"); } /* Test Statement row_count */ @Test public void testStatementRowCountNoValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- row_count:"); } @Test public void testStatementRowCountNullValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- row_count: null"); } @Test public void testStatementRowCountNotInteger() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- row_count: hello"); } @Test public void testStatementRowCountNegative() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- row_count: -33"); } @Test public void testStatementRowCountRepeated() throws Exception { testYamlFail(" "- Statement: a b c\n" + "- row_count: 1\n" + "- row_count: 1\n"); } @Test public void testStatementRowCountWrongValue() throws Exception { testYamlFail( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + "- row_count: 1\n"); } @Test public void testStatementRowCountDifferentFromOutput() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- output: [[a]]\n" + "- row_count: 2"); } @Test public void testStatementRowCountCorrect() throws Exception { testYaml( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + "- row_count: 2\n"); } @Test public void testStatementRowCountSelectEngine() throws Exception { testYaml( " "- CreateTable: customers (cid int, name varchar(32));\n" + " "- Statement:\n" + " INSERT INTO customers VALUES (1, 'Smith'), (2, 'Jones');\n" + "- row_count: !select-engine { foo: 7, all: 2}\n"); } /* Test Statement output_types */ @Test public void testStatementOutputTypesNoValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- output_types:"); } @Test public void testStatementOutputTypesRepeated() throws Exception { testYamlFail(" "- CreateTable: t (i int)\n" + " "- Statement: INSERT INTO t VALUES (1)\n" + " "- Statement: SELECT * FROM t\n" + "- output_types: [INTEGER]\n" + "- output_types: [INTEGER]\n"); } @Test public void testStatementOutputTypesNullValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- output_types: null"); } @Test public void testStatementOutputTypesNotSequence() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- output_types: 33"); } @Test public void testStatementOutputTypesEmpty() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- output_types: []"); } @Test public void testStatementOutputTypesWrongLengthFromOutput() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- output_types: [BOOLEAN]\n" + "- output: [[a, b, c]]"); } @Test public void testStatementOutputTypesUnknownType() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- output_types: [GROOVY]"); } @Test public void testStatementOutputTypesWrongNumberOfTypes() throws Exception { testYamlFail( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- output_types: [INTEGER]"); } @Test public void testStatementOutputTypesWrongType() throws Exception { testYamlFail( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- output_types: [INTEGER, BOOLEAN]"); } @Test public void testStatementOutputTypesCorrectTypes() throws Exception { testYaml( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- output_types: [INTEGER, VARCHAR]"); } @Test public void testStatementOutputTypesSelectEngine() throws Exception { testYaml( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- output_types: [INTEGER, !select-engine { it: VARCHAR }]"); } /* Test Statement explain */ @Test public void testStatementExplainNoValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- explain:"); } @Test public void testStatementExplainRepeated() throws Exception { testYamlFail(" "- CreateTable: t (i int)\n" + " "- Statement: SELECT * FROM t\n" + "- explain: foo\n" + "- explain: bar\n"); } @Test public void testStatementExplainNullValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- explain: null"); } @Test public void testStatementExplainSequenceValue() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- explain: [d, e, f]"); } @Test public void testStatementExplainWrong() throws Exception { testYamlFail( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- explain: Nope"); } @Test public void testStatementExplainRight() throws Exception { testYaml( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- explain: |\n" + " project([Field(0), Field(1)])\n" + " Filter_Default([user.c])\n" + " GroupScan_Default(full scan on _akiban_c)\n"); } @Test public void testStatementExplainSelectEngine() throws Exception { testYamlFail( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones')\n" + " "- Statement: SELECT * FROM c\n" + "- explain: !select-engine { all: stuff }"); } /* Test Statement error */ @Test public void testStatementErrorNoValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- error:"); } @Test public void testStatementErrorRepeated() throws Exception { testYamlFail(" "- CreateTable: t (int_field int)\n" + " "- Statement: WHAT IS THIS\n" + "- error: [42000]\n" + "- error: [42000]\n"); } @Test public void testStatementErrorAndOutput() throws Exception { testYamlFail(" "- CreateTable: t (int_field int)\n" + " "- Statement: INSERT INTO t VALUES (1)\n" + " "- Statement: SELECT * FROM t\n" + "- output: [[1]]\n" + "- error: [0]\n"); } @Test public void testStatementErrorAndRowCount() throws Exception { testYamlFail(" "- CreateTable: t (int_field int)\n" + " "- Statement: INSERT INTO t VALUES (1)\n" + " "- Statement: SELECT * FROM t\n" + "- row_count: 1\n" + "- error: [0]\n"); } @Test public void testStatementErrorNullValue() throws Exception { testYaml( " "- CreateTable: t (int_field int)\n" + " "- Statement: SELECT * FROM t\n" + "- error: null"); } @Test public void testStatementErrorNotSequence() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- error: fooey"); } @Test public void testStatementErrorEmptySequence() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- error: []"); } @Test public void testStatementErrorSequenceTooLong() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- error: [1, a, b]"); } @Test public void testStatementErrorCodeNotScalar() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- error: [[x, y], a, b]"); } @Test public void testStatementErrorNotError() throws Exception { testYamlFail( " "- CreateTable a (i int)\n" + " "- Statement: SELECT * FROM a\n" + "- error: [1]"); } @Test public void testStatementErrorWrongError() throws Exception { testYamlFail( " "- Statement: SELECT * FR\n" + "- error: [37]"); } @Test public void testStatementErrorRightError() throws Exception { testYaml( " "- Statement: SELECT * FR\n" + "- error: [42000]"); } @Test public void testStatementErrorWrongErrorMessage() throws Exception { testYamlFail( " "- Statement: SELECT * FR\n" + "- error: [42000, nope]"); } @Test public void testStatementErrorRightErrorMessage() throws Exception { testYaml( " "- Statement: SELECT * FR\n" + "- error:\n" + " - 42000\n" + " - |\n" + " ERROR: Encountered \" <IDENTIFIER> \"FR \"\" at line 1, column 10.\n" + " Was expecting one of:\n" + " <EOF> \n" + " \"except\" ...\n" + " \"fetch\" ...\n" + " \"for\" ...\n" + " \"from\" ...\n" + " \"group\" ...\n" + " \"having\" ...\n" + " \"intersect\" ...\n" + " \"order\" ...\n" + " \"union\" ...\n" + " \"where\" ...\n" + " \"window\" ...\n" + " \"with\" ...\n" + " \"offset\" ...\n" + " \"limit\" ...\n" + " \",\" ...\n" + " \n" + " Position: 10"); } @Test public void testStatementErrorSelectEngineNoMatch() throws Exception { testYamlFail( " "- Statement: SELECT * FR\n" + "- error: !select-engine { foo: [bar] }"); } @Test public void testStatementErrorSelectEngineNoMatchWithMessage() throws Exception { testYamlFail( " "- Statement: SELECT * FR\n" + "- error: [!select-engine { foo: bar }, Hello]"); } @Test public void testStatementErrorSelectEngineMatch() throws Exception { testYaml( " "- Statement: SELECT * FR\n" + "- error: [!select-engine { it: 42000, all: 42 }]"); } /* Test Statement sorted_output */ @Test public void testSortedOutput() throws Exception { testYamlFail( " "- CreateTable: c (cid int, name varchar(32))\n" + " "- Statement: INSERT INTO c VALUES (1, 'Smith'), (2, 'Jones'), (3, 'Zoolander'), (4, 'Adams') \n" + " "- Statement: SELECT * FROM c\n" + "- output: [[1, 'Smith'],[2, 'Jones'],[4, 'Adams'],[3, 'Zoolander']]"); testYaml(" "- Statement: SELECT * FROM c\n" + "- output_ordered: [[1, 'Smith'],[2, 'Jones'],[4, 'Adams'],[3, 'Zoolander']]"); testYaml(" "- Statement: SELECT * FROM c\n" + "- output_ordered: [[3, 'Zoolander'],[1, 'Smith'],[2, 'Jones'],[4, 'Adams']]"); testYamlFail(" "- Statement: SELECT * FROM c\n" + "- output_ordered: [[3, 'Zoolander'],[1, 'Wendel'],[2, 'Jones'],[4, 'Adams']]"); testYamlFail(" "- Statement: SELECT * FROM c order by cid desc \n" + "- output: [[3, 'Zoolander'],[1, 'Smith'],[2, 'Jones'],[4, 'Adams']]"); } @Test public void testIgnoreBulkloadCommand() throws Exception { testYamlFail("---\n- Bulkload: /home/akiba/fts_basis.properties\n"+ "- properties: {'dataset.coi.address.ratio': 3, 'dataset.coi.order.ratio': 2, 'dataset.coi.customer.count': 200, 'dataset.coi.item.ratio': 2}\n..."); } /* Test Statement warnings_count */ @Test public void testStatementWarningsCountNoValue() throws Exception { testYaml(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count:\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsCountRepeated() throws Exception { testYamlFail(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: 1\n" + "- warnings_count: 2\n"); } @Test public void testStatementWarningsCountNullValue() throws Exception { testYaml(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: null\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsCountString() throws Exception { testYamlFail(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: 'abc'\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsCountWrongValue() throws Exception { testYamlFail(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: 1\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsCountDifferentFromWarnings() throws Exception { testYamlFail(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: 2\n" + "- warnings: [[ 'abc' ]]\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsCountNonZeroNoWarnings() throws Exception { testYamlFail(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: 1\n"); } @Test public void testStatementWarningsCountZero() throws Exception { testYaml(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings_count: 0\n"); } @Test public void testStatementWarningsCountZeroWithWarnings() throws Exception { testYamlFail(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings_count: 0\n"); } @Test public void testStatementWarningsCountWithWarnings() throws Exception { testYaml(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings_count: 1\n"); } @Test public void testStatementWarningsCountRegexpWithWarnings() throws Exception { testYaml(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings_count: !re '[1-9]'\n"); } /* Test Statement warnings */ @Test public void testStatementWarningsNoValue() throws Exception { testYaml(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings:\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsRepeated() throws Exception { testYamlFail(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings: [[1]]\n" + "- warnings: [[2]]\n"); } @Test public void testStatementWarningsNullValue() throws Exception { testYaml(" "- CreateTable: t (f int)\n" + " "- Statement: SELECT * FROM t\n" + "- warnings: null\n" + "- row_count: 0\n"); } @Test public void testStatementWarningsValueNotSequence() throws Exception { testYamlFail("- Statement: a b c\n" + "- warnings: 33"); } @Test public void testStatementWarningsValueNotSequenceOfSequences() throws Exception { testYamlFail("- Statement: a b c\n" + "- warnings: [33]"); } @Test public void testStatementWarningsValueNotSequenceOfSequencesOfScalars() throws Exception { testYamlFail("- Statement: a b c\n" + "- warnings: [[[33]]]"); } @Test public void testStatementWarningsEmpty() throws Exception { testYamlFail("- Statement: a b c\n" + "- warnings: []"); } @Test public void testStatementWarningsEmptyElement() throws Exception { testYamlFail("- Statement: a b c\n" + "- warnings: [[]]"); } @Test public void testStatementWarningsSequenceTooLong() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- warnings: [[1, a, b]]"); } @Test public void testStatementWarningsCodeNotScalar() throws Exception { testYamlFail( " "- Statement: a b c\n" + "- warnings: [[[x, y]]]"); } @Test public void testStatementWarningsWrongCode() throws Exception { testYamlFail(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings: [[1234], [1234], [1234], [1234]]\n"); } @Test public void testStatementWarningsWrongMessage() throws Exception { testYamlFail(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings: [[22007, 'Foo'],\n" + " [22007, 'Foo'],\n" + " [22007, 'Foo'],\n" + " [22007, 'Foo']]"); } @Test public void testStatementWarningsRightMessage() throws Exception { testYaml(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings: [[55003, \"Can't convert source type `VARCHAR` to target `DATETIME`\"]]"); } @Test public void testStatementWarningsDontMatchCount() throws Exception { testYamlFail(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings_count: 3\n" + "- warnings: [[22007, 'Invalid date format: a'],\n" + " [22007, 'Invalid date format: a'],\n" + " [22007, 'Invalid timestamp format: a'],\n" + " [22007, 'Invalid year format: a']]"); } @Test public void testStatementWarningsMatchCount() throws Exception { testYaml(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings_count: 1\n" + "- warnings: [[55003, \"Can\'t convert source type `VARCHAR` to target `DATETIME`\"]]"); } @Test public void testStatementWarningsRegexp() throws Exception { testYaml(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: INSERT INTO t VALUES ('a')\n" + " "- Statement: SELECT DATE(vc) FROM t\n" + "- warnings: [[!re '[0-9]+', !re \"Can't convert .*\"]]"); } @Test public void testConnectionReuse() throws Exception { boolean failed = false; try { testYaml(" "- CreateTable: t (vc varchar(32))\n" + " "- Statement: SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY\n" + " "- Statement: SELECT garbage FROM t\n"); } catch (AssertionError e) { failed = true; } assertTrue("First half failed", failed); // ^ Left connection read-only. testYaml(" "- Statement: INSERT INTO t VALUES ('a')\n"); } /* Other methods */ private void testYaml(String yaml) throws Exception { if (DEBUG) { StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); if (callStack.length > 2) { String testMethod = callStack[2].getMethodName(); System.err.println(testMethod + ": "); } } Connection connection = getConnection(); try { new YamlTester(null, new StringReader(yaml), connection).test(); } catch (Exception e) { if (DEBUG) { System.err.println("Test failed:"); e.printStackTrace(); } forgetConnection(); throw e; } catch (Error e) { if (DEBUG) { System.err.println("Test failed:"); e.printStackTrace(); } forgetConnection(); throw e; } if (DEBUG) { System.err.println("Test passed"); } } private void testYamlFail(String yaml) throws Exception { if (DEBUG) { StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); if (callStack.length > 2) { String testMethod = callStack[2].getMethodName(); System.err.println(testMethod + ": "); } } Connection connection = getConnection(); try { new YamlTester(null, new StringReader(yaml), connection).test(); if (DEBUG) { System.err.println("Test failed: Expected exception"); } } catch (Throwable t) { if (DEBUG) { System.err.println(t); //t.printStackTrace(); } return; } fail("Expected exception"); } private void writeFile(File file, String text) throws IOException { Writer out = new FileWriter(file); try { out.write(text); } finally { out.close(); } } }
package lux; import static lux.IndexTestSupport.QUERY_CONSTANT; import static lux.IndexTestSupport.QUERY_EXACT; import static lux.IndexTestSupport.QUERY_MINIMAL; import static lux.IndexTestSupport.QUERY_NO_DOCS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Iterator; import lux.exception.LuxException; import lux.saxon.UnOptimizer; import lux.xpath.AbstractExpression; import lux.xquery.XQuery; import net.sf.saxon.s9api.XQueryExecutable; import net.sf.saxon.s9api.XdmNode; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; /** * Check a variety of XPath queries, ensuring that results when executed using the default indexing * settings, as provided by IndexTestSupport, are correct, * and test that expected optimizations are in fact being applied. */ @RunWith (MultiThreadedRunner.class) public class SearchTest extends BaseSearchTest { @BeforeClass public static void setup() throws Exception { setup ("lux/hamlet.xml"); } @Test public void testSearchAllDocs() throws Exception { XdmResultSet results = assertSearch("/", IndexTestSupport.QUERY_EXACT); assertEquals (index.totalDocs, results.size()); } @Test public void testCountAllDocs () throws Exception { XdmResultSet results = assertSearch ("count(/)", QUERY_NO_DOCS, totalDocs); assertEquals (String.valueOf(totalDocs), results.iterator().next().toString()); results = assertSearch ("count(collection())", QUERY_NO_DOCS, totalDocs); assertEquals (String.valueOf(totalDocs), results.iterator().next().toString()); results = assertSearch ("count(lux:search('*:*'))", QUERY_NO_DOCS, totalDocs); assertEquals (String.valueOf(totalDocs), results.iterator().next().toString()); } @Test public void testExists () throws Exception { assertSearch ("true", "exists(/)", QUERY_NO_DOCS, 1); assertSearch ("true", "exists(//SCENE)", QUERY_NO_DOCS, 1); assertSearch ("false", "exists(//foo)", QUERY_NO_DOCS, 0); assertSearch ("true", "exists(//SCENE/root())", QUERY_NO_DOCS, 1); assertSearch ("true", "exists(//SCENE) and exists(//ACT)", QUERY_NO_DOCS, 2); assertSearch ("true", "exists(//SCENE/root()//ACT)", QUERY_NO_DOCS, 1); assertSearch ("true", "exists((/)[.//SCENE and .//ACT])", QUERY_NO_DOCS, 1); assertSearch ("true", "exists(//ACT//SCENE)", QUERY_NO_DOCS, 1); } @Test public void testEmpty () throws Exception { XdmResultSet results = assertSearch ("empty(/)", QUERY_NO_DOCS, 1); assertEquals ("false", results.iterator().next().toString()); assertSearch ("false", "empty(//SCENE)", QUERY_NO_DOCS, 1); assertSearch ("true", "empty(//foo)", QUERY_NO_DOCS, 0); assertSearch ("false", "empty(//SCENE/root())", QUERY_NO_DOCS, 1); assertSearch ("true", "empty(//SCENE) or empty(//foo)", QUERY_NO_DOCS, 1); assertSearch ("false", "empty(//SCENE/root()//ACT)", QUERY_NO_DOCS, 1); assertSearch ("false", "empty((/)[.//SCENE and .//ACT])", QUERY_NO_DOCS, 1); } @Test public void testNot() throws Exception { XdmResultSet results = assertSearch ("not(/)", QUERY_NO_DOCS, 1); assertEquals ("false", results.iterator().next().toString()); assertSearch ("false", "not(//SCENE)", QUERY_NO_DOCS, 1); assertSearch ("true", "not(//foo)", QUERY_NO_DOCS, 0); assertSearch ("false", "not(//SCENE/root())", QUERY_NO_DOCS, 1); assertSearch ("true", "not(//SCENE) or not(//foo)", QUERY_NO_DOCS, 1); assertSearch ("false", "not(//SCENE/root()//ACT)", QUERY_NO_DOCS, 1); assertSearch ("false", "not((/)[.//SCENE and .//ACT])", QUERY_NO_DOCS, 1); assertSearch ("true", "not(//SCENE//ACT)", QUERY_NO_DOCS, 0); } @Test public void testPathOrder () throws Exception { // Make sure that the Optimizer doesn't incorrectly assert // order is *not* significant in the generated query; // it should be (SCENE AND ACT): // Overall there are 20 scenes in 5 acts in 1 play // 40 = 20 (SCENEs in /PLAY) + 20 (SCENEs in the 5 /ACTs together) assertSearch ("40", "count(//ACT/root()//SCENE)", 0, 6); // 10 = 5 (ACTs in /PLAY) + 5 /ACT documents. assertSearch ("10", "count(//SCENE/root()//ACT)", 0, 6); // Why did we think this?: // 120 = 20 (scenes) * 5 (acts) in 1 /PLAY + 20 scenes in 5 /ACT documents } @Test public void testSearchAct() throws Exception { // path indexes make this exact XdmResultSet results = assertSearch ("/ACT", QUERY_EXACT); assertEquals (index.elementCounts.get("ACT") + 0, results.size()); // Make sure that collection() is optimized results = assertSearch ("collection()/ACT", QUERY_EXACT); assertEquals (index.elementCounts.get("ACT") + 0, results.size()); // and that references to variables are optimized results = assertSearch ("let $context := collection() return $context/ACT", QUERY_EXACT); assertEquals (index.elementCounts.get("ACT") + 0, results.size()); } @Test public void testSearchActScene() throws Exception { XdmResultSet results = assertSearch("/ACT/SCENE", QUERY_MINIMAL); assertEquals (index.elementCounts.get("SCENE") + 0, results.size()); } @Test public void testSearchAllScenes() throws Exception { XdmResultSet results = assertSearch("/ACT", QUERY_MINIMAL); assertEquals (5, results.size()); XdmNode node = (XdmNode) results.iterator().next(); String actURI = node.getDocumentURI().toString(); results = assertSearch("//SCENE", QUERY_MINIMAL); // every SCENE, in its ACT and in the PLAY assertEquals (index.elementCounts.get("SCENE") * 3, results.size()); Iterator<?> iter = results.iterator(); for (int i = 0; i < index.elementCounts.get("SCENE"); i++) { // each scene, from the /PLAY document node = (XdmNode) iter.next(); assertEquals ("lux://lux/hamlet.xml", node.getDocumentURI().toString()); assertEquals ("lux://lux/hamlet.xml", node.getBaseURI().toString()); } XdmNode act1 = (XdmNode) iter.next(); assertEquals (actURI, act1.getBaseURI().toString()); } @Test public void testSearchAllSceneDocs() throws Exception { XdmResultSet results = assertSearch("(/)[.//SCENE]", QUERY_EXACT); // every SCENE, in its ACT and in the PLAY assertEquals (index.elementCounts.get("SCENE") + index.elementCounts.get("ACT") + 1, results.size()); } @Test public void testSearchAllSceneDocsRoot() throws Exception { XdmResultSet results = assertSearch("//SCENE/root()", QUERY_EXACT); // every SCENE, in its ACT and in the PLAY assertEquals (index.elementCounts.get("SCENE") + index.elementCounts.get("ACT") + 1, results.size()); } @Test public void testCountDocs () throws Exception { // every SCENE, in its ACT and in the PLAY int sceneDocCount = index.elementCounts.get("SCENE") + index.elementCounts.get("ACT") + 1; XdmResultSet results = assertSearch("count (//SCENE/root())", QUERY_NO_DOCS); assertResultValue(results, sceneDocCount); results = assertSearch("count ((/)[.//SCENE])", QUERY_NO_DOCS); assertResultValue(results, sceneDocCount); results = assertSearch("count (//SCENE/ancestor::document-node())", QUERY_NO_DOCS); assertResultValue(results, sceneDocCount); results = assertSearch("count (/descendant-or-self::SCENE/root())", QUERY_NO_DOCS); assertResultValue(results, sceneDocCount); results = assertSearch("count (/descendant::SCENE/root())", QUERY_NO_DOCS); assertResultValue(results, sceneDocCount); } @Test public void testSyntaxError () throws Exception { try { assertSearch ("hey bad boy"); assertTrue ("expected LuxException to be thrown for syntax error", false); } catch (LuxException e) { } } @Test public void testTextComparison () throws Exception { long t = System.currentTimeMillis(); String xpath = "//SCNDESCR >= //PERSONA"; Evaluator eval = index.makeEvaluator(); Compiler compiler = eval.getCompiler(); XQueryExecutable xquery = compiler.compile(xpath); XdmResultSet results = eval.evaluate(xquery); System.out.println ("query evaluated in " + (System.currentTimeMillis() - t) + " msec, retrieved " + results.size() + " result"); AbstractExpression aex = compiler.makeTranslator().queryFor(xquery).getBody(); aex = new UnOptimizer(index.indexer.getConfiguration()).unoptimize(aex); XQueryExecutable baseline = compiler.compile(aex.toString()); XdmResultSet baseResult = eval.evaluate(baseline); assertEquals ("result count mismatch for: " + xquery.toString(), baseResult.size(), results.size()); } @Test public void testComparisonPredicate () throws Exception { long t = System.currentTimeMillis(); String xpath = "//SCNDESCR[. >= //PERSONA]"; Evaluator eval = index.makeEvaluator(); Compiler compiler = eval.getCompiler(); XQueryExecutable xquery = compiler.compile(xpath); XdmResultSet results = eval.evaluate(xquery); System.out.println ("query evaluated in " + (System.currentTimeMillis() - t) + " msec, retrieved " + results.size() + " results"); XQuery optimized = eval.getCompiler().makeTranslator().queryFor(xquery); XQuery unoptimized = new UnOptimizer(index.indexer.getConfiguration()).unoptimize(optimized); XQueryExecutable baseline = compiler.compile(unoptimized.toString()); XdmResultSet baseResult = eval.evaluate(baseline); assertEquals ("result count mismatch for: " + xpath, baseResult.size(), results.size()); } @Test public void testConstantExpression() throws Exception { // This resolves to a constant (Literal=true()) XPath expression and generates // a null Lucene query. Make sure we don't try to execute the query. XdmResultSet results = assertSearch("'remorseless' or descendant::text", QUERY_CONSTANT); assertEquals (1, results.size()); } @Test public void testMultipleAbsolutePaths() throws Exception { // /PLAY/PERSONAE/PGROUP/PERSONA assertSearch("4", "count (//PERSONA[.='ROSENCRANTZ'])", 0, 4); assertSearch("4", "count (//PERSONA[.='GUILDENSTERN'])", 0, 4); // Our first naive implementation tried to fetch all relevant documents // using a single database query - this test tests multiple independent // sequences. // we retrieved 8 documents from search, because there are two queries generated, but // only 5 unique docs, and we cache, so only 5 docs are actually retrieved assertSearch("8", "count (//PERSONA[.='ROSENCRANTZ']) + count(//PERSONA[.='GUILDENSTERN'])", 0, 8); } @Test public void testLazyEvaluation () throws Exception { // These expressions are optimized in the sense that lux evaluates them all by retrieving // only the minimal number of required documents (with the available indexes). // Note this relies on Lucene's default sort by order of insertion (ie by docid) assertSearch ("BERNARDO", "subsequence(//SCENE, 1, 1)/SPEECH[1]/SPEAKER/string()", null, 1); assertSearch ("BERNARDO", "(//SCENE)[1]/SPEECH[1]/SPEAKER/string()", null, 1); // /PLAY/ACT[1]/SCENE[1], /ACT[1]/SCENE[1], /SCENE[1], /SCENE[2], /SCENE[3], /SCENE[4] // count reduced from 6 to 4 by path queries; skip /PLAY and /ACT[1] assertSearch ("HAMLET", "subsequence(/SCENE, 4, 1)/SPEECH[1]/SPEAKER/string()", null, 4); } @Test public void testSkipDocs () throws Exception { // Earlier implementations failed to indicate that the returned sequence of documents is sorted in document // order, causing Saxon to pull the entire result sequence. // TODO: We shouldn't need to retrieve (the text of) the first 3 documents in the first query below since // they are going to be discarded assertSearch ("KING CLAUDIUS", "subsequence((/)[.//SCENE], 4, 1)//SPEECH[1]/SPEAKER/string()", null, 4); assertSearch ("BERNARDO", "(//SCENE/SPEECH)[1]/SPEAKER/string()", null, 1); } @Test public void testSkipDocs2 () throws Exception { assertSearch ("BERNARDO", "(//SCENE/SPEECH)[1]/SPEAKER/string()", null, 1); } @Test public void testRoot () throws Exception { assertSearch ("KING CLAUDIUS", "(//SCENE/root())[4]//SPEECH[1]/SPEAKER/string()", null, 4); assertSearch ("KING CLAUDIUS", "subsequence(//SCENE/root(), 4, 1)//SPEECH[1]/SPEAKER/string()", null, 4); } @Test @Ignore public void testOptimizeLast () throws Exception { // Failed to optimize this. // We should be able to retrieve the last document, and then get its last speech // best idea for optimizing this is to add pagination to lux:search assertSearch ("PRINCE FORTINBRAS", "(lux:search('lux_elt_name_ms:SPEECH')[last()]//SPEECH)[last()]/SPEAKER/string()", null, 1); assertSearch ("PRINCE FORTINBRAS", "(//SPEECH)[last()]/SPEAKER/string()", null, 1164); } @Test public void testIntersection () throws Exception { // There were issues with // document order, which we have to assert in order to get lazy evaluation. // Intersect in particular exposes the problem since it's optimized based on // correct sorting (tip from Michael Kay). // NB - count was 1164; reduced to 1138 by path query (20 scenes + 5 acts + 1 play = 26). // Then reduced to 2! by a full text term query assertSearch ("2", "count(/SPEECH[contains(., 'philosophy')])", null, 2); // TODO - why is this 141 and not 28? assertSearch ("28", "count(/SPEECH[contains(., 'Horatio')])", null, 141); assertSearch ("8", "count(//SPEECH[contains(., 'philosophy')])", null, 7); // saxon cleverly optimizes this and gets rid of the intersect // but TODO our optimizer fails to see the opportunity for a word query assertSearch ("1", "count(/SPEECH[contains(., 'philosophy')] intersect /SPEECH[contains(., 'Horatio')])", null, 1138); } @Test public void testDocumentIdentity() throws Exception { /* This test confirms that document identity is preserved when creating Saxon documents. * document count was 1670 using path indexes; reduced to 88 using full text queries * TODO: Why is this not more optimal? * */ assertSearch ("1", "count(//SPEECH[contains(., 'philosophy')] intersect /SPEECH[contains(., 'Horatio')])", null, 88, 87); } @Test public void testDocumentOrder() throws Exception { /* This test confirms that the document ordering asserted by the Optimizer * is correct since if document order in Saxon * is not the same as document order in Lucene, then the first 31st document will not be * what we expect. 31 is a magic number because /PLAY has 20 /PLAY/ACT/SCENE, * /ACT 1 has 5 /ACT/SCENE, then those 5 are repeated as /SCENE. The 31st should be * /ACT[2]/SCENE[1], but since this will already have been created, its Saxon document * number would be low using the built-in numbering scheme, and the order mismatch causes * Saxon to terminate the intersection prematurely. */ assertSearch ("5", "count(/ACT/SCENE intersect subsequence(//SCENE, 1, 30))", null, 9, 8); assertSearch ("6", "count(/ACT/SCENE intersect subsequence(//SCENE, 1, 31))", null, 10, 8); } @Test public void testPaths () throws Exception { // test path ordering: assertSearch (null, "/ACT/PLAY", null, 0); assertSearch (null, "//ACT//PLAY", null, 0); // test path distance: assertSearch ("Where is your son?", "string(/PLAY/ACT[4]/SCENE[1]/SPEECH[1]/LINE[3])", null, 1); // Q: who decides what serialization to use? //assertSearch ("Where is your son?", "/PLAY/ACT[4]/SCENE[1]/SPEECH[1]/LINE[3]", null, 1); assertSearch ("Where is your son?", "string((/PLAY/ACT[4]LINE)[3])", null, 1); // no result, but we can't tell from the query and have to retrieve the document and process it assertSearch (null, "/PLAY/ACT[4]*/*/LINE", null, 1); } @Test public void testElementFullTextPhrase () throws Exception { // test phrase query generation // also handling of capitalization and tokenization (w/punctuation) assertSearch ("5", "count(//LINE[.='Holla! Bernardo!'])", null, 5, 5); assertSearch ("0", "count(//LINE[.='Holla!'])", null, 5, 5); assertSearch ("0", "count(//LINE[.='Holla Bernardo'])", null, 5, 5); assertSearch ("5", "count(//LINE[lower-case(.)='holla! bernardo!'])", null, 5, 5); // check stop word handling assertSearch ("<LINE>Where is your son?</LINE>", "//LINE[.='Where is your son?']", null, 5, 5); } @Test public void testFullText () throws Exception { " order by lux:field-values('doctype', $doc) return $doc/*/name())[1]", 0, 1); " order by lux:field-values('doctype', $doc) return $doc/*/name())[21]", 0, 21);
package tests; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import pages.HomePage; import utils.LocalDriverManager; import utils.Log4Test; import utils.PropertyLoader; import utils.WebDriverFactory; abstract public class BaseTest { @BeforeMethod public void setUp() { WebDriver driver = WebDriverFactory.initDriver(PropertyLoader.loadProperty("browser.name")); driver.manage().window().maximize(); LocalDriverManager.setDriver(driver); Log4Test.info("-_-_-_-_- Start of the test. -_-_-_-_-"); HomePage homePage = new HomePage(); homePage.open(); Assert.assertTrue(homePage.isOpened(), "Home page is not open."); } @AfterMethod public void tearDown() { Log4Test.info("-_-_-_-_- End of the test. -_-_-_-_-"); WebDriver driver = LocalDriverManager.getDriver(); if (driver != null) { driver.quit(); } } }
package morfologik.fsa.bytes; import java.util.Comparator; import java.util.HashMap; import morfologik.util.Arrays; /** * Automaton builder that uses <code>byte</code>s to label transitions. */ public class FSABuilder { /** * Lexicographic order of input sequences. */ public static int compare(byte [] s1, int lens1, byte [] s2, int lens2) { final int max = Math.min(lens1, lens2); for (int i = 0; i < max; i++) { final byte c1 = s1[i]; final byte c2 = s2[i]; if (c1 != c2) return c1 - c2; } return lens1 - lens2; } /** * Comparator comparing full byte arrays. */ protected static final Comparator<byte[]> LEXICAL_ORDERING = new Comparator<byte[]>() { public int compare(byte[] o1, byte[] o2) { return FSABuilder.compare(o1, o1.length, o2, o2.length); } }; /** * "register" for state interning. */ private HashMap<State, State> register = new HashMap<State, State>(); /** * Root automaton state. */ private State root = new State(); /** * Previous sequence added to the automaton in {@link #add(byte[], int)}. */ private byte [] previous; private int previousLength; /** * Add another byte sequence to this automaton. The sequence must be * lexicographically larger or equal compared to any previous sequences * added to this automaton (the input must be sorted). */ public void add(byte [] current, int length) { assert register != null : "Automaton already built."; assert length > 0 : "Input sequences must not be empty."; assert previous == null || compare(previous, previousLength, current, length) <= 0 : "Input must be sorted: " + Arrays.toString(previous, previousLength) + " >= " + Arrays.toString(current, length); assert setPrevious(current, length); // Descend in the automaton (find matching prefix). int pos = 0, max = length; State next, state = root; while (pos < max && (next = state.lastChild(current[pos])) != null) { state = next; pos++; } if (state.hasChildren()) replaceOrRegister(state); addSuffix(state, current, length, pos); } /** * Finalize the automaton and return the root state. No more strings can be * added to the builder after this call. * * @return Root automaton state. */ public State complete() { if (this.register == null) throw new IllegalStateException(); if (root.hasChildren()) replaceOrRegister(root); register = null; return root; } /** * Build a minimal, deterministic automaton from a sorted list of byte sequences. */ public static State build(byte[][] input) { final FSABuilder builder = new FSABuilder(); for (byte [] chs : input) builder.add(chs, chs.length); return builder.complete(); } /** * Build a minimal, deterministic automaton from an iterable list of byte sequences. */ public static State build(Iterable<byte[]> input) { final FSABuilder builder = new FSABuilder(); for (byte [] chs : input) builder.add(chs, chs.length); return builder.complete(); } /** * Copy <code>current</code> into an internal buffer. */ private boolean setPrevious(byte [] current, int length) { if (previous == null || previous.length < current.length) { previous = new byte [current.length]; } System.arraycopy(current, 0, previous, 0, length); previousLength = length; return true; } /** * Replace last child of <code>state</code> with an already registered * state or register the last child state. */ private void replaceOrRegister(State state) { final State child = state.lastChild(); if (child.hasChildren()) replaceOrRegister(child); final State registered = register.get(child); if (registered != null) { state.replaceLastChild(registered); } else { register.put(child, child); } } /** * Add a suffix of <code>current</code> starting at <code>fromIndex</code> * (inclusive) to state <code>state</code>. */ private void addSuffix(State state, byte[] current, int length, int fromIndex) { final int len = length; for (int i = fromIndex; i < len; i++) { state = state.newState(current[i]); } state.is_final = true; } }
package test.query; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javafx.util.Duration; import javax.json.JsonArray; import javax.json.JsonObject; import test.data.sale.Sale; import test.data.sale.SaleFactory; import test.text.ApplicationKeyUtils; public enum CommerceQuery { INSTANCE; public static Duration SERVER_RETENTION_DURATION = Duration.minutes(5); /** * L'URL de base de cet endpoint. */ private static final String basecode = "https://api.guildwars2.com/v2/commerce"; // NOI18N. public static final List<Sale> listSalesHistory(final String applicationKey) throws IOException, IllegalArgumentException { final boolean applicationKeyValid = ApplicationKeyUtils.validateApplicationKey(applicationKey); if (!applicationKeyValid) { throw new IllegalArgumentException(); } final String url = String.format("%s/transactions/current/sells?access_token=%s", basecode, applicationKey); // NOI18N. final JsonArray array = QueryUtils.queryArray(url); final List<Sale> result = array.getValuesAs(JsonObject.class) .stream() .map(value -> SaleFactory.createSale(value)) .collect(Collectors.toList()); return Collections.unmodifiableList(result); } }
package org.decimal4j.op.arith; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.decimal4j.api.Decimal; import org.decimal4j.api.DecimalArithmetic; import org.decimal4j.op.AbstractDecimalIntToDecimalTest; import org.decimal4j.scale.ScaleMetrics; import org.decimal4j.test.ArithmeticResult; import org.decimal4j.test.TestSettings; import org.decimal4j.truncate.TruncationPolicy; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; /** * Unit test for {@link Decimal#pow(int)} */ @RunWith(Parameterized.class) public class PowTest extends AbstractDecimalIntToDecimalTest { private static final int MAX_POW_EXPONENT = getMaxPowExponent(); public PowTest(ScaleMetrics scaleMetrics, TruncationPolicy truncationPolicy, DecimalArithmetic arithmetic) { super(arithmetic); } private static int getMaxPowExponent() { switch (TestSettings.TEST_CASES) { case ALL: return 2000; case LARGE: return 1000; case STANDARD: return 500; case SMALL: return 200; case TINY: return 100; default: throw new RuntimeException("unsupported: " + TestSettings.TEST_CASES); } } @Parameters(name = "{index}: {0}, {1}") public static Iterable<Object[]> data() { final List<Object[]> data = new ArrayList<Object[]>(); for (final ScaleMetrics s : TestSettings.SCALES) { for (final TruncationPolicy tp : TestSettings.POLICIES) { final DecimalArithmetic arith = s.getArithmetic(tp); data.add(new Object[] {s, tp, arith}); } } return data; } @Override protected <S extends ScaleMetrics> Decimal<S> randomDecimal(S scaleMetrics) { final long one = scaleMetrics.getScaleFactor(); // final long unscaled = one * (4 - RND.nextInt(9)) + one - RND.nextLong(2*one + 1); final long unscaled = one * (8 - RND.nextInt(17)) + one - RND.nextLong(2*one + 1); return newDecimal(scaleMetrics, unscaled); } @Override protected <S extends ScaleMetrics> int randomIntOperand(Decimal<S> decimalOperand) { if (decimalOperand.isZero() || decimalOperand.isOne() || decimalOperand.isMinusOne()) { return MAX_POW_EXPONENT - RND.nextInt(2 * MAX_POW_EXPONENT + 1); } final boolean posExp = RND.nextBoolean(); final double absBase; if (posExp) { absBase = Math.abs(decimalOperand.doubleValue(RoundingMode.UP)); } else { absBase = Math.abs(1.0/decimalOperand.doubleValue(RoundingMode.DOWN)); } final int maxPow; if (absBase >= 1) { maxPow = (int)(Math.log(decimalOperand.getScaleMetrics().getMaxIntegerValue())/Math.max(1e-10, Math.log(absBase))); } else { maxPow = -(int)(64 / (Math.log(absBase) / Math.log(2))); } final int pow = Math.max(1, Math.min(MAX_POW_EXPONENT, maxPow)); return posExp ? RND.nextInt(pow) : -RND.nextInt(pow); } @Test public void test3pow27() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "3^27", newDecimal(m, m.multiplyByScaleFactor(3)), 27); } @Test public void test3pow28() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "3^28", newDecimal(m, m.multiplyByScaleFactor(3)), 28); } @Test public void test3pow29() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "3^29", newDecimal(m, m.multiplyByScaleFactor(3)), 29); } @Test public void test10pow3() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "10^3", newDecimal(m, m.multiplyByScaleFactor(10)), 3); } @Test public void test100pow3() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "100^3", newDecimal(m, m.multiplyByScaleFactor(100)), 3); } @Test public void test2powNeg16() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "2^-16", newDecimal(m, m.multiplyByScaleFactor(3)), -16); } @Test public void test3powNeg10() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "3^-10", newDecimal(m, m.multiplyByScaleFactor(3)), -10); } @Test public void test3_1powNeg2() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "3.1^-2", newDecimal(m, m.multiplyByScaleFactor(3) + m.getScaleFactor()/10), -2); } @Test public void test3_2powNeg2() { final ScaleMetrics m = getScaleMetrics(); runTest(m, "3.2^-2", newDecimal(m, m.multiplyByScaleFactor(3) + m.getScaleFactor()/5), -2); } @Test public void test0_84pow254() { if (getScale() == 18) { final ScaleMetrics m = getScaleMetrics(); runTest(m, "0.849628138173771215^254", newDecimal(m, 849628138173771215L), 254); } } @Test public void test0_9979046pow914() { if (getScale() == 7) { final ScaleMetrics m = getScaleMetrics(); runTest(m, "0.9979046^914", newDecimal(m, 9979046), 914); } } @Test public void testMinus0_943powMinus625() { if (getScale() == 3) { final ScaleMetrics m = getScaleMetrics(); runTest(m, "-0.943^-625", newDecimal(m, -943), -625); } } @Test public void testMinus0_935341829powMinus342() { if (getScale() == 9) { final ScaleMetrics m = getScaleMetrics(); runTest(m, "0.935341829^-342", newDecimal(m, -935341829), -342); } } @Override protected int getRandomTestCount() { return 1000; } @Override protected int[] getSpecialIntOperands() { final Set<Integer> exp = new TreeSet<Integer>(); //1..9 and negatives for (int i = 1; i < 10; i++) { exp.add(i); exp.add(-i); } //10..50 in steps of 10 and negatives for (int i = 10; i <= 50; i+=10) { exp.add(i); exp.add(-i); } //100 and -100 exp.add(100); exp.add(-100); //zero exp.add(0); //extremes // exp.add(-999999999); // exp.add(999999999); exp.add(-999999999-1); exp.add(999999999+1); exp.add(Integer.MIN_VALUE); exp.add(Integer.MAX_VALUE); //convert to array final int[] result = new int[exp.size()]; int index = 0; for (final int val : exp) { result[index] = val; index++; } return result; } @Override protected String operation() { return "^"; } @Override protected <S extends ScaleMetrics> void runTest(S scaleMetrics, String name, Decimal<S> dOperandA, int b) { final String messagePrefix = getClass().getSimpleName() + name + ": " + dOperandA + " " + operation() + " " + b; final BigDecimal bdOperandA = toBigDecimal(dOperandA); //expected ArithmeticResult<Long> expected; try { expected = ArithmeticResult.forResult(arithmetic, expectedResult(bdOperandA, b)); } catch (IllegalArgumentException e) { expected = ArithmeticResult.forException(e); } catch (ArithmeticException e) { expected = ArithmeticResult.forException(e); } //actual ArithmeticResult<Long> actual; try { actual = ArithmeticResult.forResult(actualResult(dOperandA, b)); } catch (IllegalArgumentException e) { actual = ArithmeticResult.forException(e); } catch (ArithmeticException e) { actual = ArithmeticResult.forException(e); } //assert try { actual.assertEquivalentTo(expected, messagePrefix); } catch (AssertionError e) { if (isUnchecked() && expected.isOverflow() ) { //overflown results without CHECKED mode don't match return; } if (!isWithinAllowedTolerance(expected, actual, b)) { throw e; } } } //By definition pow precision is //n >= 0: rounding = HALF_UP, HALF_DOWN, HALF_EVEN: 1 ULP //n >= 0: other rounding modes: 0 //n < 0: 16 ULP ??? private boolean isWithinAllowedTolerance(ArithmeticResult<Long> expected, ArithmeticResult<Long> actual, int exponent) { final int maxTolerance = exponent >= 0 ? 0 : 17; final int maxRoundingHalfTolerance = exponent >= 0 ? 1 : 17; final Long exp = expected.getCompareValue(); final Long act = actual.getCompareValue(); if (exp == null || act == null) { return false; } final boolean neg = (exp < 0 & act < 0) | ((exp == 0 | act == 0) & (exp < 0 | act < 0)); final long diff = act - exp; switch (getRoundingMode()) { case UP: return neg ? diff <= 0 & diff >= -maxTolerance : diff >= 0 & diff <= maxTolerance; case DOWN: return neg ? diff >= 0 & diff <= maxTolerance : diff <= 0 & diff >= -maxTolerance; case CEILING: return diff >= 0 & diff <= maxTolerance; case FLOOR: return diff <= 0 & diff >= -maxTolerance; case HALF_UP://fallthrough case HALF_DOWN://fallthrough case HALF_EVEN: return diff <= maxRoundingHalfTolerance & diff >= -maxRoundingHalfTolerance; case UNNECESSARY: return false; default: return false; } } @Override protected BigDecimal expectedResult(BigDecimal a, int b) { if (b < -999999999 | b > 999999999) { throw new IllegalArgumentException("exponent out of range: " + b); } final BigDecimal result = a.pow(Math.abs(b)); return b >= 0 ? result.setScale(getScale(), getRoundingMode()) : BigDecimal.ONE.divide(result, getScale(), getRoundingMode()); } @Override protected <S extends ScaleMetrics> Decimal<S> actualResult(Decimal<S> a, int b) { if (isStandardTruncationPolicy() && RND.nextBoolean()) { return a.pow(b); } else { if (isUnchecked() && RND.nextBoolean()) { return a.pow(b, getRoundingMode()); } else { return a.pow(b, getTruncationPolicy()); } } } }
package org.jdbdt.tutorial; // Java/JDBC API imports import java.sql.Date; import java.sql.SQLException; import java.util.List; //JUnit imports import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; // JDBDT import import static org.jdbdt.JDBDT.*; import org.jdbdt.Conversion; import org.jdbdt.DB; import org.jdbdt.DataSet; import org.jdbdt.Table; // Static import for user roles import static org.jdbdt.tutorial.Role.*; @SuppressWarnings("javadoc") public abstract class UserDAOTest { // JDBDT handle for the database static DB theDB; // DAO (the SUT) static UserDAO theDAO; // User table. static Table theTable; // Fixed date used for test data static final Date FIXED_DATE = Date.valueOf("2016-01-01"); // Data set that we use for populating the table. // (we need this as a field so it can be referred to in a few test methods) static DataSet theInitialData; // Global setup protected static void globalSetup(String jdbcDriverClass, String databaseURL) throws Throwable { // Load JDBC driver class Class.forName(jdbcDriverClass); // Create database handle theDB = database(databaseURL); // Create DAO and in turn let it create USERS table theDAO = new UserDAO(theDB.getConnection()); theDAO.createTable(); // Create table data source. theTable = table(theDB, "USERS") .columns("ID", "LOGIN", "NAME", "PASSWORD", "ROLE", "CREATED" ); // Define data set for populating the database theInitialData = builder(theTable) .sequence("ID", 0) .sequence("PASSWORD", i -> "pass" + i) .value("LOGIN", "root") .nullValue("NAME") .value("CREATED", FIXED_DATE) .value("ROLE", ADMIN) .generate(1) .sequence("LOGIN", "alice", "bob", "charles") .sequence("NAME", "Alice", "Bob", "Charles") .value("ROLE", REGULAR) .generate(3) .sequence("LOGIN", i -> "guest" + i, 1) .sequence("NAME", i -> "Guest User " + i, 1) .value("ROLE", GUEST) .generate(2) .data(); // dump(theInitialData, System.err); // Populate database using the built data set populate(theInitialData); // Set auto-commit off (to allow for save-points) theDB.getConnection().setAutoCommit(false); } @AfterClass public static void globalTeardown() { truncate(theTable); teardown(theDB, true); } @Before public void saveState() { // Set save point save(theDB); } @After public void restoreState() { // Restore state to save point restore(theDB); } private static final Conversion<User> CONVERSION = u -> new Object[] { u.getId(), u.getLogin(), u.getName(), u.getPassword(), u.getRole().toString(), u.getCreated() }; static DataSet toDataSet(User u) { return data(theTable, CONVERSION).row(u); } static User anExistingUser() { return new User(0, "root", null, "pass0", Role.ADMIN, FIXED_DATE); } static User nonExistingUser() { return new User(99, "john99", "John Doe 99", "doeit 99", Role.REGULAR, FIXED_DATE); } @Test public void testNonExistingUserInsertion() throws SQLException { User u = nonExistingUser(); theDAO.insertUser(u); assertInserted("DB change", toDataSet(u)); } @Test public void testNonExistingUserInsertionVariant() throws SQLException { User u = nonExistingUser(); theDAO.insertUser(u); DataSet expected = DataSet.join(theInitialData, toDataSet(u)); assertState("DB state", expected); } @Test public void testExistingUserInsertion() { try { User u = anExistingUser(); theDAO.insertUser(u); fail("Expected " + SQLException.class); } catch (SQLException e) { assertUnchanged("No DB changes", theTable); } } @Test public void testExistingUserDelete() throws SQLException { User u = anExistingUser(); boolean deleted = theDAO.deleteUser(u); assertDeleted("DB change", toDataSet(u)); assertTrue("return value", deleted); } @Test public void testNonExistingUserDelete() throws SQLException { User u = nonExistingUser(); boolean deleted = theDAO.deleteUser(u); assertUnchanged("No DB changes", theTable); assertFalse("return value", deleted); } @Test public void testDeleteAll() throws SQLException { int count = theDAO.deleteAllUsers(); assertEmpty("DB cleaned up", theTable); assertEquals("return value", count, theInitialData.size()); } @Test public void testExistingUserUpdate() throws SQLException { User u = anExistingUser(); u.setPassword("new pass"); u.setName("new name"); boolean updated = theDAO.updateUser(u); assertDelta("DB change", toDataSet(anExistingUser()), toDataSet(u)); assertTrue("return value", updated); } @Test public void testNonExistingUserUpdate() throws SQLException { User u = nonExistingUser(); boolean updated = theDAO.updateUser(u); assertUnchanged("No DB changes", theTable); assertFalse("return value", updated); } @Test public void testGetAllUsers() throws SQLException { List<User> list = theDAO.getAllUsers(); DataSet expected = theInitialData; DataSet actual = data(theTable, CONVERSION).rows(list); assertEquals("User list", expected, actual); assertUnchanged("No DB changes", theTable); } @Test public void testGetUsersByRole() throws SQLException { List<User> list = theDAO.getUsers(Role.GUEST); DataSet expected = DataSet.tail(theInitialData, 2); DataSet actual = data(theTable, CONVERSION).rows(list); assertEquals("Guest user list", expected, actual); assertUnchanged("No DB changes", theTable); } @Test public void testGetUserById() throws SQLException { User expected = anExistingUser(); User actual = theDAO.getUser(expected.getId()); assertEquals("User", expected, actual); assertUnchanged("No DB changes", theTable); } @Test public void testGetUserByLogin() throws SQLException { User expected = anExistingUser(); User actual = theDAO.getUser(expected.getLogin()); assertEquals("User", expected, actual); assertUnchanged("No DB changes", theTable); } }
package us.jubat.graph; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import us.jubat.testutil.JubaServer; import us.jubat.testutil.JubatusClientTest; public class GraphClientTest extends JubatusClientTest { private GraphClient client; public GraphClientTest() { super(JubaServer.graph); } @Before public void setUp() throws Exception { server.start(server.getConfigPath()); client = new GraphClient(server.getHost(), server.getPort(), TIMEOUT_SEC); } @After public void tearDown() throws Exception { server.stop(); } @Test public void testNode() { // create String nid = client.create_node(NAME); assertThat(nid, is("0")); // update Map<String, String> property = new HashMap<String, String>(); for (int i = 1; i <= 10; i++) { String key = "key" + Integer.toString(i); String value = "value" + Integer.toString(i); property.put(key, value); } assertThat(client.update_node(NAME, nid, property), is(true)); // get Node node = client.get_node(NAME, nid); assertThat(node.in_edges, is(notNullValue())); assertThat(node.in_edges.size(), is(0)); assertThat(node.out_edges, is(notNullValue())); assertThat(node.out_edges.size(), is(0)); assertThat(node.property, is(property)); // create here assertThat(client.create_node_here(NAME, nid + 1), is(true)); // remove assertThat(client.remove_node(NAME, nid), is(true)); } @Test public void testEdge() { // create String src = client.create_node(NAME); String tgt = client.create_node(NAME); Map<String, String> property = new HashMap<String, String>(); for (int i = 1; i <= 10; i++) { String key = "key" + Integer.toString(i); String value = "value" + Integer.toString(i); property.put(key, value); } client.update_node(NAME, src, property); client.update_node(NAME, tgt, property); Edge e = new Edge(); e.source = src; e.target = tgt; e.property = property; long eid = client.create_edge(NAME, src, e); assertThat(Long.valueOf(eid), is(2L)); // update assertThat(client.update_edge(NAME, src, eid, e), is(true)); // get Edge edge = client.get_edge(NAME, tgt, eid); assertThat(edge.source, is(src)); assertThat(edge.target, is(tgt)); assertThat(edge.property, is(property)); // create here assertThat(client.create_edge_here(NAME, eid + 1, e), is(true)); // remove assertThat(client.remove_edge(NAME, src, eid), is(true)); } @Test public void testGetCentrality() { PresetQuery q = new PresetQuery(); q.edge_query = new ArrayList<TupleStringString>(); q.node_query = new ArrayList<TupleStringString>(); client.add_centrality_query(NAME, q); String nid = client.create_node(NAME); client.update_index(NAME); assertThat(client.get_centrality(NAME, nid, 0, q), is(1.0)); } @Test public void testAdd_centrality_query() { TupleStringString s = new TupleStringString(); s.first = ""; s.second = ""; List<TupleStringString> query = new ArrayList<TupleStringString>(); query.add(s); PresetQuery q = new PresetQuery(); q.node_query = query; q.edge_query = query; assertThat(client.add_centrality_query(NAME, q), is(true)); } @Test public void testAdd_shortest_path_query() { PresetQuery q = new PresetQuery(); q.node_query = new ArrayList<TupleStringString>(); q.edge_query = new ArrayList<TupleStringString>(); assertThat(client.add_shortest_path_query(NAME, q), is(true)); } @Test public void testRemove_centrality_query() { PresetQuery q = new PresetQuery(); q.node_query = new ArrayList<TupleStringString>(); q.edge_query = new ArrayList<TupleStringString>(); assertThat(client.remove_centrality_query(NAME, q), is(true)); } @Test public void testRemove_shortest_path_query() { PresetQuery q = new PresetQuery(); q.node_query = new ArrayList<TupleStringString>(); q.edge_query = new ArrayList<TupleStringString>(); assertThat(client.remove_shortest_path_query(NAME, q), is(true)); } @Test public void testShortest_path() { PresetQuery q = new PresetQuery(); q.node_query = new ArrayList<TupleStringString>(); q.edge_query = new ArrayList<TupleStringString>(); client.add_shortest_path_query(NAME, q); String src = client.create_node(NAME); String tgt = client.create_node(NAME); ShortestPathQuery r = new ShortestPathQuery(); r.source = src; r.target = tgt; r.query = q; r.max_hop = 0; List<String> result = client.get_shortest_path(NAME, r); assertThat(result, is(notNullValue())); assertThat(result.size(), is(0)); } @Test public void testUpdate_index() { assertThat(client.update_index(NAME), is(true)); } @Test public void testClear() { assertThat(client.clear(NAME), is(true)); } @Test public void testSave_and_Load() { String id = "graph.test_java-client.model"; assertThat(client.save(NAME, id), is(true)); assertThat(client.load(NAME, id), is(true)); } @Test public void testGet_status() { Map<String, Map<String, String>> status = client.get_status(NAME); assertThat(status, is(not(nullValue()))); assertThat(status.size(), is(1)); } @Test public void testGlobal_node() { String nid = client.create_node(NAME); assertThat(client.remove_global_node(NAME, nid), is(true)); } }
package tools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.TreeSet; public class InvertedFileMerger { private final File directorySource; private int marqueur = 1; private String pathSource; public InvertedFileMerger(String pathSource) { this.pathSource = pathSource; this.directorySource = new File( this.pathSource); } public void run() throws IOException { final String[] fileNames = this.directorySource.list(); this.merge(fileNames); } private void merge(final String[] fileNames) throws IOException { // S'il n'ya qu'un seul fichier dans le repertoire, on lui applique un if (fileNames.length == 1) { this.splitInvertedFileResultWithTwoLetters(fileNames[0]); final File file = new File(fileNames[0]); file.delete(); } else { for (int i = 0; i < fileNames.length; i = i + 2) { if (i >= fileNames.length - 1) { } else { final File fileA = new File( this.pathSource + fileNames[i]); final File fileB = new File( this.pathSource + fileNames[i + 1]); final File fileResultat = new File( this.pathSource + "FileResultat" + this.marqueur + ".txt"); this.mergeInvertedFiles(fileA, fileB, fileResultat); fileA.delete(); fileB.delete(); this.marqueur++; } } final String[] newFileNames = this.directorySource.list(); this.merge(newFileNames); } } private void splitInvertedFileResult(final String fileName) throws IOException { final File file = new File(Const.PATH_TO_INVERTED_FILE_FROM_INDEXER + fileName); final BufferedReader reader = new BufferedReader(new FileReader(file)); final BufferedWriter trucDeMerde = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + "trucDeMerde.txt")); final BufferedWriter chiffre = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + "chiffre.txt")); BufferedWriter writer = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + "a.txt")); String currentString = "a"; String mot = reader.readLine(); while (mot != null) { final String firstLetter = mot.substring(0, 1).toLowerCase(); if (Const.LETTRES.contains(firstLetter)) { if (currentString.equals(firstLetter)) { writer.write(mot + "\n"); } else { writer.close(); currentString = firstLetter; writer = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + currentString + ".txt")); writer.write(mot + "\n"); } } else if (Const.CHIFFRES.contains(firstLetter)) { chiffre.write(mot + "\n"); } else { trucDeMerde.write(mot + "\n"); } mot = reader.readLine(); } reader.close(); trucDeMerde.close(); chiffre.close(); writer.close(); } private void splitInvertedFileResultWithTwoLetters(final String fileName) throws IOException { final File file = new File(this.pathSource + fileName); final BufferedReader reader = new BufferedReader(new FileReader(file)); final BufferedWriter trucDeMerde = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + "otherCharacter.txt")); final BufferedWriter chiffre = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + "chiffre.txt")); BufferedWriter writer = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + "aa.txt")); String currentString = "aa"; String mot = reader.readLine(); while (mot != null) { final String firstLetter = mot.substring(0, 1).toLowerCase(); final String secondLetter = mot.substring(1, 2).toLowerCase(); final String twoFirstLetters = mot.substring(0, 2).toLowerCase(); if (Const.LETTRES_ET_CHIFFRES.contains(firstLetter)) { if (currentString.equals(twoFirstLetters)) { writer.write(mot + "\n"); } else { if (Const.LETTRES_ET_CHIFFRES.contains(secondLetter)) { writer.close(); currentString = twoFirstLetters; writer = new BufferedWriter(new FileWriter( Const.PATH_TO_INVERTED_FILE_FROM_MERGER + currentString + ".txt")); writer.write(mot + "\n"); } else { trucDeMerde.write(mot + "\n"); } } }/* else if (Const.CHIFFRES.contains(firstLetter)) { chiffre.write(mot + "\n"); } else { trucDeMerde.write(mot + "\n"); }*/ mot = reader.readLine(); } reader.close(); trucDeMerde.close(); chiffre.close(); writer.close(); } private void mergeInvertedFiles(final File invertedFile1, final File invertedFile2, final File mergedInvertedFile) throws IOException { final BufferedReader readerA = new BufferedReader(new FileReader( invertedFile1)); final BufferedReader readerB = new BufferedReader(new FileReader( invertedFile2)); final BufferedWriter writer = new BufferedWriter(new FileWriter( mergedInvertedFile)); try { String motA = readerA.readLine(); String motB = readerB.readLine(); while (motA != null && motB != null) { // On split les lignes courantes selon la tabulation final String[] wordFreqDocsA = motA.split("\t"); final String[] wordFreqDocsB = motB.split("\t"); if (wordFreqDocsA[0].equals(wordFreqDocsB[0])) { final String[] documentListA = wordFreqDocsA[2].split(","); final String[] documentListB = wordFreqDocsB[2].split(","); final TreeSet<String> documentListResult = new TreeSet<String>(); for (final String s : documentListB) { documentListResult.add(s); } for (final String s : documentListA) { documentListResult.add(s); } if(wordFreqDocsA[1].equals("")){ motA = readerA.readLine(); continue; } if(wordFreqDocsB[1].equals("")){ motB = readerB.readLine(); continue; } /*System.out.print("f: " + invertedFile1.getName() + ", w:" + wordFreqDocsA[0] + ", d: " + wordFreqDocsA[1] + "files : "+ wordFreqDocsA[2]+ "\t"); System.out.print("f: " + invertedFile2.getName() + ", w:" + wordFreqDocsB[0] + ", d: " + wordFreqDocsB[1] + "files : "+ wordFreqDocsB[2] + "\n");*/ final int a = Integer.parseInt(wordFreqDocsA[1]) + Integer.parseInt(wordFreqDocsB[1]); writer.write(wordFreqDocsA[0] + "\t" + a + "\t"); // Ecriture de la liste des documents final Iterator it = documentListResult.iterator(); final int size = documentListResult.size(); int cpt = 0; while (it.hasNext()) { cpt++; writer.append((String) it.next()); if (cpt != size) { writer.append(","); } } writer.append('\n'); motA = readerA.readLine(); motB = readerB.readLine(); } else if (wordFreqDocsA[0].compareTo(wordFreqDocsB[0]) < 0) { writer.write(motA + "\n"); motA = readerA.readLine(); } else if (wordFreqDocsA[0].compareTo(wordFreqDocsB[0]) > 0) { writer.write(motB + "\n"); motB = readerB.readLine(); } } if (motA == null) { while (motB != null) { writer.write(motB + "\n"); motB = readerB.readLine(); } } if (motB == null) { while (motA != null) { writer.write(motA + "\n"); motA = readerA.readLine(); } } } finally { writer.close(); readerA.close(); readerB.close(); } } }
package ui.issuepanel; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.HashSet; import javafx.event.EventHandler; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Priority; import javafx.stage.Stage; import javafx.util.Callback; import model.Model; import model.TurboIssue; import service.ServiceManager; import ui.UI; import ui.components.NavigableListView; import ui.issuecolumn.ColumnControl; import ui.issuecolumn.IssueColumn; import util.KeyPress; import util.events.IssueSelectedEvent; import command.TurboCommandExecutor; public class IssuePanel extends IssueColumn { private final Model model; private final UI ui; private NavigableListView<TurboIssue> listView; private final KeyCombination keyCombBoxToList = new KeyCodeCombination(KeyCode.DOWN, KeyCombination.CONTROL_DOWN); private final KeyCombination keyCombListToBox = new KeyCodeCombination(KeyCode.UP, KeyCombination.CONTROL_DOWN); private HashMap<Integer, Integer> issueCommentCounts = new HashMap<>();; public IssuePanel(UI ui, Stage mainStage, Model model, ColumnControl parentColumnControl, int columnIndex, TurboCommandExecutor dragAndDropExecutor) { super(ui, mainStage, model, parentColumnControl, columnIndex, dragAndDropExecutor); this.model = model; this.ui = ui; listView = new NavigableListView<>(); setupListView(); getChildren().add(listView); refreshItems(); } /** * Determines if an issue has had new comments added (or removed) based on * its last-known comment count in {@link #issueCommentCounts}. * @param issue * @return true if the issue has changed, false otherwise */ private boolean issueHasNewComments(TurboIssue issue) { if (!issueCommentCounts.containsKey(issue.getId())) { return false; } return Math.abs(issueCommentCounts.get(issue.getId()) - issue.getCommentCount()) > 0; } @Override public void deselect() { } /** * Updates {@link #issueCommentCounts} with the latest counts. * Returns a list of issues which have new comments. * @return */ private HashSet<Integer> updateIssueCommentCounts() { HashSet<Integer> result = new HashSet<>(); for (TurboIssue issue : getIssueList()) { if (issueCommentCounts.containsKey(issue.getId())) { // We know about this issue; check if it's been updated if (issueHasNewComments(issue)) { result.add(issue.getId()); } } else { // We don't know about this issue issueCommentCounts.put(issue.getId(), issue.getCommentCount()); } } return result; } @Override public void refreshItems() { super.refreshItems(); WeakReference<IssuePanel> that = new WeakReference<IssuePanel>(this); final HashSet<Integer> issuesWithNewComments = updateIssueCommentCounts(); // Set the cell factory every time - this forces the list view to update listView.setCellFactory(new Callback<ListView<TurboIssue>, ListCell<TurboIssue>>() { @Override public ListCell<TurboIssue> call(ListView<TurboIssue> list) { if(that.get() != null){ return new IssuePanelCell(ui, model, that.get(), columnIndex, issuesWithNewComments); } else{ return null; } } }); listView.saveSelection(); // Supposedly this also causes the list view to update - not sure // if it actually does on platforms other than Linux... listView.setItems(null); listView.setItems(getIssueList()); listView.restoreSelection(); } private void setupListView() { setVgrow(listView, Priority.ALWAYS); setupKeyboardShortcuts(); listView.setOnItemSelected(i -> { TurboIssue issue = listView.getItems().get(i); ui.triggerEvent(new IssueSelectedEvent(issue.getId(), columnIndex)); if (issueHasNewComments(issue)) { issueCommentCounts.put(issue.getId(), issue.getCommentCount()); refreshItems(); } }); } private void setupKeyboardShortcuts(){ filterTextField.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() { public void handle(KeyEvent event) { if (keyCombBoxToList.match(event)) { event.consume(); listView.selectFirstItem(); } if(event.getCode() == KeyCode.SPACE){ event.consume(); } if (KeyPress.isDoublePress(KeyCode.SPACE, event.getCode())) { event.consume(); listView.selectFirstItem(); } } }); addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() { public void handle(KeyEvent event) { if (event.getCode() == KeyCode.F5) { ServiceManager.getInstance().updateModelNow(); } if (event.getCode() == KeyCode.F1) { ui.getBrowserComponent().showDocs(); } if (keyCombListToBox.match(event)) { filterTextField.requestFocus(); } if (event.getCode() == KeyCode.SPACE && KeyPress.isDoublePress(KeyCode.SPACE, event.getCode())) { filterTextField.requestFocus(); } if(event.getCode() == KeyCode.I) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showIssues(); } } if(event.getCode() == KeyCode.P) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showPullRequests(); } } if(event.getCode() == KeyCode.H) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showDocs(); } } if(event.getCode() == KeyCode.K) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showKeyboardShortcuts(); } } if(event.getCode() == KeyCode.D) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showContributors(); event.consume(); } } if(event.getCode() == KeyCode.U) { ui.getBrowserComponent().scrollToTop(); } if(event.getCode() == KeyCode.N) { ui.getBrowserComponent().scrollToBottom(); } if(event.getCode() == KeyCode.J || event.getCode() == KeyCode.K) { ui.getBrowserComponent().scrollPage(event.getCode() == KeyCode.K); } if(event.getCode() == KeyCode.G) { KeyPress.setLastKeyPressedCodeAndTime(event.getCode()); } if(event.getCode() == KeyCode.C && ui.getBrowserComponent().isCurrentUrlIssue()) { ui.getBrowserComponent().jumpToComment(); } if(event.getCode() == KeyCode.L) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().newLabel(); } else if(ui.getBrowserComponent().isCurrentUrlIssue()){ ui.getBrowserComponent().manageLabels(event.getCode().toString()); } } if(event.getCode() == KeyCode.A && ui.getBrowserComponent().isCurrentUrlIssue()) { ui.getBrowserComponent().manageAssignees(event.getCode().toString()); } if(event.getCode() == KeyCode.M) { if(KeyPress.isValidKeyCombination(KeyCode.G, event.getCode())) { ui.getBrowserComponent().showMilestones(); } else if(ui.getBrowserComponent().isCurrentUrlIssue()){ ui.getBrowserComponent().manageMilestones(event.getCode().toString()); } } } }); addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { public void handle(KeyEvent event) { if(event.getCode() == KeyCode.V || event.getCode() == KeyCode.T) { listView.selectFirstItem(); } } }); } }
package org.apache.xerces.dom; import org.w3c.dom.DOMException; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.CharacterData; import org.apache.xerces.dom.DOMExceptionImpl; import org.apache.xerces.dom.DocumentImpl; import org.w3c.dom.range.*; import java.util.Vector; import java.util.Enumeration; /** The RangeImpl class implements the org.w3c.dom.range.Range interface. * <p> Please see the API documentation for the interface classes * and use the interfaces in your client programs. */ public class RangeImpl implements Range { // Constants // Where to collapse to. static final int START = 0; static final int AFTER = 1; static final int BEFORE = -1; // Data DocumentImpl fDocument; Node fStartContainer; Node fEndContainer; int fStartOffset; int fEndOffset; boolean fIsCollapsed; boolean fDetach = false; Node fInsertNode = null; Node fDeleteNode = null; Node fSplitNode = null; /** The constructor. Clients must use DocumentRange.createRange(), * because it registers the Range with the document, so it can * be fixed-up. */ public RangeImpl(DocumentImpl document) { fDocument = document; fStartContainer = document; fEndContainer = document; fStartOffset = 0; fEndOffset = 0; fDetach = false; } public Node getStartContainer() { return fStartContainer; } public int getStartOffset() { return fStartOffset; } public Node getEndContainer() { return fEndContainer; } public int getEndOffset() { return fEndOffset; } public boolean getIsCollapsed() { return (fStartContainer == fEndContainer && fStartOffset == fEndOffset); } public Node getCommonAncestorContainer(){ Vector startV = new Vector(); Node node; for (node=fStartContainer; node != null; node=node.getParentNode()) { startV.addElement(node); } Vector endV = new Vector(); for (node=fEndContainer; node != null; node=node.getParentNode()) { endV.addElement(node); } int s = startV.size()-1; int e = endV.size()-1; Object result = null; while (s>=0 && e>=0) { if (startV.elementAt(s) == endV.elementAt(e)) { result = startV.elementAt(s); } else { break; } --s; --e; } return (Node)result; } public void setStart(Node refNode, int offset) throws RangeException, DOMException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } checkIndex(refNode, offset); fStartContainer = refNode; fStartOffset = offset; } public void setEnd(Node refNode, int offset) throws RangeException, DOMException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } checkIndex(refNode, offset); fEndContainer = refNode; fEndOffset = offset; } public void setStartBefore(Node refNode) throws RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } fStartContainer = refNode.getParentNode(); int i = 0; for (Node n = refNode; n!=null; n = n.getPreviousSibling()) { i++; } fStartOffset = i-1; } public void setStartAfter(Node refNode) throws RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } fStartContainer = refNode.getParentNode(); int i = 0; for (Node n = refNode; n!=null; n = n.getPreviousSibling()) { i++; } fStartOffset = i; } public void setEndBefore(Node refNode) throws RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } fEndContainer = refNode.getParentNode(); int i = 0; for (Node n = refNode; n!=null; n = n.getPreviousSibling()) { i++; } fEndOffset = i-1; } public void setEndAfter(Node refNode) throws RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } fEndContainer = refNode.getParentNode(); int i = 0; for (Node n = refNode; n!=null; n = n.getPreviousSibling()) { i++; } fEndOffset = i; } public void collapse(boolean toStart) { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if (toStart) { fEndContainer = fStartContainer; fEndOffset = fStartOffset; } else { fStartContainer = fEndContainer; fStartOffset = fEndOffset; } } public void selectNode(Node refNode) throws RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } Node parent = refNode.getParentNode(); if (parent != null ) // REVIST: what to do if it IS null? { fStartContainer = parent; fEndContainer = parent; int i = 0; for (Node n = refNode; n!=null; n = n.getPreviousSibling()) { i++; } fStartOffset = i-1; fEndOffset = fStartOffset+1; } } public void selectNodeContents(Node refNode) throws RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } if ( !isAncestorTypeValid(refNode)) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } fStartContainer = refNode; fEndContainer = refNode; Node first = refNode.getFirstChild(); fStartOffset = 0; if (first == null) { fEndOffset = 0; } else { int i = 0; for (Node n = first; n!=null; n = n.getNextSibling()) { i++; } fEndOffset = i; } } public static final int StartToStart = 1; public static final int StartToEnd = 2; public static final int EndToEnd = 3; public static final int EndToStart = 4; public short compareBoundaryPoints(int how, Range sourceRange) throws DOMException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } Node endPointA; Node endPointB; int offsetA; int offsetB; if (how == StartToStart) { endPointA = sourceRange.getStartContainer(); endPointB = fStartContainer; offsetA = sourceRange.getStartOffset(); offsetB = fStartOffset; } else if (how == StartToEnd) { endPointA = sourceRange.getStartContainer(); endPointB = fEndContainer; offsetA = sourceRange.getStartOffset(); offsetB = fEndOffset; } else if (how == EndToStart) { endPointA = sourceRange.getEndContainer(); endPointB = fStartContainer; offsetA = sourceRange.getEndOffset(); offsetB = fStartOffset; } else { endPointA = sourceRange.getEndContainer(); endPointB = fEndContainer; offsetA = sourceRange.getEndOffset(); offsetB = fEndOffset; } // case 1: same container if (endPointA == endPointB) { if (offsetA < offsetB) return -1; if (offsetA == offsetB) return 0; return 1; } // case 2: Child C of container A is ancestor of B for (Node node=endPointA.getFirstChild(); node != null; node=node.getNextSibling()) { if (isAncestorOf(node, endPointB)) { int index = indexOf(node, endPointA); if (offsetA < index) return -1; if (offsetA == index) return 0; return 1; } } // case 3: Child C of container B is ancestor of A for (Node node=endPointB.getFirstChild(); node != null; node=node.getNextSibling()) { if (isAncestorOf(node, endPointA)) { int index = indexOf(node, endPointB); if (offsetB < index) return -1; if (offsetB == index) return 0; return 1; } } // case 4: preorder traversal of context tree. Node ancestor = getCommonAncestorContainer(); Node current = ancestor; do { if (current == endPointA) return -1; if (current == endPointB) return 1; current = nextNode(current, true);// REVIST this... } while (current!=null && current!=ancestor); // REVISIT: this should never happen?!?!?!? return -2; } public void deleteContents() throws DOMException { Node current = fStartContainer; Node parent = null; Node next; boolean deleteCurrent = false; Node root = getCommonAncestorContainer(); // if same container, simplify case if (fStartContainer == fEndContainer) { if (fStartOffset == fEndOffset) { // eg collapsed return; } if (fStartContainer.getNodeType() == Node.TEXT_NODE) { String value = fStartContainer.getNodeValue(); //REVIST: This section should probably throw an exception! // This should NEVER happen, if the Range is always valid. int realStart = fStartOffset; int realEnd = fEndOffset; if (fStartOffset > value.length()) realStart = value.length()-1; if (fEndOffset > value.length()) realEnd = value.length()-1; deleteData((CharacterData)fStartContainer, realStart, realEnd-realStart); } else { current = fStartContainer.getFirstChild(); int i = 0; for(i = 0; i < fStartOffset && current != null; i++) { current=current.getNextSibling(); } for(i = 0; i < fEndOffset-fStartOffset && current != null; i++) { Node newCurrent=current.getNextSibling(); removeChild(fStartContainer, current); current = newCurrent; } } collapse(true); return; } Node partialNode = null; int partialInt = START; Node startRoot = null; // initialize current for startContainer. if (current.getNodeType() == Node.TEXT_NODE) { deleteData((CharacterData)current, fStartOffset, current.getNodeValue().length()-fStartOffset); } else { current = current.getFirstChild(); for (int i = 0 ; i < fStartOffset && current != null; i++){ current = current.getNextSibling(); } if (current==null) { current = fStartContainer; } else if (current != fStartContainer) { deleteCurrent = true; } } // traverse up from the startContainer... // current starts as the node to delete; while (current != root && current != null) { parent = current.getParentNode(); if (parent == root) { if (startRoot == null) startRoot = current; } else { if (partialNode==null) { partialNode = parent; partialInt = AFTER; } } if (parent != root) { next = current.getNextSibling(); Node nextnext; while (next != null) { nextnext = next.getNextSibling(); //parent.removeChild(next); removeChild(parent, next); next = nextnext; } } if (deleteCurrent) { //parent.removeChild(current); removeChild(parent, current); deleteCurrent = false; } current = parent; } Node endRoot = null; // initialize current for endContainer. current = fEndContainer; if (current.getNodeType() == Node.TEXT_NODE) { deleteData((CharacterData)current, 0, fEndOffset); } else { if (fEndOffset == 0) { // "before" current = fEndContainer; } else { current = current.getFirstChild(); for(int i = 1; i < fEndOffset && current != null; i++) { current=current.getNextSibling(); } if (current==null) { // REVIST: index-out-of-range what to do? current = fEndContainer.getLastChild(); } else if (current != fStartContainer) { deleteCurrent = true; } } } // traverse up from the endContainer... while (current != root && current != null) { parent = current.getParentNode(); if (parent == root) { if (endRoot == null) endRoot = current; } else { if (partialNode==null) { partialNode = parent; partialInt = BEFORE; } } if (parent != root && parent != null) { next = current.getPreviousSibling(); Node nextnext; while (next != null) { nextnext = next.getPreviousSibling(); removeChild(parent, next); next = nextnext; } } if (deleteCurrent) { removeChild(parent, current); deleteCurrent = false; } current = parent; } //if (endRoot == null || startRoot == null) return; //REVIST current = endRoot.getPreviousSibling(); Node prev = null; while (current != null && current != startRoot ) { prev = current.getPreviousSibling(); parent = current.getParentNode(); if (parent != null) { removeChild(parent, current); } current = prev; } if (partialNode == null) { collapse(true); } else if (partialInt == AFTER) { setStartAfter(partialNode); setEndAfter(partialNode); } else if (partialInt == BEFORE) { setStartBefore(partialNode); setEndBefore(partialNode); } } public DocumentFragment extractContents() throws DOMException { return traverseContents(EXTRACT_CONTENTS); } public DocumentFragment cloneContents() throws DOMException { return traverseContents(CLONE_CONTENTS); } public void insertNode(Node newNode) throws DOMException, RangeException { if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } int type = newNode.getNodeType(); if (type == Node.ATTRIBUTE_NODE || type == Node.ENTITY_NODE || type == Node.NOTATION_NODE || type == Node.DOCUMENT_NODE || type == Node.DOCUMENT_FRAGMENT_NODE) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } if (newNode == null) return; //throw exception? Node cloneCurrent; Node current; boolean MULTIPLE_MODE = false; if (fStartContainer.getNodeType() == Node.TEXT_NODE) { if (newNode.getNodeType()!= Node.TEXT_NODE) { // result is 3 text nodes... cloneCurrent = fStartContainer.cloneNode(false); ((NodeImpl)cloneCurrent).setNodeValueInternal( (cloneCurrent.getNodeValue()).substring(fStartOffset)); ((NodeImpl)fStartContainer).setNodeValueInternal( (fStartContainer.getNodeValue()).substring(0,fStartOffset)); Node next = fStartContainer.getNextSibling(); if (next != null) { Node parent = fStartContainer.getParentNode(); if (parent != null) { parent.insertBefore(newNode, next); parent.insertBefore(cloneCurrent, next); } } else { Node parent = fStartContainer.getParentNode(); if (parent != null) { parent.appendChild(newNode); parent.appendChild(cloneCurrent); } } // signal other Ranges to update their start/end containers/offsets signalSplitData(fStartContainer, cloneCurrent, fStartOffset); } else { // result is 1 text node. String value = fStartContainer.getNodeValue(); String newValue = newNode.getNodeValue(); insertData( (CharacterData)fStartContainer, fStartOffset, newValue); } } else { // ! TEXT_NODE current = fStartContainer.getFirstChild(); int i = 0; for(i = 0; i < fStartOffset && current != null; i++) { current=current.getNextSibling(); } if (current != null) { fStartContainer.insertBefore(newNode, current); } else { fStartContainer.appendChild(newNode); } } } public void surroundContents(Node newParent) throws DOMException, RangeException { if (newParent==null) return; if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } int type = newParent.getNodeType(); if (type == Node.ATTRIBUTE_NODE || type == Node.ENTITY_NODE || type == Node.NOTATION_NODE || type == Node.DOCUMENT_TYPE_NODE || type == Node.DOCUMENT_NODE || type == Node.DOCUMENT_FRAGMENT_NODE) { throw new RangeExceptionImpl( RangeException.INVALID_NODE_TYPE_ERR, "DOM012 Invalid node type"); } Node root = getCommonAncestorContainer(); Node realStart = fStartContainer; Node realEnd = fEndContainer; if (fStartContainer.getNodeType() == Node.TEXT_NODE) { realStart = fStartContainer.getParentNode(); } if (fEndContainer.getNodeType() == Node.TEXT_NODE) { realEnd = fEndContainer.getParentNode(); } if (realStart != realEnd) { throw new RangeExceptionImpl( RangeException.BAD_BOUNDARYPOINTS_ERR, "DOM013 Bad boundary points"); } DocumentFragment frag = extractContents(); insertNode(newParent); newParent.appendChild(frag); selectNode(newParent); } public Range cloneRange(){ if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } Range range = fDocument.createRange(); range.setStart(fStartContainer, fStartOffset); range.setEnd(fEndContainer, fEndOffset); return range; } public String toString(){ if( fDetach) { throw new DOMExceptionImpl( DOMException.INVALID_STATE_ERR, "DOM011 Invalid state"); } Node node = fStartContainer; StringBuffer sb = new StringBuffer(); if (fStartContainer.getNodeType() == Node.TEXT_NODE || fStartContainer.getNodeType() == Node.CDATA_SECTION_NODE ) { if (fStartContainer == fEndContainer) { sb.append(fStartContainer.getNodeValue().substring(fStartOffset, fEndOffset)); return sb.toString(); } else { sb.append(fStartContainer.getNodeValue().substring(fStartOffset)); } } while (node != fEndContainer) { node = nextNode(node, true); if (node == null) break; if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE ) { sb.append(node.getNodeValue()); } } if (fEndContainer.getNodeType() == Node.TEXT_NODE || fEndContainer.getNodeType() == Node.CDATA_SECTION_NODE) { sb.append(fEndContainer.getNodeValue().substring(0,fEndOffset)); } return sb.toString(); } public void detach() { fDetach = true; fDocument.removeRange(this); } // Mutation functions /** Signal other Ranges to update their start/end * containers/offsets. The data has already been * into the two Nodes. */ void signalSplitData(Node node, Node newNode, int offset) { fSplitNode = node; // fix-up other Ranges Enumeration ranges = fDocument.getRanges(); if (ranges != null) { while ( ranges.hasMoreElements()) { ((RangeImpl)ranges.nextElement()).receiveSplitData(node, newNode, offset); } } fSplitNode = null; } /** Fix up this Range if another Range has split a Text Node * into 2 Nodes. */ void receiveSplitData(Node node, Node newNode, int offset) { if (node == null || newNode == null) return; if (fSplitNode == node) return; if (node == fStartContainer && fStartContainer.getNodeType() == Node.TEXT_NODE) { if (fStartOffset > offset) { fStartOffset = fStartOffset - offset; fStartContainer = newNode; } } if (node == fEndContainer && fEndContainer.getNodeType() == Node.TEXT_NODE) { if (fEndOffset > offset) { fEndOffset = fEndOffset-offset; fEndContainer = newNode; } } } /** This function inserts text into a Node and invokes * a method to fix-up all other Ranges. */ void deleteData(CharacterData node, int offset, int count) { fDeleteNode = node; node.deleteData( offset, count); fDeleteNode = null; } /** This function is called from DOM. * The text has already beeen inserted. * Fix-up any offsets. */ void receiveDeletedText(Node node, int offset, int count) { if (node == null) return; if (fDeleteNode == node) return; if (node == fStartContainer && fStartContainer.getNodeType() == Node.TEXT_NODE) { if (fStartOffset > offset+count) { fStartOffset = offset+(fStartOffset-(offset+count)); } else if (fStartOffset > offset) { fStartOffset = offset; } } if (node == fEndContainer && fEndContainer.getNodeType() == Node.TEXT_NODE) { if (fEndOffset > offset+count) { fEndOffset = offset+(fEndOffset-(offset+count)); } else if (fEndOffset > offset) { fEndOffset = offset; } } } /** This function inserts text into a Node and invokes * a method to fix-up all other Ranges. */ void insertData(CharacterData node, int index, String insert) { fInsertNode = node; node.insertData( index, insert); fInsertNode = null; } /** This function is called from DOM. * The text has already beeen inserted. * Fix-up any offsets. */ void receiveInsertedText(Node node, int index, int len) { if (node == null) return; if (fInsertNode == node) return; if (node == fStartContainer && fStartContainer.getNodeType() == Node.TEXT_NODE) { if (index < fStartOffset) { fStartOffset = fStartOffset+len; } } if (node == fEndContainer && fEndContainer.getNodeType() == Node.TEXT_NODE) { if (index < fEndOffset) { fEndOffset = fEndOffset+len; } } } /** This function is called from DOM. * The text has already beeen replaced. * Fix-up any offsets. */ void receiveReplacedText(Node node) { if (node == null) return; if (node == fStartContainer && fStartContainer.getNodeType() == Node.TEXT_NODE) { fStartOffset = 0; } if (node == fEndContainer && fEndContainer.getNodeType() == Node.TEXT_NODE) { fEndOffset = 0; } } /** This function is called from the DOM. * This node has already been inserted into the DOM. * Fix-up any offsets. */ public void insertedNodeFromDOM(Node node) { if (node == null) return; if (fInsertNode == node) return; Node parent = node.getParentNode(); if (parent == fStartContainer) { int index = indexOf(node, fStartContainer); if (index < fStartOffset) { fStartOffset++; } } if (parent == fEndContainer) { int index = indexOf(node, fEndContainer); if (index < fEndOffset) { fEndOffset++; } } } /** This function is called within Range * instead of Node.removeChild, * so that the range can remember that it is actively * removing this child. */ Node fRemoveChild = null; Node removeChild(Node parent, Node child) { fRemoveChild = child; Node n = parent.removeChild(child); fRemoveChild = null; return n; } /** This function must be called by the DOM _BEFORE_ * a node is deleted, because at that time it is * connected in the DOM tree, which we depend on. */ void removeNode(Node node) { if (node == null) return; if (fRemoveChild == node) return; Node parent = node.getParentNode(); if (parent == fStartContainer) { int index = indexOf(node, fStartContainer); if (index <= fStartOffset) { fStartOffset } } if (parent == fEndContainer) { int index = indexOf(node, fEndContainer); if (index < fEndOffset) { fEndOffset } } if (parent != fStartContainer && parent != fEndContainer) { if (isAncestorOf(node, fStartContainer)) { fStartContainer = parent; fStartOffset = indexOf( node, parent)-1; } if (isAncestorOf(node, fEndContainer)) { fEndContainer = parent; fEndOffset = indexOf( node, parent)-1; } } } // Utility functions. // parameters for traverseContents(int) //REVIST: use boolean, since there are only 2 now... static final int EXTRACT_CONTENTS = 1; static final int CLONE_CONTENTS = 2; /** This is the master traversal function which is used by * both extractContents and cloneContents(). */ DocumentFragment traverseContents(int traversalType) throws DOMException { if (fStartContainer == null || fEndContainer == null) { return null; // REVIST: Throw exception? } DocumentFragment frag = fDocument.createDocumentFragment(); Node current = fStartContainer; Node cloneCurrent = null; Node cloneParent = null; Node partialNode = null; int partialInt = START; Vector d = new Vector(); // if same container, simplify case if (fStartContainer == fEndContainer) { if (fStartOffset == fEndOffset) { // eg collapsed return frag; // REVIST: what is correct re spec? } if (fStartContainer.getNodeType() == Node.TEXT_NODE) { cloneCurrent = fStartContainer.cloneNode(false); cloneCurrent.setNodeValue( (cloneCurrent.getNodeValue()).substring(fStartOffset, fEndOffset)); if (traversalType == EXTRACT_CONTENTS) { deleteData((CharacterData)current, fStartOffset, fEndOffset-fStartOffset); } frag.appendChild(cloneCurrent); } else { current = current.getFirstChild(); int i = 0; for(i = 0; i < fStartOffset && current != null; i++) { current=current.getNextSibling(); } int n = fEndOffset-fStartOffset; for(i = 0; i < n && current != null ;i++) { Node newCurrent=current.getNextSibling(); if (traversalType == CLONE_CONTENTS) { cloneCurrent = current.cloneNode(true); frag.appendChild(cloneCurrent); } else if (traversalType == EXTRACT_CONTENTS) { frag.appendChild(current); } current = newCurrent; } } return frag; } /** is a an ancestor of b ? */ /** what is the index of the child in the parent */
package org.broad.igv.track; import htsjdk.tribble.AsciiFeatureCodec; import htsjdk.tribble.Feature; import htsjdk.variant.vcf.VCFHeader; import org.apache.log4j.Logger; import org.broad.igv.bbfile.BBFileReader; import org.broad.igv.bigwig.BigWigDataSource; import org.broad.igv.das.DASFeatureSource; import org.broad.igv.data.*; import org.broad.igv.data.cufflinks.*; import org.broad.igv.data.expression.ExpressionDataset; import org.broad.igv.data.expression.ExpressionFileParser; import org.broad.igv.data.rnai.RNAIDataSource; import org.broad.igv.data.rnai.RNAIGCTDatasetParser; import org.broad.igv.data.rnai.RNAIGeneScoreParser; import org.broad.igv.data.rnai.RNAIHairpinParser; import org.broad.igv.data.seg.*; import org.broad.igv.dev.SegmentedReader; import org.broad.igv.dev.api.LoadHandler; import org.broad.igv.dev.db.DBProfile; import org.broad.igv.dev.db.SQLCodecSource; import org.broad.igv.dev.db.SampleInfoSQLReader; import org.broad.igv.dev.db.SegmentedSQLReader; import org.broad.igv.exceptions.DataLoadException; import org.broad.igv.feature.*; import org.broad.igv.feature.basepair.BasePairTrack; import org.broad.igv.feature.bionano.SMAPParser; import org.broad.igv.feature.bionano.SMAPRenderer; import org.broad.igv.feature.dranger.DRangerParser; import org.broad.igv.feature.dsi.DSIRenderer; import org.broad.igv.feature.dsi.DSITrack; import org.broad.igv.feature.genome.GenbankParser; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.feature.tribble.CodecFactory; import org.broad.igv.feature.tribble.FeatureFileHeader; import org.broad.igv.feature.tribble.TribbleIndexNotFoundException; import org.broad.igv.ga4gh.Ga4ghAPIHelper; import org.broad.igv.ga4gh.OAuthUtils; import org.broad.igv.goby.GobyAlignmentQueryReader; import org.broad.igv.goby.GobyCountArchiveDataSource; import org.broad.igv.gwas.GWASData; import org.broad.igv.gwas.GWASParser; import org.broad.igv.gwas.GWASTrack; import org.broad.igv.lists.GeneList; import org.broad.igv.lists.GeneListManager; import org.broad.igv.maf.MultipleAlignmentTrack; import org.broad.igv.methyl.MethylTrack; import org.broad.igv.peaks.PeakTrack; import org.broad.igv.prefs.IGVPreferences; import org.broad.igv.prefs.PreferencesManager; import org.broad.igv.renderer.*; import org.broad.igv.sam.*; import org.broad.igv.sam.reader.IndexNotFoundException; import org.broad.igv.synteny.BlastMapping; import org.broad.igv.synteny.BlastParser; import org.broad.igv.tdf.TDFDataSource; import org.broad.igv.tdf.TDFReader; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.ConfirmDialog; import org.broad.igv.ui.util.ConvertFileDialog; import org.broad.igv.ui.util.ConvertOptions; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.FileUtils; import org.broad.igv.util.HttpUtils; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import org.broad.igv.variant.VariantTrack; import org.broad.igv.variant.util.PedigreeUtils; import java.awt.*; import java.io.IOException; import java.net.MalformedURLException; import java.util.*; import java.util.List; import static org.broad.igv.prefs.Constants.*; public class TrackLoader { private static Logger log = Logger.getLogger(TrackLoader.class); private static Collection<? extends Class> NOLogExceptions = Arrays.asList(TribbleIndexNotFoundException.class); /** * Switches on various attributes of locator (mainly locator path extension and whether the locator is indexed) * to call the appropriate loading method. * * @param locator * @param genome * @return */ public List<Track> load(ResourceLocator locator, Genome genome) throws DataLoadException { final String path = locator.getPath().trim(); log.info("Loading resource, path " + path); try { String typeString = locator.getTypeString(); if (typeString.endsWith(".tbi")) { MessageUtils.showMessage("<html><b>Error:</b>File type '.tbi' is not recognized. If this is a 'tabix' index <br>" + " load the associated gzipped file, which should have an extension of '.gz'"); } //This list will hold all new tracks created for this locator List<Track> newTracks = new ArrayList<Track>(); String dbUrl = locator.getDBUrl(); LoadHandler handler = getTrackLoaderHandler(typeString); if (dbUrl != null) { this.loadFromDatabase(locator, newTracks, genome); } else if (typeString.endsWith(".dbxml")) { loadFromDBProfile(locator, newTracks); } else if (typeString.endsWith(".gmt")) { loadGMT(locator); } else if (typeString.equals("das")) { loadDASResource(locator, newTracks); } else if (typeString.endsWith(".vcf.list")) { loadVCFListFile(locator, newTracks, genome); } else if (typeString.endsWith(".trio")) { loadTrioData(locator); } else if (typeString.endsWith(".rnai.gct")) { loadRnaiGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".gct") || typeString.endsWith("res") || typeString.endsWith("tab")) { loadGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".gbk") || typeString.endsWith(".gb")) { loadGbkFile(locator, newTracks, genome); } else if (typeString.endsWith(".cn") || typeString.endsWith(".xcn") || typeString.endsWith(".snp") || typeString.endsWith(".igv") || typeString.endsWith(".loh")) { loadIGVFile(locator, newTracks, genome); } else if (typeString.endsWith(".cbs") || typeString.endsWith(".seg") || typeString.endsWith("glad") || typeString.endsWith("birdseye_canary_calls") || typeString.endsWith(".seg.zip")) { loadSegFile(locator, newTracks, genome); } else if (typeString.endsWith(".gistic")) { loadGisticFile(locator, newTracks); } else if (typeString.endsWith(".gs")) { loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.GENE_SCORE, genome); } else if (typeString.endsWith(".riger")) { loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.POOLED, genome); } else if (typeString.endsWith(".hp")) { loadRNAiHPScoreFile(locator); } else if (typeString.contains(".tabblastn") || typeString.endsWith(".orthologs")) { loadSyntentyMapping(locator, newTracks); } else if (isAlignmentTrack(typeString)) { loadAlignmentsTrack(locator, newTracks, genome); } else if (typeString.endsWith(".shape") || typeString.endsWith(".map")) { convertLoadShapeFile(locator, newTracks, genome); } else if (typeString.endsWith(".wig") || typeString.endsWith(".bedgraph") || typeString.endsWith(".bdg") || typeString.endsWith("cpg.txt") || typeString.endsWith(".expr")) { loadWigFile(locator, newTracks, genome); } else if (typeString.endsWith("fpkm_tracking") || typeString.endsWith("gene_exp.diff") || typeString.endsWith("cds_exp.diff")) { loadCufflinksFile(locator, newTracks, genome); } else if (typeString.contains(".dranger")) { loadDRangerFile(locator, newTracks, genome); } else if (typeString.endsWith(".ewig.tdf") || (typeString.endsWith(".ewig.ibf"))) { loadEwigIBFFile(locator, newTracks, genome); } else if (typeString.endsWith(".bw") || typeString.endsWith(".bb") || typeString.endsWith(".bigwig") || typeString.endsWith(".bigbed")) { loadBWFile(locator, newTracks, genome); } else if (typeString.endsWith(".ibf") || typeString.endsWith(".tdf")) { loadTDFFile(locator, newTracks, genome); } else if (typeString.endsWith(".counts")) { loadGobyCountsArchive(locator, newTracks, genome); } else if (WiggleParser.isWiggle(locator)) { loadWigFile(locator, newTracks, genome); } else if (typeString.endsWith(".maf")) { if (MutationTrackLoader.isMutationAnnotationFile(locator)) { loadMutFile(locator, newTracks, genome); // Must be tried before generic "loadIndexed" below } else { loadMultipleAlignmentTrack(locator, newTracks, genome); } } else if (typeString.endsWith(".maf.dict")) { loadMultipleAlignmentTrack(locator, newTracks, genome); } else if (typeString.contains(".peak.bin")) { loadPeakTrack(locator, newTracks, genome); } else if (typeString.endsWith("mage-tab") || ExpressionFileParser.parsableMAGE_TAB(locator)) { locator.setDescription("MAGE_TAB"); loadGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".db") || typeString.endsWith(".dbn")) { convertLoadStructureFile(locator, newTracks, genome, "dotBracket"); } else if (typeString.endsWith(".ct")) { convertLoadStructureFile(locator, newTracks, genome, "connectTable"); } else if (typeString.endsWith(".dp")) { convertLoadStructureFile(locator, newTracks, genome, "pairingProb"); } else if (typeString.endsWith(".bp")) { loadBasePairFile(locator, newTracks, genome); } else if (GWASParser.isGWASFile(typeString)) { loadGWASFile(locator, newTracks, genome); } else if (GobyAlignmentQueryReader.supportsFileType(path)) { loadAlignmentsTrack(locator, newTracks, genome); } else if (typeString.endsWith(".list")) { // This should be deprecated loadListFile(locator, newTracks, genome); } else if (typeString.endsWith(".smap")) { loadSMAPFile(locator, newTracks, genome); } else if (typeString.endsWith("dsi")) { loadDSIFile(locator, newTracks, genome); } else if (CodecFactory.hasCodec(locator, genome) && !forceNotTribble(typeString)) { loadTribbleFile(locator, newTracks, genome); } else if (handler != null) { //Custom loader specified log.info(String.format("Loading %s with %s", path, handler)); handler.load(path, newTracks); } else if (AttributeManager.isSampleInfoFile(locator)) { // This might be a sample information file. AttributeManager.getInstance().loadSampleInfo(locator); } else { MessageUtils.showMessage("<html>Unknown file type: " + path + "<br>Check file extension"); } // Track line TrackProperties tp = null; String trackLine = locator.getTrackLine(); if (trackLine != null) { tp = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, tp); } for (Track track : newTracks) { if (locator.getFeatureInfoURL() != null) { track.setUrl(locator.getFeatureInfoURL()); } if (tp != null) { track.setProperties(tp); } if (locator.getColor() != null) { track.setColor(locator.getColor()); } if (locator.getSampleId() != null) { track.setSampleId(locator.getSampleId()); } } return newTracks; } catch (Exception e) { if (!NOLogExceptions.contains(e.getClass())) { log.error(e.getMessage(), e); } throw new DataLoadException(e.getMessage()); } } public static boolean isAlignmentTrack(String typeString) { return typeString.endsWith(".sam") || typeString.endsWith(".bam") || typeString.endsWith(".cram") || typeString.endsWith(".sam.list") || typeString.endsWith(".bam.list") || typeString.endsWith(".aligned") || typeString.endsWith(".sai") || typeString.endsWith(".bai") || typeString.equals("alist") || typeString.equals(Ga4ghAPIHelper.RESOURCE_TYPE); } private void loadSMAPFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { List<Feature> features = SMAPParser.parseFeatures(locator, genome); FeatureCollectionSource src = new FeatureCollectionSource(features, genome); FeatureTrack track = new FeatureTrack(locator, locator.getName(), src); track.setRendererClass(SMAPRenderer.class); track.setDisplayMode(Track.DisplayMode.EXPANDED); newTracks.add(track); } private boolean forceNotTribble(String typeString) { List<String> nonTribble = Arrays.asList("fpkm_tracking", "exp_diff", "_exp.diff"); for (String s : nonTribble) { if (typeString.endsWith(s)) { return true; } } return false; } private void loadGMT(ResourceLocator locator) throws IOException { List<GeneList> lists = GeneListManager.getInstance().loadGMTFile(locator.getPath()); if (lists.size() == 1) { GeneList gl = lists.get(0); IGV.getInstance().setGeneList(gl, true); } else { MessageUtils.showMessage("Loaded " + lists.size() + " gene lists."); } } private void loadVCF(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException, TribbleIndexNotFoundException { TribbleFeatureSource src = TribbleFeatureSource.getFeatureSource(locator, genome); VCFHeader header = (VCFHeader) src.getHeader(); // Test if the input VCF file contains methylation rate data: // This is determined by testing for the presence of two sample format fields: MR and GB, used in the // rendering of methylation rate. // MR is the methylation rate on a scale of 0 to 100% and GB is the number of bases that pass // filter for the position. GB is needed to avoid displaying positions for which limited coverage // prevents reliable estimation of methylation rate. boolean enableMethylationRateSupport = (header.getFormatHeaderLine("MR") != null && header.getFormatHeaderLine("GB") != null); List<String> allSamples = new ArrayList(header.getGenotypeSamples()); VariantTrack t = new VariantTrack(locator, src, allSamples, enableMethylationRateSupport); // VCF tracks handle their own margin t.setMargin(0); newTracks.add(t); } private void loadVCFListFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException, TribbleIndexNotFoundException { TribbleListFeatureSource src = new TribbleListFeatureSource(locator.getPath(), genome); VCFHeader header = (VCFHeader) src.getHeader(); // Test if the input VCF file contains methylation rate data: // This is determined by testing for the presence of two sample format fields: MR and GB, used in the // rendering of methylation rate. // MR is the methylation rate on a scale of 0 to 100% and GB is the number of bases that pass // filter for the position. GB is needed to avoid displaying positions for which limited coverage // prevents reliable estimation of methylation rate. boolean enableMethylationRateSupport = (header.getFormatHeaderLine("MR") != null && header.getFormatHeaderLine("GB") != null); List<String> allSamples = new ArrayList(header.getGenotypeSamples()); VariantTrack t = new VariantTrack(locator, src, allSamples, enableMethylationRateSupport); // VCF tracks handle their own margin t.setMargin(0); newTracks.add(t); } private void loadSyntentyMapping(ResourceLocator locator, List<Track> newTracks) { List<BlastMapping> mappings = (new BlastParser()).parse(locator.getPath()); List<htsjdk.tribble.Feature> features = new ArrayList<htsjdk.tribble.Feature>(mappings.size()); features.addAll(mappings); Genome genome = GenomeManager.getInstance().getCurrentGenome(); FeatureTrack track = new FeatureTrack(locator, new FeatureCollectionSource(features, genome)); track.setName(locator.getTrackName()); // track.setRendererClass(AlignmentBlockRenderer.class); newTracks.add(track); } private void loadDRangerFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { DRangerParser parser = new DRangerParser(); newTracks.addAll(parser.loadTracks(locator, genome)); } /** * Load the input file as a feature, mutation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadTribbleFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException, TribbleIndexNotFoundException { String typeString = locator.getTypeString(); // Mutation (mut, maf, vcf) files are handled special. Check here, rather than depend on order in giant case statement. if (MutationTrackLoader.isMutationAnnotationFile(locator)) { loadMutFile(locator, newTracks, genome); // Must be tried before generic "loadIndexed" below } else if (VariantTrack.isVCF(typeString)) { loadVCF(locator, newTracks, genome); } else { TribbleFeatureSource tribbleFeatureSource = TribbleFeatureSource.getFeatureSource(locator, genome); FeatureSource src = GFFFeatureSource.isGFF(locator.getPath()) ? new GFFFeatureSource(tribbleFeatureSource) : tribbleFeatureSource; // Create feature source and track FeatureTrack t = new FeatureTrack(locator, src); t.setName(locator.getTrackName()); //t.setRendererClass(BasicTribbleRenderer.class); // Set track properties from header Object header = tribbleFeatureSource.getHeader(); if (header != null && header instanceof FeatureFileHeader) { FeatureFileHeader ffh = (FeatureFileHeader) header; if (ffh.getTrackType() != null) { t.setTrackType(ffh.getTrackType()); } if (ffh.getTrackProperties() != null) { TrackProperties tp = ffh.getTrackProperties(); t.setProperties(tp); t.setTrackLine(tp.getTrackLine()); } if (ffh.getTrackType() == TrackType.REPMASK) { t.setHeight(15); } } if (locator.getPath().contains(".narrowPeak") || locator.getPath().contains(".broadPeak") || locator.getPath().contains(".gappedPeak")) { t.setUseScore(true); } newTracks.add(t); } } private void loadDSIFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException, TribbleIndexNotFoundException { TribbleFeatureSource tribbleFeatureSource = TribbleFeatureSource.getFeatureSource(locator, genome); // Create feature source and track DSITrack t = new DSITrack(locator, tribbleFeatureSource); t.setName(locator.getTrackName()); //t.setRendererClass(BasicTribbleRenderer.class); // Set track properties from header Object header = tribbleFeatureSource.getHeader(); if (header != null && header instanceof TrackProperties) { TrackProperties tp = (TrackProperties) header; t.setProperties(tp); t.setTrackLine(tp.getTrackLine()); } t.setRendererClass(DSIRenderer.class); newTracks.add(t); } /** * Load GWAS PLINK result file * * @param locator * @param newTracks * @throws IOException */ private void loadGWASFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { GWASParser gwasParser = new GWASParser(locator, genome); GWASData gwasData = gwasParser.parse(); GWASTrack gwasTrack = new GWASTrack(locator, locator.getPath(), locator.getFileName(), gwasData, gwasParser); newTracks.add(gwasTrack); } private void loadRnaiGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { RNAIGCTDatasetParser parser = new RNAIGCTDatasetParser(locator, genome); Collection<RNAIDataSource> dataSources = parser.parse(); if (dataSources != null) { String path = locator.getPath(); for (RNAIDataSource ds : dataSources) { String trackId = path + "_" + ds.getName(); DataSourceTrack track = new DataSourceTrack(locator, trackId, ds.getName(), ds); // Set attributes. track.setAttributeValue("SCREEN", ds.getScreen()); track.setHeight(80); newTracks.add(track); } } } private void loadGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { if (locator.isLocal()) { if (!checkSize(locator)) { return; } } ExpressionFileParser parser = null; ExpressionDataset ds = null; parser = new ExpressionFileParser(locator, null, genome); ds = parser.createDataset(); if (ds.isEmpty()) { String message = "The probes in the file <br>&nbsp;&nbsp;&nbsp;" + locator.getPath() + "<br>" + "could not be mapped to genomic positions. This can be corrected by specify a probe mapping<br>" + "file from the Preferences window (Probes tab), or by specifing the genomic positions in the<br>" + "expression data file. Please see the user guide for more details."; MessageUtils.showMessage(message); } else { ds.setName(locator.getTrackName()); ds.setNormalized(true); ds.setLogValues(true); /* * File outputFile = new File(IGV.DEFAULT_USER_DIRECTORY, file.getName() + ".h5"); * OverlappingProcessor proc = new OverlappingProcessor(ds); * proc.setZoomMax(0); * proc.process(outputFile.getAbsolutePath()); * loadH5File(outputFile, messages, attributeList, group); */ // Counter for generating ID TrackProperties trackProperties = ds.getTrackProperties(); String path = locator.getPath(); for (String trackName : ds.getTrackNames()) { DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, genome); String trackId = path + "_" + trackName; Track track = new DataSourceTrack(locator, trackId, trackName, dataSource); track.setRendererClass(HeatmapRenderer.class); track.setProperties(trackProperties); newTracks.add(track); } } } /** * Load features from a genbank (.gbk)file. This method ignores the fasta section. To define a genome from * a genbank file use GenomeManager. * * @param newTracks * @param genome * @throws IOException */ private void loadGbkFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { GenbankParser genbankParser = new GenbankParser(locator.getPath()); genbankParser.readFeatures(false); FeatureCollectionSource src = new FeatureCollectionSource(genbankParser.getFeatures(), genome); FeatureTrack track = new FeatureTrack(locator, src); newTracks.add(track); } private void loadIGVFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator)) { return; } } String dsName = locator.getTrackName(); IGVDataset ds = new IGVDataset(locator, genome); ds.setName(dsName); TrackProperties trackProperties = ds.getTrackProperties(); String path = locator.getPath(); TrackType type = ds.getType(); for (String trackName : ds.getTrackNames()) { DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, genome); String trackId = path + "_" + trackName; DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource); // track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); track.setProperties(trackProperties); if (type == TrackType.ALLELE_FREQUENCY) { track.setRendererClass(PointsRenderer.class); track.setHeight(40); } newTracks.add(track); } } private void loadCufflinksFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { final String path = locator.getPath(); final String s = path.toLowerCase(); List<DataTrack> cuffTracks = new ArrayList<DataTrack>(); if (s.endsWith("fpkm_tracking")) { FPKMTrackingCodec codec = new FPKMTrackingCodec(path); List<FPKMValue> values = CufflinksParser.parse(codec, path); for (int sampleIndex = 0; sampleIndex < codec.getNumSamples(); sampleIndex++) { CufflinksDataSource ds = new CufflinksDataSource(sampleIndex, values, genome); String supId = String.format("q%02d", sampleIndex); DataTrack track = new DataSourceTrack(locator, locator.getPath() + " " + supId, locator.getTrackName() + " " + supId, ds); cuffTracks.add(track); } } else if (s.endsWith("gene_exp.diff") || s.endsWith("cds_exp.diff")) { AsciiFeatureCodec<ExpDiffValue> codec = new ExpDiffCodec(path); List<ExpDiffValue> values = CufflinksParser.parse(codec, path); CufflinksDataSource ds = new CufflinksDataSource(values, genome); DataTrack track = new DataSourceTrack(locator, locator.getPath(), locator.getTrackName(), ds); cuffTracks.add(track); } else { throw new RuntimeException("Unsupported file type: " + path); } for (DataTrack track : cuffTracks) { track.setTrackType(TrackType.FPKM); CufflinksTrack.setCufflinksScale(track); newTracks.add(track); } } private static boolean checkSize(ResourceLocator locator) { if (!PreferencesManager.getPreferences().getAsBoolean(SHOW_SIZE_WARNING)) { return true; } final String path = locator.getPath(); long size = FileUtils.getLength(path); int maxSize = 200000000; // 200 mb if (path.endsWith(".gz") || path.endsWith(".bgz")) { maxSize /= 4; } if (size > maxSize) { String message = "The file " + path + " is large (" + (size / 1000000) + " mb). It is recommended " + "that large files be converted to the binary <i>.tdf</i> format using the IGVTools " + "<b>toTDF</b> command. Loading unconverted ascii fies of this size can lead to poor " + "performance or unresponsiveness (freezing). " + "<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a " + "command line program. See the user guide for more details.<br><br>Click <b>Continue</b> " + "to continue loading, or <b>Cancel</b> to skip this file."; return ConfirmDialog.optionallyShowConfirmDialog(message, SHOW_SIZE_WARNING, true); } return true; } private void loadDOTFile(ResourceLocator locator, List<Track> newTracks) { //GraphTrack gt = new GraphTrack(locator); //gt.setHeight(80); //newTracks.add(gt); } private void loadWigFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator)) { return; } } WiggleDataset ds = (new WiggleParser(locator, genome)).parse(); TrackProperties props = ds.getTrackProperties(); // In case of conflict between the resource locator display name and the track properties name, // use the resource locator String name = props == null ? null : props.getName(); String label = locator.getName(); if (name == null) { name = locator.getFileName(); } else if (label != null) { props.setName(label); // erase name rom track properties } String path = locator.getPath(); boolean multiTrack = ds.getTrackNames().length > 1; for (String heading : ds.getTrackNames()) { String trackId = multiTrack ? path + "_" + heading : path; String trackName = multiTrack ? heading : name; DatasetDataSource dataSource = new DatasetDataSource(trackId, ds, genome); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource); String displayName = (label == null || multiTrack) ? heading : label; track.setName(displayName); track.setProperties(props); track.setTrackType(ds.getType()); if (ds.getType() == TrackType.EXPR) { track.setWindowFunction(WindowFunction.none); } newTracks.add(track); } } public void loadTDFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { log.debug("Loading TDF file " + locator.getPath()); TDFReader reader = TDFReader.getReader(locator); TrackType type = reader.getTrackType(); TrackProperties props = null; String trackLine = reader.getTrackLine(); if (trackLine != null && trackLine.length() > 0) { props = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, props); } // In case of conflict between the resource locator display name and the track properties name, // use the resource locator String name = locator.getName(); if (name != null && props != null) { props.setName(name); } if (name == null) { name = props == null ? locator.getTrackName() : props.getName(); } int trackNumber = 0; String path = locator.getPath(); boolean multiTrack = reader.getTrackNames().length > 1; for (String heading : reader.getTrackNames()) { String trackId = multiTrack ? path + "_" + heading : path; String trackName = multiTrack ? heading : name; final DataSource dataSource = locator.getPath().endsWith(".counts") ? new GobyCountArchiveDataSource(locator) : new TDFDataSource(reader, trackNumber, heading, genome); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource); String displayName = (name == null || multiTrack) ? heading : name; track.setName(displayName); track.setTrackType(type); if (props != null) { track.setProperties(props); } newTracks.add(track); trackNumber++; } } public void loadBWFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { String trackName = locator.getTrackName(); String trackId = locator.getPath(); String path = locator.getPath(); BBFileReader reader = new BBFileReader(path); BigWigDataSource bigwigSource = new BigWigDataSource(reader, genome); if (reader.isBigWigFile()) { DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, bigwigSource); newTracks.add(track); } else if (reader.isBigBedFile()) { if (locator.getPath().contains("RRBS_cpgMethylation") || locator.getPath().contains("BiSeq_cpgMethylation") || (reader.getAutoSql() != null && reader.getAutoSql().startsWith("table BisulfiteSeq"))) { loadMethylTrack(locator, reader, newTracks, genome); } else { FeatureTrack track = new FeatureTrack(locator, trackId, trackName, bigwigSource); newTracks.add(track); } } else { throw new RuntimeException("Unknown BIGWIG type: " + locator.getPath()); } } private void loadMethylTrack(ResourceLocator locator, BBFileReader reader, List<Track> newTracks, Genome genome) throws IOException { MethylTrack track = new MethylTrack(locator, reader, genome); newTracks.add(track); } private void loadGobyCountsArchive(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (log.isDebugEnabled()) { log.debug("Loading Goby counts archive: " + locator.toString()); } String trackId = locator.getSampleId() + " coverage"; String trackName = locator.getFileName(); final DataSource dataSource = new GobyCountArchiveDataSource(locator); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource); newTracks.add(track); } private void loadEwigIBFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { TDFReader reader = TDFReader.getReader(locator.getPath()); TrackProperties props = null; String trackLine = reader.getTrackLine(); if (trackLine != null && trackLine.length() > 0) { props = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, props); } EWigTrack track = new EWigTrack(locator, genome); if (props != null) { track.setProperties(props); } track.setName(locator.getTrackName()); newTracks.add(track); } private void loadListFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { try { FeatureSource source = new FeatureDirSource(locator, genome); FeatureTrack track = new FeatureTrack(locator, source); track.setName(locator.getTrackName()); track.setVisibilityWindow(0); newTracks.add(track); } catch (IOException ex) { throw new RuntimeException(ex); } } private void loadGisticFile(ResourceLocator locator, List<Track> newTracks) { GisticTrack track = GisticFileParser.loadData(locator); track.setName(locator.getTrackName()); newTracks.add(track); } /** * Load a rnai gene score file and create a datasource and track. * <p/> * * @param locator * @param newTracks */ private void loadRNAiGeneScoreFile(ResourceLocator locator, List<Track> newTracks, RNAIGeneScoreParser.Type type, Genome genome) { RNAIGeneScoreParser parser = new RNAIGeneScoreParser(locator.getPath(), type, genome); Collection<RNAIDataSource> dataSources = parser.parse(); String path = locator.getPath(); for (RNAIDataSource ds : dataSources) { String name = ds.getName(); String trackId = path + "_" + name; DataSourceTrack track = new DataSourceTrack(locator, trackId, name, ds); // Set attributes. This "hack" is neccessary to register these attributes with the // attribute manager to get displayed. track.setAttributeValue("SCREEN", ds.getScreen()); if ((ds.getCondition() != null) && (ds.getCondition().length() > 0)) { track.setAttributeValue("CONDITION", ds.getCondition()); } track.setHeight(80); //track.setDataRange(new DataRange(-3, 0, 3)); newTracks.add(track); } } /** * Load a RNAi haripin score file. The results of this action are hairpin scores * added to the RNAIDataManager. Currently no tracks are created for hairpin * scores, although this could change. * * @param locator */ private void loadRNAiHPScoreFile(ResourceLocator locator) { (new RNAIHairpinParser(locator.getPath())).parse(); } private void loadMultipleAlignmentTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { MultipleAlignmentTrack t = new MultipleAlignmentTrack(locator, genome); t.setName("Multiple Alignments"); newTracks.add(t); } private void loadPeakTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { PeakTrack t = new PeakTrack(locator, genome); newTracks.add(t); } private void loadAlignmentsTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { try { String dsName = locator.getTrackName(); // If the user tried to load the index, look for the file (this is a common mistake) if (locator.getTypeString().endsWith(".sai") || locator.getTypeString().endsWith(".bai")) { MessageUtils.showMessage("<html><b>ERROR:</b> Loading SAM/BAM index files are not supported: " + locator.getPath() + "<br>Load the SAM or BAM file directly. "); return; } AlignmentDataManager dataManager = new AlignmentDataManager(locator, genome); // Check that alignments we loaded actually match some data. Many BAM files will contain some sequences // not represented in the genome, buf if there are no matches warn the user. List<String> seqNames = dataManager.getSequenceNames(); if (seqNames != null && seqNames.size() > 0) { if (!checkSequenceNames(locator.getPath(), genome, seqNames)) { return; } } if (locator.getTypeString().endsWith("bam") || locator.getTypeString().endsWith("cram")) { if (!dataManager.hasIndex()) { MessageUtils.showMessage("<html>Could not load index file for: " + locator.getPath() + "<br> An index file is required for SAM & BAM files."); return; } } AlignmentTrack alignmentTrack = new AlignmentTrack(locator, dataManager, genome); // parser.loadTrack(locator, dsName) alignmentTrack.setName(dsName); alignmentTrack.setVisible(PreferencesManager.getPreferences().getAsBoolean(SAM_SHOW_ALIGNMENT_TRACK)); // Create coverage track CoverageTrack covTrack = new CoverageTrack(locator, dsName + " Coverage", alignmentTrack, genome); covTrack.setVisible(PreferencesManager.getPreferences().getAsBoolean(SAM_SHOW_COV_TRACK)); newTracks.add(covTrack); covTrack.setDataManager(dataManager); dataManager.setCoverageTrack(covTrack); alignmentTrack.setCoverageTrack(covTrack); // Search for precalculated coverage data // Skip for GA4GH & SU2C resources if (!(Ga4ghAPIHelper.RESOURCE_TYPE.equals(locator.getType()) || locator.getPath().contains("dataformat=.bam") || OAuthUtils.isGoogleCloud(locator.getPath()))) { String covPath = locator.getCoverage(); if (covPath == null) { boolean bypassFileAutoDiscovery = PreferencesManager.getPreferences().getAsBoolean(BYPASS_FILE_AUTO_DISCOVERY); String path = locator.getPath(); if (!bypassFileAutoDiscovery && !path.contains("/query.cgi?")) { covPath = path + ".tdf"; } } if (covPath != null && !covPath.equals(".")) { if (FileUtils.resourceExists(covPath)) { log.debug("Loading TDF for coverage: " + covPath); try { TDFReader reader = TDFReader.getReader(covPath); TDFDataSource ds = new TDFDataSource(reader, 0, dsName + " coverage", genome); covTrack.setDataSource(ds); } catch (Exception e) { log.error("Error loading coverage TDF file", e); } } } } boolean showSpliceJunctionTrack = PreferencesManager.getPreferences().getAsBoolean(SAM_SHOW_JUNCTION_TRACK); SpliceJunctionTrack spliceJunctionTrack = new SpliceJunctionTrack(locator, dsName + " Junctions", dataManager, alignmentTrack, SpliceJunctionTrack.StrandOption.BOTH); spliceJunctionTrack.setHeight(60); spliceJunctionTrack.setVisible(showSpliceJunctionTrack); newTracks.add(spliceJunctionTrack); alignmentTrack.setSpliceJunctionTrack(spliceJunctionTrack); newTracks.add(alignmentTrack); log.debug("Alignment track loaded"); } catch (IndexNotFoundException e) { MessageUtils.showMessage("<html>Could not find the index file for <br><br>&nbsp;&nbsp;" + e.getSamFile() + "<br><br>Note: The index file can be created using igvtools and must be in the same directory as the .sam file."); } } /** * Compare the sequence names against sequence (chromosome) names in the genome. If no matches warn the user. * * @param filename * @param genome * @param seqNames * @return true if there is at least one sequence match, false otherwise */ private boolean checkSequenceNames(String filename, Genome genome, List<String> seqNames) { boolean atLeastOneMatch = false; for (String seqName : seqNames) { if (genome.getChromosome(seqName) != null) { atLeastOneMatch = true; break; } } if (!atLeastOneMatch) { StringBuffer message = new StringBuffer(); message.append("<html>File: " + filename + "<br>does not contain any sequence names which match the current genome."); message.append("<br><br>File: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); int n = 0; for (String sn : seqNames) { message.append(sn + ", "); n++; if (n > 3) { message.append(" ..."); break; } } message.append("<br>Genome: "); n = 0; for (String cn : genome.getAllChromosomeNames()) { message.append(cn + ", "); n++; if (n > 3) { message.append(" ..."); break; } } MessageUtils.showMessage(message.toString()); } return atLeastOneMatch; } /** * Load a mutation file (".mut" or ".maf"). * * @param locator * @param newTracks */ private void loadMutFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException, TribbleIndexNotFoundException { MutationTrackLoader loader = new MutationTrackLoader(); List<FeatureTrack> mutationTracks = loader.loadMutationTracks(locator, genome); for (FeatureTrack track : mutationTracks) { track.setTrackType(TrackType.MUTATION); track.setRendererClass(MutationRenderer.class); newTracks.add(track); } } private void loadFromDBProfile(ResourceLocator profileLocator, List<Track> newTracks) throws IOException { DBProfile dbProfile = DBProfile.parseProfile(profileLocator.getPath()); for (DBProfile.DBTable table : dbProfile.getTableList()) { SQLCodecSource source = SQLCodecSource.getFromTable(table); if (source != null) { CachingFeatureSource cachingReader = new CachingFeatureSource(source); FeatureTrack track = new FeatureTrack(profileLocator, cachingReader); track.setName(source.getTableName()); newTracks.add(track); } else if (table.getFormat().equals("seg")) { Genome genome = GenomeManager.getInstance().getCurrentGenome(); SegmentedAsciiDataSet ds = (new SegmentedReader(table.getDbLocator(), genome)).loadFromDB(table); loadSegTrack(table.getDbLocator(), newTracks, genome, ds); } else if (table.getFormat().equals("sample.info")) { //TODO sampleIdColumnLabel was previously hardcoded as "SAMPLE_ID_ARRAY" //TODO Basically I'm shoehorning this information into a field usually used for something else. Only slightly better String sampleIdColumnLabel = table.getBinColName(); if (sampleIdColumnLabel == null) { throw new IllegalArgumentException("Profile must have binColName specifying the sample id column label"); } (new SampleInfoSQLReader(table, sampleIdColumnLabel)).load(); } } } /** * @param locator * @param newTracks * @param genome * @deprecated See loadFromDBProfile, which loads from an xml file specifying table characteristics */ @Deprecated private void loadFromDatabase(ResourceLocator locator, List<Track> newTracks, Genome genome) { //For backwards/forwards compatibility //We used to put path in the serverURL field ResourceLocator dbLocator = new ResourceLocator(locator.getDBUrl()); if (".seg".equals(locator.getTypeString())) { //TODO Don't hardcode table name, this might note even be right for our target case SegmentedAsciiDataSet ds = (new SegmentedSQLReader(dbLocator, "CNV", genome)).load(); loadSegTrack(locator, newTracks, genome, ds); } else { (new SampleInfoSQLReader(dbLocator, "SAMPLE_INFO", "SAMPLE_ID_ARRAY")).load(); } } private void loadSegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { // TODO - -handle remote resource SegmentedDataSet ds; String path = locator.getPath().toLowerCase(); if (path.endsWith("seg.zip")) { ds = new SegmentedBinaryDataSet(locator); } else { SegmentFileParser parser = new SegmentFileParser(locator); ds = parser.loadSegments(locator, genome); } loadSegTrack(locator, newTracks, genome, ds); } /** * Add the provided SegmentedDataSet to the list of tracks, * set other relevant properties * * @param locator * @param newTracks * @param genome * @param ds */ private void loadSegTrack(ResourceLocator locator, List<Track> newTracks, Genome genome, SegmentedDataSet ds) { String path = locator.getPath(); TrackProperties props = null; if (ds instanceof SegmentedAsciiDataSet) { props = ((SegmentedAsciiDataSet) ds).getTrackProperties(); } // The "freq" track. TODO - make this optional if ((ds.getType() == TrackType.COPY_NUMBER || ds.getType() == TrackType.CNV) && ds.getSampleNames().size() > 1) { FreqData fd = new FreqData(ds, genome); String freqTrackId = path; String freqTrackName = "CNV Summary"; CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd); if (props != null) { freqTrack.setProperties(props); } newTracks.add(freqTrack); } for (String trackName : ds.getSampleNames()) { String trackId = path + "_" + trackName; SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource); track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); if (props != null) { track.setProperties(props); } newTracks.add(track); } } private void loadDASResource(ResourceLocator locator, List<Track> currentTracks) throws DataLoadException { //TODO Connect and get all the attributes of the DAS server, and run the appropriate load statements //TODO Currently we are only going to be doing features // TODO -- move the source creation to a factory DASFeatureSource featureSource = null; try { featureSource = new DASFeatureSource(locator); } catch (MalformedURLException e) { log.error("Malformed URL", e); throw new DataLoadException("Error: Malformed URL "); } FeatureTrack track = new FeatureTrack(locator, featureSource); // Try to create a sensible name from the path String name = locator.getName(); if (name == null || name.length() == 0) { if (locator.getPath().contains("genome.ucsc.edu")) { name = featureSource.getType(); } else { name = featureSource.getPath().replace("/das/", "").replace("/features", ""); } } track.setName(name); // A hack until we can notate this some other way if (locator.getPath().contains("cosmic")) { track.setRendererClass(CosmicFeatureRenderer.class); track.setMinimumHeight(2); track.setHeight(20); track.setDisplayMode(Track.DisplayMode.EXPANDED); } else { track.setRendererClass(IGVFeatureRenderer.class); track.setMinimumHeight(35); track.setHeight(45); } currentTracks.add(track); } private void loadTrioData(ResourceLocator locator) throws IOException { PedigreeUtils.parseTrioFile(locator.getPath()); } /** * Convert an RNA chemical reactivity file (.shape, .map) into a .wig file * and load. */ private void convertLoadShapeFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { String inPath = locator.getPath(); String fileName = locator.getFileName(); String outPath = inPath + ".wig"; String message = "The chemical reactivity file <br> &nbsp;&nbsp;" + fileName + "<br> needs to be converted to IGV chromosome <br>" + "coordinates and .wig format before loading. <br><br>Click <b>Continue</b> " + "to save converted file to <br> &nbsp;&nbsp;" + fileName+".wig" + "<br>and load with the selected options, or <b>Cancel</b> to skip this<br>file."; ConvertOptions opts = ConvertFileDialog.showConvertFileDialog(message); if (opts.doConvert) { ShapeFileUtils.shapeToWigFile(inPath, outPath, opts.chrom, opts.strand, opts.start); loadWigFile(new ResourceLocator(outPath), newTracks, genome); } } /** * Convert various RNA structure formats to a more easily parseable format * in genomic coordinates, then load converted file. */ private void convertLoadStructureFile(ResourceLocator locator, List<Track> newTracks, Genome genome, String fileType) throws IOException { String inPath = locator.getPath(); String fileName = locator.getFileName(); String outPath = inPath + ".bp"; String message = "The RNA structure file <br> &nbsp;&nbsp;" + fileName + "<br> needs to be converted to IGV chromosome <br>" + "coordinates and .bp format before loading. <br><br>Click <b>Continue</b> " + "to save converted file to <br> &nbsp;&nbsp;" + fileName+".bp" + "<br>and load with the selected options, or <b>Cancel</b> to skip this<br>file."; ConvertOptions opts = ConvertFileDialog.showConvertFileDialog(message); if (opts.doConvert){ if (fileType == "connectTable") { BasePairFileUtils.connectTableToBasePairFile(inPath, outPath, opts.chrom, opts.strand, opts.start); } else if (fileType == "pairingProb") { BasePairFileUtils.pairingProbToBasePairFile(inPath, outPath, opts.chrom, opts.strand, opts.start); } else if (fileType == "dotBracket") { BasePairFileUtils.dotBracketToBasePairFile(inPath, outPath, opts.chrom, opts.strand, opts.start); } loadBasePairFile(new ResourceLocator(outPath), newTracks, genome); } } private void loadBasePairFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { String name = locator.getTrackName(); String path = locator.getPath(); String id = path + "_" + name; newTracks.add(new BasePairTrack(locator, id, name, genome)); } public static boolean isIndexed(ResourceLocator locator, Genome genome) { // Checking for the index is expensive over HTTP. First see if this is an indexable format by fetching the codec String fullPath = locator.getPath(); String pathNoQuery = locator.getURLPath(); if (!CodecFactory.hasCodec(locator, genome)) { return false; } String indexExtension = pathNoQuery.endsWith("gz") ? ".tbi" : ".idx"; String indexPath = fullPath + indexExtension; if (HttpUtils.isRemoteURL(fullPath)) { //Handle query string, if it exists String[] toks = fullPath.split("\\?", 2); if (toks.length == 2) { indexPath = String.format("%s%s?%s", toks[0], indexExtension, toks[1]); } } return FileUtils.resourceExists(indexPath); } public static TrackProperties getTrackProperties(Object header) { try { FeatureFileHeader ffHeader = (FeatureFileHeader) header; if (ffHeader != null) { return ffHeader.getTrackProperties(); } else { return null; } } catch (ClassCastException e) { return null; } } private static Map<String, LoadHandler> handlers = new HashMap<String, LoadHandler>(); /** * Register a custom handler for the given extension. * Note that this does NOT override built-in IGV behavior * * @param extension * @param loader * @api */ public static void registerHandler(String extension, LoadHandler loader) { handlers.put(extension, loader); } /** * Get the registered {@link org.broad.igv.dev.api.LoadHandler} for this path/typeString, * or null if one not found * * @param typeString * @return * @api */ private LoadHandler getTrackLoaderHandler(String typeString) { String lower = typeString.toLowerCase(); for (Map.Entry<String, LoadHandler> entry : handlers.entrySet()) { if (lower.endsWith(entry.getKey().toLowerCase())) { return entry.getValue(); } } return null; } }
package org.exist.launcher; import javax.swing.*; import java.awt.*; import java.net.URL; /** * Display a splash screen showing the eXist-db logo and a status line. * * @author Wolfgang Meier */ public class SplashScreen extends JFrame { private JLabel statusLabel; public SplashScreen() { setUndecorated(true); setBackground(new Color(255, 255, 255, 125)); setAlwaysOnTop(true); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); URL imageURL = SplashScreen.class.getResource("logo.jpg"); ImageIcon icon = new ImageIcon(imageURL, "eXist-db Logo"); getContentPane().setLayout(new BorderLayout()); // add the image label JLabel imageLabel = new JLabel(); imageLabel.setIcon(icon); getContentPane().add(imageLabel, BorderLayout.CENTER); // message label statusLabel = new JLabel("Launching eXist-db ...", SwingConstants.CENTER); statusLabel.setFont(new Font(statusLabel.getFont().getName(), Font.BOLD, 14)); statusLabel.setForeground(Color.black); getContentPane().add(statusLabel, BorderLayout.SOUTH); // show it setSize(new Dimension(icon.getIconWidth(), icon.getIconHeight() + 20)); //pack(); this.setLocationRelativeTo(null); setVisible(true); } public void setStatus(final String status) { statusLabel.setText(status); } }
package org.firebears.subsystems; import org.firebears.Robot; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** * Subsystem interface to the lights running on the Raspberry Pi. Communicates * to the pi through the Network Tables. */ public class Lights extends Subsystem { double range; static NetworkTable table; boolean isCelebrateMode = false; public Lights() { table = NetworkTable.getTable("lights"); setStrip(STRIP_CHASSIS_FRONT, ANIM_FIRE); setStrip(STRIP_CHASSIS_BACK, ANIM_FIRE); setStrip(STRIP_CHASSIS_BOTTOM, ANIM_FIRE); setStrip(STRIP_SIGNAL, ANIM_FIRE); } public void initDefaultCommand() { } public static void setStrip(String stripName, String animationName) { table.putString(stripName, animationName); } public void setValue(String stripName, double value) { table.putNumber(stripName + ".value", value); } public void teleopMode() { String allianceColor = getAllianceColor(); range = Robot.gearChute.getRangeFinderDistance(); if (isCelebrateMode) { setStrip(Lights.STRIP_SIGNAL, Lights.ANIM_EXPLODE); setStrip(Lights.STRIP_CHASSIS_BACK, Lights.ANIM_EXPLODE); setStrip(Lights.STRIP_CHASSIS_FRONT, Lights.ANIM_EXPLODE); setStrip(Lights.STRIP_CHASSIS_BOTTOM, Lights.ANIM_EXPLODE); return; } setValue(STRIP_SIGNAL, range); if (Robot.climber.isRunning()) { } else if (!Robot.climber.isRunning()) { if (Robot.vision.isDetecting()) { if (range <= 60) { setStrip(Lights.STRIP_SIGNAL, Lights.ANIM_RANGE); } } else if (!Robot.vision.isDetecting()) { if (Robot.gearChute.isGearInChute()) { } if (!Robot.acquisition.isNotRunning()) { if (Robot.acquisition.isRunningForward()) { } if (Robot.acquisition.isRunningBackward()) { } } else if (Robot.acquisition.isNotRunning()) { if (Robot.dumper.isFloorHigh()) { } if (Robot.dumper.isFloorLow()) { } if (Robot.dumper.isGoingDown()) { } if (Robot.dumper.isGoingUp()) { } } } } } public void autonomousMode() { setStrip(STRIP_CHASSIS_BOTTOM, ANIM_IGNITE); } public void disabledMode() { String anim = getAllianceColor(); setStrip(Lights.STRIP_SIGNAL, anim); setStrip(Lights.STRIP_CHASSIS_BACK, anim); setStrip(Lights.STRIP_CHASSIS_FRONT, anim); setStrip(Lights.STRIP_CHASSIS_BOTTOM, anim); } public void celebrateMode(boolean celebrate) { isCelebrateMode = celebrate; } protected String getAllianceColor() { if (DriverStation.getInstance().getAlliance() == DriverStation.Alliance.Blue) { return Lights.ANIM_PULSING_BLUE; } else { return Lights.ANIM_PULSING_RED; } } // public void shootMode() { // setStrip(Lights.STRIP_CELEBRATE, Lights.ANIM_SPARK); // Constants for pixel strips public static final String STRIP_CHASSIS_FRONT = "strip_chassis_front"; public static final String STRIP_CHASSIS_BACK = "strip_chassis_back"; public static final String STRIP_CHASSIS_BOTTOM = "strip_chassis_bottom"; public static final String STRIP_SIGNAL = "strip_signal"; // Constants for animations public static final String ANIM_PULSING_GREEN = "ANIM_PULSING_GREEN"; public static final String ANIM_PULSING_RED = "ANIM_PULSING_RED"; public static final String ANIM_PULSING_BLUE = "ANIM_PULSING_BLUE"; public static final String ANIM_MOVING_BLUE = "ANIM_MOVING_BLUE"; public static final String ANIM_EXPLODING_R_W_B = "ANIM_EXPLODING_R_W_B"; public static final String ANIM_FIRE = "ANIM_FIRE"; public static final String ANIM_CRAZY = "ANIM_CRAZY"; public static final String ANIM_BINARY = "ANIM_BINARY"; public static final String ANIM_BULB = "ANIM_BULB"; public static final String ANIM_CATERPILLAR = "ANIM_CATERPILLAR"; public static final String ANIM_SPARK = "ANIM_SPARK"; public static final String ANIM_THEATER = "ANIM_THEATER"; public static final String ANIM_EXPLODE = "ANIM_EXPLODE"; public static final String ANIM_RANGE = "ANIM_RANGE"; public static final String ANIM_IGNITE = "ANIM_IGNITE"; }
/* * $Id: PluginManager.java,v 1.48 2003-09-11 07:47:08 tlipkis Exp $ */ package org.lockss.plugin; import java.util.*; import java.io.IOException; import org.lockss.daemon.*; import org.lockss.daemon.status.*; import org.lockss.poller.*; import org.lockss.util.*; import org.lockss.app.BaseLockssManager; /** * Plugin global functionality * * @author TAL * @version 0.0 */ public class PluginManager extends BaseLockssManager { public static final String PARAM_AU_TREE = Configuration.PREFIX + "au"; private static String PARAM_PLUGIN_LOCATION = Configuration.PREFIX + "platform.pluginDir"; private static Logger log = Logger.getLogger("PluginMgr"); private ConfigManager configMgr; private StatusService statusSvc; private String pluginDir = null; private Map pluginMap = new HashMap(); //maps plugin keys(not ids) to plugins private Map auMap = new HashMap(); public PluginManager() { } /** * start the plugin manager. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); configMgr = getDaemon().getConfigManager(); statusSvc = getDaemon().getStatusService(); statusSvc.registerStatusAccessor("AUS", new Status(this)); initPluginRegistry(); resetConfig(); } /** * stop the plugin manager * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { // tk - checkpoint if nec. for (Iterator iter = pluginMap.values().iterator(); iter.hasNext(); ) { Plugin plugin = (Plugin)iter.next(); plugin.stopPlugin(); } super.stopService(); } Configuration prevAllPlugs = ConfigManager.EMPTY_CONFIGURATION; protected void setConfig(Configuration config, Configuration oldConfig, Set changedKeys) { pluginDir = config.get(PARAM_PLUGIN_LOCATION); // Don't load and start plugins until the daemon is running. // Because we don't necessarily process the config, we must keep track // of the previous config ourselves. if (isDaemonInited()) { Configuration allPlugs = config.getConfigTree(PARAM_AU_TREE); for (Iterator iter = allPlugs.nodeIterator(); iter.hasNext(); ) { String pluginKey = (String)iter.next(); log.debug("Configuring plugin key: " + pluginKey); Configuration pluginConf = allPlugs.getConfigTree(pluginKey); Configuration prevPluginConf = prevAllPlugs.getConfigTree(pluginKey); configurePlugin(pluginKey, pluginConf, prevPluginConf); } prevAllPlugs = allPlugs; } } /** * Convert plugin property key to plugin class name. * @param key the key * @return the plugin name */ public static String pluginNameFromKey(String key) { return StringUtil.replaceString(key, "|", "."); } /** * Convert plugin class name to key suitable for property file. * @param className the class name * @return the plugin key */ public static String pluginKeyFromName(String className) { return StringUtil.replaceString(className, ".", "|"); } /** * Convert plugin id to key suitable for property file. Plugin id is * currently the same as plugin class name, but that may change. * @param id the plugin id * @return String the plugin key */ public static String pluginKeyFromId(String id) { // tk - needs to do real mapping from IDs obtained from all available // plugins. return StringUtil.replaceString(id, ".", "|"); } /** * Return a unique identifier for an au based on its plugin id and defining * properties. * * @return a unique identifier for an au based on its plugin id and defining * properties. * @param pluginId plugin id (with . not escaped) * @param auDefProps defining properties for the au * {@see Plugin.getDefiningConfigKeys} */ public static String generateAUId(String pluginId, Properties auDefProps) { return generateAuId(pluginId, PropUtil.propsToCanonicalEncodedString(auDefProps)); } public static String generateAUId(Plugin plugin, Configuration auConf) { Collection defKeys = plugin.getDefiningConfigKeys(); Properties props = new Properties(); for (Iterator it = defKeys.iterator(); it.hasNext();) { String curKey = (String)it.next(); props.setProperty(curKey, auConf.get(curKey)); } return generateAUId(plugin.getPluginId(), props); } static String generateAuId(String pluginId, String auKey) { return pluginKeyFromId(pluginId)+"&"+auKey; } static String configKeyFromAuId(String auid) { return StringUtil.replaceFirst(auid, "&", "."); } /** * Return the plugin with the given key. * @param pluginKey the plugin key * @return the plugin or null */ public Plugin getPlugin(String pluginKey) { return (Plugin)pluginMap.get(pluginKey); } static final String PARAM_WRAPPER = "reserved.wrapper"; /** Returns true if the reserved.wrapper key is true */ private boolean isAuWrapped(Configuration auConf) { try { return WrapperState.isUsingWrapping() && auConf.getConfigTree("reserved").getBoolean("wrapper"); } catch (Configuration.InvalidParam e) { return false; } } private Configuration removeWrapper(Configuration auConf) { Configuration copy = auConf.copy(); if (copy.containsKey(PARAM_WRAPPER)) { copy.remove(PARAM_WRAPPER); } return copy; } private void configurePlugin(String pluginKey, Configuration pluginConf, Configuration oldPluginConf) { for (Iterator iter = pluginConf.nodeIterator(); iter.hasNext(); ) { String auKey = (String)iter.next(); // if (pluginOk) { try { Configuration auConf = pluginConf.getConfigTree(auKey); Configuration oldAuConf = oldPluginConf.getConfigTree(auKey); if (!auConf.equals(oldAuConf)) { log.debug("Configuring AU id: " + auKey); if (!isAuWrapped(auConf)) { boolean pluginOk = ensurePluginLoaded(pluginKey); if (pluginOk) { Plugin plugin = getPlugin(pluginKey); if (WrapperState.isWrappedPlugin(plugin)) { throw new ArchivalUnit.ConfigurationException( "An attempt was made to have load unwrapped " + auKey + " from plugin " + pluginKey + " which is already wrapped."); } configureAu(plugin, auConf, generateAuId(pluginKey, auKey)); } else { log.warning("Not configuring AU " + auKey); } } else { if ((pluginMap.containsKey(pluginKey)) && (!WrapperState.isWrappedPlugin(pluginMap.get(pluginKey)))) { throw new ArchivalUnit.ConfigurationException( "An attempt was made to wrap AU " + auKey + " from plugin " + pluginKey + " which is already loaded."); } Plugin wrappedPlugin = WrapperState.retrieveWrappedPlugin( pluginKey, theDaemon); if (wrappedPlugin==null) { log.warning("Not configuring AU " + auKey); log.error("Error instantiating " + WrapperState.WRAPPED_PLUGIN_NAME); } else { setPlugin(pluginKey,wrappedPlugin); Configuration wrappedAuConf = removeWrapper(auConf); configureAu(wrappedPlugin, wrappedAuConf, generateAuId( pluginKey, auKey)); } } } else { log.debug("Not configuring AU id: " + auKey + ", already configured"); } } catch (ArchivalUnit.ConfigurationException e) { log.error("Failed to configure AU " + auKey, e); } catch (Exception e) { log.error("Unexpected exception configuring AU " + auKey, e); } /* } else { log.warning("Not configuring AU " + auKey); }*/ } } void configureAu(Plugin plugin, Configuration auConf, String auId) throws ArchivalUnit.ConfigurationException { try { ArchivalUnit au = plugin.configureAU(auConf, (ArchivalUnit)auMap.get(auId)); log.debug("Configured AU " + au); try { getDaemon().startAUManagers(au); } catch (Exception e) { throw new ArchivalUnit.ConfigurationException("Couldn't start AU processes", e); } log.debug("putAuMap(" + au.getAUId() +", " + au); if (!auId.equals(au.getAUId())) { throw new ArchivalUnit.ConfigurationException("Configured AU has " +"unexpected AUId, " +"is: "+au.getAUId() +" expected: "+auId); } putAuInMap(au); } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error configuring AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } ArchivalUnit createAu(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException { String auid; ArchivalUnit oldAu = null; try { auid = generateAUId(plugin, auConf); oldAu = getAuFromId(auid); } catch (Exception e) { // no action. Bad/missing config value might cause getAuFromId() to // throw. It will be caught soon when creating the AU; for now we // can assume it means the AU doesn't already exist. } if (oldAu != null) { throw new ArchivalUnit.ConfigurationException("Cannot create that AU because it already exists"); } try { ArchivalUnit au = plugin.createAU(auConf); log.debug("Created AU " + au); try { getDaemon().startAUManagers(au); } catch (Exception e) { log.error("Couldn't start AU processes", e); throw new ArchivalUnit.ConfigurationException("Couldn't start AU processes", e); } log.debug("putAuMap(" + au.getAUId() +", " + au); putAuInMap(au); return au; } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error creating AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } private void putAuInMap(ArchivalUnit au) { auMap.put(au.getAUId(), au); } public ArchivalUnit getAuFromId(String auId) { ArchivalUnit au = (ArchivalUnit)auMap.get(auId); log.debug3("getAu(" + auId + ") = " + au); return au; } // These don't belong here /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAUConfiguration(ArchivalUnit au, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { setAndSaveAUConfiguration(au, ConfigManager.fromProperties(auProps)); } /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAUConfiguration(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Reconfiguring AU " + au); au.setConfiguration(auConf); updateAuConfigFile(au, auConf); } private void updateAuConfigFile(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { String auid = au.getAUId(); String prefix = PARAM_AU_TREE + "." + configKeyFromAuId(auid); Configuration fqConfig = auConf.addPrefix(prefix); configMgr.updateAuConfigFile(fqConfig, prefix); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAUConfiguration(Plugin plugin, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { return createAndSaveAUConfiguration(plugin, ConfigManager.fromProperties(auProps)); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAUConfiguration(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { ArchivalUnit au = createAu(plugin, auConf); updateAuConfigFile(au, auConf); return au; } /** * Delete AU configuration from the local config file. Need to find a * better place for this. * @param au the ArchivalUnit to be unconfigured * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void deleteAUConfiguration(ArchivalUnit au) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Deleting AU config: " + au); updateAuConfigFile(au, ConfigManager.EMPTY_CONFIGURATION); } /** * Return the stored config info for an AU (from config file, not from * AU instance). * @param au the ArchivalUnit * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(ArchivalUnit au) { Configuration config = configMgr.readAuConfigFile(); String auid = au.getAUId(); String prefix = PARAM_AU_TREE + "." + configKeyFromAuId(auid); return config.getConfigTree(prefix); } Plugin retrievePlugin(String pluginKey) throws Exception { if (pluginMap.containsKey(pluginKey)) { return (Plugin)pluginMap.get(pluginKey); } String pluginName = pluginNameFromKey(pluginKey); Class pluginClass; try { pluginClass = Class.forName(pluginName); } catch (ClassNotFoundException e) { log.debug(pluginName + " not on classpath"); // not on classpath try { // tk - search plugin dir for signed jar, try loading again throw e; // for now, simulate failure of that process } catch (ClassNotFoundException e1) { // plugin is really not available log.error(pluginName + " not found"); return null; } } catch (Exception e) { // any other exception while loading class if not recoverable log.error("Error loading " + pluginName, e); return null; } log.debug("Instantiating " + pluginClass); Plugin plugin = (Plugin) pluginClass.newInstance(); plugin.initPlugin(theDaemon); return plugin; } /** * Load a plugin with the given class name from somewhere in our classpath * @param pluginKey the key for this plugin * @return true if loaded */ public boolean ensurePluginLoaded(String pluginKey) { if (pluginMap.containsKey(pluginKey)) { return true; } String pluginName = ""; try { pluginName = pluginNameFromKey(pluginKey); Plugin plugin = retrievePlugin(pluginKey); if (plugin != null) { setPlugin(pluginKey, plugin); return true; } else { return false; } } catch (Exception e) { log.error("Error instantiating " + pluginName, e); return false; } } // separate method so can be called by test code private void setPlugin(String pluginKey, Plugin plugin) { log.debug3("PluginManager.setPlugin(" + pluginKey + ", " + plugin.getPluginName() + ")"); pluginMap.put(pluginKey, plugin); titleMap = null; } /** * Searches all ArchivalUnits to find the most recent CachedUrl for the URL. * @param url The URL to search for. * @return a CachedUrl, or null if URL not present in any AU */ public CachedUrl findMostRecentCachedUrl(String url) { CachedUrl best = null; for (Iterator iter = getAllAUs().iterator(); iter.hasNext();) { ArchivalUnit au = (ArchivalUnit)iter.next(); if (au.shouldBeCached(url)) { CachedUrl cu = au.makeCachedUrl(au.getAUCachedUrlSet(), url); if (cu != null && cu.hasContent() && cuNewerThan(cu, best)) { best = cu; } } } return best; } // return true if cu1 is newer than cu2, or cu2 is null // tk - no date available for comparison yet, return arbitrary order private boolean cuNewerThan(CachedUrl cu1, CachedUrl cu2) { if (cu2 == null) return true; Properties p1 = cu1.getProperties(); Properties p2 = cu2.getProperties(); // tk - this should use the crawl-date prop taht the crawler will add // Long.parseLong(p1.getProperty(HttpFields.__LastModified, "-1")); return true; } /** * Return a list of all configured ArchivalUnits. * @return the List of aus */ public List getAllAUs() { return new ArrayList(auMap.values()); } public Collection findAllTitles() { return getTitleMap().keySet(); } public Collection getTitlePlugins(String title) { return (Collection)getTitleMap().get(title); } private Map titleMap = null; public Map getTitleMap() { if (titleMap == null) { titleMap = buildTitleMap(); } return titleMap; } Map buildTitleMap() { Map map = new org.apache.commons.collections.MultiHashMap(); Collection plugs = getRegisteredPlugins(); for (Iterator iter = plugs.iterator(); iter.hasNext();) { Plugin p = (Plugin)iter.next(); Collection titles = p.getSupportedTitles(); for (Iterator iter2 = titles.iterator(); iter2.hasNext();) { String title = (String)iter2.next(); map.put(title, p); } } return map; } /** * Find the CachedUrlSet from a PollSpec. * @param spec the PollSpec (from an incoming message) * @return a CachedUrlSet for the plugin, au and URL in the spec, or * null if au not present on this cache */ public CachedUrlSet findCachedUrlSet(PollSpec spec) { if (log.isDebug3()) log.debug3(this +".findCachedUrlSet2("+spec+")"); String auId = spec.getAUId(); ArchivalUnit au = getAuFromId(auId); if (log.isDebug3()) log.debug3("au: " + au); if (au == null) return null; String url = spec.getUrl(); CachedUrlSet cus; if (AuUrl.isAuUrl(url)) { cus = au.getAUCachedUrlSet(); } else if ((spec.getLwrBound()!=null) && (spec.getLwrBound().equals(PollSpec.SINGLE_NODE_LWRBOUND))) { cus = au.makeCachedUrlSet(new SingleNodeCachedUrlSetSpec(url)); } else { cus = au.makeCachedUrlSet(new RangeCachedUrlSetSpec(url, spec.getLwrBound(), spec.getUprBound())); } if (log.isDebug3()) log.debug3("ret cus: " + cus); return cus; } // Plugin registry // List the plugins that should always be listed in UI menus. // Other plugins that were loaded because of an configured AU will // be included automatically private String builtinPluginNames[] = { "org.lockss.plugin.highwire.HighWirePlugin", "org.lockss.plugin.projmuse.ProjectMusePlugin", // "org.lockss.plugin.simulated.SimulatedPlugin", }; public Collection getRegisteredPlugins() { return pluginMap.values(); } void initPluginRegistry() { for (int ix = 0; ix < builtinPluginNames.length; ix++) { ensurePluginLoaded(pluginKeyFromName(builtinPluginNames[ix])); } } private class Status implements StatusAccessor { private final List sortRules = ListUtil.list(new StatusTable.SortRule("au", true)); private final List colDescs = ListUtil.list( new ColumnDescriptor("au", "Journal Volume", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("auid", "AUID", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("poll", "Poll Status", ColumnDescriptor.TYPE_STRING), new ColumnDescriptor("crawl", "Crawl Status", ColumnDescriptor.TYPE_STRING) ); // need this because the statics above require this to be a nested, // not inner class. PluginManager mgr; Status(PluginManager mgr) { this.mgr = mgr; } public List getColumnDescriptors(String key) { return colDescs; } public List getRows(String key) { List table = new ArrayList(); for (Iterator iter = mgr.getAllAUs().iterator(); iter.hasNext();) { Map row = new HashMap(); ArchivalUnit au = (ArchivalUnit)iter.next(); row.put("au", au.getName()); row.put("auid", au.getAUId()); row.put("poll", statusSvc.getReference(PollerStatus.MANAGER_STATUS_TABLE_NAME, au)); table.add(row); } return table; } public List getDefaultSortRules(String key) { return sortRules; } public boolean requiresKey() { return false; } public String getTitle(String key) { return "Archival Units"; } public void populateTable(StatusTable table) { String key = table.getKey(); table.setTitle(getTitle(key)); table.setColumnDescriptors(getColumnDescriptors(key)); table.setDefaultSortRules(getDefaultSortRules(key)); table.setRows(getRows(key)); } } // protected void initPlugins() { // /* grab our 3rd party plugins and load them using security manager */ // String[] files = new java.io.File(pluginDir).list(); // for(int i= 0; i < files.length; i++) { // if(files[i].endsWith(".jar")) { // loadPlugin(files[i].substring(0,files[i].lastIndexOf(".jar"))); // else { // loadPlugin(files[i]); }
package org.loklak.api.cms; import org.eclipse.jetty.util.log.Log; import org.json.JSONObject; import org.loklak.data.DAO; import org.loklak.server.*; import org.loklak.tools.IO; import org.loklak.tools.storage.JSONObjectWithDefault; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.security.*; import java.time.Instant; import java.util.Base64; import java.util.TreeMap; /** * This service allows users to login, logout or to check their login status. * For login, there are three options: session, cookie (both stateful, for browsers) and access-token (stateless, for api access) * It requires the following parameters: login (the login id, usually an email), password and type (one of the above) * To check if the user is logged it, set the parameter 'checkLogin' to true * To logout, set the parameter 'logout' to true */ public class LoginService extends AbstractAPIHandler implements APIHandler { private static final long serialVersionUID = 8578478303032749879L; private static final long defaultAccessTokenExpireTime = 7 * 24 * 60 * 60; @Override public BaseUserRole getMinimalBaseUserRole() { return BaseUserRole.ANONYMOUS; } @Override public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) { JSONObject result = new JSONObject(); result.put("maxInvalidLogins", 10); result.put("blockTimeSeconds", 120); result.put("periodSeconds", 60); result.put("blockedUntil", 0); return result; } public String getAPIPath() { return "/api/login.json"; } @Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { // login check for app if(post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else{ result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested if(post.get("logout", false)){ // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); JSONObject result = new JSONObject(); result.put("message", "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if(post.get("login", null) != null && post.get("password", null) != null && post.get("type", null ) != null){ passwordLogin = true; } else if(post.get("login", null) != null && post.get("keyhash", null) != null){ pubkeyHello = true; } else if(post.get("sessionID", null) != null && post.get("response", null) != null){ pubkeyLogin = true; } else{ throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if(passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if(valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info("login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if(pubkeyHello){ // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if(!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if(pubkeyLogin){ // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e){ throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e){ throw new APIException(400, "Invalid key"); } catch (Throwable e){ throw new APIException(400, "Bad signature"); } if(verified){ long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if(valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); } /** * little helper function to avoid code duplication * @param post * @param authorization * @param credential * @return * @throws APIException */ private Authentication getAuthentication(Query post, Authorization authorization, ClientCredential credential) throws APIException{ // create Authentication Authentication authentication = new Authentication(credential, DAO.authentication); if (authentication.getIdentity() == null) { // check if identity is valid authentication.delete(); authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for unknown user: " + credential.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } if (!authentication.getBoolean("activated", false)) { // check if identity is valid Log.getLog().info("Invalid login try for user: " + credential.getName() + " from host: " + post.getClientHost() + " : user not activated yet"); throw new APIException(422, "User not yet activated"); } return authentication; } private String createAccessToken(ClientIdentity identity, long valid_seconds) throws APIException{ String token = createRandomString(30); ClientCredential accessToken = new ClientCredential(ClientCredential.Type.access_token, token); Authentication tokenAuthentication = new Authentication(accessToken, DAO.authentication); tokenAuthentication.setIdentity(identity); if (valid_seconds == 0 || valid_seconds < -1) { // invalid values throw new APIException(400, "Invalid value for 'valid_seconds'"); } else if (valid_seconds != -1){ tokenAuthentication.setExpireTime(valid_seconds); } return token; } private void checkInvalidLogins(Query post, Authorization authorization, JSONObjectWithDefault permissions) throws APIException { // is already blocked? long blockedUntil = permissions.getLong("blockedUntil"); if(blockedUntil != 0) { if (blockedUntil > Instant.now().getEpochSecond()) { Log.getLog().info("Blocked ip " + post.getClientHost() + " because of too many invalid login attempts."); throw new APIException(403, "Too many invalid login attempts. Try again in " + (blockedUntil - Instant.now().getEpochSecond()) + " seconds"); } else{ authorization.setPermission(this, "blockedUntil", 0); } } // check if too many invalid login attempts were made already JSONObject invalidLogins = authorization.getAccounting().getRequests(this.getClass().getCanonicalName()); long period = permissions.getLong("periodSeconds", 600) * 1000; // get time period in which wrong logins are counted (e.g. the last 10 minutes) int counter = 0; for(String key : invalidLogins.keySet()){ if(Long.parseLong(key, 10) > System.currentTimeMillis() - period) counter++; } if(counter > permissions.getInt("maxInvalidLogins", 10)){ authorization.setPermission(this, "blockedUntil", Instant.now().getEpochSecond() + permissions.getInt("blockTimeSeconds", 120)); throw new APIException(403, "Too many invalid login attempts. Try again in " + permissions.getInt("blockTimeSeconds", 120) + " seconds"); } } }
package org.loklak.harvester; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.loklak.LoklakServer; import org.loklak.data.AbstractIndexEntry; import org.loklak.data.AccountEntry; import org.loklak.data.DAO; import org.loklak.data.UserEntry; import org.loklak.geo.GeoMark; import org.loklak.tools.DateParser; import org.loklak.tools.storage.JsonDataset; import org.loklak.tools.storage.JsonFactory; import org.loklak.tools.storage.JsonMinifier; import org.loklak.tools.storage.JsonDataset.JsonFactoryIndex; import com.google.common.base.Charsets; import com.google.common.io.Files; import twitter4j.IDs; import twitter4j.RateLimitStatus; import twitter4j.ResponseList; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.TwitterObjectFactory; import twitter4j.User; import twitter4j.conf.ConfigurationBuilder; @SuppressWarnings("unused") public class TwitterAPI { private final static String RATE_ACCOUNT_LOGIN_VERIFICATION_ENROLLMENT = "/account/login_verification_enrollment"; // limit = 15 private final static String RATE_ACCOUNT_SETTINGS = "/account/settings"; // limit = 15 private final static String RATE_ACCOUNT_UPDATE_PROFILE = "/account/update_profile"; // limit = 15 private final static String RATE_ACCOUNT_VERIFY_CREDENTIALS = "/account/verify_credentials"; // limit = 15 private final static String RATE_APPLICATION_RATE_LIMIT_STATUS = "/application/rate_limit_status"; // limit = 180 private final static String RATE_BLOCKS_IDS = "/blocks/ids"; // limit = 15 private final static String RATE_BLOCKS_LIST = "/blocks/list"; // limit = 15 private final static String RATE_COLLECTIONS_ENTRIES = "/collections/entries"; // limit = 1000 private final static String RATE_COLLECTIONS_LIST = "/collections/list"; // limit = 1000 private final static String RATE_COLLECTIONS_SHOW = "/collections/show"; // limit = 1000 private final static String RATE_CONTACTS_ADDRESSBOOK = "/contacts/addressbook"; // limit = 300 private final static String RATE_CONTACTS_DELETE_STATUS = "/contacts/delete/status"; // limit = 300 private final static String RATE_CONTACTS_UPLOADED_BY = "/contacts/uploaded_by"; // limit = 300 private final static String RATE_CONTACTS_USERS = "/contacts/users"; // limit = 300 private final static String RATE_CONTACTS_USERS_AND_UPLOADED_BY = "/contacts/users_and_uploaded_by"; // limit = 300 private final static String RATE_DEVICE_TOKEN = "/device/token"; // limit = 15 private final static String RATE_DIRECT_MESSAGES = "/direct_messages"; // limit = 15 private final static String RATE_DIRECT_MESSAGES_SENT = "/direct_messages/sent"; // limit = 15 private final static String RATE_DIRECT_MESSAGES_SENT_AND_RECEIVED = "/direct_messages/sent_and_received"; // limit = 15 private final static String RATE_DIRECT_MESSAGES_SHOW = "/direct_messages/show"; // limit = 15 private final static String RATE_FAVORITES_LIST = "/favorites/list"; // limit = 15 private final static String RATE_FOLLOWERS_IDS = "/followers/ids"; // limit = 15 private final static String RATE_FOLLOWERS_LIST = "/followers/list"; // limit = 15 private final static String RATE_FRIENDS_FOLLOWING_IDS = "/friends/following/ids"; // limit = 15 private final static String RATE_FRIENDS_FOLLOWING_LIST = "/friends/following/list"; // limit = 15 private final static String RATE_FRIENDS_IDS = "/friends/ids"; // limit = 15 private final static String RATE_FRIENDS_LIST = "/friends/list"; // limit = 15 private final static String RATE_FRIENDSHIPS_INCOMING = "/friendships/incoming"; // limit = 15 private final static String RATE_FRIENDSHIPS_LOOKUP = "/friendships/lookup"; // limit = 15 private final static String RATE_FRIENDSHIPS_NO_RETWEETS_IDS = "/friendships/no_retweets/ids"; // limit = 15 private final static String RATE_FRIENDSHIPS_OUTGOING = "/friendships/outgoing"; // limit = 15 private final static String RATE_FRIENDSHIPS_SHOW = "/friendships/show"; // limit = 180 private final static String RATE_GEO_ID_PLACE_ID = "/geo/id/:place_id"; // limit = 15 private final static String RATE_GEO_REVERSE_GEOCODE = "/geo/reverse_geocode"; // limit = 15 private final static String RATE_GEO_SEARCH = "/geo/search"; // limit = 15 private final static String RATE_GEO_SIMILAR_PLACES = "/geo/similar_places"; // limit = 15 private final static String RATE_HELP_CONFIGURATION = "/help/configuration"; // limit = 15 private final static String RATE_HELP_LANGUAGES = "/help/languages"; // limit = 15 private final static String RATE_HELP_PRIVACY = "/help/privacy"; // limit = 15 private final static String RATE_HELP_SETTINGS = "/help/settings"; // limit = 15 private final static String RATE_HELP_TOS = "/help/tos"; // limit = 15 private final static String RATE_LISTS_LIST = "/lists/list"; // limit = 15 private final static String RATE_LISTS_MEMBERS = "/lists/members"; // limit = 180 private final static String RATE_LISTS_MEMBERS_SHOW = "/lists/members/show"; // limit = 15 private final static String RATE_LISTS_MEMBERSHIPS = "/lists/memberships"; // limit = 15 private final static String RATE_LISTS_OWNERSHIPS = "/lists/ownerships"; // limit = 15 private final static String RATE_LISTS_SHOW = "/lists/show"; // limit = 15 private final static String RATE_LISTS_STATUSES = "/lists/statuses"; // limit = 180 private final static String RATE_LISTS_SUBSCRIBERS = "/lists/subscribers"; // limit = 180 private final static String RATE_LISTS_SUBSCRIBERS_SHOW = "/lists/subscribers/show"; // limit = 15 private final static String RATE_LISTS_SUBSCRIPTIONS = "/lists/subscriptions"; // limit = 15 private final static String RATE_MUTES_USERS_IDS = "/mutes/users/ids"; // limit = 15 private final static String RATE_MUTES_USERS_LIST = "/mutes/users/list"; // limit = 15 private final static String RATE_SAVED_SEARCHES_DESTROY_ID = "/saved_searches/destroy/:id"; // limit = 15 private final static String RATE_SAVED_SEARCHES_LIST = "/saved_searches/list"; // limit = 15 private final static String RATE_SAVED_SEARCHES_SHOW_ID = "/saved_searches/show/:id"; // limit = 15 private final static String RATE_SEARCH_TWEETS = "/search/tweets"; // limit = 180 private final static String RATE_STATUSES_FRIENDS = "/statuses/friends"; // limit = 15 private final static String RATE_STATUSES_HOME_TIMELINE = "/statuses/home_timeline"; // limit = 15 private final static String RATE_STATUSES_LOOKUP = "/statuses/lookup"; // limit = 180 private final static String RATE_STATUSES_MENTIONS_TIMELINE = "/statuses/mentions_timeline"; // limit = 15 private final static String RATE_STATUSES_OEMBED = "/statuses/oembed"; // limit = 180 private final static String RATE_STATUSES_RETWEETERS_IDS = "/statuses/retweeters/ids"; // limit = 15 private final static String RATE_STATUSES_RETWEETS_ID = "/statuses/retweets/:id"; // limit = 60 private final static String RATE_STATUSES_RETWEETS_OF_ME = "/statuses/retweets_of_me"; // limit = 15 private final static String RATE_STATUSES_SHOW_ID = "/statuses/show/:id"; // limit = 180 private final static String RATE_STATUSES_USER_TIMELINE = "/statuses/user_timeline"; // limit = 180 private final static String RATE_TRENDS_AVAILABLE = "/trends/available"; // limit = 15 private final static String RATE_TRENDS_CLOSEST = "/trends/closest"; // limit = 15 private final static String RATE_TRENDS_PLACE = "/trends/place"; // limit = 15 private final static String RATE_USERS_DERIVED_INFO = "/users/derived_info"; // limit = 15 private final static String RATE_USERS_LOOKUP = "/users/lookup"; // limit = 180 private final static String RATE_USERS_PROFILE_BANNER = "/users/profile_banner"; // limit = 180 private final static String RATE_USERS_REPORT_SPAM = "/users/report_spam"; // limit = 15 private final static String RATE_USERS_SEARCH = "/users/search"; // limit = 180 private final static String RATE_USERS_SHOW_ID = "/users/show/:id"; // limit = 180 private final static String RATE_USERS_SUGGESTIONS = "/users/suggestions"; // limit = 15 private final static String RATE_USERS_SUGGESTIONS_SLUG = "/users/suggestions/:slug"; // limit = 15 private final static String RATE_USERS_SUGGESTIONS_SLUG_MEMBERS = "/users/suggestions/:slug/members"; // limit = 15 private static TwitterFactory appFactory = null; private static Map<String, TwitterFactory> userFactory = new HashMap<>(); public static TwitterFactory getAppTwitterFactory() { String twitterAccessToken = DAO.getConfig("twitterAccessToken", ""); String twitterAccessTokenSecret = DAO.getConfig("twitterAccessTokenSecret", ""); if (twitterAccessToken.length() == 0 || twitterAccessTokenSecret.length() == 0) return null; if (appFactory == null) appFactory = getUserTwitterFactory(twitterAccessToken, twitterAccessTokenSecret); return appFactory; } public static TwitterFactory getUserTwitterFactory(String screen_name) { TwitterFactory uf = userFactory.get(screen_name); if (uf != null) return uf; AccountEntry accountEntry = DAO.searchLocalAccount(screen_name); if (accountEntry == null) return null; uf = getUserTwitterFactory(accountEntry.getOauthToken(), accountEntry.getOauthTokenSecret()); if (uf != null) userFactory.put(screen_name, uf); return uf; } private static TwitterFactory getUserTwitterFactory(String accessToken, String accessTokenSecret) { if (accessToken == null || accessToken.length() == 0 || accessTokenSecret == null || accessTokenSecret.length() == 0) return null; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(DAO.getConfig("client.twitterConsumerKey", "")) .setOAuthConsumerSecret(DAO.getConfig("client.twitterConsumerSecret", "")) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); cb.setJSONStoreEnabled(true); return new TwitterFactory(cb.build()); } public static RateLimitStatus getRateLimitStatus(final String rate_type) throws TwitterException { return getAppTwitterFactory().getInstance().getRateLimitStatus().get(rate_type); } private static final int getUserLimit = 180; private static int getUserRemaining = getUserLimit; private static long getUserResetTime = 0; public static int getUserRemaining() {return System.currentTimeMillis() > getUserResetTime ? getUserLimit : getUserRemaining;} public static Map<String, Object> getUser(String screen_name, boolean forceReload) throws TwitterException, IOException { if (!forceReload) { JsonFactory mapcapsule = DAO.user_dump.get("screen_name",screen_name); if (mapcapsule == null) mapcapsule = DAO.user_dump.get("id_str", screen_name); if (mapcapsule != null) { Map<String, Object> map = mapcapsule.getJson(); if (map.size() > 0) { // check if the entry is maybe outdated, i.e. if it is empty or too old try { Date d = DAO.user_dump.parseDate(map); if (d.getTime() + DateParser.DAY_MILLIS > System.currentTimeMillis()) return map; } catch (ParseException e) { return map; } } } } TwitterFactory tf = getUserTwitterFactory(screen_name); if (tf == null) tf = getAppTwitterFactory(); if (tf == null) return new HashMap<>(); Twitter twitter = tf.getInstance(); User user = twitter.showUser(screen_name); RateLimitStatus rateLimitStatus = user.getRateLimitStatus(); getUserResetTime = System.currentTimeMillis() + rateLimitStatus.getSecondsUntilReset() * 1000; getUserRemaining = rateLimitStatus.getRemaining(); Map<String, Object> map = user2json(user); enrichLocation(map); DAO.user_dump.putUnique(map); return map; } public static Map<String, Object> user2json(User user) throws IOException { String json = TwitterObjectFactory.getRawJSON(user); Map<String, Object> map = DAO.jsonMapper.readValue(json, DAO.jsonTypeRef); map.put("retrieval_date", AbstractIndexEntry.utcFormatter.print(System.currentTimeMillis())); Object status = map.remove("status"); // we don't need to store the latest status update in the user dump // TODO: store the latest status in our message database return map; } /** * enrich the user data with geocoding information * @param map the user json */ public static void enrichLocation(Map<String, Object> map) { // if a location is given, try to reverse geocode to get country name, country code and coordinates String location = (String) map.get("location"); // in case that no location is given, we try to hack that information out of the context if (location == null || location.length() == 0) { // sometimes the time zone contains city names! Try that String time_zone = (String) map.get("time_zone"); if (time_zone != null && time_zone.length() > 0) { GeoMark loc = DAO.geoNames.analyse(time_zone, null, 5, 0); // check if the time zone was actually a location name if (loc != null && loc.getNames().contains(time_zone)) { // success! It's just a guess, however... location = time_zone; map.put("location", location); //DAO.log("enrichLocation: TRANSLATED time_zone to location '" + location + "'"); } } } // if we finally have a location, then compute country name and geo-coordinates if (location != null && location.length() > 0) { String location_country = (String) map.get("location_country"); String location_country_code = (String) map.get("location_country_code"); Object location_point = map.get("location_point"); Object location_mark = map.get("location"); // maybe we already computed these values before, but they may be incomplete. If they are not complete, we repeat the geocoding if (location_country == null || location_country.length() == 0 || location_country_code == null || location_country_code.length() == 0 || location_point == null || location_mark == null ) { // get a salt String created_at = (String) map.get("created_at"); int salt = created_at == null ? map.hashCode() : created_at.hashCode(); // reverse geocode GeoMark loc = DAO.geoNames.analyse(location, null, 5, salt); if (loc != null) { String countryCode = loc.getISO3166cc(); if (countryCode != null && countryCode.length() > 0) { String countryName = DAO.geoNames.getCountryName(countryCode); map.put("location_country", countryName); map.put("location_country_code", countryCode); } map.put("location_point", new double[]{loc.lon(), loc.lat()}); //[longitude, latitude] map.put("location_mark", new double[]{loc.mlon(), loc.mlat()}); //[longitude, latitude] //DAO.log("enrichLocation: FOUND location '" + location + "'"); } else { //DAO.log("enrichLocation: UNKNOWN location '" + location + "'"); } } } } /** * beautify given location information. This should only be called before an export is done, not for storage * @param map */ public static void correctLocation(Map<String, Object> map) { // if a location is given, try to reverse geocode to get country name, country code and coordinates String location = (String) map.get("location"); // if we finally have a location, then compute country name and geo-coordinates if (location != null && location.length() > 0) { String location_country = (String) map.get("location_country"); // maybe we already computed these values before, but they may be incomplete. If they are not complete, we repeat the geocoding if (location_country != null && location_country.length() > 0) { // check if the location name was made in a "City-Name, Country-Name" schema if (location.endsWith(", " + location_country)) { // remove the country name from the location name location = location.substring(0, location.length() - location_country.length() - 2); map.put("location", location); //DAO.log("correctLocation: CORRECTED '" + location + ", " + location_country + "'"); } } } } public static Map<String, Object> getNetwork(String screen_name, int maxFollowers, int maxFollowing) throws IOException, TwitterException { Map<String, Object> map = new HashMap<>(); // we clone the maps because we modify it map.putAll(getNetworkerNames(screen_name, maxFollowers, Networker.FOLLOWERS)); map.putAll(getNetworkerNames(screen_name, maxFollowing, Networker.FOLLOWING)); map.remove("screen_name"); //int with_before = 0, with_after = 0; for (String setname : new String[]{"followers","unfollowers","following","unfollowing"}) { List<Map<String, Object>> users = new ArrayList<>(); Map<String, Number> names = (Map<String, Number>) map.remove(setname + "_names"); if (names != null) { for (String sn: names.keySet()) { JsonFactory user = DAO.user_dump.get("screen_name", sn); if (user != null) { Map<String, Object> usermap = user.getJson(); //if (usermap.get("location") != null && ((String) usermap.get("location")).length() > 0) with_before++; enrichLocation(usermap); correctLocation(usermap); //if (usermap.get("location") != null && ((String) usermap.get("location")).length() > 0) with_after++; users.add(usermap); } } } //if (users.size() > 0) DAO.log("enrichLocation result: set = " + setname + ", users = " + users.size() + ", with location before = " + with_before + ", with location after = " + with_after + ", success = " + (100 * (with_after - with_before) / users.size()) + "%"); map.put(setname + "_count", users.size()); map.put(setname, users); } return map; } private static enum Networker { FOLLOWERS, FOLLOWING; } private static final int getFollowerIdLimit = 180, getFollowingIdLimit = 180; private static int getFollowerIdRemaining = getFollowerIdLimit, getFollowingIdRemaining = getFollowingIdLimit; private static long getFollowerIdResetTime = 0, getFollowingIdResetTime = 0; public static int getFollowerIdRemaining() {return System.currentTimeMillis() > getFollowerIdResetTime ? getFollowerIdLimit : getFollowerIdRemaining;} public static int getFollowingIdRemaining() {return System.currentTimeMillis() > getFollowingIdResetTime ? getFollowingIdLimit : getFollowingIdRemaining;} public static Map<String, Object> getFollowersNames(final String screen_name, final int max_count) throws IOException, TwitterException { return getNetworkerNames(screen_name, max_count, Networker.FOLLOWERS); } public static Map<String, Object> getFollowingNames(final String screen_name, final int max_count) throws IOException, TwitterException { return getNetworkerNames(screen_name, max_count, Networker.FOLLOWING); } public static Map<String, Object> getNetworkerNames(final String screen_name, final int max_count, final Networker networkRelation) throws IOException, TwitterException { if (max_count == 0) return new HashMap<>(); boolean complete = true; Set<Number> networkingIDs = new LinkedHashSet<>(); Set<Number> unnetworkingIDs = new LinkedHashSet<>(); JsonFactory mapcapsule = (networkRelation == Networker.FOLLOWERS ? DAO.followers_dump : DAO.following_dump).get("screen_name", screen_name); if (mapcapsule == null) { JsonDataset ds = networkRelation == Networker.FOLLOWERS ? DAO.followers_dump : DAO.following_dump; mapcapsule = ds.get("screen_name", screen_name); } if (mapcapsule != null) { // check if the map is complete Map<String, Object> map = mapcapsule.getJson(); complete = (Boolean) map.get("complete"); if (complete) return map; // TODO: check date List<Object> fro = (List<Object>) map.get(networkRelation == Networker.FOLLOWERS ? "follower" : "following"); for (Object f: fro) { networkingIDs.add((Number) f); } } TwitterFactory tf = getUserTwitterFactory(screen_name); if (tf == null) tf = getAppTwitterFactory(); if (tf == null) return new HashMap<String, Object>(); Twitter twitter = tf.getInstance(); long cursor = -1; collect: while (cursor != 0) { try { IDs ids = networkRelation == Networker.FOLLOWERS ? twitter.getFollowersIDs(screen_name, cursor) : twitter.getFriendsIDs(screen_name, cursor); RateLimitStatus rateStatus = ids.getRateLimitStatus(); if (networkRelation == Networker.FOLLOWERS) { getFollowerIdRemaining = rateStatus.getRemaining(); getFollowerIdResetTime = System.currentTimeMillis() + rateStatus.getSecondsUntilReset() * 1000; } else { getFollowingIdRemaining = rateStatus.getRemaining(); getFollowingIdResetTime = System.currentTimeMillis() + rateStatus.getSecondsUntilReset() * 1000; } //System.out.println("got: " + ids.getIDs().length + " ids"); //System.out.println("Rate Status: " + rateStatus.toString() + "; time=" + System.currentTimeMillis()); boolean dd = false; for (long id: ids.getIDs()) { if (networkingIDs.contains(id)) dd = true; // don't break loop here networkingIDs.add(id); } if (dd) break collect; // this is complete! if (rateStatus.getRemaining() == 0) { complete = false; break collect; } if (networkingIDs.size() >= Math.min(10000, max_count >= 0 ? max_count : 10000)) { complete = false; break collect; } cursor = ids.getNextCursor(); } catch (TwitterException e) { complete = false; break collect; } } // create result Map<String, Object> map = new LinkedHashMap<>(); map.put("screen_name", screen_name); map.put("retrieval_date", AbstractIndexEntry.utcFormatter.print(System.currentTimeMillis())); map.put("complete", complete); Map<String, Number> networking = getScreenName(networkingIDs, max_count, true); Map<String, Number> unnetworking = getScreenName(unnetworkingIDs, max_count, true); if (networkRelation == Networker.FOLLOWERS) { map.put("followers_count", networking.size()); map.put("unfollowers_count", unnetworking.size()); map.put("followers_names", networking); map.put("unfollowers_names", unnetworking); if (complete) DAO.followers_dump.putUnique(map); // currently we write only complete data sets. In the future the update of datasets shall be supported } else { map.put("following_count", networking.size()); map.put("unfollowing_count", unnetworking.size()); map.put("following_names", networking); map.put("unfollowing_names", unnetworking); if (complete) DAO.following_dump.putUnique(map); } return map; } /** * search for twitter user names by a given set of user id's * @param id_strs * @param lookupLocalUsersByUserId if this is true and successful, the resulting names may contain users without user info in the user dump * @return * @throws IOException * @throws TwitterException */ public static Map<String, Number> getScreenName(Set<Number> id_strs, final int maxFollowers, boolean lookupLocalUsersByUserId) throws IOException, TwitterException { // we have several sources to get this mapping: // - 1st / fastest: mapping from DAO.twitter_user_dump // - 2nd / fast : mapping from DAO.searchLocalUserByUserId(user_id) // - 3rd / slow : from twitter API with twitter.lookupUsers(String[] user_id) // first we check all fast solutions until trying the twitter api Map<String, Number> r = new HashMap<>(); Set<Number> id4api = new HashSet<>(); for (Number id_str: id_strs) { if (r.size() >= maxFollowers) break; JsonFactory mapcapsule = DAO.user_dump.get("id_str", id_str.toString()); if (mapcapsule != null) { Map<String, Object> map = mapcapsule.getJson(); String screen_name = (String) map.get("screen_name"); if (screen_name != null) { r.put(screen_name, id_str); continue; } } if (lookupLocalUsersByUserId) { UserEntry ue = DAO.searchLocalUserByUserId(id_str.toString()); if (ue != null) { String screen_name = ue.getScreenName(); if (screen_name != null) { r.put(screen_name, id_str); continue; } } } id4api.add(id_str); } while (id4api.size() > 100 && id4api.size() + r.size() > maxFollowers) id4api.remove(id4api.iterator().next()); // resolve the remaining user_ids from the twitter api if (r.size() < maxFollowers && id4api.size() > 0) { TwitterFactory tf = getAppTwitterFactory(); if (tf == null) return new HashMap<>(); Twitter twitter = tf.getInstance(); collect: while (id4api.size() > 0) { // construct a query term with at most 100 id's int chunksize = Math.min(100, id4api.size()); long[] u = new long[chunksize]; Iterator<Number> ni = id4api.iterator(); for (int i = 0; i < chunksize; i++) { u[i] = ni.next().longValue(); } try { ResponseList<User> users = twitter.lookupUsers(u); for (User usr: users) { Map<String, Object> map = user2json(usr); enrichLocation(map); DAO.user_dump.putUnique(map); r.put(usr.getScreenName(), usr.getId()); id4api.remove(usr.getId()); } } catch (TwitterException e) { if (r.size() == 0) throw e; break collect; } } } return r; } public static void main(String[] args) { try { Path data = FileSystems.getDefault().getPath("data"); DAO.init(LoklakServer.readConfig(data), data); try { System.out.println(getRateLimitStatus(RATE_FOLLOWERS_IDS)); } catch (TwitterException e) { e.printStackTrace(); } try { System.out.println(getFollowersNames("loklak_app", 10000)); } catch (IOException | TwitterException e) { e.printStackTrace(); } try { System.out.println(getFollowingNames("loklak_app", 10000)); } catch (IOException | TwitterException e) { e.printStackTrace(); } DAO.close(); } catch (IOException e1) { e1.printStackTrace(); } System.exit(0); } }
package org.mockito.exceptions; import static org.mockito.exceptions.Pluralizer.*; import static org.mockito.internal.util.StringJoiner.*; import java.util.List; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; import org.mockito.exceptions.misusing.MissingMethodInvocationException; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.exceptions.misusing.NullInsteadOfMockException; import org.mockito.exceptions.misusing.UnfinishedStubbingException; import org.mockito.exceptions.misusing.UnfinishedVerificationException; import org.mockito.exceptions.misusing.WrongTypeOfReturnValue; import org.mockito.exceptions.verification.ArgumentsAreDifferent; import org.mockito.exceptions.verification.NeverWantedButInvoked; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.SmartNullPointerException; import org.mockito.exceptions.verification.TooLittleActualInvocations; import org.mockito.exceptions.verification.TooManyActualInvocations; import org.mockito.exceptions.verification.VerificationInOrderFailure; import org.mockito.exceptions.verification.WantedButNotInvoked; import org.mockito.exceptions.verification.junit.JUnitTool; import org.mockito.internal.debugging.Location; import org.mockito.internal.exceptions.VerificationAwareInvocation; import org.mockito.internal.exceptions.util.ScenarioPrinter; import org.mockito.internal.invocation.Invocation; /** * Reports verification and misusing errors. * <p> * One of the key points of mocking library is proper verification/exception * messages. All messages in one place makes it easier to tune and amend them. * <p> * Reporter can be injected and therefore is easily testable. * <p> * Generally, exception messages are full of line breaks to make them easy to * read (xunit plugins take only fraction of screen on modern IDEs). */ public class Reporter { public void checkedExceptionInvalid(Throwable t) { throw new MockitoException(join( "Checked exception is invalid for this method!", "Invalid: " + t )); } public void cannotStubWithNullThrowable() { throw new MockitoException(join( "Cannot stub with null throwable!" )); } public void unfinishedStubbing(Location location) { throw new UnfinishedStubbingException(join( "Unfinished stubbing detected here:", location, "", "E.g. thenReturn() may be missing.", "Examples of correct stubbing:", " when(mock.isOk()).thenReturn(true);", " when(mock.isOk()).thenThrow(exception);", " doThrow(exception).when(mock).someVoidMethod();", "Hints:", " 1. missing thenReturn()", " 2. although stubbed methods may return mocks, you cannot inline mock creation (mock()) call inside a thenReturn method (see issue 53)", " 3. you are trying to stub a final method, you naughty developer!", "" )); } public void missingMethodInvocation() { throw new MissingMethodInvocationException(join( "when() requires an argument which has to be 'a method call on a mock'.", "For example:", " when(mock.getArticles()).thenReturn(articles);", "", "Also, this error might show up because:", "1. you stub either of: final/private/equals()/hashCode() methods.", " Those methods *cannot* be stubbed/verified.", "2. inside when() you don't call method on mock but on some other object." )); } public void unfinishedVerificationException(Location location) { UnfinishedVerificationException exception = new UnfinishedVerificationException(join( "Missing method call for verify(mock) here:", location, "", "Example of correct verification:", " verify(mock).doSomething()", "", "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.", "Those methods *cannot* be stubbed/verified.", "" )); throw exception; } public void notAMockPassedToVerify() { throw new NotAMockException(join( "Argument passed to verify() is not a mock!", "Examples of correct verifications:", " verify(mock).someMethod();", " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();" )); } public void nullPassedToVerify() { throw new NullInsteadOfMockException(join( "Argument passed to verify() should be a mock but is null!", "Examples of correct verifications:", " verify(mock).someMethod();", " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();", "Also, if you use @Mock annotation don't miss initMocks()" )); } public void notAMockPassedToWhenMethod() { throw new NotAMockException(join( "Argument passed to when() is not a mock!", "Example of correct stubbing:", " doThrow(new RuntimeException()).when(mock).someMethod();" )); } public void nullPassedToWhenMethod() { throw new NullInsteadOfMockException(join( "Argument passed to when() is null!", "Example of correct stubbing:", " doThrow(new RuntimeException()).when(mock).someMethod();", "Also, if you use @Mock annotation don't miss initMocks()" )); } public void mocksHaveToBePassedToVerifyNoMoreInteractions() { throw new MockitoException(join( "Method requires argument(s)!", "Pass mocks that should be verified, e.g:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);" )); } public void notAMockPassedToVerifyNoMoreInteractions() { throw new NotAMockException(join( "Argument(s) passed is not a mock!", "Examples of correct verifications:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);" )); } public void nullPassedToVerifyNoMoreInteractions() { throw new NullInsteadOfMockException(join( "Argument(s) passed is null!", "Examples of correct verifications:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);" )); } public void notAMockPassedWhenCreatingInOrder() { throw new NotAMockException(join( "Argument(s) passed is not a mock!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);" )); } public void nullPassedWhenCreatingInOrder() { throw new NullInsteadOfMockException(join( "Argument(s) passed is null!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);" )); } public void mocksHaveToBePassedWhenCreatingInOrder() { throw new MockitoException(join( "Method requires argument(s)!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);" )); } public void inOrderRequiresFamiliarMock() { throw new MockitoException(join( "InOrder can only verify mocks that were passed in during creation of InOrder.", "For example:", " InOrder inOrder = inOrder(mockOne);", " inOrder.verify(mockOne).doStuff();" )); } public void invalidUseOfMatchers(int expectedMatchersCount, int recordedMatchersCount) { throw new InvalidUseOfMatchersException(join( "Invalid use of argument matchers!", expectedMatchersCount + " matchers expected, " + recordedMatchersCount + " recorded.", "This exception may occur if matchers are combined with raw values:", " //incorrect:", " someMethod(anyObject(), \"raw String\");", "When using matchers, all arguments have to be provided by matchers.", "For example:", " //correct:", " someMethod(anyObject(), eq(\"String by matcher\"));", "", "For more info see javadoc for Matchers class." )); } public void argumentsAreDifferent(String wanted, String actual, Location actualLocation) { String message = join("Argument(s) are different! Wanted:", wanted, new Location(), "Actual invocation has different arguments:", actual, actualLocation, "" ); if (JUnitTool.hasJUnit()) { throw JUnitTool.createArgumentsAreDifferentException(message, wanted, actual); } else { throw new ArgumentsAreDifferent(message); } } public void wantedButNotInvoked(PrintableInvocation wanted) { throw new WantedButNotInvoked(createWantedButNotInvokedMessage(wanted)); } public void wantedButNotInvoked(PrintableInvocation wanted, List<? extends PrintableInvocation> invocations) { String allInvocations; if (invocations.isEmpty()) { allInvocations = "Actually, there were zero interactions with this mock.\n"; } else { StringBuilder sb = new StringBuilder("\nHowever, there were other interactions with this mock:\n"); for (PrintableInvocation i : invocations) { sb.append(i.getLocation()); sb.append("\n"); } allInvocations = sb.toString(); } String message = createWantedButNotInvokedMessage(wanted); throw new WantedButNotInvoked(message + allInvocations); } private String createWantedButNotInvokedMessage(PrintableInvocation wanted) { return join( "Wanted but not invoked:", wanted.toString(), new Location(), "" ); } public void wantedButNotInvokedInOrder(PrintableInvocation wanted, PrintableInvocation previous) { throw new VerificationInOrderFailure(join( "Verification in order failure", "Wanted but not invoked:", wanted.toString(), new Location(), "Wanted anywhere AFTER following interaction:", previous.toString(), previous.getLocation(), "" )); } public void tooManyActualInvocations(int wantedCount, int actualCount, PrintableInvocation wanted, Location firstUndesired) { String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, firstUndesired); throw new TooManyActualInvocations(message); } private String createTooManyInvocationsMessage(int wantedCount, int actualCount, PrintableInvocation wanted, Location firstUndesired) { return join( wanted.toString(), "Wanted " + Pluralizer.pluralize(wantedCount) + ":", new Location(), "But was " + pluralize(actualCount) + ". Undesired invocation:", firstUndesired, "" ); } public void neverWantedButInvoked(PrintableInvocation wanted, Location firstUndesired) { throw new NeverWantedButInvoked(join( wanted.toString(), "Never wanted here:", new Location(), "But invoked here:", firstUndesired, "" )); } public void tooManyActualInvocationsInOrder(int wantedCount, int actualCount, PrintableInvocation wanted, Location firstUndesired) { String message = createTooManyInvocationsMessage(wantedCount, actualCount, wanted, firstUndesired); throw new VerificationInOrderFailure(join( "Verification in order failure:" + message )); } private String createTooLittleInvocationsMessage(Discrepancy discrepancy, PrintableInvocation wanted, Location lastActualInvocation) { String ending = (lastActualInvocation != null)? lastActualInvocation + "\n" : "\n"; String message = join( wanted.toString(), "Wanted " + discrepancy.getPluralizedWantedCount() + ":", new Location(), "But was " + discrepancy.getPluralizedActualCount() + ":", ending ); return message; } public void tooLittleActualInvocations(Discrepancy discrepancy, PrintableInvocation wanted, Location lastActualLocation) { String message = createTooLittleInvocationsMessage(discrepancy, wanted, lastActualLocation); throw new TooLittleActualInvocations(message); } public void tooLittleActualInvocationsInOrder(Discrepancy discrepancy, PrintableInvocation wanted, Location lastActualLocation) { String message = createTooLittleInvocationsMessage(discrepancy, wanted, lastActualLocation); throw new VerificationInOrderFailure(join( "Verification in order failure:" + message )); } public void noMoreInteractionsWanted(Invocation undesired, List<VerificationAwareInvocation> invocations) { ScenarioPrinter scenarioPrinter = new ScenarioPrinter(); String scenario = scenarioPrinter.print(invocations); throw new NoInteractionsWanted(join( "No interactions wanted here:", new Location(), "But found this interaction:", undesired.getLocation(), scenario, "" )); } public void noMoreInteractionsWantedInOrder(Invocation undesired) { throw new VerificationInOrderFailure(join( "No interactions wanted here:", new Location(), "But found this interaction:", undesired.getLocation(), "" )); } public void cannotMockFinalClass(Class<?> clazz) { throw new MockitoException(join( "Cannot mock/spy " + clazz.toString(), "Mockito cannot mock/spy following:", " - final classes", " - anonymous classes", " - primitive types" )); } public void cannotStubVoidMethodWithAReturnValue(String methodName) { throw new MockitoException(join( "'" + methodName + "' is a *void method* and it *cannot* be stubbed with a *return value*!", "Voids are usually stubbed with Throwables:", " doThrow(exception).when(mock).someVoidMethod();", "If the method you are trying to stub is *overloaded* then make sure you are calling the right overloaded version.", "This exception might also occur when somewhere in your test you are stubbing *final methods*." )); } public void onlyVoidMethodsCanBeSetToDoNothing() { throw new MockitoException(join( "Only void methods can doNothing()!", "Example of correct use of doNothing():", " doNothing().", " doThrow(new RuntimeException())", " .when(mock).someVoidMethod();", "Above means:", "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called" )); } public void wrongTypeOfReturnValue(String expectedType, String actualType, String methodName) { throw new WrongTypeOfReturnValue(join( actualType + " cannot be returned by " + methodName + "()", methodName + "() should return " + expectedType, "***", "This exception *might* occur in wrongly written multi-threaded tests.", "Please refer to Mockito FAQ on limitations of concurrency testing.", "" )); } public void wantedAtMostX(int maxNumberOfInvocations, int foundSize) { throw new MockitoAssertionError(join("Wanted at most " + pluralize(maxNumberOfInvocations) + " but was " + foundSize)); } public void misplacedArgumentMatcher(Location location) { throw new InvalidUseOfMatchersException(join( "Misplaced argument matcher detected here:", location, "", "You cannot use argument matchers outside of verification or stubbing.", "Examples of correct usage of argument matchers:", " when(mock.get(anyInt())).thenReturn(null);", " doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());", " verify(mock).someMethod(contains(\"foo\"))", "", "Also, this error might show up because you use argument matchers with methods that cannot be mocked.", "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().", "" )); } public void smartNullPointerException(Location location) { throw new SmartNullPointerException(join( "You have a NullPointerException here:", new Location(), "Because this method was *not* stubbed correctly:", location, "" )); } public void noArgumentValueWasCaptured() { throw new MockitoException(join( "No argument value was captured!", "You might have forgotten to use argument.capture() in verify()...", "...or you used capture() in stubbing but stubbed method was not called.", "Be aware that it is recommended to use capture() only with verify()", "", "Examples of correct argument capturing:", " ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);", " verify(mock).doSomething(argument.capture());", " assertEquals(\"John\", argument.getValue().getName());", "" )); } public void extraInterfacesDoesNotAcceptNullParameters() { throw new MockitoException(join( "extraInterfaces() does not accept null parameters." )); } public void extraInterfacesAcceptsOnlyInterfaces(Class<?> wrongType) { throw new MockitoException(join( "extraInterfaces() accepts only interfaces.", "You passed following type: " + wrongType.getSimpleName() + " which is not an interface." )); } public void extraInterfacesCannotContainMockedType(Class<?> wrongType) { throw new MockitoException(join( "extraInterfaces() does not accept the same type as the mocked type.", "You mocked following type: " + wrongType.getSimpleName(), "and you passed the same very interface to the extraInterfaces()" )); } public void extraInterfacesRequiresAtLeastOneInterface() { throw new MockitoException(join( "extraInterfaces() requires at least one interface." )); } public void mockedTypeIsInconsistentWithSpiedInstanceType(Class<?> mockedType, Object spiedInstance) { throw new MockitoException(join( "Mocked type must be the same as the type of your spied instance.", "Mocked type must be: " + spiedInstance.getClass().getSimpleName() + ", but is: " + mockedType.getSimpleName(), " //correct spying:", " spy = mock( ->ArrayList.class<- , withSettings().spiedInstance( ->new ArrayList()<- );", " //incorrect - types don't match:", " spy = mock( ->List.class<- , withSettings().spiedInstance( ->new ArrayList()<- );" )); } public void cannotCallRealMethodOnInterface() { throw new MockitoException(join( "Cannot call real method on java interface. Interface does not have any implementation!", "Calling real methods is only possible when mocking concrete classes.", " //correct example:", " when(mockOfConcreteClass.doStuff()).thenCallRealMethod();" )); } public void cannotVerifyToString() { throw new MockitoException(join( "Mockito cannot verify toString()", "toString() is too often used behind of scenes (i.e. during String concatenation, in IDE debugging views). " + "Verifying it may give inconsistent or hard to understand results. " + "Not to mention that verifying toString() most likely hints awkward design (hard to explain in a short exception message. Trust me...)", "However, it is possible to stub toString(). Stubbing toString() smells a bit funny but there are rare, legitimate use cases." )); } public void moreThanOneAnnotationNotAllowed(String fieldName) { throw new MockitoException("You cannot have more than one Mockito annotation on a field!\n" + "The field '" + fieldName + "' has multiple Mockito annotations.\n" + "For info how to use annotations see examples in javadoc for MockitoAnnotations class."); } public void unsupportedCombinationOfAnnotations(String undesiredAnnotationOne, String undesiredAnnotationTwo) { throw new MockitoException("This combination of annotations is not permitted on a single field:\n" + "@" + undesiredAnnotationOne + " and @" + undesiredAnnotationTwo); } public void injectMockAnnotationFieldIsNull(String field) { throw new MockitoException("Field '" + field + "' annotated with @InjectMocks is null.\n" + "Please make sure the instance is created *before* MockitoAnnotations.initMocks();\n" + "Example of correct usage:\n" + " class SomeTest {\n" + " @InjectMocks private Foo foo = new Foo();\n" + " \n" + " @Before public void setUp() {\n" + " MockitoAnnotations.initMock(this);\n" ); } }
package org.myrobotlab.service; import java.io.File; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Stack; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.data.AudioData; import org.myrobotlab.service.interfaces.AudioListener; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; import org.myrobotlab.service.interfaces.TextListener; import org.slf4j.Logger; import com.voicerss.tts.AudioCodec; import com.voicerss.tts.AudioFormat; //import com.voicerss.tts.Languages; //import com.voicerss.tts.SpeechDataEvent; //import com.voicerss.tts.SpeechDataEventListener; //import com.voicerss.tts.SpeechErrorEvent; //import com.voicerss.tts.SpeechErrorEventListener; import com.voicerss.tts.VoiceParameters; import com.voicerss.tts.VoiceProvider; public class VoiceRss extends Service implements TextListener, SpeechSynthesis, AudioListener { transient public final static Logger log = LoggerFactory.getLogger(VoiceRss.class); private static final long serialVersionUID = 1L; // default voice public String voice = "fr-fr"; public HashSet<String> voices = new HashSet<String>(); public String key = "0000"; public Integer rate = 0; // this is a peer service. transient AudioFile audioFile = null; // TODO: fix the volume control // private float volume = 1.0f; transient CloseableHttpClient client; public VoiceRss(String n) { super(n); // TODO: be country/language aware when asking for voices? // maybe have a get voices by language/locale // Arabic voices.add("ca-es");// Catalan voices.add("zh-cn");// Chinese (China) voices.add("cn");// Chinese (China) voices.add("zh-hk");// Chinese (Hong Kong) voices.add("zh-tw");// Chinese (Taiwan) voices.add("da-dk");// Danish voices.add("nl-nl");// Dutch voices.add("en-au");// English (Australia) voices.add("en-ca");// English (Canada) voices.add("en-gb");// English (Great Britain) voices.add("en-in");// English (India) voices.add("en-us");// English (United States) voices.add("en");// English (United States) voices.add("fi-fi");// Finnish voices.add("fr-ca");// French (Canada) voices.add("fr-fr");// French (France) voices.add("fr");// French (France) voices.add("de-de");// German voices.add("de");// German voices.add("it-it");// Italian voices.add("ja-jp");// Japanese voices.add("ja");// Japanese voices.add("jp");// Japanese voices.add("ko-kr");// Korean voices.add("nb-no");// Norwegian voices.add("pl-pl");// Polish voices.add("pt-br");// Portuguese (Brazil) voices.add("pt-pt");// Portuguese (Portugal) voices.add("ru-ru");// Russian voices.add("es-mx");// Spanish (Mexico) voices.add("es-es");// Spanish (Spain) voices.add("es");// Spanish (Spain) voices.add("sv-se");// Swedish (Sweden) } public void startService() { super.startService(); if (client == null) { // new MultiThreadedHttpConnectionManager() client = HttpClients.createDefault(); } audioFile = (AudioFile) startPeer("audioFile"); audioFile.startService(); subscribe(audioFile.getName(), "publishAudioStart"); subscribe(audioFile.getName(), "publishAudioEnd"); // attach a listener when the audio file ends playing. audioFile.addListener("finishedPlaying", this.getName(), "publishEndSpeaking"); } public AudioFile getAudioFile() { return audioFile; } @Override public ArrayList<String> getVoices() { return new ArrayList<String>(voices); } @Override public String getVoice() { return voice; } @Override public boolean setVoice(String voice) { // backward compatibility because voicerss doesnt support setvoice //return true; return voices.contains(voice); } public String getKey() { return key; } public Integer getRate() { return rate; } public void setKey(String key) { this.key = key; } public void setRate(Integer rate) { if (rate<-10){rate=-10;} if (rate>10){rate=10;} this.rate = rate; } @Override public void setLanguage(String l) { // backward compatibility about simple language syntaxe if (l.toLowerCase()=="fr"){l="fr-fr";} if (l.toLowerCase()=="en"){l="en-us";} if (l.toLowerCase()=="es"){l="es-es";} if (l.toLowerCase()=="cn"){l="zh-cn";} if (l.toLowerCase()=="de"){l="de-de";} if (l.toLowerCase()=="jp"){l="ja-jp";} voice = l; // FIXME ! "MyLanguages", "sonid8" ??? // FIXME - implement !!! } public String getMp3Url(String toSpeak) { HttpPost post = null; try { String url = ""; post = new HttpPost(url); HttpResponse response = client.execute(post); log.info(response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); byte[] b = FileIO.toByteArray(entity.getContent()); // parse out mp3 file url String mp3Url = null; String data = new String(b); String startTag = "var myPhpVar = '"; int startPos = data.indexOf(startTag); if (startPos != -1) { int endPos = data.indexOf("';", startPos); if (endPos != -1) { mp3Url = data.substring(startPos + startTag.length(), endPos); } } if (mp3Url == null) { error("could not get mp3 back from voicerss server !"); } return mp3Url; } catch (Exception e) { Logging.logError(e); } return null; } public byte[] getRemoteFile(String toSpeak) { String mp3Url = getMp3Url(toSpeak); HttpGet get = null; byte[] b = null; try { HttpResponse response = null; // fetch file get = new HttpGet(mp3Url); log.info("mp3Url {}", mp3Url); // get mp3 file & save to cache response = client.execute(get); log.info("got {}", response.getStatusLine()); HttpEntity entity = response.getEntity(); // cache the mp3 content b = FileIO.toByteArray(entity.getContent()); EntityUtils.consume(entity); } catch (Exception e) { Logging.logError(e); } finally { if (get != null) { get.releaseConnection(); } } return b; } @Override public boolean speakBlocking(String toSpeak) throws Exception { log.info("speak {}", toSpeak); if (voice == null) { log.warn("voice is null! setting to default: fr-fr"); voice = "fr-fr"; } String filename = this.getLocalFileName(this, toSpeak + rate.toString() , "mp3"); String filenametts = "audioFile" + File.separator + filename; VoiceProvider tts = new VoiceProvider(getKey()); VoiceParameters params = new VoiceParameters(toSpeak, getVoice()); // Languages.English_UnitedStates params.setCodec(AudioCodec.WAV); params.setFormat(AudioFormat.Format_44KHZ.AF_44khz_16bit_stereo); params.setBase64(false); params.setSSML(false); params.setRate(rate); if (audioFile.cacheContains(filename)) { invoke("publishStartSpeaking", toSpeak); audioFile.playBlocking(filenametts); invoke("publishEndSpeaking", toSpeak); log.info("Finished waiting for completion."); return false; } byte[] voix = tts.speech(params); String filenametts2 = "audioFile" + File.separator + filename; String dossier = this.getLocalDirectory(this); File f = new File(dossier); if (f.exists()) { } else { File fb = new File(dossier); fb.mkdirs(); } FileOutputStream fos = new FileOutputStream(filenametts2); fos.write(voix, 0, voix.length); fos.flush(); fos.close(); invoke("publishStartSpeaking", toSpeak); audioFile.playBlocking(filenametts2); invoke("publishEndSpeaking", toSpeak); log.info("Finished waiting for completion."); return false; } @Override public void setVolume(float volume) { // TODO: fix the volume control log.warn("Volume control not implemented in VoiceRss."); } @Override public float getVolume() { return 0; } @Override public void interrupt() { // TODO: Implement me! } @Override public void onText(String text) { log.info("ON Text Called: {}", text); try { speak(text); } catch (Exception e) { Logging.logError(e); } } @Override public String getLanguage() { return null; } // HashSet<String> audioFiles = new HashSet<String>(); Stack<String> audioFiles = new Stack<String>(); public AudioData speak(String toSpeak) throws Exception { // this will flip to true on the audio file end playing. AudioData ret = null; log.info("speak {}", toSpeak); if (voice == null) { log.warn("voice is null! setting to default: fr-fr"); voice = "fr-fr"; } String filename = this.getLocalFileName(this, toSpeak, "mp3"); VoiceProvider tts = new VoiceProvider(getKey()); VoiceParameters params = new VoiceParameters(toSpeak, getVoice()); // Languages.English_UnitedStates params.setCodec(AudioCodec.WAV); params.setFormat(AudioFormat.Format_44KHZ.AF_44khz_16bit_stereo); params.setBase64(false); params.setSSML(false); params.setRate(rate); if (audioFile.cacheContains(filename)) { ret = audioFile.playCachedFile(filename); utterances.put(ret, toSpeak); return ret; } byte[] voix = tts.speech(params); String filenametts = "audioFile" + File.separator + filename; String dossier = this.getLocalDirectory(this); File f = new File(dossier); if (f.exists()) { } else { File fb = new File(dossier); fb.mkdirs(); } FileOutputStream fos = new FileOutputStream(filenametts); fos.write(voix, 0, voix.length); fos.flush(); fos.close(); ret = audioFile.playCachedFile(filename); utterances.put(ret, toSpeak); return ret; } public String getLocalDirectory(SpeechSynthesis provider) throws UnsupportedEncodingException { // TODO: make this a base class sort of thing. return "audioFile" + File.separator + provider.getClass().getSimpleName() + File.separator + URLEncoder.encode(provider.getVoice(), "UTF-8"); } @Override public String getLocalFileName(SpeechSynthesis provider, String toSpeak, String audioFileType) throws UnsupportedEncodingException { // TODO: make this a base class sort of thing. return provider.getClass().getSimpleName() + File.separator + URLEncoder.encode(provider.getVoice(), "UTF-8") + File.separator + DigestUtils.md5Hex(toSpeak) + "." + audioFileType; } @Override public void addEar(SpeechRecognizer ear) { // TODO: move this to a base class. it's basically the same for all // mouths/ speech synth stuff. // when we add the ear, we need to listen for request confirmation addListener("publishStartSpeaking", ear.getName(), "onStartSpeaking"); addListener("publishEndSpeaking", ear.getName(), "onEndSpeaking"); } public void onRequestConfirmation(String text) { try { speakBlocking(String.format("did you say. %s", text)); } catch (Exception e) { Logging.logError(e); } } @Override public List<String> getLanguages() { // TODO Auto-generated method stub ArrayList<String> ret = new ArrayList<String>(); // FIXME - add iso language codes currently supported e.g. en en_gb de // etc.. return ret; } // audioData to utterance map TODO: revisit the design of this HashMap<AudioData, String> utterances = new HashMap<AudioData, String>(); @Override public String publishStartSpeaking(String utterance) { log.info("publishStartSpeaking {}", utterance); return utterance; } @Override public String publishEndSpeaking(String utterance) { log.info("publishEndSpeaking {}", utterance); return utterance; } @Override public void onAudioStart(AudioData data) { log.info("onAudioStart {} {}", getName(), data.toString()); // filters on only our speech if (utterances.containsKey(data)) { String utterance = utterances.get(data); invoke("publishStartSpeaking", utterance); } } @Override public void onAudioEnd(AudioData data) { log.info("onAudioEnd {} {}", getName(), data.toString()); // filters on only our speech if (utterances.containsKey(data)) { String utterance = utterances.get(data); invoke("publishEndSpeaking", utterance); utterances.remove(data); } } // TODO Add a function to compare (is there the word "fruit" in the banana's // document ? ) public static void main(String[] args) { LoggingFactory.init(Level.INFO); try { VoiceRss speech = (VoiceRss) Runtime.start("speech", "VoiceRss"); speech.setKey("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); speech.setLanguage("en-gb"); speech.setRate(0); // TODO: fix the volume control // speech.setVolume(0); speech.speakBlocking("it works, yes I believe it does"); speech.speakBlocking("yes yes. oh good. excellent!"); speech.speakBlocking("to be or not to be that is the question, weather tis nobler in the mind to suffer the slings and arrows of "); speech.speakBlocking("I'm afraid I can't do that."); // speech.speak("this is a test"); // speech.speak("i am saying something new once again again"); // speech.speak("one"); // speech.speak("two"); // speech.speak("three"); // speech.speak("four"); /* * speech.speak("what is going on"); //speech.speakBlocking( * speech.speak("hello world"); speech.speak("one two three four"); */ // arduino.setBoard(Arduino.BOARD_TYPE_ATMEGA2560); // arduino.connect(port); // arduino.broadcastState(); } catch (Exception e) { Logging.logError(e); } } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(VoiceRss.class.getCanonicalName()); meta.addDescription("VoiceRss speech synthesis service."); meta.addCategory("speech"); meta.setSponsor("Steve"); meta.addPeer("audioFile", "AudioFile", "audioFile"); meta.addTodo("test speak blocking - also what is the return type and AudioFile audio track id ?"); meta.addDependency("org.apache.commons.httpclient", "4.5.2"); meta.addDependency("com.voicerss.tts", "1.0"); return meta; } }
package org.redkale.boot; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.net.*; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.logging.Level; import javax.annotation.*; import static org.redkale.boot.Application.RESNAME_SNCP_ADDR; import org.redkale.boot.ClassFilter.FilterEntry; import org.redkale.net.*; import org.redkale.net.http.*; import org.redkale.net.sncp.Sncp; import org.redkale.service.*; import org.redkale.util.AnyValue.DefaultAnyValue; import org.redkale.util.*; import org.redkale.watch.*; @NodeProtocol({"HTTP"}) public class NodeHttpServer extends NodeServer { protected final boolean rest; //REST truerestRESTServiceRestServlet protected final HttpServer httpServer; public NodeHttpServer(Application application, AnyValue serconf) { super(application, createServer(application, serconf)); this.httpServer = (HttpServer) server; this.rest = serconf == null ? false : serconf.getAnyValue("rest") != null; } private static Server createServer(Application application, AnyValue serconf) { return new HttpServer(application.getStartTime(), application.getResourceFactory().createChild()); } public HttpServer getHttpServer() { return httpServer; } @Override public InetSocketAddress getSocketAddress() { return httpServer == null ? null : httpServer.getSocketAddress(); } @Override @SuppressWarnings("unchecked") protected ClassFilter<Service> createServiceClassFilter() { return createClassFilter(this.sncpGroup, null, Service.class, new Class[]{org.redkale.watch.WatchService.class}, Annotation.class, "services", "service"); } @Override @SuppressWarnings("unchecked") protected ClassFilter<Filter> createFilterClassFilter() { return createClassFilter(null, null, HttpFilter.class, new Class[]{WatchFilter.class}, null, "filters", "filter"); } @Override @SuppressWarnings("unchecked") protected ClassFilter<Servlet> createServletClassFilter() { return createClassFilter(null, WebServlet.class, HttpServlet.class, new Class[]{WatchServlet.class}, null, "servlets", "servlet"); } @Override protected ClassFilter createOtherClassFilter() { return createClassFilter(null, RestWebSocket.class, WebSocket.class, null, null, "rest", "websocket"); } @Override protected void loadService(ClassFilter<? extends Service> serviceFilter, ClassFilter otherFilter) throws Exception { super.loadService(serviceFilter, otherFilter); initWebSocketService(); } @Override protected void loadFilter(ClassFilter<? extends Filter> filterFilter, ClassFilter otherFilter) throws Exception { if (httpServer != null) loadHttpFilter(this.serverConf.getAnyValue("filters"), filterFilter); } @Override @SuppressWarnings("unchecked") protected void loadServlet(ClassFilter<? extends Servlet> servletFilter, ClassFilter otherFilter) throws Exception { if (httpServer != null) loadHttpServlet(servletFilter, otherFilter); } private void initWebSocketService() { final NodeServer self = this; final ResourceFactory regFactory = application.getResourceFactory(); resourceFactory.register((ResourceFactory rf, final Object src, final String resourceName, Field field, Object attachment) -> { try { if (field.getAnnotation(Resource.class) == null) return; if (!(src instanceof WebSocketServlet)) return; ResourceFactory.ResourceLoader loader = null; ResourceFactory sncpResFactory = null; for (NodeServer ns : application.servers) { if (!ns.isSNCP()) continue; sncpResFactory = ns.resourceFactory; loader = sncpResFactory.findLoader(WebSocketNode.class, field); if (loader != null) break; } if (loader != null) loader.load(sncpResFactory, src, resourceName, field, attachment); synchronized (regFactory) { Service nodeService = (Service) rf.find(resourceName, WebSocketNode.class); if (sncpResFactory != null && resourceFactory.find(RESNAME_SNCP_ADDR, String.class) == null) { resourceFactory.register(RESNAME_SNCP_ADDR, InetSocketAddress.class, sncpResFactory.find(RESNAME_SNCP_ADDR, InetSocketAddress.class)); resourceFactory.register(RESNAME_SNCP_ADDR, SocketAddress.class, sncpResFactory.find(RESNAME_SNCP_ADDR, SocketAddress.class)); resourceFactory.register(RESNAME_SNCP_ADDR, String.class, sncpResFactory.find(RESNAME_SNCP_ADDR, String.class)); } if (nodeService == null) { nodeService = Sncp.createLocalService(serverClassLoader, resourceName, WebSocketNodeService.class, application.getResourceFactory(), application.getSncpTransportFactory(), (InetSocketAddress) null, (Set<String>) null, (AnyValue) null); regFactory.register(resourceName, WebSocketNode.class, nodeService); } resourceFactory.inject(nodeService, self); field.set(src, nodeService); logger.fine("[" + Thread.currentThread().getName() + "] Load Service " + nodeService); } } catch (Exception e) { logger.log(Level.SEVERE, "WebSocketNode inject error", e); } }, WebSocketNode.class); } @SuppressWarnings("unchecked") protected void loadHttpFilter(final AnyValue filtersConf, final ClassFilter<? extends Filter> classFilter) throws Exception { final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null; final String threadName = "[" + Thread.currentThread().getName() + "] "; List<FilterEntry<? extends Filter>> list = new ArrayList(classFilter.getFilterEntrys()); for (FilterEntry<? extends Filter> en : list) { Class<HttpFilter> clazz = (Class<HttpFilter>) en.getType(); if (Modifier.isAbstract(clazz.getModifiers())) continue; final HttpFilter filter = clazz.getDeclaredConstructor().newInstance(); resourceFactory.inject(filter, this); DefaultAnyValue filterConf = (DefaultAnyValue) en.getProperty(); this.httpServer.addHttpFilter(filter, filterConf); if (sb != null) sb.append(threadName).append(" Load ").append(clazz.getName()).append(LINE_SEPARATOR); } if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString()); } @SuppressWarnings("unchecked") protected void loadHttpServlet(final ClassFilter<? extends Servlet> servletFilter, ClassFilter<? extends WebSocket> webSocketFilter) throws Exception { final AnyValue servletsConf = this.serverConf.getAnyValue("servlets"); final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null; String prefix0 = servletsConf == null ? "" : servletsConf.getValue("path", ""); if (!prefix0.isEmpty() && prefix0.charAt(prefix0.length() - 1) == '/') prefix0 = prefix0.substring(0, prefix0.length() - 1); if (!prefix0.isEmpty() && prefix0.charAt(0) != '/') prefix0 = '/' + prefix0; final String prefix = prefix0; final String threadName = "[" + Thread.currentThread().getName() + "] "; List<FilterEntry<? extends Servlet>> list = new ArrayList(servletFilter.getFilterEntrys()); list.sort((FilterEntry<? extends Servlet> o1, FilterEntry<? extends Servlet> o2) -> { //WebSocketServlet HttpServletWebSocketNode boolean ws1 = WebSocketServlet.class.isAssignableFrom(o1.getType()); boolean ws2 = WebSocketServlet.class.isAssignableFrom(o2.getType()); if (ws1 == ws2) { Priority p1 = o1.getType().getAnnotation(Priority.class); Priority p2 = o2.getType().getAnnotation(Priority.class); int v = (p2 == null ? 0 : p2.value()) - (p1 == null ? 0 : p1.value()); return v == 0 ? o1.getType().getName().compareTo(o2.getType().getName()) : 0; } return ws1 ? -1 : 1; }); final List<AbstractMap.SimpleEntry<String, String[]>> ss = sb == null ? null : new ArrayList<>(); for (FilterEntry<? extends Servlet> en : list) { Class<HttpServlet> clazz = (Class<HttpServlet>) en.getType(); if (Modifier.isAbstract(clazz.getModifiers())) continue; WebServlet ws = clazz.getAnnotation(WebServlet.class); if (ws == null || ws.value().length == 0) continue; final HttpServlet servlet = clazz.getDeclaredConstructor().newInstance(); resourceFactory.inject(servlet, this); final String[] mappings = ws.value(); String pref = ws.repair() ? prefix : ""; DefaultAnyValue servletConf = (DefaultAnyValue) en.getProperty(); this.httpServer.addHttpServlet(servlet, pref, servletConf, mappings); if (ss != null) { for (int i = 0; i < mappings.length; i++) { mappings[i] = pref + mappings[i]; } ss.add(new AbstractMap.SimpleEntry<>(clazz.getName(), mappings)); } } int max = 0; if (ss != null && sb != null) { Collections.sort(ss, (AbstractMap.SimpleEntry<String, String[]> o1, AbstractMap.SimpleEntry<String, String[]> o2) -> o1.getKey().compareTo(o2.getKey())); for (AbstractMap.SimpleEntry<String, String[]> as : ss) { if (as.getKey().length() > max) max = as.getKey().length(); } for (AbstractMap.SimpleEntry<String, String[]> as : ss) { sb.append(threadName).append(" Load ").append(as.getKey()); for (int i = 0; i < max - as.getKey().length(); i++) { sb.append(' '); } sb.append(" mapping to ").append(Arrays.toString(as.getValue())).append(LINE_SEPARATOR); } } if (rest && serverConf != null) { final List<Object> restedObjects = new ArrayList<>(); for (AnyValue restConf : serverConf.getAnyValues("rest")) { loadRestServlet(webSocketFilter, restConf, restedObjects, sb); } } if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString().trim()); } @SuppressWarnings("unchecked") protected void loadRestServlet(final ClassFilter<? extends WebSocket> webSocketFilter, final AnyValue restConf, final List<Object> restedObjects, final StringBuilder sb) throws Exception { if (!rest) return; if (restConf == null) return; //REST final long starts = System.currentTimeMillis(); String prefix0 = restConf.getValue("path", ""); if (!prefix0.isEmpty() && prefix0.charAt(prefix0.length() - 1) == '/') prefix0 = prefix0.substring(0, prefix0.length() - 1); if (!prefix0.isEmpty() && prefix0.charAt(0) != '/') prefix0 = '/' + prefix0; final String prefix = prefix0; final String threadName = "[" + Thread.currentThread().getName() + "] "; final List<AbstractMap.SimpleEntry<String, String[]>> ss = sb == null ? null : new ArrayList<>(); final boolean autoload = restConf.getBoolValue("autoload", true); { //RestService String userTypeStr = restConf.getValue("usertype"); final Class userType = userTypeStr == null ? null : this.serverClassLoader.loadClass(userTypeStr); final Class baseServletType = this.serverClassLoader.loadClass(restConf.getValue("base", HttpServlet.class.getName())); final Set<String> includeValues = new HashSet<>(); final Set<String> excludeValues = new HashSet<>(); for (AnyValue item : restConf.getAnyValues("service")) { if (item.getBoolValue("ignore", false)) { excludeValues.add(item.getValue("value", "")); } else { includeValues.add(item.getValue("value", "")); } } final ClassFilter restFilter = ClassFilter.create(null, restConf.getValue("includes", ""), restConf.getValue("excludes", ""), includeValues, excludeValues); final boolean finest = logger.isLoggable(Level.FINEST); final CountDownLatch scdl = new CountDownLatch(super.interceptorServices.size()); super.interceptorServices.stream().parallel().forEach((service) -> { try { final Class stype = Sncp.getServiceType(service); final String name = Sncp.getResourceName(service); RestService rs = (RestService) stype.getAnnotation(RestService.class); if (rs == null || rs.ignore()) return; final String stypename = stype.getName(); if (!autoload && !includeValues.contains(stypename)) return; if (!restFilter.accept(stypename)) return; synchronized (restedObjects) { if (restedObjects.contains(service)) { logger.log(Level.WARNING, stype.getName() + " repeat create rest servlet, so ignore"); return; } restedObjects.add(service); //Rest } HttpServlet servlet = httpServer.addRestServlet(serverClassLoader, service, userType, baseServletType, prefix); if (servlet == null) return; //HttpMappingHttpServletRest.createRestServletnull String prefix2 = prefix; WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class); if (ws != null && !ws.repair()) prefix2 = ""; resourceFactory.inject(servlet, NodeHttpServer.this); //if (finest) logger.finest(threadName + " Create RestServlet(resource.name='" + name + "') = " + servlet); if (ss != null) { String[] mappings = servlet.getClass().getAnnotation(WebServlet.class).value(); for (int i = 0; i < mappings.length; i++) { mappings[i] = prefix2 + mappings[i]; } synchronized (ss) { ss.add(new AbstractMap.SimpleEntry<>(servlet.getClass().getName() + "(rest.name='" + name + "')", mappings)); } } } finally { scdl.countDown(); } }); scdl.await(); } if (webSocketFilter != null) { //RestWebSocket final Set<String> includeValues = new HashSet<>(); final Set<String> excludeValues = new HashSet<>(); for (AnyValue item : restConf.getAnyValues("websocket")) { if (item.getBoolValue("ignore", false)) { excludeValues.add(item.getValue("value", "")); } else { includeValues.add(item.getValue("value", "")); } } final ClassFilter restFilter = ClassFilter.create(null, restConf.getValue("includes", ""), restConf.getValue("excludes", ""), includeValues, excludeValues); final boolean finest = logger.isLoggable(Level.FINEST); List<FilterEntry<? extends WebSocket>> list = new ArrayList(webSocketFilter.getFilterEntrys()); for (FilterEntry<? extends WebSocket> en : list) { Class<WebSocket> clazz = (Class<WebSocket>) en.getType(); if (Modifier.isAbstract(clazz.getModifiers())) { logger.log(Level.FINE, clazz.getName() + " cannot abstract on rest websocket, so ignore"); continue; } if (Modifier.isFinal(clazz.getModifiers())) { logger.log(Level.FINE, clazz.getName() + " cannot final on rest websocket, so ignore"); continue; } final Class<? extends WebSocket> stype = en.getType(); RestWebSocket rs = stype.getAnnotation(RestWebSocket.class); if (rs == null || rs.ignore()) return; final String stypename = stype.getName(); if (!autoload && !includeValues.contains(stypename)) return; if (!restFilter.accept(stypename)) return; if (restedObjects.contains(stype)) { logger.log(Level.WARNING, stype.getName() + " repeat create rest websocket, so ignore"); return; } restedObjects.add(stype); //Rest HttpServlet servlet = httpServer.addRestWebSocketServlet(serverClassLoader, stype, prefix, en.getProperty()); if (servlet == null) return; //RestOnMessageHttpServletRest.createRestWebSocketServletnull String prefix2 = prefix; WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class); if (ws != null && !ws.repair()) prefix2 = ""; resourceFactory.inject(servlet, NodeHttpServer.this); if (finest) logger.finest(threadName + " " + stype.getName() + " create a RestWebSocketServlet"); if (ss != null) { String[] mappings = servlet.getClass().getAnnotation(WebServlet.class).value(); for (int i = 0; i < mappings.length; i++) { mappings[i] = prefix2 + mappings[i]; } ss.add(new AbstractMap.SimpleEntry<>(servlet.getClass().getName(), mappings)); } } } if (ss != null && !ss.isEmpty() && sb != null) { Collections.sort(ss, (AbstractMap.SimpleEntry<String, String[]> o1, AbstractMap.SimpleEntry<String, String[]> o2) -> o1.getKey().compareTo(o2.getKey())); int max = 0; for (AbstractMap.SimpleEntry<String, String[]> as : ss) { if (as.getKey().length() > max) max = as.getKey().length(); } for (AbstractMap.SimpleEntry<String, String[]> as : ss) { sb.append(threadName).append(" Load ").append(as.getKey()); for (int i = 0; i < max - as.getKey().length(); i++) { sb.append(' '); } sb.append(" mapping to ").append(Arrays.toString(as.getValue())).append(LINE_SEPARATOR); } sb.append(threadName).append(" All HttpServlets load cost " + (System.currentTimeMillis() - starts) + " ms" + LINE_SEPARATOR); } } }
package org.smof.collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.bson.BsonDocument; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.smof.element.Element; import org.smof.exception.SmofException; import org.smof.parsers.SmofParser; import com.google.common.cache.Cache; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; @SuppressWarnings("javadoc") public class SmofResults<T extends Element> { private static void handleError(Throwable cause) { throw new SmofException(cause); } private final Bson filter; private final FindIterable<BsonDocument> results; private final SmofParser parser; private final Class<T> elClass; private final Cache<ObjectId, T> cache; private final MongoCollection<BsonDocument> collection; SmofResults(SmofParser parser, Class<T> elementClass, Cache<ObjectId, T> cache, MongoCollection<BsonDocument> collection, Bson filter) { this.parser = parser; elClass = elementClass; this.cache = cache; this.collection = collection; this.filter = filter; results = collection.find(filter); } public Stream<T> stream() { return StreamSupport.stream(results.spliterator(), false) .filter(d -> d != null) .map(d -> parse(d)); } private T parse(BsonDocument d) { try { if(d != null) { final ObjectId id = d.get(Element.ID).asObjectId().getValue(); return cache.get(id, new DocumentParser(d)); } } catch (ExecutionException e) { handleError(e); } return null; } public List<T> asList() { return stream().collect(Collectors.toList()); } public T first() { final BsonDocument result = results.first(); if(result == null) { return null; } return parse(result); } public long count() { return filter == null ? collection.count() : collection.count(filter); } private class DocumentParser implements Callable<T>{ private final BsonDocument document; private DocumentParser(BsonDocument document) { super(); this.document = document; } @Override public T call() throws Exception { return parser.fromBson(document, elClass); } } }
package purejavacomm; import java.io.*; import java.util.*; import com.sun.jna.Platform; import jtermios.*; import static jtermios.JTermios.JTermiosLogging.*; import static jtermios.JTermios.*; import com.sun.jna.Platform; public class PureJavaSerialPort extends SerialPort { private Thread m_Thread; private volatile SerialPortEventListener m_EventListener; private volatile int m_FD = -1; private volatile int m_BaudRate; private volatile int m_DataBits; private volatile int m_FlowControlMode; private volatile int m_Parity; private volatile int m_StopBits; private volatile boolean m_ReceiveTimeOutEnabled; private volatile int m_ReceiveTimeOutValue; private volatile boolean m_ReceiveThresholdEnabled; private volatile int m_ReceiveThresholdValue; private volatile boolean m_NotifyOnDataAvailable; private volatile boolean m_DataAvailableNotified; private volatile boolean m_NotifyOnOutputEmpty; private volatile boolean m_OutputEmptyNotified; private volatile boolean m_NotifyOnRI; private volatile boolean m_NotifyOnCTS; private volatile boolean m_NotifyOnDSR; private volatile boolean m_NotifyOnCD; private volatile boolean m_NotifyOnOverrunError; private volatile boolean m_NotifyOnParityError; private volatile boolean m_NotifyOnFramingError; private volatile boolean m_NotifyOnBreakInterrupt; private volatile boolean m_ThreadRunning; private volatile boolean m_ThreadStarted; private int[] m_ioctl = { 0 }; private int m_ControlLineStates; // we cache termios in m_Termios because we don't rely on reading it back with tcgetattr() // which for Mac OS X / CRTSCTS does not work, it is also more efficient private Termios m_Termios = new Termios(); private void sendDataEvents(boolean read, boolean write) { if (read && m_NotifyOnDataAvailable && !m_DataAvailableNotified) { m_DataAvailableNotified = true; m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DATA_AVAILABLE, false, true)); } if (write && m_NotifyOnOutputEmpty && !m_OutputEmptyNotified) { m_OutputEmptyNotified = true; m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.OUTPUT_BUFFER_EMPTY, false, true)); } } private synchronized void sendNonDataEvents() { if (ioctl(m_FD, TIOCMGET, m_ioctl) < 0) return; //FIXME decide what to with errors in the background thread int oldstates = m_ControlLineStates; m_ControlLineStates = m_ioctl[0]; int newstates = m_ControlLineStates; int changes = oldstates ^ newstates; if (changes == 0) return; int line; if (m_NotifyOnCTS && (((line = TIOCM_CTS) & changes) != 0)) m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CTS, (oldstates & line) != 0, (newstates & line) != 0)); if (m_NotifyOnDSR && (((line = TIOCM_DSR) & changes) != 0)) m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.DSR, (oldstates & line) != 0, (newstates & line) != 0)); if (m_NotifyOnRI && (((line = TIOCM_RI) & changes) != 0)) m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.RI, (oldstates & line) != 0, (newstates & line) != 0)); if (m_NotifyOnCD && (((line = TIOCM_CD) & changes) != 0)) m_EventListener.serialEvent(new SerialPortEvent(this, SerialPortEvent.CD, (oldstates & line) != 0, (newstates & line) != 0)); } @Override synchronized public void addEventListener(SerialPortEventListener eventListener) throws TooManyListenersException { checkState(); if (eventListener == null) throw new IllegalArgumentException("eventListener cannot be null"); if (m_EventListener != null) throw new TooManyListenersException(); m_EventListener = eventListener; if (!m_ThreadStarted) { m_ThreadStarted = true; m_Thread.start(); } } @Override synchronized public int getBaudRate() { checkState(); return m_BaudRate; } @Override synchronized public int getDataBits() { checkState(); return m_DataBits; } @Override synchronized public int getFlowControlMode() { checkState(); return m_FlowControlMode; } @Override synchronized public int getParity() { checkState(); return m_Parity; } @Override synchronized public int getStopBits() { checkState(); return m_StopBits; } @Override synchronized public boolean isCD() { checkState(); return getControlLineState(TIOCM_CD); } @Override synchronized public boolean isCTS() { checkState(); return getControlLineState(TIOCM_CTS); } @Override synchronized public boolean isDSR() { checkState(); return getControlLineState(TIOCM_DSR); } @Override synchronized public boolean isDTR() { checkState(); return getControlLineState(TIOCM_DTR); } @Override synchronized public boolean isRI() { checkState(); return getControlLineState(TIOCM_RI); } @Override synchronized public boolean isRTS() { checkState(); return getControlLineState(TIOCM_RTS); } @Override synchronized public void notifyOnBreakInterrupt(boolean x) { checkState(); m_NotifyOnBreakInterrupt = x; } @Override synchronized public void notifyOnCTS(boolean x) { checkState(); if (x) updateControlLineState(TIOCM_CTS); m_NotifyOnCTS = x; } @Override synchronized public void notifyOnCarrierDetect(boolean x) { checkState(); if (x) updateControlLineState(TIOCM_CD); m_NotifyOnCD = x; } @Override synchronized public void notifyOnDSR(boolean x) { checkState(); if (x) updateControlLineState(TIOCM_DSR); m_NotifyOnDSR = x; } @Override synchronized public void notifyOnDataAvailable(boolean x) { checkState(); m_NotifyOnDataAvailable = x; } @Override synchronized public void notifyOnFramingError(boolean x) { checkState(); m_NotifyOnFramingError = x; } @Override synchronized public void notifyOnOutputEmpty(boolean x) { checkState(); m_NotifyOnOutputEmpty = x; } @Override synchronized public void notifyOnOverrunError(boolean x) { checkState(); m_NotifyOnOverrunError = x; } @Override synchronized public void notifyOnParityError(boolean x) { checkState(); m_NotifyOnParityError = x; } @Override synchronized public void notifyOnRingIndicator(boolean x) { checkState(); if (x) updateControlLineState(TIOCM_RI); m_NotifyOnRI = x; } @Override synchronized public void removeEventListener() { checkState(); m_EventListener = null; } @Override synchronized public void sendBreak(int duration) { checkState(); // FIXME POSIX does not specify how duration is interpreted // Opengroup POSIX says: // If the terminal is using asynchronous serial data transmission, tcsendbreak() // shall cause transmission of a continuous stream of zero-valued bits for a specific duration. // If duration is 0, it shall cause transmission of zero-valued bits for at least 0.25 seconds, // and not more than 0.5 seconds. If duration is not 0, it shall send zero-valued bits for an implementation-defined period of time. // From the man page for Linux tcsendbreak: // The effect of a non-zero duration with tcsendbreak() varies. // SunOS specifies a break of duration*N seconds, // where N is at least 0.25, and not more than 0.5. Linux, AIX, DU, Tru64 send a break of duration milliseconds. // FreeBSD and NetBSD and HP-UX and MacOS ignore the value of duration. // Under Solaris and Unixware, tcsendbreak() with non-zero duration behaves like tcdrain(). tcsendbreak(m_FD, duration); } @Override synchronized public void setDTR(boolean x) { checkState(); setControlLineState(TIOCM_DTR, x); } @Override synchronized public void setRTS(boolean x) { checkState(); setControlLineState(TIOCM_RTS, x); } @Override synchronized public void disableReceiveFraming() { checkState(); // Not supported } @Override synchronized public void disableReceiveThreshold() { checkState(); m_ReceiveThresholdEnabled = false; setReceiveTimeout(); } @Override synchronized public void disableReceiveTimeout() { checkState(); m_ReceiveTimeOutEnabled = false; setReceiveTimeout(); } @Override synchronized public void enableReceiveFraming(int arg0) throws UnsupportedCommOperationException { checkState(); throw new UnsupportedCommOperationException(); } @Override synchronized public void enableReceiveThreshold(int value) throws UnsupportedCommOperationException { checkState(); m_ReceiveThresholdEnabled = true; m_ReceiveThresholdValue = value; setReceiveTimeout(); } @Override synchronized public int getInputBufferSize() { checkState(); // Not supported return 0; } @Override synchronized public int getOutputBufferSize() { checkState(); // Not supported return 0; } @Override synchronized public void enableReceiveTimeout(int value) throws UnsupportedCommOperationException { checkState(); m_ReceiveTimeOutEnabled = true; m_ReceiveTimeOutValue = value; setReceiveTimeout(); } @Override synchronized public void setFlowControlMode(int mode) throws UnsupportedCommOperationException { checkState(); m_Termios.c_iflag &= ~IXANY; if ((mode & (FLOWCONTROL_RTSCTS_IN | FLOWCONTROL_RTSCTS_OUT)) != 0) m_Termios.c_cflag |= CRTSCTS; else m_Termios.c_cflag &= ~CRTSCTS; if ((mode & FLOWCONTROL_XONXOFF_IN) != 0) m_Termios.c_iflag |= IXOFF; else m_Termios.c_iflag &= ~IXOFF; if ((mode & FLOWCONTROL_XONXOFF_OUT) != 0) m_Termios.c_iflag |= IXON; else m_Termios.c_iflag &= ~IXON; checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios)); m_FlowControlMode = mode; } @Override synchronized public void setSerialPortParams(int baudRate, int dataBits, int stopBits, int parity) throws UnsupportedCommOperationException { checkState(); Termios prev = new Termios();// (termios); // save a copy in case we need to restore it prev.set(m_Termios); try { checkReturnCode(setspeed(m_FD, m_Termios, baudRate)); int db; switch (dataBits) { case SerialPort.DATABITS_5: db = CS5; break; case SerialPort.DATABITS_6: db = CS6; break; case SerialPort.DATABITS_7: db = CS7; break; case SerialPort.DATABITS_8: db = CS8; break; default: throw new UnsupportedCommOperationException("dataBits = " + dataBits); } int sb; switch (stopBits) { case SerialPort.STOPBITS_1: sb = 1; break; case SerialPort.STOPBITS_2: sb = 2; break; default: throw new UnsupportedCommOperationException("stopBits = " + stopBits); } int fi = m_Termios.c_iflag; int fc = m_Termios.c_cflag; switch (parity) { case SerialPort.PARITY_NONE: fc &= ~PARENB; fi &= ~(INPCK | ISTRIP); break; case SerialPort.PARITY_EVEN: fc |= PARENB; fc &= ~PARODD; fi &= ~(INPCK | ISTRIP); break; case SerialPort.PARITY_ODD: fc |= PARENB; fc |= PARODD; fi &= ~(INPCK | ISTRIP); break; default: throw new UnsupportedCommOperationException("parity = " + parity); } // update the hardware fc &= ~CSIZE; /* Mask the character size bits */ fc |= db; /* Set data bits */ if (sb == 2) fc |= CSTOPB; else fc &= ~CSTOPB; m_Termios.c_cflag = fc; m_Termios.c_iflag = fi; checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios)); checkReturnCode(tcflush(m_FD, TCIOFLUSH)); // finally everything went ok, so we can update our settings m_BaudRate = baudRate; m_Parity = parity; m_DataBits = dataBits; m_StopBits = stopBits; } catch (UnsupportedCommOperationException e) { m_Termios.set(prev); checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios)); throw e; } catch (IllegalStateException e) { m_Termios.set(prev); checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios)); throw e; } } private static int min(int a, int b) { return a < b ? a : b; } @Override synchronized public OutputStream getOutputStream() throws IOException { checkState(); return new OutputStream() { private byte[] m_Buffer = new byte[2048]; @Override public void write(int b) throws IOException { checkState(); byte[] buf = { (byte) b }; write(buf, 0, 1); } @Override public void write(byte[] b, int off, int len) throws IOException { checkState(); while (len > 0) { int n = min(len, min(m_Buffer.length, b.length - off)); if (off > 0) { System.arraycopy(b, off, m_Buffer, 0, n); n = jtermios.JTermios.write(m_FD, m_Buffer, n); } else n = jtermios.JTermios.write(m_FD, b, n); if (n < 0) { PureJavaSerialPort.this.close(); throw new IOException(); } len -= n; off += n; } m_OutputEmptyNotified = false; } @Override public void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public void flush() throws IOException { checkState(); if (tcdrain(m_FD) < 0) { close(); throw new IOException(); } } }; } synchronized public InputStream getInputStream() throws IOException { checkState(); return new InputStream() { private TimeVal m_TimeOut = new TimeVal(); private int[] m_Available = { 0 }; private byte[] m_Buffer = new byte[2048]; @Override public int available() throws IOException { checkState(); if (ioctl(m_FD, FIONREAD, m_Available) < 0) { PureJavaSerialPort.this.close(); throw new IOException(); } return m_Available[0]; } @Override public int read() throws IOException { checkState(); byte[] buf = { 0 }; int n = read(buf, 0, 1); return n > 0 ? buf[0] & 0xFF : -1; } @Override public int read(byte[] b, int off, int len) throws IOException { checkState(); long T0 = m_ReceiveTimeOutEnabled ? System.currentTimeMillis() : 0; int N = 0; while (true) { int n = len - N; if (off > 0) { n = min(n, min(m_Buffer.length, b.length - off)); n = jtermios.JTermios.read(m_FD, m_Buffer, n); if (n > 0) System.arraycopy(m_Buffer, 0, b, off, n); } else n = jtermios.JTermios.read(m_FD, b, n); if (n < 0) throw new IOException(); N += n; //System.out.printf("n=%d off=%d left=%d N=%d th=%d to=%d dt=%d\n",n, off,left,N,m_ReceiveThresholdValue,m_ReceiveTimeOutValue,System.currentTimeMillis() - T0); if (!m_ReceiveThresholdEnabled && N > 0) break; if (m_ReceiveThresholdEnabled && N >= m_ReceiveThresholdValue) break; if (m_ReceiveTimeOutEnabled && System.currentTimeMillis() - T0 >= m_ReceiveTimeOutValue) break; off += n; } m_DataAvailableNotified = false; return N; } }; } @Override synchronized public int getReceiveFramingByte() { checkState(); // Not supported return 0; } @Override synchronized public int getReceiveThreshold() { checkState(); // Not supported return 0; } @Override synchronized public int getReceiveTimeout() { checkState(); return m_ReceiveTimeOutValue; } @Override synchronized public boolean isReceiveFramingEnabled() { checkState(); // Not supported return false; } @Override synchronized public boolean isReceiveThresholdEnabled() { checkState(); // Not supported return false; } @Override synchronized public boolean isReceiveTimeoutEnabled() { checkState(); return m_ReceiveTimeOutEnabled; } @Override synchronized public void setInputBufferSize(int arg0) { checkState(); // Not supported } @Override synchronized public void setOutputBufferSize(int arg0) { checkState(); // Not supported } @Override synchronized public void close() { int fd = m_FD; if (fd != -1) { m_FD = -1; int flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK; int fcres = fcntl(fd, F_SETFL, flags); if (fcres != 0) // not much we can do if this fails, so just log it log = log && log(1, "fcntl(%d,%d,%d) returned %d\n", m_FD, F_SETFL, flags, fcres); m_Thread.interrupt(); int err = jtermios.JTermios.close(fd); if (err < 0) log = log && log(1, "JTermios.close returned %d, errno %d\n", err, errno()); long t0 = System.currentTimeMillis(); while (m_ThreadRunning) { try { Thread.sleep(5); if (System.currentTimeMillis() - t0 > 2000) break; } catch (InterruptedException e) { break; } } super.close(); } } /* package */PureJavaSerialPort(String name, int timeout) throws PortInUseException { super(); this.name = name; // unbelievable, sometimes quickly closing and re-opening fails on Windows // so try a few times int tries = 100; long T0 = System.currentTimeMillis(); while ((m_FD = open(name, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0) { try { Thread.sleep(10); } catch (InterruptedException e) { } if (tries-- < 0 || System.currentTimeMillis() - T0 >= timeout) throw new PortInUseException(); } int flags = fcntl(m_FD, F_GETFL, 0); flags &= ~O_NONBLOCK; checkReturnCode(fcntl(m_FD, F_SETFL, flags)); m_BaudRate = 9600; m_DataBits = SerialPort.DATABITS_8; m_FlowControlMode = SerialPort.FLOWCONTROL_NONE; m_Parity = SerialPort.PARITY_NONE; m_StopBits = SerialPort.STOPBITS_1; checkReturnCode(tcgetattr(m_FD, m_Termios)); cfmakeraw(m_FD, m_Termios); m_Termios.c_cflag |= CLOCAL | CREAD; m_Termios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); m_Termios.c_oflag &= ~OPOST; m_Termios.c_cc[VSTART] = (byte) DC1; m_Termios.c_cc[VSTOP] = (byte) DC3; m_Termios.c_cc[VMIN] = 0; m_Termios.c_cc[VTIME] = 0; checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios)); try { setSerialPortParams(m_BaudRate, m_DataBits, m_StopBits, m_Parity); } catch (UnsupportedCommOperationException e) { // This really should not happen e.printStackTrace(); } setReceiveTimeout(); checkReturnCode(ioctl(m_FD, TIOCMGET, m_ioctl)); m_ControlLineStates = m_ioctl[0]; Runnable runnable = new Runnable() { public void run() { try { m_ThreadRunning = true; final boolean USE_SELECT = true; final int TIMEOUT = 10; // msec TimeVal timeout; FDSet rset; FDSet wset; Pollfd[] pollfd; if (USE_SELECT) { rset = newFDSet(); wset = newFDSet(); timeout = new TimeVal(); timeout.tv_sec = 0; timeout.tv_usec = TIMEOUT * 1000; // 10 msec polling period } else pollfd = new Pollfd[] { new Pollfd() }; while (m_FD >= 0) { // lets die if the file descriptor dies on us ie the port closes boolean read = (m_NotifyOnDataAvailable && !m_DataAvailableNotified); boolean write = (m_NotifyOnOutputEmpty && !m_OutputEmptyNotified); int n = 0; if (!read && !write) Thread.sleep(TIMEOUT); else { // do all this only if we actually wait for read or write if (USE_SELECT) { FD_ZERO(rset); FD_ZERO(wset); if (read) FD_SET(m_FD, rset); if (write) FD_SET(m_FD, wset); n = select(m_FD + 1, rset, wset, null, timeout); read = read && FD_ISSET(m_FD, rset); write = write && FD_ISSET(m_FD, wset); } else { // use poll pollfd[0].fd = m_FD; short e = 0; if (read) e |= POLLIN; if (write) e |= POLLOUT; pollfd[0].events = e; pollfd[0].revents = 0; n = poll(pollfd, 1, TIMEOUT); int re = pollfd[0].revents; if ((re & POLLNVAL) != 0) { log = log && log(1, "poll() returned POLLNVAL, errno %\n", errno()); break; } read = read && (re & POLLIN) != 0; write = write && (re & POLLOUT) != 0; } if (Thread.currentThread().isInterrupted()) break; if (n < 0) { log = log && log(1, "select() or poll() returned %d, errno %d\n", n, errno()); close(); break; } } if (m_EventListener != null) { if (read || write) sendDataEvents(read, write); if (m_NotifyOnCTS || m_NotifyOnDSR || m_NotifyOnRI || m_NotifyOnCD) sendNonDataEvents(); } } } catch (InterruptedException ie) { } finally { m_ThreadRunning = false; } } }; m_Thread = new Thread(runnable, getName()); m_Thread.setDaemon(true); } synchronized private void updateControlLineState(int line) { checkState(); if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1) throw new IllegalStateException(); m_ControlLineStates = (m_ioctl[0] & line) + (m_ControlLineStates & ~line); } synchronized private boolean getControlLineState(int line) { checkState(); if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1) throw new IllegalStateException(); return (m_ioctl[0] & line) != 0; } synchronized private void setControlLineState(int line, boolean state) { checkState(); if (ioctl(m_FD, TIOCMGET, m_ioctl) == -1) throw new IllegalStateException(); if (state) m_ioctl[0] |= line; else m_ioctl[0] &= ~line; if (ioctl(m_FD, TIOCMSET, m_ioctl) == -1) throw new IllegalStateException(); } private void setReceiveTimeout() { // Javadoc for javacomm says: // Enabling the Timeout OR Threshold with a value a zero is a special case. // This causes the underlying driver to poll for incoming data instead being // event driven. Otherwise, the behaviour is identical to having both the // Timeout and Threshold disabled. // but what does it mean? // Threshold Timeout Behaviour // disabled - disabled - n bytes block until any data is available // VMIN = 1, VTIME = 0 // enabled m bytes disabled - n bytes block until min(m,n) bytes are available // VMIN = 1, VTIME = 0 // need to loop, inside InputStream.read(), // until min(m,n) bytes received // disabled - enabled x ms n bytes block for x ms or until any data is available // VMIN = 0 // if x<25500 then // VTIME = x / 100 // else // k = (x / 25500 + 1); // VTIME = x / k / 100 + 1 // and we need to loop k times // inside InputStream.read() // enabled m bytes enabled x ms n bytes block for x ms or until min(m,n) bytes are available // same as previous, except we need to loop // inside InputStream.read() until // until min(m,n) bytes received byte vmin = 1; byte vtime = 0; if (m_ReceiveTimeOutEnabled) { vmin = 0; int t = m_ReceiveTimeOutValue; if (t < 25500) vtime = (byte) (t / 100); else { int n = t / 25500 + 1; vtime = (byte) (t / n / 100 + 1); } } m_Termios.c_cc[VMIN] = vmin; m_Termios.c_cc[VTIME] = vtime; checkReturnCode(tcsetattr(m_FD, TCSANOW, m_Termios)); } private void checkState() { if (m_FD < 0) throw new IllegalStateException("File descriptor is " + m_FD + " < 0, maybe closed by previous error condition"); } private void checkReturnCode(int code) { if (code != 0) { close(); StackTraceElement ste = Thread.currentThread().getStackTrace()[1]; String msg = String.format("JTermios call returned %d at %s", code, lineno()); log = log && log(1, "%s\n", msg); throw new IllegalStateException(msg); } } }
package purejavacomm.testsuite; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Random; import purejavacomm.CommPortIdentifier; import purejavacomm.NoSuchPortException; import purejavacomm.SerialPort; public class TestBase { static class TestFailedException extends Exception { } protected static volatile String m_TestPortName; protected static volatile SerialPort m_Port; private static volatile long m_T0; protected static volatile OutputStream m_Out; protected static volatile InputStream m_In; protected static volatile int[] m_SyncSema4 = { 0 }; protected static int m_Tab; protected static int m_Progress; protected static void sync(int N) throws InterruptedException { synchronized (m_SyncSema4) { m_SyncSema4[0]++; if (m_SyncSema4[0] < N) { m_SyncSema4.wait(); } else { m_SyncSema4[0] = 0; m_SyncSema4.notifyAll(); } } } static protected void openPort() throws Exception { try { CommPortIdentifier portid = CommPortIdentifier.getPortIdentifier(m_TestPortName); m_Port = (SerialPort) portid.open("PureJavaCommTestSuite", 1000); m_Out = m_Port.getOutputStream(); m_In = m_Port.getInputStream(); drain(m_In); } catch (NoSuchPortException e) { fail("could no open port '%s'\n", m_TestPortName); } } static protected void closePort() { if (m_Port != null) { try { m_Out.flush(); m_Port.close(); } catch (IOException e) { e.printStackTrace(); } finally { m_Port = null; } } } static protected void drain(InputStream ins) throws Exception { sleep(100); int n; while ((n = ins.available()) > 0) { for (int i = 0; i < n; ++i) ins.read(); sleep(100); } } static void begin(String name) { System.out.printf("%-46s", name); m_Tab = 46; m_T0 = System.currentTimeMillis(); m_Progress = 0; } /** * Sleep a short amount of time to allow hardware feedback, which isn't * instant */ static protected void sleep() throws InterruptedException { sleep(40); } static protected void sleep(int t) throws InterruptedException { int m = 1000; while (t > 0) { Thread.sleep(t > m ? m : t); t -= m; while ((System.currentTimeMillis() - m_T0) / m > m_Progress) { System.out.print("."); m_Tab m_Progress++; } } } static void fail(String format, Object... args) throws TestFailedException { System.out.println(" FAILED"); System.out.println(" System.out.printf(format, args); System.out.println(); System.out.println(" throw new TestFailedException(); } static void finishedOK() { finishedOK(""); } static void finishedOK(String format, Object... args) { for (int i = 0; i < m_Tab; i++) System.out.print("."); System.out.printf(" OK " + format, args); System.out.println(); } static public void init(String[] args) { m_TestPortName = "cu.usbserial-FTOXM3NX"; if (args.length > 0) m_TestPortName = args[0]; } static public String getPortName() { return m_TestPortName; } }
package readinstruction; import java.util.UUID; public abstract class ReadInstruction { private UUID instructionId; private int readAddres; private int arrivalTime; private boolean hasDeadline; public ReadInstruction (UUID instructionId, int readAddres, int arrivalTime, boolean hasDeadline){ this.arrivalTime = arrivalTime; this.instructionId = instructionId; this.readAddres = readAddres; this.hasDeadline = hasDeadline; } public UUID getInstructionId() { return instructionId; } public int getReadAddres() { return readAddres; } public int getArrivalTime() { return arrivalTime; } public boolean isHasDeadline() { return hasDeadline; } }
package ru.org.linux.site.boxes; import java.io.IOException; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import ru.org.linux.boxlet.Boxlet; import ru.org.linux.site.config.PropertiesConfig; import ru.org.linux.site.config.SQLConfig; import ru.org.linux.util.*; public final class gallery extends Boxlet { public String getContentImpl(ProfileHashtable profile) throws IOException, SQLException { Connection db = null; try { db = ((SQLConfig) config).getConnection("gallery"); StringBuffer out = new StringBuffer(); out.append("<h2><a href=\"view-news.jsp?section=3\"></a></h2> <h3> </h3>"); Statement st = db.createStatement(); ResultSet rs = st.executeQuery("SELECT topics.id as msgid, topics.stat1, topics.title, topics.url, topics.linktext, nick FROM topics, sections, groups, users WHERE groups.id=topics.groupid AND groups.section=sections.id AND users.id=topics.userid AND topics.moderate AND sections.id=3 AND NOT deleted ORDER BY commitdate DESC LIMIT 3"); while (rs.next()) { String icon = rs.getString("linktext"); String img = rs.getString("url"); String htmlPath = ((PropertiesConfig) config).getProperties().getProperty("HTMLPathPrefix"); String nick = rs.getString("nick"); String title = StringUtil.makeTitle(rs.getString("title")); out.append("<a href=\"view-message.jsp?msgid=").append(rs.getInt("msgid")).append("\">"); try { ImageInfo info = new ImageInfo(htmlPath + icon); out.append("<img border=1 src=\"/").append(icon).append("\" alt=\": ").append(title).append("\" ").append(info.getCode()).append('>'); } catch (BadImageException e) { out.append("[bad image] <img border=1 src=\"").append(icon).append("\" alt=\": ").append(title).append("\" " + '>'); } out.append("</a><br>"); try { ImageInfo imginfo = new ImageInfo(htmlPath + img); out.append("<i>").append(imginfo.getWidth()).append('x').append(imginfo.getHeight()).append("</i>, \"").append(title).append("\" <a href=\"whois.jsp?nick=").append(URLEncoder.encode(nick)).append("\">").append(nick).append("</a>"); } catch (BadImageException e) { out.append("<i>Bad image!</i>, \"").append(title).append("\" <a href=\"whois.jsp?nick=").append(URLEncoder.encode(nick)).append("\">").append(nick).append("</a>"); } int c = rs.getInt("stat1"); if (c > 0) { out.append(" (").append(c).append(')'); } out.append("<p>"); } rs.close(); out.append("<a href=\"view-news.jsp?section=3\"> ...</a>"); return out.toString(); } finally { if (db != null) { ((SQLConfig) config).SQLclose(); } } } public String getInfo() { return " "; } public String getVariantID(ProfileHashtable prof) throws UtilException { return "SearchMode=" + prof.getBoolean("SearchMode"); } public Date getExpire() { return new Date(new Date().getTime() + 2 * 60 * 1000); } }
package services.admin; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import resources.Location; import resources.objects.SWGObject; import resources.objects.cell.CellObject; import resources.player.Player; import resources.server_info.Log; import services.admin.http.HttpImageType; import services.admin.http.HttpSession; import services.admin.http.HttpSocket; import services.admin.http.HttpSocket.HttpRequest; import services.admin.http.HttpStatusCode; class WebserverHandler { private static final Charset ASCII = Charset.forName("ASCII"); private static final String REQUIRED_PREFIX = new File("res/webserver").getAbsolutePath().replace('/', File.separatorChar); private static final String INDEX_PATH = new File("res/webserver/index.html".replace('/', File.separatorChar)).getAbsolutePath(); private static final String AUTHENTICATED_PATH = new File("res/webserver/authenticated.html".replace('/', File.separatorChar)).getAbsolutePath(); private final WebserverData data; private final Pattern variablePattern; public WebserverHandler(WebserverData data) { this.data = data; variablePattern = Pattern.compile("\\$\\{.+\\}"); // Looks for variables: ${VAR_NAME} } public void handleRequest(HttpSocket socket, HttpRequest request) throws IOException { String file = request.getURI().toASCIIString(); Map<String, String> getVariables = new HashMap<>(); if (file.contains("?")) { String vars = file.substring(file.indexOf('?')+1); String [] variables = vars.split("&"); for (String var : variables) { String [] parts = var.split("=", 2); if (parts.length == 2) getVariables.put(parts[0], parts[1]); } file = file.substring(0, file.indexOf('?')); } if (file.contains(" file = file.substring(0, file.indexOf(' switch (file) { case "/memory_usage.png": if (socket.getSession().isAuthenticated()) socket.send(createMemoryUsage(), HttpImageType.PNG); else socket.send(HttpStatusCode.NOT_FOUND, request.getURI() + " is not found!"); break; default: { byte [] response = parseFile(socket.getSession(), file, getVariables); if (response == null) socket.send(HttpStatusCode.NOT_FOUND, request.getURI() + " is not found!"); else socket.send(getFileType(file), response); break; } } } private BufferedImage createMemoryUsage() { double [] memoryUsage = data.getMemoryUsage(); final int graphHeight = 300; BufferedImage image = new BufferedImage(900, graphHeight + 25, BufferedImage.TYPE_3BYTE_BGR); Graphics2D g = image.createGraphics(); Font font = g.getFont(); g.setFont(font.deriveFont(Font.TRUETYPE_FONT, Math.min(image.getHeight()/10.0f, 25.0f))); Map <RenderingHints.Key, Object> hints = new HashMap<>(); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHints(new RenderingHints(hints)); g.setColor(Color.WHITE); renderGraph(g, image.getWidth(), image.getHeight(), graphHeight); FontMetrics fm = g.getFontMetrics(); String inUse = getMemoryInUse(); int width = fm.stringWidth(inUse); int x = 5; x += drawStr(g, image.getHeight(), x, "Proc:"); g.drawString(inUse, image.getWidth()-width - 5, image.getHeight() - 5); x += drawDataSet(g, Color.RED, " M:", image.getWidth(), image.getHeight(), graphHeight, x, memoryUsage); x += drawDataSet(g, Color.CYAN, " C:", image.getWidth(), image.getHeight(), graphHeight, x, data.getCpuUsage()); g.setColor(Color.WHITE); x += drawStr(g, image.getHeight(), x, " Sys:"); x += drawDataSet(g, Color.YELLOW, " M:", image.getWidth(), image.getHeight(), graphHeight, x, data.getSystemMemoryUsage()); drawDataSet(g, Color.GREEN, " C:", image.getWidth(), image.getHeight(), graphHeight, x, data.getSystemCpuUsage()); return image; } private void renderGraph(Graphics2D g, int width, int height, int graphHeight) { g.drawRect(0, 0, width-1, graphHeight-1); g.drawLine(0, height-1, width, height-1); for (int i = 1; i < 10; i++) { g.drawLine(0, (int) ((i/10.0)*graphHeight), 10, (int) ((i/10.0)*graphHeight)); } } private int drawDataSet(Graphics2D g, Color c, String pre, int width, int height, int graphHeight, int x, double [] data) { g.setColor(c); drawLines(g, data, width, graphHeight-1); return drawStr(g, height, x, String.format("%s%.2f%%", pre, (int) (data[data.length-1] * 10000) / 100.0)); } private int drawStr(Graphics2D g, int height, int x, String str) { g.drawString(str, x, height - 5); return g.getFontMetrics().stringWidth(str); } private void drawLines(Graphics2D g, double [] data, int width, int height) { int start = 0; for (double d : data) { if (d == 0) start++; else break; } int prevX = -1; int prevY = -1; for (int i = start; i < data.length; i++) { int x = (int) ((double) i / data.length * width); int y = (int) ((1-data[i]) * height); if (prevX != -1 && prevY != -1) g.drawLine(prevX, prevY, x, y); prevX = x; prevY = y; } } private String getMemoryInUse() { double memory = Runtime.getRuntime().totalMemory(); String [] types = new String[]{"B", "KB", "MB", "GB"}; String type = types[0]; for (int i = 0; i < types.length && memory >= 1024; i++) { memory /= 1024; type = types[i]; } return String.format("In-Use: %.2f%s", memory, type); } private String getFileType(String filepath) { if (!filepath.contains(".")) return "text/html"; String type = filepath.substring(filepath.lastIndexOf('.')+1).toLowerCase(Locale.US); switch (type) { case "png": case "gif": case "jpg": case "jpeg": case "ico": return "image/" + type; default: return "text/" + type; } } private byte [] parseFile(HttpSession session, String filepath, Map<String, String> getVariables) throws IOException { String type = getFileType(filepath); File file = verifyAndModifyFile(session, filepath, type); if (file == null) return null; if (type.equalsIgnoreCase("text/html")) return parseHtmlFile(file, getVariables).getBytes(ASCII); try (InputStream is = new FileInputStream(file)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(is.available()); byte [] buffer = new byte[Math.min(1024, is.available())]; while (is.available() > 0) { if (is.available() > buffer.length && buffer.length < 1024) buffer = new byte[Math.min(1024, is.available())]; int len = is.read(buffer); baos.write(buffer, 0, len); } return baos.toByteArray(); } } private File verifyAndModifyFile(HttpSession session, String filepath, String type) { File file = new File("res/webserver" + filepath); if (File.separatorChar != '/') file = new File(file.getAbsolutePath().replace('/', File.separatorChar)); if (file.isDirectory()) file = new File(file, "index.html"); if (file.getAbsolutePath().equals(INDEX_PATH)) { if (session.isAuthenticated()) { file = new File(AUTHENTICATED_PATH); } } else if (!session.isAuthenticated() && !type.equals("text/css") && !type.equals("text/js") && !type.startsWith("image")) return null; if (!verifyPath(file)) { Log.e("WebserverHandler", "Cannot access %s - not a valid path", file); return null; } return file; } private boolean verifyPath(File file) { if (!file.getAbsolutePath().startsWith(REQUIRED_PREFIX)) return false; if (!file.isFile()) return false; return true; } private String parseHtmlFile(File file, Map<String, String> getVariables) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), ASCII))) { String line = null; StringBuilder builder = new StringBuilder(); while (reader.ready()) { line = reader.readLine(); if (line == null) break; Matcher matcher = variablePattern.matcher(line); while (matcher.find()) { String var = matcher.group(); var = var.substring(2, var.length()-1); line = line.replaceAll("\\$\\{"+var+"\\}", getVariable(var, getVariables)); matcher.reset(line); } builder.append(line + System.lineSeparator()); } return builder.toString(); } } private String getVariable(String var, Map<String, String> getVariables) throws IOException { var = var.toLowerCase(Locale.US); switch (var) { case "log": return data.getLog().replace("\n", "\n<br />"); case "online_player_count": return getOnlinePlayerCount(); case "online_players": return getOnlinePlayerData(); case "character_info": { if (!getVariables.containsKey("character_id")) return ""; long i = Long.parseLong(getVariables.get("character_id")); for (Player p : data.getOnlinePlayers()) { if (p.getCreatureObject().getObjectId() == i) { return getCreatureData(p.getCreatureObject()); } } return "No Creature Found!"; } default: return ""; } } private String getOnlinePlayerCount() { Set<Player> players = data.getOnlinePlayers(); return ("Online Players: ["+players.size()+"]"); } private String getOnlinePlayerData() { Set<Player> players = data.getOnlinePlayers(); StringBuilder ret = new StringBuilder("<table class=\"online_players_table\"><tr><th>Username</th><th>User ID</th><th>Character</th><th>Character ID</th></tr>"); for (Player p : players) { ret.append("<tr>"); long id = p.getCreatureObject().getObjectId(); ret.append(String.format("<td class=\"online_player_cell\"><a href=\"?character_id=%d\">%s</a></td>", id, p.getUsername())); ret.append(String.format("<td class=\"online_player_cell\"><a href=\"?character_id=%d\">%d</a></td>", id, p.getUserId())); ret.append(String.format("<td class=\"online_player_cell\"><a href=\"?character_id=%d\">%s</a></td>", id, p.getCharacterName())); ret.append(String.format("<td class=\"online_player_cell\"><a href=\"?character_id=%d\">%d</a></td>", id, p.getCreatureObject().getObjectId())); ret.append("</tr>"); } ret.append("</table>"); return ret.toString(); } private String getCreatureData(SWGObject creature) { StringBuilder str = new StringBuilder(""); Location world = creature.getWorldLocation(); str.append(String.format(" Object ID: %s<br />", creature.getObjectId())); str.append(String.format(" Name: %s<br />", creature.getName())); str.append(String.format("<b>World:</b><br />")); str.append(addLocationData(world)); if (creature.getParent() != null) { Location cell = creature.getLocation(); str.append(String.format("<b>Local:</b><br />")); str.append(addLocationData(cell)); SWGObject parent = creature.getParent(); if (parent != null) { str.append(String.format(" <b>Parent:</b><br />")); str.append(addParentData(parent, " ")); parent = parent.getParent(); if (parent != null) { str.append(String.format(" <b>Grandparent:</b><br />")); str.append(addParentData(parent, " ")); } } } return str.toString().replace(" ", "&nbsp;").replace("<br&nbsp;/>", "<br />"); } private String addParentData(SWGObject obj, String indent) { StringBuilder str = new StringBuilder(""); str.append(indent + String.format(" Object ID: %d<br />", obj.getObjectId())); str.append(indent + String.format(" Template: %s<br />", obj.getTemplate())); if (obj instanceof CellObject) { str.append(indent + String.format(" Cell Index: %d<br />", ((CellObject) obj).getNumber())); str.append(indent + String.format(" Cell Name: %s<br />", ((CellObject) obj).getCellName())); } return str.toString(); } private String addLocationData(Location l) { StringBuilder str = new StringBuilder(""); str.append(String.format(" Location: %.2f, %.2f, %.2f [%s]<br />", l.getX(), l.getY(), l.getZ(), l.getTerrain())); str.append(String.format("Orientation: %.2f, %.2f, %.2f, %.2f<br />", l.getOrientationX(), l.getOrientationY(), l.getOrientationZ(), l.getOrientationW())); return str.toString(); } }
import java.net.*; import java.io.*; import java.util.*; public class update { static final int ZONE = dns.QUERY; static final int PREREQUISITE = dns.ANSWER; static final int UPDATE = dns.AUTHORITY; static final int ADDITIONAL = dns.ADDITIONAL; static dnsName name = null; static short type = dns.A, _class = dns.IN; static void usage() { System.out.println("Usage: update @server name [-t ttl] [-p port]"); System.exit(0); } static void doUpdate(dnsMessage query, dnsResolver res) throws IOException { dnsMessage response; response = res.send(query); System.out.print(";; ->>HEADER<<- "); System.out.print("opcode: "); System.out.print(dns.opcodeString(response.getHeader().getOpcode())); System.out.print(", status: "); System.out.print(dns.rcodeString(response.getHeader().getRcode())); System.out.println(", id: " + response.getHeader().getID()); System.out.print(";; flags: " + response.getHeader().printFlags()); System.out.print("; "); for (int i = 0; i < 4; i++) { System.out.print(dns.sectionString(i)); System.out.print(": "); System.out.print(response.getHeader().getCount(i)); System.out.print(" "); } System.out.println(); System.out.println(";; done"); } public static void main(String argv[]) throws IOException { String server; dnsName name, domain; InetAddress addr; int ttl = 3600; dnsMessage query = new dnsMessage(); dnsRecord soa, a; dnsResolver res = null; query.getHeader().setRandomID(); query.getHeader().setOpcode(dns.UPDATE); if (argv.length < 2) { usage(); } if (!argv[0].startsWith("@")) { usage(); } server = argv[0].substring(1); res = new dnsResolver(server); name = new dnsName(argv[1]); for (int arg = 2; arg < argv.length; arg++) { if (!argv[arg].startsWith("-") || argv[arg].length() < 2) continue; switch (argv[arg].charAt(1)) { case 'p': String portStr; int port; if (argv[arg].length() > 2) portStr = argv[arg].substring(2); else portStr = argv[++arg]; port = Integer.parseInt(portStr); if (port < 0 || port > 65536) { System.out.println("Invalid port"); return; } res.setPort(port); break; case 't': ttl = Integer.parseInt(argv[arg]); if (ttl <= 0) ttl = 3600; break; default: System.out.print("Invalid option" + argv[arg]); } } try { addr = InetAddress.getLocalHost(); } catch (UnknownHostException e) { System.out.println(e); return; } domain = new dnsName(name, 1); soa = new dnsSOARecord(domain, dns.IN); a = new dnsARecord(name, dns.IN, ttl, addr); query.addRecord(ZONE, soa); query.addRecord(UPDATE, a); doUpdate(query, res); } }
import java.net.*; import java.io.*; import java.util.*; import org.xbill.DNS.*; import org.xbill.DNS.utils.*; /** @author Brian Wellington &lt;bwelling@xbill.org&gt; */ public class update { Message query, response; Resolver res; String server = null; Name origin, zone; int defaultTTL; short defaultClass = DClass.IN; PrintStream log = null; void print(Object o) { System.out.println(o); if (log != null) log.println(o); } public update(InputStream in) throws IOException { Vector inputs = new Vector(); Vector istreams = new Vector(); query = new Message(); query.getHeader().setOpcode(Opcode.UPDATE); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); inputs.addElement(br); istreams.addElement(in); while (true) { try { String line = null; do { InputStream is; is = (InputStream) istreams.lastElement(); br = (BufferedReader)inputs.lastElement(); if (is == System.in) System.out.print("> "); line = Master.readExtendedLine(br); if (line == null) { br.close(); inputs.removeElement(br); istreams.removeElement(is); if (inputs.isEmpty()) return; } } while (line == null); if (log != null) log.println("> " + line); if (line.length() == 0 || line.charAt(0) == ' continue; MyStringTokenizer st = new MyStringTokenizer(line); if (!st.hasMoreTokens()) continue; String operation = st.nextToken(); if (operation.equals("server")) { server = st.nextToken(); res = new SimpleResolver(server); } else if (operation.equals("key")) { String keyname = st.nextToken(); String keydata = st.nextToken(); if (res == null) res = new SimpleResolver(server); res.setTSIGKey(keyname, keydata); } else if (operation.equals("port")) { if (res == null) res = new SimpleResolver(server); res.setPort(Short.parseShort(st.nextToken())); } else if (operation.equals("tcp")) { if (res == null) res = new SimpleResolver(server); res.setTCP(true); } else if (operation.equals("class")) { String s = st.nextToken(); short newClass = DClass.value(s); if (newClass > 0) defaultClass = newClass; else print("Invalid class " + newClass); } else if (operation.equals("ttl")) defaultTTL = TTL.parseTTL(st.nextToken()); else if (operation.equals("origin")) origin = new Name(st.nextToken()); else if (operation.equals("zone")) zone = new Name(st.nextToken()); else if (operation.equals("require")) doRequire(st); else if (operation.equals("prohibit")) doProhibit(st); else if (operation.equals("add")) doAdd(st); else if (operation.equals("delete")) doDelete(st); else if (operation.equals("glue")) doGlue(st); else if (operation.equals("help")) { if (st.hasMoreTokens()) help(st.nextToken()); else help(null); } else if (operation.equals("echo")) print(line.substring(4).trim()); else if (operation.equals("send")) { if (res == null) res = new SimpleResolver(server); sendUpdate(); query = new Message(); query.getHeader().setOpcode(Opcode.UPDATE); } else if (operation.equals("query")) doQuery(st); else if (operation.equals("quit") || operation.equals("q")) { if (log != null) log.close(); Enumeration e = inputs.elements(); while (e.hasMoreElements()) { BufferedReader tbr; tbr = (BufferedReader) e.nextElement(); tbr.close(); } System.exit(0); } else if (operation.equals("file")) doFile(st, inputs, istreams); else if (operation.equals("log")) doLog(st); else if (operation.equals("assert")) { if (doAssert(st) == false) return; } else print("invalid keyword: " + operation); } catch (NullPointerException npe) { System.out.println("Parse error"); } catch (InterruptedIOException iioe) { System.out.println("Operation timed out"); } } } void sendUpdate() throws IOException { if (query.getHeader().getCount(Section.ZONE) == 0) { Name updzone; if (zone != null) updzone = zone; else updzone = origin; short dclass = defaultClass; if (updzone == null) { Enumeration updates = query.getSection(Section.UPDATE); if (updates == null) { print("Invalid update"); return; } Record r = (Record) updates.nextElement(); updzone = new Name(r.getName(), 1); dclass = r.getDClass(); } Record soa = Record.newRecord(updzone, Type.SOA, dclass); query.addRecord(soa, Section.ZONE); } response = res.send(query); if (response == null) return; print(response); } /* * <name> [ttl] [class] <type> <data> * Ignore the class, if present. */ Record parseRR(MyStringTokenizer st, short classValue, int TTLValue) throws IOException { Name name = new Name(st.nextToken(), origin); int ttl; short type; String s = st.nextToken(); try { ttl = TTL.parseTTL(s); s = st.nextToken(); } catch (NumberFormatException e) { ttl = TTLValue; } if (DClass.value(s) >= 0) s = st.nextToken(); if ((type = Type.value(s)) < 0) /* Close enough... */ throw new NullPointerException("Parse error"); return Record.fromString(name, type, classValue, ttl, st, origin); } /* * <name> <type> */ Record parseSet(MyStringTokenizer st, short classValue) throws IOException { Name name = new Name(st.nextToken(), origin); short type; if ((type = Type.value(st.nextToken())) < 0) throw new IOException("Parse error"); return Record.newRecord(name, type, classValue, 0); } /* * <name> */ Record parseName(MyStringTokenizer st, short classValue) throws IOException { Name name = new Name(st.nextToken(), origin); return Record.newRecord(name, Type.ANY, classValue, 0); } void doRequire(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, 0); else if (qualifier.equals("-s")) rec = parseSet(st, DClass.ANY); else if (qualifier.equals("-n")) rec = parseName(st, DClass.ANY); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.PREREQ); print(rec); } } void doProhibit(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, 0); else if (qualifier.equals("-s")) rec = parseSet(st, DClass.NONE); else if (qualifier.equals("-n")) rec = parseName(st, DClass.NONE); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.PREREQ); print(rec); } } void doAdd(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (!qualifier.startsWith("-")) { st.putBackToken(qualifier); qualifier = "-r"; } if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, defaultTTL); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.UPDATE); print(rec); } } void doDelete(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (qualifier.equals("-r")) rec = parseRR(st, DClass.NONE, 0); else if (qualifier.equals("-s")) rec = parseSet(st, DClass.ANY); else if (qualifier.equals("-n")) rec = parseName(st, DClass.ANY); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.UPDATE); print(rec); } } void doGlue(MyStringTokenizer st) throws IOException { Record rec; String qualifier = st.nextToken(); if (!qualifier.startsWith("-")) { st.putBackToken(qualifier); qualifier = "-r"; } if (qualifier.equals("-r")) rec = parseRR(st, defaultClass, defaultTTL); else { print("qualifier " + qualifier + " not supported"); return; } if (rec != null) { query.addRecord(rec, Section.ADDITIONAL); print(rec); } } void doQuery(MyStringTokenizer st) throws IOException { Record rec; rec = parseSet(st, defaultClass); Message newQuery = Message.newQuery(rec); if (res == null) res = new SimpleResolver(server); if (rec.getType() == Type.AXFR) response = res.sendAXFR(newQuery); else response = res.send(newQuery); print(response); } void doFile(MyStringTokenizer st, Vector inputs, Vector istreams) { String s = st.nextToken(); try { InputStreamReader isr2; if (!s.equals("-")) { FileInputStream fis = new FileInputStream(s); isr2 = new InputStreamReader(fis); istreams.addElement(fis); } else { isr2 = new InputStreamReader(System.in); istreams.addElement(System.in); } BufferedReader br2 = new BufferedReader(isr2); inputs.addElement(br2); } catch (FileNotFoundException e) { print(s + "not found"); } } void doLog(MyStringTokenizer st) { String s = st.nextToken(); try { FileOutputStream fos = new FileOutputStream(s); log = new PrintStream(fos); } catch (Exception e) { print("Error opening " + s); } } boolean doAssert(MyStringTokenizer st) { String field = st.nextToken(); String expected = st.nextToken(); String value = null; boolean flag = true; int section; if (field.equalsIgnoreCase("rcode")) { short rcode = response.getHeader().getRcode(); if (rcode != Rcode.value(expected)) { value = Rcode.string(rcode); flag = false; } } else if ((section = Section.value(field)) >= 0) { short count = response.getHeader().getCount(section); if (count != Short.parseShort(expected)) { value = new Short(count).toString(); flag = false; } } else print("Invalid assertion keyword: " + field); if (flag == false) { print("Expected " + field + " " + expected + ", received " + value); if (st.hasMoreTokens()) print(st.nextToken()); } return flag; } static void helpResolver() { System.out.println("Resolver options:\n" + " server <name>" + "\tserver that receives the updates\n" + " key <name> <data>" + "\tTSIG key used to sign the messages\n" + " port <port>" + "\t\tUDP/TCP port the message is sent to (default: 53)\n" + " tcp" + "\t\t\tTCP should be used to send messages (default: unset)\n" ); } static void helpAttributes() { System.out.println("Attributes:\n" + " class <class>\t" + "class of the zone to be updated (default: IN)\n" + " ttl <ttl>\t\t" + "ttl of an added record, if unspecified (default: 0)\n" + " origin <origin>\t" + "default origin of each record name (default: .)\n" + " zone <zone>\t" + "zone to update (default: value of <origin>)\n" ); }; static void helpData() { System.out.println("Data:\n" + " require/prohibit\t" + "require that a record, set, or name is/is not present\n" + "\t-r <name> [ttl] [class] <type> <data ...> \n" + "\t-s <name> <type> \n" + "\t-n <name> \n\n" + " add\t\t" + "specify a record to be added\n" + "\t[-r] <name> [ttl] [class] <type> <data ...> \n\n" + " delete\t" + "specify a record, set, or all records at a name to be deleted\n" + "\t-r <name> [ttl] [class] <type> <data ...> \n" + "\t-s <name> <type> \n" + "\t-n <name> \n\n" + " glue\t" + "specify an additional record\n" + "\t[-r] <name> [ttl] [class] <type> <data ...> \n\n" + " (notes: @ represents the origin " + "and @me@ represents the local IP address)\n" ); } static void helpOperations() { System.out.println("Operations:\n" + " help [topic]\t" + "this information\n" + " echo <text>\t\t" + "echoes the line\n" + " send\t\t" + "sends the update and resets the current query\n" + " query <name> <type>\t" + "issues a query for this name and type\n" + " quit\t\t" + "quits the program\n" + " file <file>\t\t" + "opens the specified file as the new input source\n" + " log <file>\t\t" + "opens the specified file and uses it to log output\n" + " assert <field> <value> [msg]\n" + "\t\t\tasserts that the value of the field in the last response\n" + "\t\t\tmatches the value specified. If not, the message is\n" + "\t\t\tprinted (if present) and the program exits.\n" ); } static void help(String topic) { if (topic != null) { if (topic.equalsIgnoreCase("resolver")) helpResolver(); else if (topic.equalsIgnoreCase("attributes")) helpAttributes(); else if (topic.equalsIgnoreCase("data")) helpData(); else if (topic.equalsIgnoreCase("operations")) helpOperations(); else System.out.println ("Topic " + topic + " unrecognized"); return; } System.out.println("The help topics are:\n" + " Resolver\t" + "Properties of the resolver and DNS\n" + " Attributes\t" + "Properties of some/all records\n" + " Data\t" + "Prerequisites, updates, and additional records\n" + " Operations\t" + "Actions to be taken\n" ); } public static void main(String args[]) throws IOException { InputStream in = null; if (args.length == 1) { try { in = new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.out.println(args[0] + " not found."); System.exit(-1); } } else in = System.in; update u = new update(in); } }
package org.jetel.util; /** * Implementation of simple (standard) First In First Out (FIFO) queue * *@author dpavlis *@created 23. july 2003 */ public class Fifo { Object[] fifoArray; int fifoLength; int size; /** * Constructor for the Fifo object * *@param size Maximum length of the FIFO */ public Fifo(int size) { this.size = size; fifoArray = new Object[size]; fifoLength = 0; } /** * Adds item at the beginning of FIFO * *@param item Description of the Parameter */ public void add(Object item) { if (fifoLength < size) { copyArray(fifoArray, 0, 1, fifoLength); fifoArray[0] = item; fifoLength++; } else { throw new RuntimeException("Fifo is already full !"); } } /** * Gets the empty attribute of the Fifo object * *@return The empty value */ public boolean isEmpty() { return fifoLength == 0 ? true : false; } /** * gets the next element stored in the FIFO (in FIFO order) - the oldest one * *@return Description of the Return Value */ public Object get() { if (fifoLength > 0) { return fifoArray[--fifoLength]; } else { return null; } } /** removes all elements from the FIFO */ public void removeAll() { fifoLength = 0; } /** * performs array copy (within the same array). Regions can partially overlap. * *@param array Description of the Parameter *@param from Description of the Parameter *@param to Description of the Parameter *@param length Description of the Parameter */ private final void copyArray(Object[] array, int from, int to, int length) { System.arraycopy(array,from,array,to,length); //for (int i = length - 1; i >= 0; i--) { // array[to + i] = array[from + i]; } /** Prints the content of the FIFO to stdout */ public void dump() { for (int i = 0; i < fifoLength; i++) { System.out.println(fifoArray[i]); } } /* * public static void main(String[] args){ * Fifo fifo=new Fifo(10); * fifo.add("Ahoj"); * fifo.add("Nazdar"); * fifo.add("Cau"); * fifo.dump(); * System.out.println("Get: "+fifo.get()); * System.out.println("Get: "+fifo.get()); * fifo.add("TePic"); * fifo.dump(); * System.out.println("Get: "+fifo.get()); * fifo.dump(); * } */ }
// IdentitySet.java package ed.util; import java.util.*; public class IdentitySet<T> implements Iterable<T> { public boolean add( T t ){ return _map.put( t , "a" ) == null; } public boolean contains( T t ){ return _map.containsKey( t ); } public void remove( T t ){ _map.remove( t ); } public void removeall( Iterable<T> coll ){ for ( T t : coll ) _map.remove( t ); } public void clear(){ _map.clear(); } public int size(){ return _map.size(); } public Iterator<T> iterator(){ return _map.keySet().iterator(); } public void addAll( Collection<T> c ){ for ( T t : c ){ add( t ); } } public void addAll( IdentitySet<T> c ){ for ( T t : c ) add( t ); } final IdentityHashMap<T,String> _map = new IdentityHashMap<T,String>(); }
package apoc.coll; import org.apache.commons.math3.util.Combinations; import org.neo4j.graphdb.Path; import org.neo4j.helpers.collection.Pair; import org.neo4j.kernel.impl.util.statistics.IntCounter; import org.neo4j.procedure.*; import apoc.result.*; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.Arrays.asList; import static org.neo4j.helpers.collection.Pair.*; public class Coll { public static final char ASCENDING_ORDER_CHAR = '^'; @Context public GraphDatabaseService db; @Procedure @Description("apoc.coll.zipToRows(list1,list2) - creates pairs like zip but emits one row per pair") public Stream<ListResult> zipToRows(@Name("list1") List<Object> list1, @Name("list2") List<Object> list2) { if (list1.isEmpty()) return Stream.empty(); ListIterator<Object> it = list2.listIterator(); return list1.stream().map((e) -> new ListResult(asList(e,it.hasNext() ? it.next() : null))); } @UserFunction @Description("apoc.coll.zip([list1],[list2])") public List<List<Object>> zip(@Name("list1") List<Object> list1, @Name("list2") List<Object> list2) { if (list1 == null || list2 == null) return null; if (list1.isEmpty() || list2.isEmpty()) return Collections.emptyList(); List<List<Object>> result = new ArrayList<>(list1.size()); ListIterator it = list2.listIterator(); for (Object o1 : list1) { result.add(asList(o1,it.hasNext() ? it.next() : null)); } return result; } @UserFunction @Description("apoc.coll.pairs([1,2,3]) returns [1,2],[2,3],[3,null] ") public List<List<Object>> pairs(@Name("list") List<Object> list) { if (list == null) return null; if (list.isEmpty()) return Collections.emptyList(); return zip(list,list.subList(1,list.size())); } @UserFunction @Description("apoc.coll.pairsMin([1,2,3]) returns [1,2],[2,3]") public List<List<Object>> pairsMin(@Name("list") List<Object> list) { if (list == null) return null; if (list.isEmpty()) return Collections.emptyList(); return zip(list.subList(0,list.size()-1),list.subList(1,list.size())); } @UserFunction @Description("apoc.coll.sum([0.5,1,2.3])") public Double sum(@Name("numbers") List<Number> list) { if (list == null || list.isEmpty()) return null; double sum = 0; for (Number number : list) { sum += number.doubleValue(); } return sum; } @UserFunction @Description("apoc.coll.avg([0.5,1,2.3])") public Double avg(@Name("numbers") List<Number> list) { if (list == null || list.isEmpty()) return null; double avg = 0; for (Number number : list) { avg += number.doubleValue(); } return (avg/(double)list.size()); } @UserFunction @Description("apoc.coll.min([0.5,1,2.3])") public Object min(@Name("values") List<Object> list) { if (list == null || list.isEmpty()) return null; return Collections.min((List)list, Coll::compareAsDoubles); } @UserFunction @Description("apoc.coll.max([0.5,1,2.3])") public Object max(@Name("values") List<Object> list) { if (list == null || list.isEmpty()) return null; return Collections.max((List)list, Coll::compareAsDoubles); } private static int compareAsDoubles(Object a, Object b) { return Double.compare(((Number)a).doubleValue(), ((Number)b).doubleValue()); } @Procedure @Description("apoc.coll.elements(list,limit,offset) yield _1,_2,..,_10,_1s,_2i,_3f,_4m,_5l,_6n,_7r,_8p - deconstruct subset of mixed list into identifiers of the correct type") public Stream<ElementsResult> elements(@Name("values") List<Object> list, @Name(value = "limit",defaultValue = "-1") long limit,@Name(value = "offset",defaultValue = "0") long offset) { int elements = (limit < 0 ? list.size() : Math.min((int)(offset+limit),list.size())) - (int)offset; if (elements > ElementsResult.MAX_ELEMENTS) elements = ElementsResult.MAX_ELEMENTS; ElementsResult result = new ElementsResult(); for (int i=0;i<elements;i++) { result.add(list.get((int)offset+i)); } return Stream.of(result); } public static class ElementsResult { public Object _1,_2,_3,_4,_5,_6,_7,_8,_9,_10; public String _1s,_2s,_3s,_4s,_5s,_6s,_7s,_8s,_9s,_10s; public Long _1i,_2i,_3i,_4i,_5i,_6i,_7i,_8i,_9i,_10i; public Double _1f,_2f,_3f,_4f,_5f,_6f,_7f,_8f,_9f,_10f; public Boolean _1b,_2b,_3b,_4b,_5b,_6b,_7b,_8b,_9b,_10b; public List<Object> _1l,_2l,_3l,_4l,_5l,_6l,_7l,_8l,_9l,_10l; public Map<String,Object> _1m,_2m,_3m,_4m,_5m,_6m,_7m,_8m,_9m,_10m; public Node _1n,_2n,_3n,_4n,_5n,_6n,_7n,_8n,_9n,_10n; public Relationship _1r,_2r,_3r,_4r,_5r,_6r,_7r,_8r,_9r,_10r; public Path _1p,_2p,_3p,_4p,_5p,_6p,_7p,_8p,_9p,_10p; public long elements; static final int MAX_ELEMENTS = 10; void add(Object o) { if (elements==MAX_ELEMENTS) return; setObject(o, (int) elements); if (o instanceof String) { setString((String)o, (int) elements); } if (o instanceof Number) { setLong(((Number)o).longValue(), (int) elements); setDouble(((Number)o).doubleValue(), (int) elements); } if (o instanceof Boolean) { setBoolean((Boolean)o, (int) elements); } if (o instanceof Map) { setMap((Map)o, (int)elements); } if (o instanceof Map) { setMap((Map)o, (int)elements); } if (o instanceof List) { setList((List)o, (int)elements); } if (o instanceof Node) { setNode((Node)o, (int)elements); } if (o instanceof Relationship) { setRelationship((Relationship)o, (int)elements); } if (o instanceof Path) { setPath((Path)o, (int)elements); } elements++; } public void setObject(Object o, int idx) { switch (idx) { case 0: _1 = o; break; case 1: _2 = o; break; case 2: _3 = o; break; case 3: _4 = o; break; case 4: _5 = o; break; case 5: _6 = o; break; case 6: _7 = o; break; case 7: _8 = o; break; case 8: _9 = o; break; case 9: _10= o; break; } } public void setString(String o, int idx) { switch (idx) { case 0: _1s = o; break; case 1: _2s = o; break; case 2: _3s = o; break; case 3: _4s = o; break; case 4: _5s = o; break; case 5: _6s = o; break; case 6: _7s = o; break; case 7: _8s = o; break; case 8: _9s = o; break; case 9: _10s= o; break; } } public void setLong(Long o, int idx) { switch (idx) { case 0: _1i = o; break; case 1: _2i = o; break; case 2: _3i = o; break; case 3: _4i = o; break; case 4: _5i = o; break; case 5: _6i = o; break; case 6: _7i = o; break; case 7: _8i = o; break; case 8: _9i = o; break; case 9: _10i= o; break; } } public void setBoolean(Boolean o, int idx) { switch (idx) { case 0: _1b = o; break; case 1: _2b = o; break; case 2: _3b = o; break; case 3: _4b = o; break; case 4: _5b = o; break; case 5: _6b = o; break; case 6: _7b = o; break; case 7: _8b = o; break; case 8: _9b = o; break; case 9: _10b= o; break; } } public void setDouble(Double o, int idx) { switch (idx) { case 0: _1f = o; break; case 1: _2f = o; break; case 2: _3f = o; break; case 3: _4f = o; break; case 4: _5f = o; break; case 5: _6f = o; break; case 6: _7f = o; break; case 7: _8f = o; break; case 8: _9f = o; break; case 9: _10f= o; break; } } public void setNode(Node o, int idx) { switch (idx) { case 0: _1n = o; break; case 1: _2n = o; break; case 2: _3n = o; break; case 3: _4n = o; break; case 4: _5n = o; break; case 5: _6n = o; break; case 6: _7n = o; break; case 7: _8n = o; break; case 8: _9n = o; break; case 9: _10n= o; break; } } public void setRelationship(Relationship o, int idx) { switch (idx) { case 0: _1r = o; break; case 1: _2r = o; break; case 2: _3r = o; break; case 3: _4r = o; break; case 4: _5r = o; break; case 5: _6r = o; break; case 6: _7r = o; break; case 7: _8r = o; break; case 8: _9r = o; break; case 9: _10r= o; break; } } public void setPath(Path o, int idx) { switch (idx) { case 0: _1p = o; break; case 1: _2p = o; break; case 2: _3p = o; break; case 3: _4p = o; break; case 4: _5p = o; break; case 5: _6p = o; break; case 6: _7p = o; break; case 7: _8p = o; break; case 8: _9p = o; break; case 9: _10p= o; break; } } public void setMap(Map o, int idx) { switch (idx) { case 0: _1m = o; break; case 1: _2m = o; break; case 2: _3m = o; break; case 3: _4m = o; break; case 4: _5m = o; break; case 5: _6m = o; break; case 6: _7m = o; break; case 7: _8m = o; break; case 8: _9m = o; break; case 9: _10m= o; break; } } public void setList(List o, int idx) { switch (idx) { case 0: _1l = o; break; case 1: _2l = o; break; case 2: _3l = o; break; case 3: _4l = o; break; case 4: _5l = o; break; case 5: _6l = o; break; case 6: _7l = o; break; case 7: _8l = o; break; case 8: _9l = o; break; case 9: _10l= o; break; } } } @Procedure @Description("apoc.coll.partition(list,batchSize)") public Stream<ListResult> partition(@Name("values") List<Object> list, @Name("batchSize") long batchSize) { if (list==null || list.isEmpty()) return Stream.empty(); return partitionList(list, (int) batchSize).map(ListResult::new); } @Procedure @Description("apoc.coll.split(list,value) | splits collection on given values rows of lists, value itself will not be part of resulting lists") public Stream<ListResult> split(@Name("values") List<Object> list, @Name("value") Object value) { if (list==null || list.isEmpty()) return Stream.empty(); List<Object> l = new ArrayList<>(list); List<List<Object>> result = new ArrayList<>(10); int idx = l.indexOf(value); while (idx != -1) { List<Object> subList = l.subList(0, idx); if (!subList.isEmpty()) result.add(subList); l = l.subList(idx+1,l.size()); idx = l.indexOf(value); } if (!l.isEmpty()) result.add(l); return result.stream().map(ListResult::new); } private Stream<List<Object>> partitionList(@Name("values") List list, @Name("batchSize") int batchSize) { int total = list.size(); int pages = total % batchSize == 0 ? total/batchSize : total/batchSize + 1; return IntStream.range(0, pages).parallel().boxed() .map(page -> { int from = page * batchSize; return list.subList(from, Math.min(from + batchSize, total)); }); } @UserFunction @Description("apoc.coll.contains(coll, value) optimized contains operation (using a HashSet) (returns single row or not)") public boolean contains(@Name("coll") List<Object> coll, @Name("value") Object value) { if (coll == null || coll.isEmpty()) return false; return new HashSet<>(coll).contains(value); // int batchSize = 250; // boolean result = (coll.size() < batchSize) ? coll.contains(value) : partitionList(coll, batchSize).parallel().anyMatch(list -> list.contains(value)); } @UserFunction @Description("apoc.coll.set(coll, index, value) | set index to value") public List<Object> set(@Name("coll") List<Object> coll, @Name("index") long index, @Name("value") Object value) { if (coll == null) return null; if (index < 0 || value == null || index >= coll.size()) return coll; List<Object> list = new ArrayList<>(coll); list.set( (int) index, value ); return list; } @UserFunction @Description("apoc.coll.insert(coll, index, value) | insert value at index") public List<Object> insert(@Name("coll") List<Object> coll, @Name("index") long index, @Name("value") Object value) { if (coll == null) return null; if (index < 0 || value == null || index > coll.size()) return coll; List<Object> list = new ArrayList<>(coll); list.add( (int) index, value ); return list; } @UserFunction @Description("apoc.coll.insertAll(coll, index, values) | insert values at index") public List<Object> insertAll(@Name("coll") List<Object> coll, @Name("index") long index, @Name("values") List<Object> values) { if (coll == null) return null; if (index < 0 || values == null || values.isEmpty() || index > coll.size()) return coll; List<Object> list = new ArrayList<>(coll); list.addAll( (int) index, values ); return list; } @UserFunction @Description("apoc.coll.remove(coll, index, [length=1]) | remove range of values from index to length") public List<Object> remove(@Name("coll") List<Object> coll, @Name("index") long index, @Name(value = "length",defaultValue = "1") long length) { if (coll == null) return null; if (index < 0 || index >= coll.size() || length <= 0) return coll; List<Object> list = new ArrayList<>(coll); for (long i = index+length-1; i >= index; i { if (i < list.size()) list.remove( (int) i ); } return list; } @UserFunction @Description("apoc.coll.indexOf(coll, value) | position of value in the list") public long indexOf(@Name("coll") List<Object> coll, @Name("value") Object value) { if (coll == null || coll.isEmpty()) return -1; return new ArrayList<>(coll).indexOf(value); } @UserFunction @Description("apoc.coll.containsAll(coll, values) optimized contains-all operation (using a HashSet) (returns single row or not)") public boolean containsAll(@Name("coll") List<Object> coll, @Name("values") List<Object> values) { if (coll == null || coll.isEmpty()) return false; return new HashSet<>(coll).containsAll(values); } @UserFunction @Description("apoc.coll.containsSorted(coll, value) optimized contains on a sorted list operation (Collections.binarySearch) (returns single row or not)") public boolean containsSorted(@Name("coll") List<Object> coll, @Name("value") Object value) { if (coll == null || coll.isEmpty()) return false; int batchSize = 5000-1; // Collections.binarySearchThreshold List list = (coll instanceof RandomAccess || coll.size() < batchSize) ? coll : new ArrayList(coll); return Collections.binarySearch(list, value) >= 0; // Predicate<List> contains = l -> Collections.binarySearch(l, value) >= 0; // boolean result = (list.size() < batchSize) ? contains.test(list) : partitionList(list, batchSize).parallel().anyMatch(contains); } @UserFunction @Description("apoc.coll.containsAllSorted(coll, value) optimized contains-all on a sorted list operation (Collections.binarySearch) (returns single row or not)") public boolean containsAllSorted(@Name("coll") List<Object> coll, @Name("values") List<Object> values) { if (coll == null || values == null) return false; int batchSize = 5000-1; // Collections.binarySearchThreshold List list = (coll instanceof RandomAccess || coll.size() < batchSize) ? coll : new ArrayList(coll); for (Object value : values) { boolean result = Collections.binarySearch(list, value) >= 0; if (!result) return false; } return true; } @UserFunction @Description("apoc.coll.toSet([list]) returns a unique list backed by a set") public List<Object> toSet(@Name("values") List<Object> list) { if (list == null) return null; return new SetBackedList(new LinkedHashSet(list)); } @UserFunction @Description("apoc.coll.sumLongs([1,3,3])") public Long sumLongs(@Name("numbers") List<Number> list) { if (list == null) return null; long sum = 0; for (Number number : list) { sum += number.longValue(); } return sum; } @UserFunction @Description("apoc.coll.sort(coll) sort on Collections") public List<Object> sort(@Name("coll") List<Object> coll) { if (coll == null || coll.isEmpty()) return Collections.emptyList(); List sorted = new ArrayList<>(coll); Collections.sort((List<? extends Comparable>) sorted); return sorted; } @UserFunction @Description("apoc.coll.sortNodes([nodes], 'name') sort nodes by property") public List<Node> sortNodes(@Name("coll") List<Node> coll, @Name("prop") String prop) { if (coll == null || coll.isEmpty()) return Collections.emptyList(); List<Node> sorted = new ArrayList<>(coll); int reverseOrder = reverseOrder(prop); String cleanedProp = cleanProperty(prop); Collections.sort(sorted, (x, y) -> reverseOrder * compare(x.getProperty(cleanedProp, null), y.getProperty(cleanedProp, null))); return sorted; } @UserFunction @Description("apoc.coll.sortMaps([maps], 'name') - sort maps by property") public List<Map<String,Object>> sortMaps(@Name("coll") List<Map<String,Object>> coll, @Name("prop") String prop) { if (coll == null || coll.isEmpty()) return Collections.emptyList(); List<Map<String,Object>> sorted = new ArrayList<>(coll); int reverseOrder = reverseOrder(prop); String cleanedProp = cleanProperty(prop); Collections.sort(sorted, (x, y) -> reverseOrder * compare(x.get(cleanedProp), y.get(cleanedProp))); return sorted; } public int reverseOrder(String prop) { return prop.charAt(0) == ASCENDING_ORDER_CHAR ? 1 : -1; } public String cleanProperty(String prop) { return prop.charAt(0) == ASCENDING_ORDER_CHAR ? prop.substring(1) : prop; } public static int compare(Object o1, Object o2) { if (o1 == null) return o2 == null ? 0 : -1; if (o2 == null) return 1; if (o1.equals(o2)) return 0; if (o1 instanceof Number && o2 instanceof Number) { if (o1 instanceof Double || o2 instanceof Double || o1 instanceof Float || o2 instanceof Float) return Double.compare(((Number) o1).doubleValue(), ((Number) o2).doubleValue()); return Long.compare(((Number) o1).longValue(), ((Number) o2).longValue()); } if (o1 instanceof Boolean && o2 instanceof Boolean) return ((Boolean) o1) ? 1 : -1; if (o1 instanceof Node && o2 instanceof Node) return Long.compare(((Node)o1).getId(),((Node)o2).getId()); if (o1 instanceof Relationship && o2 instanceof Relationship) return Long.compare(((Relationship)o1).getId(),((Relationship)o2).getId()); return o1.toString().compareTo(o2.toString()); } @UserFunction @Description("apoc.coll.union(first, second) - creates the distinct union of the 2 lists") public List<Object> union(@Name("first") List<Object> first, @Name("second") List<Object> second) { if (first == null) return second; if (second == null) return first; Set<Object> set = new HashSet<>(first); set.addAll(second); return new SetBackedList(set); } @UserFunction @Description("apoc.coll.subtract(first, second) - returns unique set of first list with all elements of second list removed") public List<Object> subtract(@Name("first") List<Object> first, @Name("second") List<Object> second) { if (first == null) return null; Set<Object> set = new HashSet<>(first); if (second!=null) set.removeAll(second); return new SetBackedList(set); } @UserFunction @Description("apoc.coll.removeAll(first, second) - returns first list with all elements of second list removed") public List<Object> removeAll(@Name("first") List<Object> first, @Name("second") List<Object> second) { if (first == null) return null; List<Object> list = new ArrayList<>(first); if (second!=null) list.removeAll(second); return list; } @UserFunction @Description("apoc.coll.intersection(first, second) - returns the unique intersection of the two lists") public List<Object> intersection(@Name("first") List<Object> first, @Name("second") List<Object> second) { if (first == null || second == null) return Collections.emptyList(); Set<Object> set = new HashSet<>(first); set.retainAll(second); return new SetBackedList(set); } @UserFunction @Description("apoc.coll.disjunction(first, second) - returns the disjunct set of the two lists") public List<Object> disjunction(@Name("first") List<Object> first, @Name("second") List<Object> second) { if (first == null) return second; if (second == null) return first; Set<Object> intersection = new HashSet<>(first); intersection.retainAll(second); Set<Object> set = new HashSet<>(first); set.addAll(second); set.removeAll(intersection); return new SetBackedList(set); } @UserFunction @Description("apoc.coll.unionAll(first, second) - creates the full union with duplicates of the two lists") public List<Object> unionAll(@Name("first") List<Object> first, @Name("second") List<Object> second) { if (first == null) return second; if (second == null) return first; List<Object> list = new ArrayList<>(first); list.addAll(second); return list; } @UserFunction @Description("apoc.coll.shuffle(coll) - returns the shuffled list") public List<Object> shuffle(@Name("coll") List<Object> coll) { if (coll == null || coll.isEmpty()) { return Collections.emptyList(); } else if (coll.size() == 1) { return coll; } List<Object> shuffledList = new ArrayList<>(coll); Collections.shuffle(shuffledList); return shuffledList; } @UserFunction @Description("apoc.coll.randomItem(coll)- returns a random item from the list, or null on an empty or null list") public Object randomItem(@Name("coll") List<Object> coll) { if (coll == null || coll.isEmpty()) { return null; } else if (coll.size() == 1) { return coll.get(0); } return coll.get(ThreadLocalRandom.current().nextInt(coll.size())); } @UserFunction @Description("apoc.coll.randomItems(coll, itemCount, allowRepick: false) - returns a list of itemCount random items from the original list, optionally allowing picked elements to be picked again") public List<Object> randomItems(@Name("coll") List<Object> coll, @Name("itemCount") long itemCount, @Name(value = "allowRepick", defaultValue = "false") boolean allowRepick) { if (coll == null || coll.isEmpty() || itemCount <= 0) { return Collections.emptyList(); } List<Object> pickList = new ArrayList<>(coll); List<Object> randomItems = new ArrayList<>((int)itemCount); Random random = ThreadLocalRandom.current(); if (!allowRepick && itemCount >= coll.size()) { Collections.shuffle(pickList); return pickList; } while (randomItems.size() < itemCount) { Object item = allowRepick ? pickList.get(random.nextInt(pickList.size())) : pickList.remove(random.nextInt(pickList.size())); randomItems.add(item); } return randomItems; } @UserFunction @Description("apoc.coll.containsDuplicates(coll) - returns true if a collection contains duplicate elements") public boolean containsDuplicates(@Name("coll") List<Object> coll) { if (coll == null || coll.size() <= 1) { return false; } Set<Object> set = new HashSet<>(coll); return set.size() < coll.size(); } @UserFunction @Description("apoc.coll.duplicates(coll) - returns a list of duplicate items in the collection") public List<Object> duplicates(@Name("coll") List<Object> coll) { if (coll == null || coll.size() <= 1) { return Collections.emptyList(); } Set<Object> set = new HashSet<>(coll.size()); Set<Object> duplicates = new LinkedHashSet<>(); for (Object obj : coll) { if (!set.add(obj)) { duplicates.add(obj); } } return new ArrayList(duplicates); } @UserFunction @Description("apoc.coll.duplicatesWithCount(coll) - returns a list of duplicate items in the collection and their count, keyed by `item` and `count` (e.g., `[{item: xyz, count:2}, {item:zyx, count:5}]`)") public List<Map<String, Object>> duplicatesWithCount(@Name("coll") List<Object> coll) { if (coll == null || coll.size() <= 1) { return Collections.emptyList(); } // mimicking a counted bag Map<Object, IntCounter> duplicates = new LinkedHashMap<>(coll.size()); List<Map<String, Object>> resultList = new ArrayList<>(); for (Object obj : coll) { IntCounter counter = duplicates.get(obj); if (counter == null) { counter = new IntCounter(); duplicates.put(obj, counter); } counter.increment(); } duplicates.forEach((o, intCounter) -> { int count = intCounter.value(); if (count > 1) { Map<String, Object> entry = new LinkedHashMap<>(2); entry.put("item", o); entry.put("count", Long.valueOf(count)); resultList.add(entry); } }); return resultList; } @UserFunction @Description("apoc.coll.frequencies(coll) - returns a list of frequencies of the items in the collection, keyed by `item` and `count` (e.g., `[{item: xyz, count:2}, {item:zyx, count:5}, {item:abc, count:1}]`)") public List<Map<String, Object>> frequencies(@Name("coll") List<Object> coll) { if (coll == null || coll.size() == 0) { return Collections.emptyList(); } // mimicking a counted bag Map<Object, IntCounter> counts = new LinkedHashMap<>(coll.size()); List<Map<String, Object>> resultList = new ArrayList<>(); for (Object obj : coll) { IntCounter counter = counts.get(obj); if (counter == null) { counter = new IntCounter(); counts.put(obj, counter); } counter.increment(); } counts.forEach((o, intCounter) -> { int count = intCounter.value(); Map<String, Object> entry = new LinkedHashMap<>(2); entry.put("item", o); entry.put("count", Long.valueOf(count)); resultList.add(entry); }); return resultList; } @UserFunction @Description("apoc.coll.frequenciesAsMap(coll) - return a map of frequencies of the items in the collection, key `item`, value `count` (e.g., `{1:2, 2:1}`)") public Map<String, Object> frequenciesAsMap(@Name("coll") List<Object> coll) { if (coll == null) return Collections.emptyMap(); return frequencies(coll).stream().collect(Collectors.toMap(t -> t.get("item").toString(), v-> v.get("count"))); } @UserFunction @Description("apoc.coll.occurrences(coll, item) - returns the count of the given item in the collection") public long occurrences(@Name("coll") List<Object> coll, @Name("item") Object item) { if (coll == null || coll.isEmpty()) { return 0; } long occurrences = 0; for (Object obj : coll) { if (item.equals(obj)) { occurrences++; } } return occurrences; } @UserFunction @Description("apoc.coll.flatten(coll) - flattens nested list") public List<Object> flatten(@Name("coll") List<List<Object>> coll) { if (coll == null) return Collections.emptyList(); return coll.stream().flatMap(Collection::stream).collect(Collectors.toList()); } @Deprecated @UserFunction @Description("apoc.coll.reverse(coll) - returns reversed list") public List<Object> reverse(@Name("coll") List<Object> coll) { if (coll == null || coll.isEmpty()) { return Collections.emptyList(); } else if (coll.size() == 1) { return coll; } List<Object> reversed = new ArrayList<Object>(coll); Collections.reverse(reversed); return reversed; } @UserFunction("apoc.coll.sortMulti") @Description("apoc.coll.sortMulti(coll, ['^name','age'],[limit],[skip]) - sort list of maps by several sort fields (ascending with ^ prefix) and optionally applies limit and skip") public List<Map<String,Object>> sortMulti(@Name("coll") java.util.List<Map<String,Object>> coll, @Name(value="orderFields", defaultValue = "[]") java.util.List<String> orderFields, @Name(value="limit", defaultValue = "-1") long limit, @Name(value="skip", defaultValue = "0") long skip) { List<Map<String,Object>> result = new ArrayList<>(coll); if (orderFields != null && !orderFields.isEmpty()) { List<Pair<String, Boolean>> fields = orderFields.stream().map(v -> { boolean asc = v.charAt(0) == '^'; return of(asc ? v.substring(1) : v, asc); }).collect(Collectors.toList()); Comparator<Map<String, Comparable<Object>>> compare = (o1, o2) -> { int a = 0; for (Pair<String, Boolean> s : fields) { if (a != 0) break; String name = s.first(); Comparable<Object> v1 = o1.get(name); Comparable<Object> v2 = o2.get(name); if (v1 != v2) { int cmp = (v1 == null) ? -1 : (v2 == null) ? 1 : v1.compareTo(v2); a = (s.other()) ? cmp : -cmp; } } return a; }; Collections.sort((List<Map<String, Comparable<Object>>>) (List) result, compare); } if (skip > 0 && limit != -1L) return result.subList ((int)skip, (int)(skip + limit)); if (skip > 0) return result.subList ((int)skip, result.size()); if (limit != -1L) return result.subList (0, (int)limit); return result; } @UserFunction @Description("apoc.coll.combinations(coll, minSelect, maxSelect:minSelect) - Returns collection of all combinations of list elements of selection size between minSelect and maxSelect (default:minSelect), inclusive") public List<List<Object>> combinations(@Name("coll") List<Object> coll, @Name(value="minSelect") long minSelectIn, @Name(value="maxSelect",defaultValue = "-1") long maxSelectIn) { int minSelect = (int) minSelectIn; int maxSelect = (int) maxSelectIn; maxSelect = maxSelect == -1 ? minSelect : maxSelect; if (coll == null || coll.isEmpty() || minSelect < 1 || minSelect > coll.size() || minSelect > maxSelect || maxSelect > coll.size()) { return Collections.emptyList(); } List<List<Object>> combinations = new ArrayList<>(); for (int i = minSelect; i <= maxSelect; i++) { Iterator<int[]> itr = new Combinations(coll.size(), i).iterator(); while (itr.hasNext()) { List<Object> entry = new ArrayList<>(i); int[] indexes = itr.next(); if (indexes.length > 0) { for (int index : indexes) { entry.add(coll.get(index)); } combinations.add(entry); } } } return combinations; } @UserFunction @Description("apoc.coll.different(values) - returns true if values are different") public boolean different(@Name("values") List<Object> values) { if (values == null) return false; return new HashSet(values).size() == values.size(); } }
package bdv.ui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Rectangle; import java.util.WeakHashMap; import javax.swing.UIManager; import com.formdev.flatlaf.util.UIScale; /** * AWT/Swing helpers. * * @author Tobias Pietzsch */ public final class UIUtils { /** * Mix colors {@code c1} and {@code c2} by ratios {@code c1Weight} and {@code (1-c1Weight)}, respectively. */ public static Color mix( final Color c1, final Color c2, final double c1Weight ) { final double c2Weight = 1.0 - c1Weight; return new Color( ( int ) ( c1.getRed() * c1Weight + c2.getRed() * c2Weight ), ( int ) ( c1.getGreen() * c1Weight + c2.getGreen() * c2Weight ), ( int ) ( c1.getBlue() * c1Weight + c2.getBlue() * c2Weight ) ); } /** * Set the preferred width of a component (leaving the preferred height untouched). */ public static void setPreferredWidth( final Component component, final int preferredWidth ) { component.setPreferredSize( new Dimension( preferredWidth, component.getPreferredSize().height ) ); } /** * Set the preferred height of a component (leaving the preferred width untouched). */ public static void setPreferredHeight( final Component component, final int preferredHeight ) { component.setPreferredSize( new Dimension( component.getPreferredSize().width, preferredHeight ) ); } /** * Set the minimum width of a component (leaving the minimum height untouched). */ public static void setMinimumWidth( final Component component, final int minimumWidth ) { component.setMinimumSize( new Dimension( minimumWidth, component.getMinimumSize().height ) ); } /** * Set the minimum height of a component (leaving the minimum width untouched). */ public static void setMinimumHeight( final Component component, final int minimumHeight ) { component.setMinimumSize( new Dimension( component.getMinimumSize().width, minimumHeight ) ); } public enum TextPosition { TOP_CENTER, TOP_RIGHT } public static void drawString( final Graphics g, final TextPosition textPosition, final int line, final String text ) { final Object key = UIUtils.class; final double uiScale = UIUtils.getUIScaleFactor( key ); final FontMetrics fontMetrics = g.getFontMetrics(); final Rectangle clipBounds = g.getClipBounds(); final int spacing = fontMetrics.getHeight(); final int textWidth = fontMetrics.stringWidth( text ); final int posX; switch ( textPosition ) { case TOP_CENTER: posX = ( int ) ( ( clipBounds.getWidth() - textWidth ) / 2 ); break; default: case TOP_RIGHT: posX = ( int ) ( clipBounds.getWidth() - textWidth - uiScale * 17 ); break; } final int posY = ( line + 1 ) * spacing - 1; g.drawString( text, posX, posY ); } /** * cache UI scale factors */ private static final WeakHashMap< Object, Double > uiScaleFactors = new WeakHashMap<>(); /** * Get an approximate UI scaling factor. * * TODO UI scaling depends on the LAF and there is no straight forward way * to get a consistent scaling factor that works on all platforms. * However, some LAFs have implemented their own strategy to estimate * this scaling factor and adjust font sizes and element heights * accordingly. We therefore use the default font size compared to a * hypothesized 'normal' font size of 12 as a surrogate for the UI * scaling factor. This is not great. * * @return approximate UI scaling factor */ public static double getUIScaleFactor( final Object key ) { return uiScaleFactors.computeIfAbsent( key, k -> ( double ) UIScale.getUserScaleFactor() ); } private static int getFontSize( final Font referenceFont, final String category ) { final double uiScale = getUIScaleFactor( Runtime.getRuntime() ); final int referenceFontSize = referenceFont.getSize(); switch (category) { case "mini": return ( int )Math.round( referenceFontSize - 3 * uiScale ); case "small": return ( int )Math.round( referenceFontSize - 2 * uiScale ); case "medium": return ( int )Math.round( referenceFontSize - uiScale ); case "large": return ( int )Math.round( referenceFontSize + 2 * uiScale ); default: return referenceFontSize; } } public static Font getFont( final String key ) { Font font = UIManager.getFont( key ); /* all this bruhaha is for the legacy LAFs that do not have user friendly font definitions */ if ( font == null ) { final Font defaultFont = UIManager.getFont("Label.font"); final int fontSize; if (key.contains("mini")) fontSize = getFontSize(defaultFont, "mini"); else if (key.contains("small")) fontSize = getFontSize(defaultFont, "small"); else if (key.contains("medium")) fontSize = getFontSize(defaultFont, "medium"); else if (key.contains("large")) fontSize = getFontSize(defaultFont, "large"); else fontSize = defaultFont.getSize(); final String fontName; if (key.contains("monospace") || key.contains("Monospace")) fontName = Font.MONOSPACED; else fontName = defaultFont.getName(); final int fontStyle; if (key.contains("bold")) fontStyle = Font.BOLD; else fontStyle = defaultFont.getStyle(); font = new Font(fontName, fontStyle, fontSize); } return font; } /** * Resets the caches for {@link #getUIScaleFactor}. */ public static void reset() { uiScaleFactors.clear(); } /** * Tell if the LAF color specified for the provided key is darker than 50% * gray. If the property is undefined, it is considered not dark. * * E.g. isDark( "Panel.background" ) is often a good indicator that an LAF * is dark/ inverse. * * @return true for dark colors */ public static boolean isDark( final String key ) { final Color bg = UIManager.getColor( key ); if ( bg == null ) return false; else return ( bg.getRed() + bg.getGreen() + bg.getBlue() ) / 3.0 < 127; } /** * Get boolean property with the specified {@code key} from the swing {@link UIManager}. * If the property is not set, return {@code defaultValue} instead. */ public static boolean getUIBoolean( final String key, final boolean defaultValue ) { final Object value = UIManager.get( key ); if ( value instanceof Boolean ) return ( Boolean ) value; else return defaultValue; } }
package common; import org.jgrapht.UndirectedGraph; import org.jgrapht.alg.NeighborIndex; import org.jgrapht.graph.DefaultEdge; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; /** * Represents a generic map in the game Use the JGraphT library to represent the * game map structure in terms of an undirected graph */ public class GameMap { // The map's associated graph private final UndirectedGraph<Sector, DefaultEdge> graph; // A searchable version of the map's associated graph private final NeighborIndex<Sector, DefaultEdge> searchableGraph; // The human starting sector private final Sector humanSector; // The alien starting sector private final Sector alienSector; // The horizontal span of the map private final int horizontalLength; // The vertical span of the map private final int verticalLength; // The starting horizontal coordinate private final int startingHorizontalCoord; // The starting vertical coordinate private final int startingVerticalCoord; // The map's name private final String name; // The rescue sectors of the map private final List<Sector> escapes; /** * Constructs a generic map in the game from an undirected graph, from * informations about its table like representation and from its name. A * searchable version of the undirected graph given is created and * references to the map's alien sectors and human sectors are saved. * * @param graph the graph associated with the map * @param startingHorizontalCoord considering a table like representation of the map, the map's * starting horizontal coordinate * @param startingVerticalCoord considering a table like representation of the map, the map's * starting vertical coordinate of the map * @param horizontalLength considering a table like representation of the map, the map's * number of columns * @param verticalLength considering a table like representation of the map, the map's * number of rows * @param name the map's name */ public GameMap(UndirectedGraph<Sector, DefaultEdge> graph, int startingHorizontalCoord, int startingVerticalCoord, int horizontalLength, int verticalLength, String name) { this.name = name; this.graph = graph; this.searchableGraph = new NeighborIndex<>( this.graph); this.startingHorizontalCoord = startingHorizontalCoord; this.startingVerticalCoord = startingVerticalCoord; this.horizontalLength = horizontalLength; this.verticalLength = verticalLength; this.humanSector = this.getSectorByType(SectorType.HUMAN); this.alienSector = this.getSectorByType(SectorType.ALIEN); this.escapes = this.findEscapes(); } /** * Gets the map's name * * @return the map's name */ public String getName() { return name; } /** * Considering a table like representation of the map, gets the map's * starting horizontal coordinate * * @return the map's starting horizontal coordinate */ public int getStartingHorizontalCoord() { return startingHorizontalCoord; } /** * Considering a table like representation of the map, gets the map's * starting vertical coordinate * * @return the map's starting vertical coordinate */ public int getStartingVerticalCoord() { return startingVerticalCoord; } /** * Considering a table like representation of the map, gets the map's number * of rows * * @return the map's number of rows */ public int getVerticalLength() { return verticalLength; } /** * Considering a table like representation of the map, gets the map's number * of columns * * @return the map's number of columns */ public int getHorizontalLength() { return horizontalLength; } /** * @return A reference to the graph data structure, used for testing * purposes */ public UndirectedGraph<Sector, DefaultEdge> getGraph() { return this.graph; } /** * Gets the map's searchable graph * * @return the map's searchable graph */ public NeighborIndex<Sector, DefaultEdge> getSearchableGraph() { return searchableGraph; } /** * Gets the map's human sector * * @return Gets the map's human sector */ public Sector getHumanSector() { return humanSector; } /** * Gets the map's alien sector * * @return Gets the map's alien sector */ public Sector getAlienSector() { return alienSector; } /** * Gets a map's sector from a given coordinate * * @param coordinate the coordinate of the sector to be returned * @return the map's sector whose coordinate is the one specified */ public Sector getSectorByCoords(Coordinate coordinate) throws NoSuchElementException { /* * Get list of sectors in the graph and scans this list in order to find * the correct sector if the sector doesn't exist returns null */ Set<Sector> sectors = this.graph.vertexSet(); for (Sector s : sectors) { if (s.getCoordinate().equals(coordinate)) { return s; } } return null; } /** * Gets the first map's sector that matches a given sector type * * @param sectorType the type of sector, whose first occurrence in the map we want * to return * @return the first map's sector that matches the given sector type */ public Sector getSectorByType(SectorType sectorType) { /* * Get list of sectors in the graph and scans this list in order to find * the correct sector if the sector doesn't exist returns null */ Set<Sector> sectors = this.graph.vertexSet(); for (Sector s : sectors) { if (s.getSectorType() == sectorType) { return s; } } return null; } /** * Checks if a given sector is reachable from another given sector within, or exactly with, a certain distance * * @param sourceSector The starting sector * @param targetSector The sector whose adjacency we want to check w.r.t a given starting sector * @param maxDistance The distance within which the given target sector must be reachable from the given source sector * @param forceMaxMovement A flag that forces the algorythm to check sector reachable with exactly the given distance * @return True if the reachability is verified with success, otherwise false */ public boolean checkSectorAdiacency(Sector sourceSector, Sector targetSector, int maxDistance, boolean forceMaxMovement) { if (targetSector.getSectorType() == SectorType.CLOSED_RESCUE){ return false; } List<List<Sector>> visitedSectors = new ArrayList<>(); List<Sector> neighbors = this.searchableGraph.neighborListOf(sourceSector); visitedSectors.add(neighbors); for (int i = 1; i < maxDistance; i++) { visitedSectors.add(new ArrayList<Sector>()); for (Sector sector : visitedSectors.get(i - 1)) { neighbors = this.searchableGraph.neighborListOf(sector); for (Sector neighbor : neighbors) { if (!neighbor.isHasBeenChecked()) { visitedSectors.get(i).add(neighbor); } } } } for (List<Sector> sectorList : visitedSectors) { for (Sector sector : sectorList) { sector.setHasBeenChecked(false); } } if (forceMaxMovement) { for (Sector sector : visitedSectors.get(maxDistance - 1)) { if (sector.equals(targetSector)) { return true; } } } else { for (List<Sector> sectorList : visitedSectors) { for (Sector sector : sectorList) { if (sector.equals(targetSector)) { return true; } } } } return false; } /** * Find the rescue sector in the map * * @return A list of the rescue sector of the map */ private List<Sector> findEscapes() { List<Sector> toReturn = new ArrayList<>(); Set<Sector> sectors = this.graph.vertexSet(); for (Sector s : sectors) { if (s.getSectorType() == SectorType.OPEN_RESCUE || s.getSectorType() == SectorType.CLOSED_RESCUE) { toReturn.add(s); } } return toReturn; } /** * @return True if there is still an escape for the human players */ public boolean existEscapes() { for (Sector s : escapes) { if (s.getSectorType() == SectorType.OPEN_RESCUE) return true; } return false; } }
package dano; import java.util.ArrayList; import java.util.List; public class RadixTrie<T> { private static final char NUL = '\0'; private final char first; private final Node<T> root; public RadixTrie(final char first, final Node<T> root) { this.first = first; this.root = root; } public T lookup(final CharSequence s) { final char c = s.length() == 0 ? NUL : s.charAt(0); if (c != first) { return null; } return root.lookup(s, 1); } public static <T> Builder<T> builder(final Class<T> clazz) { return new Builder<T>(); } public static class Node<T> { private final char[] tail; private final char head1; private final char head2; private final Node<T> edge1; private final Node<T> edge2; private final char[] heads; private final Node<T>[] edges; private final char captureHead; private final Node<T> capture; private final T value; public Node(final String prefix, final char captureHead, final Node<T> capture, final List<Character> first, final List<Node<T>> edges, final T value) { this.tail = (prefix.length() > 1) ? prefix.substring(1).toCharArray() : null; this.captureHead = captureHead; this.capture = capture; this.edge1 = edges.size() > 0 ? edges.get(0) : null; this.edge2 = edges.size() > 1 ? edges.get(1) : null; this.head1 = (edge1 == null ? NUL : first.get(0)); this.head2 = (edge2 == null ? NUL : first.get(1)); this.edges = edges.size() > 2 ? toArray(edges.subList(2, edges.size())) : null; if (this.edges != null) { this.heads = new char[this.edges.length]; for (int i = 0; i < this.edges.length; i++) { this.heads[i] = first.get(i + 2); } } else { this.heads = null; } this.value = value; } @SuppressWarnings("unchecked") private static <T> RadixTrie.Node<T>[] toArray(final List<RadixTrie.Node<T>> edges) { return edges.toArray((RadixTrie.Node<T>[]) new RadixTrie.Node[edges.size()]); } public T lookup(final CharSequence s, final int index) { final int next = match(s, index); if (next == -1) { return null; } assert next >= index; if (next == s.length()) { return value; } final char c = s.charAt(next); final T value = descend(c, s, next); if (value != null) { return value; } return capture(s, next); } private int match(final CharSequence s, final int index) { if (index > s.length()) { return -1; } if (tail == null) { return index; } if (index + tail.length > s.length()) { return -1; } for (int i = 0; i < tail.length; i++) { if (tail[i] != s.charAt(index + i)) { return -1; } } return index + tail.length; } private T capture(final CharSequence s, final int index) { if (capture == null) { return null; } final int limit = seek(s, index, '/'); for (int i = limit; i >= index; i final int next; if (captureHead == NUL) { next = i; } else { if (i >= s.length()) { continue; } final char c = s.charAt(i); if (captureHead != c) { continue; } else { next = i + 1; } } final T value = capture.lookup(s, next); if (value != null) { return value; } } return null; } private T descend(final char c, final CharSequence s, final int next) { if (edge1 != null && head1 == c) { final T value = edge1.lookup(s, next + 1); if (value != null) { return value; } } if (edge2 != null && head2 == c) { final T value = edge2.lookup(s, next + 1); if (value != null) { return value; } } if (edges != null) { for (int i = 0; i < edges.length; i++) { if (heads[i] != c) { continue; } final Node<T> edge = edges[i]; final T value = edge.lookup(s, next + 1); if (value != null) { return value; } } } return null; } private int seek(final CharSequence s, final int start, final char c) { int i = start; for (; i < s.length(); i++) { if (s.charAt(i) == c) { return i; } } return i; } @Override public String toString() { return "Node{'" + (tail == null ? "" : new String(tail)) + "\':" + ", d=" + degree() + ", e=" + edgesToString() + ", c=" + (capture == null ? "" : captureHead == NUL ? "" : "'" + captureHead + "'") + ", v=" + value + '}'; } private int degree() { return ((capture == null ? 0 : 1) + (edge1 == null ? 0 : 1) + (edge2 == null ? 0 : 1) + (edges == null ? 0 : edges.length)); } private String edgesToString() { final List<Character> chars = new ArrayList<Character>(); if (edge1 != null) { chars.add(head1); } if (edge2 != null) { chars.add(head2); } if (heads != null) { for (final char head : heads) { chars.add(head); } } return chars.toString(); } } @Override public String toString() { return "RadixTrie{" + "root=" + root + '}'; } public static class Builder<T> { private final Trie<T> trie = new Trie<T>(); public Builder<T> insert(final CharSequence path, final T value) { trie.insert(path, value); return this; } public RadixTrie<T> build() { return trie.compress(); } } }
package ee.shy.io; import com.google.gson.*; import com.google.gson.stream.JsonWriter; import ee.shy.storage.Hash; import java.io.*; import java.lang.reflect.Type; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; /** * Class providing general JSON serialization/deserialization via gson. */ public class Json { /** * gson object used for all operations. */ private static final Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(Hash.class, new HashBiserializer()) .registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeBiserializer()) .create(); /** * Writes an object to an output stream as JSON. * @param os output stream to write to * @param object object to write * @throws IOException if there was a problem writing to the output stream */ public static void write(OutputStream os, Object object) throws IOException { try (Writer writer = new OutputStreamWriter(os, "UTF-8")) { JsonWriter jsonWriter = gson.newJsonWriter(writer); jsonWriter.setIndent(" "); gson.toJson(object, object.getClass(), jsonWriter); } } /** * Reads an object from an input stream as JSON. * @param is input stream to read from * @param classofT class of object to read * @param <T> type of readable object * @return object read * @throws IOException if there was a problem reading from the input stream */ public static <T> T read(InputStream is, Class<T> classofT) throws IOException { try (Reader reader = new InputStreamReader(is, "UTF-8")) { return gson.fromJson(reader, classofT); } } /** * Serializer and deserializer for {@link Hash} objects. */ private static class HashBiserializer implements JsonBiserializer<Hash> { @Override public JsonElement serialize(Hash hash, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(hash.toString()); } @Override public Hash deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return new Hash(jsonElement.getAsString()); } } /** * Serializer and deserializer for {@link OffsetDateTime} objects in ISO 8601 format. */ private static class OffsetDateTimeBiserializer implements JsonBiserializer<OffsetDateTime> { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME; @Override public JsonElement serialize(OffsetDateTime offsetDateTime, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(offsetDateTime.toString()); } @Override public OffsetDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return FORMATTER.parse(jsonElement.getAsString(), OffsetDateTime::from); } } }
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import javax.swing.JFrame; import ca.sfu.cmpt431.facility.*; import ca.sfu.cmpt431.message.*; import ca.sfu.cmpt431.message.join.*; import ca.sfu.cmpt431.message.regular.*; import ca.sfu.message.AutomataMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private MessageSender Sender1; private MessageSender Sender2; private String client1_ip; private String client2_ip; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { JFrame frame = new JFrame(); frame.setSize(480, 480); //AutomataMsg auto = new AutomataMsg(10, 10); Board b = new Board(10, 10); BoardOperation.Randomize(b,20); AutomataPanel panel = new AutomataPanel(); panel.setBoard(b); frame.setContentPane(panel); frame.setVisible(true); System.out.println("UI"); MessageWithIp m; while(true) { if(!Receiver.isEmpty()) { System.out.println(status); m = Receiver.getNextMessageWithIp(); switch(status) { //waiting for first client case 0: handleNewAdding(m,1); handlePending(); status = 1; break; //waiting for confirm from first client //send it the outfit case 1: if(handleNewAdding(m,1)) //!every status, handle an unexpected new adding message first break; // if it is a new adding request, go to status 1 to wait the confirm msg again handleConfirm(m,2); //expect only one confirm message //send the board regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAdding(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg //send you a start for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; break; //waiting for the respond for nextClockMsg case 3: case -1: client1_ip = m.getIp(); Sender1 = new MessageSender(client1_ip, LISTEN_PORT); System.out.println(client1_ip + "connected!!!"); status = 1; break; case -2: client2_ip = m.getIp(); Sender2 = new MessageSender(client2_ip, LISTEN_PORT); System.out.println(client2_ip + "connected!!!"); Sender1.sendMsg(client2_ip); status = 2; break; case -3: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg(client1_ip); status = 3; break; case -4: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); System.out.println("before"); //Sender1.sendMsg(auto.left()); // Sender1.sendMsg(auto); // Sender1.sendMsg(new AutomataMsg(3, 4)); // Sender1.sendMsg("left"); System.out.println("after"); status = 4; break; case 4: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); //Sender2.sendMsg(auto.right()); status = 5; break; case 5: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("left"); status = 6; break; case 6: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("right"); status = 7; break; case 7: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("start"); status = 8; break; case 8: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("start"); status = 9; break; case 9: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); status = 10; break; case 10: // if(m == null) System.out.println("null"); if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } status = 11; break; case 11: if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } frame.repaint(); Sender1.sendMsg("start"); status = 8; break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAdding(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding new to pending"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } return false; } //deal with the pending adding request //manage the heap protected void handlePending() throws IOException{ while(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level regedClientSender.remove(0); regedClientSender.add(c); } regedClientSender.add(new Comrade(cid, newClientSender.get(0))); //remove the pending one newClientSender.remove(0); regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); waiting4confirm++; System.out.println("register a new client"); } } protected void gandleNewBoard(MessageWithIp m, Board bigBoard, int nextStatus){ waiting4confirm System.out.println("getting a result"); bigBoard = (Board)m.extracMessage(); if(waiting4confirm==0) status = nextStatus; } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
package htn; import fluentSolver.Fluent; import fluentSolver.FluentConstraint; import fluentSolver.FluentNetworkSolver; import htn.TaskApplicationMetaConstraint.markings; import hybridDomainParsing.HybridDomainPlanner; import org.metacsp.framework.Constraint; import org.metacsp.framework.ConstraintNetwork; import org.metacsp.framework.Variable; import org.metacsp.framework.VariablePrototype; import org.metacsp.framework.meta.MetaConstraintSolver; import org.metacsp.framework.meta.MetaVariable; import org.metacsp.multi.allenInterval.AllenIntervalConstraint; import org.metacsp.utility.logging.MetaCSPLogging; import unify.CompoundSymbolicValueConstraint; import java.util.Map; import java.util.Vector; import java.util.logging.Logger; public class HTNPlanner extends MetaConstraintSolver implements HybridDomainPlanner { private static final long serialVersionUID = 8031573555691611305L; private Map<String, String[]> typesInstancesMap; private final FluentNetworkSolver groundSolver; private Logger logger = MetaCSPLogging.getLogger(HTNPlanner.class); public HTNPlanner(long origin, long horizon, long animationTime, String[][] symbols, int[] symbolicingredients) { // Currently only FluentConstraints. Other constraint should be added later. super(new Class[] {FluentConstraint.class}, animationTime, new FluentNetworkSolver(origin, horizon, symbols, symbolicingredients)); logger = MetaCSPLogging.getLogger(HTNPlanner.class); groundSolver = (FluentNetworkSolver)this.getConstraintSolvers()[0]; } @Override public void preBacktrack() { } @Override public void postBacktrack(MetaVariable mv) { // if (mv.getMetaConstraint() instanceof TaskApplicationMetaConstraint) { // for (Variable v : mv.getConstraintNetwork().getVariables()) { // v.setMarking(markings.SELECTED); // else if (mv.getMetaConstraint() instanceof PreconditionMetaConstraint) { // for (Variable v : mv.getConstraintNetwork().getVariables()) { // v.setMarking(markings.UNJUSTIFIED); // else if (mv.getMetaConstraint() instanceof HTNMetaConstraint) { // for (Variable v : mv.getConstraintNetwork().getVariables()) { // v.setMarking(markings.UNPLANNED); // System.out.println("SET TO UNPLANNED: " + v); } /** * Defines extra operations that should happen * after retracting a meta-value in the meta-CSP search (e.g., when backtracking). * @param metaVariable The {@link MetaVariable} over which backtracking occurs. * @param metaValue The meta-value that has been retracted. */ @Override protected void retractResolverSub(ConstraintNetwork metaVariable, ConstraintNetwork metaValue) { long startTime = System.nanoTime(); // remove added fluents Vector<Variable> varsToRemove = new Vector<Variable>(); for (Variable v : metaValue.getVariables()) { if (!metaVariable.containsVariable(v)) { if (v instanceof VariablePrototype) { Variable vReal = metaValue.getSubstitution((VariablePrototype)v); if (vReal != null) { varsToRemove.add(vReal); // System.out.println("GONNA REMOVE " + vReal); } } } } groundSolver.removeVariables(varsToRemove.toArray(new Variable[varsToRemove.size()])); // change CLOSED fluents back to OPEN for(Constraint c : metaValue.getConstraints()) { if ((c instanceof FluentConstraint) && (((FluentConstraint) c).getType() == FluentConstraint.Type.CLOSES)) { ((FluentConstraint) c).getTo().setMarking(markings.OPEN); } } long endTime = System.nanoTime(); logger.finest("RECTRACT_RESOLVER_SUB Took: " + ((endTime - startTime) / 1000000) + " ms"); } /** * Defines additional operations that should happen before * adding a meta-value in the meta-CSP search (e.g., when branching). * * Make real {@link Variable}s from {@link VariablePrototype}s. * Involve real {@link Variable}s in the Constraints. * @param metaVariable The {@link MetaVariable} over which the search is branching. * @param metaValue The meta-value that has been selected (the branch). */ @Override protected boolean addResolverSub(ConstraintNetwork metaVariable, ConstraintNetwork metaValue) { long startTime = System.nanoTime(); FluentNetworkSolver groundSolver = (FluentNetworkSolver)this.getConstraintSolvers()[0]; //Make real variables from variable prototypes for (Variable v : metaValue.getVariables()) { if (v instanceof VariablePrototype) { // Parameters for real instantiation: the first is the component // and the second is the type, the third are the arguments of the fluent String component = (String)((VariablePrototype) v).getParameters()[0]; String symbol = (String)((VariablePrototype) v).getParameters()[1]; Fluent fluent = (Fluent)groundSolver.createVariable(component); String[] arguments = (String[])((VariablePrototype) v).getParameters()[2]; fluent.setName(symbol, arguments); fluent.setMarking(v.getMarking()); metaValue.addSubstitution((VariablePrototype)v, fluent); } } //Involve real variables in the constraints for (Constraint con : metaValue.getConstraints()) { Constraint clonedConstraint = (Constraint)con.clone(); Variable[] oldScope = con.getScope(); Variable[] newScope = new Variable[oldScope.length]; for (int i = 0; i < oldScope.length; i++) { if (oldScope[i] instanceof VariablePrototype) { if (con instanceof CompoundSymbolicValueConstraint){ newScope[i] = ((Fluent) metaValue.getSubstitution((VariablePrototype)oldScope[i])).getCompoundSymbolicVariable(); } else if (con instanceof AllenIntervalConstraint){ newScope[i] = ((Fluent) metaValue.getSubstitution((VariablePrototype)oldScope[i])).getAllenInterval(); }else { newScope[i] = metaValue.getSubstitution((VariablePrototype)oldScope[i]); } } else { newScope[i] = oldScope[i]; } } clonedConstraint.setScope(newScope); metaValue.removeConstraint(con); metaValue.addConstraint(clonedConstraint); } // set marking of closed fluents to CLOSED for (Constraint con : metaValue.getConstraints()) { if (con instanceof FluentConstraint) { if (((FluentConstraint) con).getType() == FluentConstraint.Type.CLOSES) { ((FluentConstraint) con).getTo().setMarking(markings.CLOSED); // TODO These markings are not really used and could be removed } } } long endTime = System.nanoTime(); logger.finest("ADD_RESOLVER_SUB Took: " + ((endTime - startTime) / 1000000) + " ms"); return true; } @Override protected double getUpperBound() { // Auto-generated method stub return 0; } @Override protected void setUpperBound() { // Auto-generated method stub } @Override protected double getLowerBound() { // Auto-generated method stub return 0; } @Override protected void setLowerBound() { // Auto-generated method stub } @Override protected boolean hasConflictClause(ConstraintNetwork metaValue) { // Auto-generated method stub return false; } @Override protected void resetFalseClause() { // Auto-generated method stub } public Map<String, String[]> getTypesInstancesMap() { return typesInstancesMap; } public void setTypesInstancesMap(Map<String, String[]> typesInstancesMap) { this.typesInstancesMap = typesInstancesMap; } @Override public FluentNetworkSolver getFluentNetworkSolver() { return (FluentNetworkSolver) getConstraintSolvers()[0]; } }
package ca.sfu.server; import java.io.IOException; import java.util.ArrayList; import javax.swing.JFrame; import ca.sfu.cmpt431.facility.*; import ca.sfu.cmpt431.message.*; import ca.sfu.cmpt431.message.join.*; import ca.sfu.cmpt431.message.regular.*; import ca.sfu.message.AutomataMsg; import ca.sfu.network.MessageReceiver; import ca.sfu.network.MessageSender; import ca.sfu.network.SynchronizedMsgQueue.MessageWithIp; public class Server{ protected static final int LISTEN_PORT = 6560; private MessageReceiver Receiver; private MessageSender Sender1; private MessageSender Sender2; private String client1_ip; private String client2_ip; private ArrayList<MessageSender> newClientSender = new ArrayList<MessageSender>(); private ArrayList<Comrade> regedClientSender = new ArrayList<Comrade>(); private int waiting4confirm = 0; private int nextClock = 0; private int status; public Server() throws IOException { Receiver = new MessageReceiver(LISTEN_PORT); status = 0; } protected void startServer() throws IOException, ClassNotFoundException, InterruptedException { JFrame frame = new JFrame(); frame.setSize(480, 480); //AutomataMsg auto = new AutomataMsg(10, 10); Board b = new Board(10, 10); BoardOperation.Randomize(b,0.2); AutomataPanel panel = new AutomataPanel(); panel.setBoard(b); frame.setContentPane(panel); frame.setVisible(true); System.out.println("UI"); MessageWithIp m; while(true) { if(!Receiver.isEmpty()) { System.out.println(status); m = Receiver.getNextMessageWithIp(); switch(status) { //waiting for first client case 0: handleNewAdding(m,1); handlePending(); status = 1; break; //waiting for confirm from first client //send it the outfit case 1: if(handleNewAdding(m,1)) //!every status, handle an unexpected new adding message first break; // if it is a new adding request, go to status 1 to wait the confirm msg again handleConfirm(m,2); //expect only one confirm message //send the board regedClientSender.get(0).sender.sendMsg(new JoinOutfitsMsg(-1, -1, new Outfits(0,nextClock,0,0,b))); waiting4confirm++; status = 2; break; //wait for the confirm //start a cycle case 2: if(handleNewAdding(m,2)) break; handleConfirm(m,3); //expect only one message responding for JoinOutfitsMsg //send you a start for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } status = 3; break; //waiting for the client to send the result back //restart next cycle case 3: handleNewBoard(m,b,3); frame.repaint(); BoardOperation.Print(b); if(waiting4confirm==0){ for (Comrade var : regedClientSender) { var.sender.sendMsg(new RegularNextClockMsg(nextClock)); waiting4confirm++; } } break; case -1: client1_ip = m.getIp(); Sender1 = new MessageSender(client1_ip, LISTEN_PORT); System.out.println(client1_ip + "connected!!!"); status = 1; break; case -2: client2_ip = m.getIp(); Sender2 = new MessageSender(client2_ip, LISTEN_PORT); System.out.println(client2_ip + "connected!!!"); Sender1.sendMsg(client2_ip); status = 2; break; case -3: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg(client1_ip); status = 3; break; case -4: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); System.out.println("before"); //Sender1.sendMsg(auto.left()); // Sender1.sendMsg(auto); // Sender1.sendMsg(new AutomataMsg(3, 4)); // Sender1.sendMsg("left"); System.out.println("after"); status = 4; break; case 4: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); //Sender2.sendMsg(auto.right()); status = 5; break; case 5: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("left"); status = 6; break; case 6: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("right"); status = 7; break; case 7: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); Sender1.sendMsg("start"); status = 8; break; case 8: if(!m.getIp().equals(client1_ip)) System.out.println("Error!"); Sender2.sendMsg("start"); status = 9; break; case 9: if(!m.getIp().equals(client2_ip)) System.out.println("Error!"); status = 10; break; case 10: // if(m == null) System.out.println("null"); if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } status = 11; break; case 11: if(m.getIp().equals(client1_ip)){ //auto.mergeLeft((AutomataMsg)m.extracMessage()); //Sender1.sendMsg("OK"); } else{ //auto.mergeRight((AutomataMsg)m.extracMessage()); //Sender2.sendMsg("OK"); } frame.repaint(); Sender1.sendMsg("start"); status = 8; break; default: break; } } } } //store all the adding request into an array protected boolean handleNewAdding(MessageWithIp m, int nextStatus) throws IOException{ //check if m is a new adding request message Message msg = (Message) m.extracMessage(); if(msg.getMessageCode()==MessageCodeDictionary.JOIN_REQUEST){ JoinRequestMsg join = (JoinRequestMsg)m.extracMessage(); newClientSender.add(new MessageSender(m.getIp(), join.clientPort)); System.out.println("adding new to pending"); //if it is a new adding request, we need to go to nextStatus //most time it should be the same status status = nextStatus; return true; } return false; } //deal with the pending adding request //manage the heap protected void handlePending() throws IOException{ while(!newClientSender.isEmpty()){ int cid = regedClientSender.size(); //manage the heap if(cid!=0){ //not the first client Comrade c = regedClientSender.get(0); //get it down one level regedClientSender.remove(0); regedClientSender.add(c); } regedClientSender.add(new Comrade(cid, newClientSender.get(0))); //remove the pending one newClientSender.remove(0); regedClientSender.get(cid).sender.sendMsg(new RegularConfirmMsg(-1)); waiting4confirm++; System.out.println("register a new client"); } } protected void handleNewBoard(MessageWithIp m, Board b, int nextStatus){ waiting4confirm System.out.println("getting a result"); if(waiting4confirm==0) status = nextStatus; b = (Board)m.extracMessage(); } //getting a new confirm message, if there is no waiting confirm, go to nextStatus protected void handleConfirm(MessageWithIp m, int nextStatus){ waiting4confirm System.out.println("getting a confirm"); if(waiting4confirm==0) status = nextStatus; } }
package pi4jdemo; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class Demo1 { public static void main(String[] args) throws Exception{ GpioController controller = GpioFactory.getInstance(); GpioPinDigitalOutput pin = controller.provisionDigitalOutputPin(RaspiPin.GPIO_29,PinState.HIGH); // set shutdown state for this pin pin.setShutdownOptions(true, PinState.LOW); Thread.sleep(5000); System.out.println("low...."); pin.low(); Thread.sleep(5000); System.out.println("high...."); pin.high(); Thread.sleep(5000); controller.shutdown(); } }
package pulley; import static pulley.Cons.cons; import static pulley.Promises.completedPromiseFactory; import static pulley.Stream.stream; import static pulley.util.Optional.absent; import static pulley.util.Optional.of; import java.util.Arrays; import java.util.List; import pulley.streams.FromIterable; import pulley.streams.Merge; import pulley.streams.Range; import pulley.util.Optional; public class Streams { private static Stream<?> EMPTY = stream(completedPromiseFactory(Optional .<Cons<Object>> absent())); private static StreamPromise<?> EMPTY_PROMISE = new StreamPromise<Object>() { @Override public Optional<Cons<Object>> get() { return absent(); } @Override public A0 closeAction() { return Actions.doNothing0(); } @Override public Scheduler scheduler() { return Schedulers.immediate(); } }; public static <T> Stream<T> just(T t) { return stream(completedPromiseFactory(of(cons(t, Streams.<T> emptyPromise())))); } @SuppressWarnings("unchecked") public static <T> StreamPromise<T> emptyPromise() { return (StreamPromise<T>) EMPTY_PROMISE; } @SuppressWarnings("unchecked") public static <T> Stream<T> just(T t1, T t2) { return from(Arrays.asList(t1, t2)); } public static <T> Stream<T> from(Iterable<T> iterable) { return FromIterable.create(iterable); } public static <T> Stream<T> merge(List<Stream<T>> streams) { return Merge.create(streams); } public static <T> Stream<T> merge(Stream<Stream<T>> streams) { return Util.notImplemented(); } @SuppressWarnings("unchecked") public static <T> Stream<T> empty() { return (Stream<T>) EMPTY; } public static Stream<Integer> range(final int start, final int count) { return Range.create(start, count); } }
// E v a l u a t o r // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.glyph; import omr.Main; import omr.constant.Constant; import omr.constant.ConstantSet; import omr.math.Moments; import omr.math.NeuralNetwork; import omr.sheet.Sheet; import omr.sheet.SystemInfo; import omr.util.Logger; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Locale; /** * Class <code>Evaluator</code> is an abstract class that gathers data and * processing common to any evaluator working on glyph characteristics to * infer glyph shape. * * @author Herv&eacute Bitteur * @version $Id$ */ public abstract class Evaluator { private static final Constants constants = new Constants(); private static final Logger logger = Logger.getLogger(Evaluator.class); // Extension used by evaluator backup files private static final String BACKUP_EXTENSION = ".def"; /** Describes the various modes for starting the training of an evaluator */ public static enum StartingMode { /** Start from scratch, with new initial values */ SCRATCH, /** Start with the current values */ INCREMENTAL; } /** * Number of useful moments */ public static final int inMoments = 10; /** * Number of useful input parameters : 10 moments + * isWithinSystem, stemNumber, hasLedger, stepLine */ public static final int inSize = inMoments + 4; /** * Number of shapes to differentiate */ public static final int outSize = Shape.LastPhysicalShape.ordinal() +1; /** * A special evaluation array, used to report NOISE */ protected static final Evaluation[] noiseEvaluations = { new Evaluation(Shape.NOISE, 0d) }; /** * An Evaluation comparator in increasing order, where smaller grave * value means better interpretation */ protected static Comparator<Evaluation> comparator = new Comparator<Evaluation>() { public int compare (Evaluation e1, Evaluation e2) { if (e1.grade < e2.grade) { return -1; } if (e1.grade > e2.grade) { return +1; } return 0; } }; /** Descriptive labels for glyph characteristics */ protected static String[] labels; // getCustomBackup // /** * Report the custom file used to store or load the internal evaluator * data * * @return the evaluator custom backup file */ protected File getCustomBackup() { // The custom file, if any, is located at the root of the train // folder return new File(Main.getTrainFolder(), getName() + BACKUP_EXTENSION); } // getSystemBackup // /** * Report the default system resource used to load the internal * evaluator data * * @return the evaluator system backup file */ protected String getSystemBackup() { // The system file, is located in the config directory of the // application jar file return "/config/" + getName() + BACKUP_EXTENSION; } // dump // /** * Dump the internals of the evaluator */ public abstract void dump (); // feedInput // /** * Prepare the evaluator input, by picking up some characteristics of * the glyph (some of its moments, and some info on surroundings) * * @param glyph the glyph to be evaluated * @param ins the evaluator input array to be filled (if null, it is * allocated by the routine) * * @return the filled input array */ public static double[] feedInput (Glyph glyph, double[] ins) { if (ins == null) { ins = new double[inSize]; } Moments m = glyph.getMoments(); // We take all the first moments System.arraycopy(m.k, 0, ins, 0, inMoments); // We append flags and step position int i = inMoments; ins[i++] = boolAsDouble(glyph.isWithinSystem()); ins[i++] = boolAsDouble(glyph.hasLedger()); ins[i++] = glyph.getStemNumber(); ins[i++] = glyph.getStepLine(); // We skip moments 17 & 18 (xMean and yMean) ??? return ins; } public static String[] getLabels () { if (labels == null) { labels = new String[inSize]; // We take all the first moments System.arraycopy(Moments.labels, 0, labels, 0, inMoments); // We append flags and step position int i = inMoments; labels[i++] = "w/iSyst"; labels[i++] = "ledger"; labels[i++] = "stemNb"; labels[i++] = "sLine"; } return labels; } // getBestEvaluation // /** * Run the network with the specified glyph, and infer a shape. * * @param glyph the glyph to be examined * * @return the best evaluation, if its grade is acceptable, null * otherwise */ public Evaluation getBestEvaluation (Glyph glyph) { return getEvaluations(glyph)[0]; } // getEvaluations // /** * Run the evaluator with the specified glyph, and return a prioritized * collection of interpretations (ordered from best to wors). * * @param glyph the glyph to be examined * * @return the ordered best evaluations */ public abstract Evaluation[] getEvaluations (Glyph glyph); // getName // /** * Report the name of this evaluator * * @return the evaluator declared name */ public abstract String getName(); // guessSheet // /** * Compute and register a guess for each of the unknown glyphs of the * sheet. Too small glyphs are flagged as noisy. * * @param sheet the sheet at hand * @param maxGrade the maximum acceptable grade value */ public void guessSheet (Sheet sheet, double maxGrade) { for (SystemInfo system : sheet.getSystems()) { for (Glyph glyph : system.getGlyphs()) { if (!glyph.isKnown()) { glyph.setGuess(vote(glyph, maxGrade)); } } } } // isBigEnough // /** * Use a threshold on glyph weight, to tell if the provided glyph is * just {@link Shape#NOISE}, or a real glyph * * @param glyph the glyph to be checked * @return true if not noise, false otherwise */ public static boolean isBigEnough (Glyph glyph) { return glyph.getMoments().k[0] >= constants.minWeight.getValue(); } // isTrained // /** * Check whether the evaluator has been trained * * @return true if trained */ public abstract boolean isTrained (); // stop // /** * Stop the on-going training. By default, this is a no-op */ public void stop() { } // train // /** * Here we train the evaluator "ab initio", based on the set of known * glyphs accumulated in the previous runs. * * @param base the list of glyphs to retrain the evaluator * @param monitor a monitoring interface * @param mode specify the starting mode of the training session */ public abstract void train (List<Glyph> base, Monitor monitor, StartingMode mode); // vote // /** * Run the evaluator with the specified glyph, and infer a shape. * * @param glyph the glyph to be examined * @param maxGrade the maximum grade to be accepted * * @return the best suitable interpretation, or null */ public Shape vote (Glyph glyph, double maxGrade) { if (isBigEnough(glyph)) { Evaluation eval = getBestEvaluation(glyph); if (eval.grade <= maxGrade) { return eval.shape; } else { return null; } } else { return Shape.NOISE; } } // boolAsDouble // private static double boolAsDouble (boolean b) { if (b) return 1d; else return 0d; } // getMaxDistance // /** * Report the maximum grade value for an evaluation to be accepted * * @return the maximum grade value */ public double getMaxDistance () { return constants.maxDistance.getValue(); } // getMaxDistanceRatio // /** * Report the maximum ratio (with respect to the best evaluation) for * secondary evaluations to be also considered * * @return the maximum "degrading" ratio */ public double getMaxDistanceRatio () { return constants.maxDistanceRatio.getValue(); } // Monitor // /** * Interface <code>Monitor</code> specifies a general monitoring * interface to pass information about the behavior of evaluators. */ public static interface Monitor extends NeuralNetwork.Monitor { /** * Entry called when a glyph is processed */ void glyphProcessed (Glyph glyph); } // Constants // private static class Constants extends ConstantSet { Constant.Double minWeight = new Constant.Double (0.19, "Minimum normalized weight to be considered not a noise"); Constant.Double okDistance = new Constant.Double (1.5, "Threshold on OK distance"); Constant.Double maxDistance = new Constant.Double (5.0, "Threshold on displayable distance"); Constant.Double maxDistanceRatio = new Constant.Double (3.0, "Max ratio, WRT the best evaluation"); Constants () { initialize(); } } }
package imj2.tools; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static net.sourceforge.aprog.tools.Tools.debugError; import static net.sourceforge.aprog.tools.Tools.debugPrint; import imj2.core.Image.Channels; import imj2.core.Image.Monochannel; import imj2.core.Image2D; import imj2.core.LinearPackedGrayImage; import imj2.core.TiledImage2D; import imj2.tools.IMJTools.TileProcessor; import imj2.tools.Image2DComponent.Painter; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Window; import java.io.Serializable; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.TicToc; /** * @author codistmonk (creation 2014-05-03) */ public final class InteractiveClassifier { private InteractiveClassifier() { throw new IllegalInstantiationException(); } /** * @param commandLineArguments * <br>Unused */ public static final void main(final String[] commandLineArguments) { if (true) { final Window window = Image2DComponent.showDefaultImage(); final Image2DComponent imageView = IMJTools.findComponent(window, Image2DComponent.class); imageView.getPainters().add(new Painter<Image2DComponent>() { private DelimitersBuilder delimitersBuilder; private LinearPackedGrayImage delimiters; @Override public final void paint(final Graphics2D g, final Image2DComponent component , final int width, final int height) { final Image2D image = component.getImage(); if (this.delimitersBuilder == null || this.delimitersBuilder.getImage() != image) { this.delimitersBuilder = new DelimitersBuilder(image, 32); this.delimiters = this.delimitersBuilder.newEmptyDelimiters(); } final Rectangle box = component.getVisibleBoxInImage(); debugPrint(box); this.delimitersBuilder.setDelimiters(this.delimiters , box.x, box.y, box.x + box.width, box.y + box.height); final int tx = -component.getXInImage(0); final int ty = -component.getYInImage(0); this.delimitersBuilder.processSegments(box.x, box.y , box.x + box.width, box.y + box.height, new SegmentProcessor() { @Override public final void segment(final int x, final int y, final int row, final int column) { final int northY = delimitersBuilder.getSegmentNorthY(delimiters, x, y, row, column); final int westX = delimitersBuilder.getSegmentWestX(delimiters, x, y, row, column); final int eastX = delimitersBuilder.getSegmentEastX(delimiters, x, y, row, column); final int southY = delimitersBuilder.getSegmentSouthY(delimiters, x, y, row, column); g.setColor(Color.BLUE); g.drawOval(x - 2 + tx, northY - 2 + ty, 4, 4); g.drawOval(westX - 2 + tx, y - 2 + ty, 4, 4); g.drawOval(eastX - 2 + tx, y - 2 + ty, 4, 4); g.drawOval(x - 2 + tx, southY - 2 + ty, 4, 4); g.setColor(Color.RED); g.drawOval(x - 2 + tx, y - 2 + ty, 4, 4); } /** * {value}. */ private static final long serialVersionUID = 3851222531284298589L; }); } /** * {@value}. */ private static final long serialVersionUID = -7467299626996751246L; }); } if (false) { final TicToc timer = new TicToc(); debugPrint("Loading image started...", new Date(timer.tic())); // final TiledImage2D image = new LociBackedImage("../Libraries/images/svs/SYS08_A10_7414-005.svs"); final TiledImage2D image = (TiledImage2D) new MultifileImage( "../Libraries/images/jpg/SYS08_A10_7414-005", "SYS08_A10_7414-005_lod0", null).getLODImage(6); debugPrint("Loading image done in", timer.toc(), "ms"); debugPrint(image.getWidth(), image.getHeight(), image.getPixelCount()); debugPrint("Analyzing image started...", new Date(timer.tic())); final DelimitersBuilder delimitersBuilder = new DelimitersBuilder(image, 32); delimitersBuilder.buildDelimitersFor(image); debugPrint("Analyzing image done in", timer.toc(), "ms"); } } /** * @author codistmonk (creation 2014-05-03) */ public static final class DelimitersBuilder implements Serializable { private final Image2D image; private final int w; private final int h; private final int s; private final int delimitersPerRow; private final int rows; private final long horizontalDelimiters; private final int delimitersPerColumn; private final int columns; private final long verticalDelimiters; private final long allDelimiters; private final AtomicLong delimitersDone; public DelimitersBuilder(final Image2D image, final int s) { this.image = image; this.w = image.getWidth(); this.h = image.getHeight(); this.s = s; this.delimitersPerRow = 1 + ceiling(this.w - s / 2, s); this.rows = 2 + ceiling(this.h - s / 2, s); this.horizontalDelimiters = (long) this.delimitersPerRow * this.rows; this.delimitersPerColumn = 1 + ceiling(this.h - s / 2, s); this.columns = 2 + ceiling(this.w - s / 2, s); this.verticalDelimiters = (long) this.delimitersPerColumn * this.columns; this.allDelimiters = this.horizontalDelimiters + this.verticalDelimiters; final LinearPackedGrayImage delimiters = this.newEmptyDelimiters(); this.delimitersDone = new AtomicLong(); debugPrint("delimitersPerRow:", this.delimitersPerRow, "rows:", this.rows , "delimitersPerColumn:", this.delimitersPerColumn, "columns:", this.columns , "delimiters:", delimiters.getPixelCount()); } public final Image2D getImage() { return this.image; } public final LinearPackedGrayImage buildDelimitersFor(final TiledImage2D image) { final LinearPackedGrayImage result = this.newEmptyDelimiters(); IMJTools.forEachTileIn(image, new TileProcessor() { @Override public final void pixel(final Info info) { debugPrint("tile:", info.getTileX(), info.getTileY(), info.getActualTileWidth(), info.getActualTileHeight()); final int xStart = info.getTileX() + info.getPixelXInTile(); final int yStart = info.getTileY() + info.getPixelYInTile(); final int xEnd = info.getTileX() + info.getActualTileWidth(); final int yEnd = info.getTileY() + info.getActualTileHeight(); DelimitersBuilder.this.setDelimiters(result, xStart, yStart, xEnd, yEnd); } @Override public final void endOfTile() { // NOP } /** * {@value}. */ private static final long serialVersionUID = 8075249791734409997L; }); this.check(result); return result; } public final LinearPackedGrayImage newEmptyDelimiters() { return new LinearPackedGrayImage("" , this.allDelimiters, new Monochannel(Long.SIZE - Long.numberOfLeadingZeros(this.s - 1L))); } public final void setDelimiters(final LinearPackedGrayImage delimiters , final int xStart, final int yStart, final int xEnd, final int yEnd) { this.processSegments(xStart, yStart, xEnd, yEnd, new SegmentProcessor() { @Override public final void segment(final int x, final int y, final int row, final int column) { // debugPrint("segment:", x, y, row, column); DelimitersBuilder.this.setHorizontalDelimiters(delimiters, y, row, x, column); DelimitersBuilder.this.setVerticalDelimiters(delimiters, y, row, x, column); } /** * {@value}. */ private static final long serialVersionUID = 7972837075735571744L; }); } public final void processSegments(final int xStart, final int yStart , final int xEnd, final int yEnd, final SegmentProcessor process) { /* * y0 <= s/2 + k s * <- y0 - s/2 <= k s * <- (y0 - s/2)/s <= k * <- k = ceiling(y0-s/2,s) */ for (int y = this.s / 2 + this.s * ceiling(yStart - this.s / 2, this.s); y < yEnd; y += this.s) { final int row = 1 + ceiling(y - this.s / 2, this.s); for (int x = this.s / 2 + this.s * ceiling(xStart - this.s / 2, this.s); x < xEnd; x += this.s) { final int column = 1 + ceiling(x - this.s / 2, this.s); process.segment(x, y, row, column); } } } public final int getSegmentNorthY(final LinearPackedGrayImage delimiters, final int x, final int y, final int row, final int column) { if (row == 1) { return 0; } final long delimiterIndex = this.horizontalDelimiters + column * this.delimitersPerColumn + row - 1L; return y - this.s + delimiters.getPixelValue(delimiterIndex); } public final int getSegmentWestX(final LinearPackedGrayImage delimiters, final int x, final int y, final int row, final int column) { if (column == 1) { return 0; } final long delimiterIndex = row * this.delimitersPerRow + column - 1L; return x - this.s + delimiters.getPixelValue(delimiterIndex); } public final int getSegmentEastX(final LinearPackedGrayImage delimiters, final int x, final int y, final int row, final int column) { final long delimiterIndex = row * this.delimitersPerRow + column; return x + delimiters.getPixelValue(delimiterIndex); } public final int getSegmentSouthY(final LinearPackedGrayImage delimiters, final int x, final int y, final int row, final int column) { final long delimiterIndex = this.horizontalDelimiters + column * this.delimitersPerColumn + row; return y + delimiters.getPixelValue(delimiterIndex); } public final void check(final LinearPackedGrayImage delimiters) { if (this.delimitersDone.get() != delimiters.getPixelCount()) { debugError("expectedDelimiters:", delimiters.getPixelCount(), "actualDelimiters:", this.delimitersDone.get()); } { long errors = 0L; for (long i = 0L; i < this.horizontalDelimiters; ++i) { final int delimiterValue = delimiters.getPixelValue(i); if (i % this.delimitersPerRow == 0) { if (delimiterValue != 0) { ++errors; } } else if (delimiterValue == 0) { ++errors; } } for (long i = this.horizontalDelimiters; i < this.allDelimiters; ++i) { final int delimiterValue = delimiters.getPixelValue(i); if ((i - this.horizontalDelimiters) % this.delimitersPerColumn == 0) { if (delimiterValue != 0) { ++errors; } } else if (delimiterValue == 0) { ++errors; } } if (0 < errors) { debugError("erroneousDelimiters:", errors); } } } final void setHorizontalDelimiters(final LinearPackedGrayImage delimiters , final int y, final int row, final int x, final int column) { if (y == this.s / 2) { { final long delimiterIndex = (row - 1L) * this.delimitersPerRow + column - 1L; if (column == 1) { delimiters.setPixelValue(delimiterIndex, 0); } else { delimiters.setPixelValue(delimiterIndex , getHorizontalOffsetOfLargestGradient(this.getImage(), x - this.s, 0, this.s)); } this.delimitersDone.incrementAndGet(); } if (this.w <= x + this.s) { final long delimiterIndex = (row - 1L) * this.delimitersPerRow + column; delimiters.setPixelValue(delimiterIndex, this.w - 1 - x); this.delimitersDone.incrementAndGet(); } } { final long delimiterIndex = row * this.delimitersPerRow + column - 1L; if (column == 1) { delimiters.setPixelValue(delimiterIndex, 0); } else { delimiters.setPixelValue(delimiterIndex , getHorizontalOffsetOfLargestGradient(this.getImage(), x - this.s, y, this.s)); } this.delimitersDone.incrementAndGet(); } if (this.w <= x + this.s) { final long delimiterIndex = row * this.delimitersPerRow + column; delimiters.setPixelValue(delimiterIndex, this.w - 1 - x); this.delimitersDone.incrementAndGet(); } if (this.h <= y + this.s) { { final long delimiterIndex = (row + 1L) * this.delimitersPerRow + column - 1L; if (column == 1) { delimiters.setPixelValue(delimiterIndex, 0); } else { delimiters.setPixelValue(delimiterIndex , getHorizontalOffsetOfLargestGradient(this.getImage(), x - this.s, this.h - 1, this.s)); } this.delimitersDone.incrementAndGet(); } if (this.w <= x + this.s) { final long delimiterIndex = (row + 1L) * this.delimitersPerRow + column; delimiters.setPixelValue(delimiterIndex, this.w - 1 - x); this.delimitersDone.incrementAndGet(); } } } final void setVerticalDelimiters(final LinearPackedGrayImage delimiters , final int y, final int row, final int x, final int column) { if (x == this.s / 2) { { final long delimiterIndex = this.horizontalDelimiters + (column - 1L) * this.delimitersPerColumn + row - 1L; if (row == 1) { delimiters.setPixelValue(delimiterIndex, 0); } else { delimiters.setPixelValue(delimiterIndex , getHorizontalOffsetOfLargestGradient(this.getImage(), 0, y - this.s, this.s)); } this.delimitersDone.incrementAndGet(); } if (this.h <= y + this.s) { final long delimiterIndex = this.horizontalDelimiters + (column - 1L) * this.delimitersPerColumn + row; delimiters.setPixelValue(delimiterIndex, this.h - 1 - y); this.delimitersDone.incrementAndGet(); } } { final long delimiterIndex = this.horizontalDelimiters + column * this.delimitersPerColumn + row - 1L; if (row == 1) { delimiters.setPixelValue(delimiterIndex, 0); } else { delimiters.setPixelValue(delimiterIndex , getVerticalOffsetOfLargestGradient(this.getImage(), x, y - this.s, this.s)); } this.delimitersDone.incrementAndGet(); } if (this.h <= y + this.s) { final long delimiterIndex = this.horizontalDelimiters + column * this.delimitersPerColumn + row; delimiters.setPixelValue(delimiterIndex, this.h - 1 - y); this.delimitersDone.incrementAndGet(); } if (this.w <= x + this.s) { { final long delimiterIndex = this.horizontalDelimiters + (column + 1L) * this.delimitersPerColumn + row - 1L; if (row == 1) { delimiters.setPixelValue(delimiterIndex, 0); } else { delimiters.setPixelValue(delimiterIndex , getVerticalOffsetOfLargestGradient(this.getImage(), this.w - 1, y - this.s, this.s)); } this.delimitersDone.incrementAndGet(); } if (this.h <= y + this.s) { final long delimiterIndex = this.horizontalDelimiters + (column + 1L) * this.delimitersPerColumn + row; delimiters.setPixelValue(delimiterIndex, this.h - 1 - y); this.delimitersDone.incrementAndGet(); } } } /** * {@value}. */ private static final long serialVersionUID = 2680059399437526583L; public static final int ceiling(final int a, final int b) { return (a + b - 1) / b; } public static final int getHorizontalOffsetOfLargestGradient(final Image2D image , final int x, final int y, final int s) { final int w = image.getWidth(); final int xStart = x + 1; final int xEnd = min(w, x + s); int largestGradient = getGradient(image, xStart, y); int result = 1; for (int xx = xStart; xx < xEnd; ++xx) { final int gradient = getGradient(image, xx, y); if (largestGradient < gradient) { largestGradient = gradient; result = xx - xStart; } } return result; } public static final int getVerticalOffsetOfLargestGradient(final Image2D image , final int x, final int y, final int s) { final int h = image.getHeight(); final int yStart = y + 1; final int yEnd = min(h, y + s); int largestGradient = getGradient(image, x, yStart); int result = 1; for (int yy = yStart; yy < yEnd; ++yy) { final int gradient = getGradient(image, x, yy); if (largestGradient < gradient) { largestGradient = gradient; result = yy - yStart; } } return result; } public static final int getGradient(final Image2D image, final int x, final int y) { final int pixelValue = image.getPixelValue(x, y); final Channels channels = image.getChannels(); final int channelCount = channels.getChannelCount(); final int w = image.getWidth(); final int h = image.getHeight(); final int xStart = max(0, x - 1); final int xEnd = min(w, x + 1); final int yStart = max(0, y - 1); final int yEnd = min(h, y + 1); int result = 0; for (int yi = yStart; yi < yEnd; ++yi) { for (int xi = xStart; xi < xEnd; ++xi) { if (xi != x || yi != y) { final int neighborValue = image.getPixelValue(xi, yi); for (int channel = 0; channel < channelCount; ++channel) { result += abs(channels.getChannelValue(pixelValue, channel) - channels.getChannelValue(neighborValue, channel)); } } } } return result; } } /** * @author codistmonk (creation 2014-05-04) */ public static abstract interface SegmentProcessor extends Serializable { public abstract void segment(int x, int y, int row, int column); } }
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static int numberNeeded(String first, String second) { HashMap<Character, Integer> firstCount = new HashMap<Character, Integer>(); HashMap<Character, Integer> secondCount = new HashMap<Character, Integer>(); for(char x : first.toCharArray()) { if (firstCount.containsKey(x)) { int numOfThisLetter = firstCount.get(x); firstCount.put(x, numOfThisLetter + 1); } else { firstCount.put(x, 1); } } for(char y : second.toCharArray()) { if (secondCount.containsKey(y)) { int numOfThisOtherLetter = secondCount.get(y); secondCount.put(y, numOfThisOtherLetter + 1); } else { secondCount.put(y, 1); } } int firstCountSimilarities = 0; int secondCountSimilarities = 0; for (char aLetter : secondCount.keySet()) { if (firstCount.containsKey(aLetter)) { int sim = secondCount.get(aLetter)<=firstCount.get(aLetter) ? secondCount.get(aLetter) : firstCount.get(aLetter); secondCountSimilarities += sim; } } for (char aLetter : firstCount.keySet()) { if (secondCount.containsKey(aLetter)) { int sim = firstCount.get(aLetter)<=secondCount.get(aLetter) ? firstCount.get(aLetter) : secondCount.get(aLetter); firstCountSimilarities += sim; } } int totalToDelete = (first.length() - firstCountSimilarities) + (second.length() - secondCountSimilarities); return totalToDelete; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String a = in.next(); String b = in.next(); System.out.println(numberNeeded(a, b)); } } /* Assuming size n string for first and size m string for second. Runtime Analysis: First two for loops insert each character of the string into their respective hashmaps, takes O(n+m) time to iterate through each string. Then next two for loops iterate through hashmaps, retrieving their values to determine the count of each character, taking O(n+m) again. Hashmap retrievals are simply O(1) so they are not counted. Finally the calculation of the exact number of differences in letters to remove is also O(1). Total runtime: O(n+m+n+m) = O(2n + 2m) ~ approximately still O(N) time at maximum. Space Complexity: Hashmaps each take up O(n) + O(m) space. Maximum space needed is O(n+m). Optimization Analysis: Really only need one Hashmap to track changes, instead use one string and add characters to hashmap, while the other string decrements from the values in the hashmap, and use counter to keep track of differences. Most upvoted solutions on Hackerrank simply use arrays/vectors and iterate throught the strings themselves to reduce space used. */
package Test; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HelloWorldTest { HelloWorld greeter = new HelloWorld(); @Test public void test() { assertEquals("Hello World! ", greeter.greetings("")); } }
package com.parc.ccn.data.util; import java.io.IOException; import java.math.BigInteger; import java.sql.Timestamp; import java.util.ArrayList; import com.parc.ccn.config.SystemConfiguration; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.utils.Base64; public class DataUtils { public static <T extends Comparable<T>> int compare(T left, T right) { int result = 0; if (null != left) { if (null == right) return 1; // sort nothing before something result = left.compareTo(right); } else { if (null != right) result = -1; // sort nothing before something // else fall through and compare publishers else result = 0; // null == null } return result; } public static int compare(byte [] left, byte [] right) { int result = 0; if (null != left) { if (null == right) { result = 1; } else { // If a is shorter than b then a comes before b if (left.length < right.length) { result = -1; } else if (left.length > right.length) { result = 1; } else { // They have equal lengths - compare byte by byte for (int i=0; i < left.length; ++i) { if ((short)(left[i] & 0xff) < (short)(right[i] & 0xff)) { result = -1; break; } else if ((short)(left[i] & 0xff) > (short)(right[i] & 0xff)) { result = 1; break; } } } } } else { if (null != right) result = -1; // sort nothing before something // else fall through and compare publishers else result = 0; // null == null } return result; } public static int compare(ArrayList<byte []> left, ArrayList<byte []> right) { int result = 0; if (null != left) { if (null == right) { result = 1; } else { // here we have the comparison. int minlen = (left.size() < right.size()) ? left.size() : right.size(); for (int i=0; i < minlen; ++i) { result = compare(left.get(i), right.get(i)); if (0 != result) break; } if (result == 0) { // ok, they're equal up to the minimum length if (left.size() < right.size()) { result = -1; } else if (left.size() > right.size()) { result = 1; } // else they're equal, result = 0 } } } else { if (null != right) result = -1; // sort nothing before something // else fall through and compare publishers else result = 0; // null == null } return result; } public static String printBytes(byte [] bytes) { BigInteger bi = new BigInteger(1, bytes); return bi.toString(SystemConfiguration.DEBUG_RADIX); } public static String printHexBytes(byte [] bytes) { BigInteger bi = new BigInteger(1, bytes); return bi.toString(16); } /* * A place to centralize interfaces to base64 encoding/decoding, as the classes * we use change depending on what ships with Java. */ public static byte [] base64Decode(byte [] input) throws IOException { try { return Base64.decode(input); } catch (Base64DecodingException e) { throw new IOException("Exception in base64 decoding: " + e.getMessage()); } } public static String base6Encode(byte [] input) { return Base64.encode(input); } public static boolean arrayEquals(byte[] left, byte[] right, int length) { if (left == null) { return ((right == null) ? true : false); } if (right == null) { return ((left == null) ? true : false); } if (left.length < length || right.length < length) return false; for (int i = 0; i < length; i++) { if (left[i] != right[i]) return false; } return true; } /** * Converts a timestamp into a fixed point representation, with 12 bits in the fractional * component, and adds this to the ContentName as a version field. The timestamp is rounded * to the nearest value in the fixed point representation. * <p> * This allows versions to be recorded as a timestamp with a 1/4096 second accuracy. */ public static byte [] timestampToBinaryTime12(Timestamp timestamp) { long timeVal = timestampToBinaryTime12AsLong(timestamp); return BigInteger.valueOf(timeVal).toByteArray(); } public static long timestampToBinaryTime12AsLong(Timestamp timestamp) { long timeVal = (timestamp.getTime() / 1000) * 4096L + (timestamp.getNanos() * 4096L + 500000000L) / 1000000000L; return timeVal; } public static Timestamp binaryTime12ToTimestamp(byte [] binaryTime12) { if ((null == binaryTime12) || (binaryTime12.length == 0)) { throw new IllegalArgumentException("Invalid binary time!"); } else if (binaryTime12.length > 6) { throw new IllegalArgumentException("Time unacceptably far in the future, can't decode: " + printHexBytes(binaryTime12)); } long time = new BigInteger(binaryTime12).longValue(); Timestamp ts = binaryTime12ToTimestamp(time); return ts; } public static Timestamp binaryTime12ToTimestamp(long binaryTime12AsLong) { Timestamp ts = new Timestamp((binaryTime12AsLong / 4096L) * 1000L); ts.setNanos((int)(((binaryTime12AsLong % 4096L) * 1000000000L) / 4096L)); return ts; } /** * Compare timestamps taking into account the resolution lost in the conversion above. */ public static boolean timestampEquals(Timestamp t1, Timestamp t2) { long timeVal1 = (t1.getTime() / 1000) * 4096L + (t1.getNanos() * 4096L + 500000000L) / 1000000000L; long timeVal2 = (t2.getTime() / 1000) * 4096L + (t2.getNanos() * 4096L + 500000000L) / 1000000000L; return (timeVal1 == timeVal2); } /** * Rounding function for timestamps. */ public static Timestamp roundTimestamp(Timestamp origTimestamp) { Timestamp newTimestamp = (Timestamp)origTimestamp.clone(); newTimestamp.setNanos((int)(((newTimestamp.getNanos() % 4096L) * 1000000000L) / 4096L)); return newTimestamp; } public static boolean isBinaryPrefix(byte [] prefix, byte [] data) { if ((null == prefix) || (prefix.length == 0)) return true; if ((null == data) || (data.length < prefix.length)) return false; for (int i=0; i < prefix.length; ++i) { if (prefix[i] != data[i]) return false; } return true; } }
package CMRestaurant.test; import java.util.Timer; import junit.framework.TestCase; import restaurant.Restaurant; import restaurant.RevolvingStandMonitor; import restaurant.interfaces.Waiter.Menu; import restaurant.test.mock.MockCustomer; import CMRestaurant.roles.CMCookRole; import CMRestaurant.roles.CMSharedWaiterRole; import CMRestaurant.roles.CMWaiterRole.CustomerState; import city.PersonAgent; public class CMRevolingStandTest extends TestCase{ CMSharedWaiterRole waiter; RevolvingStandMonitor revolvingStand; CMCookRole cook; PersonAgent person; MockCustomer customer; Restaurant restaurant; Timer timer; Menu menu = new Menu(); /** * This method is run before each test. You can use it to instantiate the class variables * for your agent and mocks, etc. */ public void setUp() throws Exception{ super.setUp(); person = new PersonAgent("Alan", 500, 500); revolvingStand = new RevolvingStandMonitor(); cook = new CMCookRole(); cook.setRevolvingStand(revolvingStand); timer = new Timer(); restaurant = new Restaurant(null, null, cook, menu, "RestaurantCMCustomerRole", "RestaurantCM", null, null, "RestaurantCMWaiterRole"); waiter = new CMSharedWaiterRole(person, restaurant); customer = new MockCustomer("James"); } /** * The test starts with an empty revolving stand. Waiter fills it to capacity and tries to add * another order but should not be able to until the cook has removed the order. */ public void testWaiterPutInOrderAtMaximumCapacity() { //setUp() runs first before this test! waiter.testingRevolvingMonitor = true; // check preconditions assertTrue("Revolving stand should have no orders in it. It does.", 0 == revolvingStand.getCount()); /** * Step 1: Customer has ordered. Put order in revolving stand. */ waiter.customers.add(waiter.new MyCustomer(customer, 1, CustomerState.ordered, "chicken")); // check postconditions of step 1 and preconditions for step 2 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Customer state should be order placed.", CustomerState.orderPlaced.equals(waiter.customers.get(0).s)); assertTrue("Revolving stand should have 1 order in it. It doesn't.", 1 == revolvingStand.getCount()); /** * Step 2: Second customer order. Put order in revolving stand. */ waiter.customers.add(waiter.new MyCustomer(customer, 2, CustomerState.ordered, "steak")); // check postconditions for step 2 and preconditions for step 3 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Customer state should be order placed.", CustomerState.orderPlaced.equals(waiter.customers.get(1).s)); assertTrue("Revolving stand should have 2 orders in it. It doesn't.", 2 == revolvingStand.getCount()); /** * Step 3: Third customer order. Put order in revolving stand. */ waiter.customers.add(waiter.new MyCustomer(customer, 3, CustomerState.ordered, "cookie")); // check postconditions for step 3 and preconditions for step 4 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Customer state should be order placed.", CustomerState.orderPlaced.equals(waiter.customers.get(2).s)); assertTrue("Revolving stand should have 3 orders in it. It doesn't.", 3 == revolvingStand.getCount()); /** * Step 4: Fourth customer order. Put order in revolving stand. */ waiter.customers.add(waiter.new MyCustomer(customer, 4, CustomerState.ordered, "salad")); // check postconditions for step 4 and preconditions for step 5 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Customer state should be order placed.", CustomerState.orderPlaced.equals(waiter.customers.get(3).s)); assertTrue("Revolving stand should have 4 orders in it. It doesn't.", 4 == revolvingStand.getCount()); /** * Step 5: Fifth customer order. Put order in revolving stand. */ waiter.customers.add(waiter.new MyCustomer(customer, 5, CustomerState.ordered, "pizza")); // check postconditions for step 5 and preconditions for step 6 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Customer state should be order placed.", CustomerState.orderPlaced.equals(waiter.customers.get(4).s)); assertTrue("Revolving stand should have 5 orders in it. It doesn't.", 5 == revolvingStand.getCount()); /** * Step 6: Sixth customer order. Attempt to put order in revolving stand but fails. */ waiter.customers.add(waiter.new MyCustomer(customer, 6, CustomerState.ordered, "chicken")); // check postconditions for step 6 and preconditions for step 7 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Customer state should be ordered since stand is full.", CustomerState.ordered.equals(waiter.customers.get(5).s)); assertTrue("Revolving stand should have 5 orders in it. It doesn't.", 5 == revolvingStand.getCount()); /** * Step 7: Cook takes an order out of the revolving stand. */ cook.checkRevolvingStand(); // check postconditions for step 7 and preconditions for step 8 assertTrue("Revolving stand should have 4 orders in it. It doesn't.", 4 == revolvingStand.getCount()); /** * Step 8: Call the waiter's schedule again for it to reattempt putting order in stand. */ assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); // check postconditions for step 8 assertTrue("Customer state should be order placed.", CustomerState.orderPlaced.equals(waiter.customers.get(5).s)); assertTrue("Revolving stand should have 5 orders in it. It doesn't.", 5 == revolvingStand.getCount()); } /** * Cook tries to remove an order from an empty revolving stand but cannot until waiter has put in an order. */ public void testCookRemoveOrderWhenEmpty() { //setUp() runs first before this test! waiter.testingRevolvingMonitor = true; cook.setRevolvingStand(revolvingStand); // check preconditions assertTrue("Revolving stand should have no orders in it. It does.", 0 == revolvingStand.getCount()); /** * Step 1: Cook tries to take an order from the revolving stand but moves on because there is nothing to take */ cook.checkRevolvingStand(); // check postconditions of step 1 and preconditions of step 2 assertTrue("Revolving stand should have no orders in it. It does.", 0 == revolvingStand.getCount()); assertTrue("Cook goes on to do other things.", cook.pickAndExecuteAnAction()); /** * Step 2: Waiter adds an order */ waiter.customers.add(waiter.new MyCustomer(customer, 5, CustomerState.ordered, "pizza")); // check postconditions for step 2 and preconditions for step 3 assertTrue("Waiter scheduler should return true.", waiter.pickAndExecuteAnAction()); assertTrue("Revolving stand should have 1 order in it. It doesn't.", 1 == revolvingStand.getCount()); /** * Step 3: Cook removes the order successfully */ cook.checkRevolvingStand(); assertTrue("Revolving stand should have no orders in it. It does.", 0 == revolvingStand.getCount()); } }
package com.timepath.steam.io; import com.timepath.steam.io.storage.ACF; import com.timepath.steam.io.storage.util.DirectoryEntry; import com.timepath.vfs.VFile; import com.timepath.vfs.ftp.FTPFS; import com.timepath.vfs.http.HTTPFS; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author timepath */ public class ArchiveHost { /** * TODO: Merge valve package formats with same interface */ public static class ArchiveFile extends VFile { DirectoryEntry de; public ArchiveFile(DirectoryEntry de) { for(DirectoryEntry e : de.children()) { VFile vf = new ArchiveFile(e); this.add(vf); } this.de = de; } @Override public boolean isDirectory() { return de.isDirectory(); } @Override public String owner() { return "ftp"; } @Override public String group() { return "ftp"; } @Override public long fileSize() { return de.getItemSize(); } @Override public long modified() { return System.currentTimeMillis(); } @Override public String path() { return "/" + de.getPath(); } @Override public String name() { return de.getName(); } @Override public InputStream content() { return de.asStream(); } } public static void main(String... args) { int appID = 440; try { final ACF acf = ACF.fromManifest(appID); new Thread(new Runnable() { public void run() { try { HTTPFS http = new HTTPFS(8080); http.addAll(new ArchiveFile(acf.getRoot()).list()); http.run(); } catch(IOException ex) { Logger.getLogger(ArchiveHost.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); try { FTPFS ftp = new FTPFS(2121); ftp.addAll(new ArchiveFile(acf.getRoot()).list()); ftp.run(); } catch(IOException ex) { Logger.getLogger(ArchiveHost.class.getName()).log(Level.SEVERE, null, ex); } } catch(FileNotFoundException ex) { Logger.getLogger(ArchiveHost.class.getName()).log(Level.SEVERE, null, ex); } } }