file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
FunctionSymbol.java
/FileExtraction/Java_unseen/rk4an_ecos-controller/app/src/main/java/com/ecos/train/object/FunctionSymbol.java
package com.ecos.train.object; import android.util.SparseArray; public class FunctionSymbol { private static FunctionSymbol INSTANCE = null; private SparseArray<String> symbols; private FunctionSymbol(){ symbols = new SparseArray<String>(); symbols.put(2, "Function"); symbols.put(3, "Head light"); symbols.put(4, "Light 1"); symbols.put(5, "Light 2"); symbols.put(6, "Function"); //Fix Function symbols.put(7, "Sound"); symbols.put(8, "Music"); symbols.put(9, "Announce"); symbols.put(10, "Routing speed"); symbols.put(11, "ABV"); symbols.put(32, "Coupler"); symbols.put(33, "Steam"); symbols.put(34, "Panto"); symbols.put(35, "Hight beam"); symbols.put(36, "Bell"); symbols.put(37, "Horn"); symbols.put(38, "Whistle"); symbols.put(39, "Door sound"); symbols.put(40, "Fan"); symbols.put(42, "Shovel work sound"); symbols.put(44, "Shift"); symbols.put(260, "Interior lighting"); symbols.put(261, "Plate light"); symbols.put(263, "Brake sound"); symbols.put(299, "Crane raise lower"); symbols.put(555, "Hook up down"); symbols.put(773, "Wheel light"); symbols.put(811, "Turn crane"); symbols.put(1031, "Steam blow"); symbols.put(1033, "Radio sound"); symbols.put(1287, "Coupler sound"); symbols.put(1543, "Track sound"); symbols.put(1607, "Diesel Engine Notch Up"); symbols.put(1608, "Diesel Engine Notch Down"); symbols.put(2055, "Thunderer whistle"); symbols.put(3847, "Buffer sound"); symbols.put(11015, "Curve sound"); symbols.put(11271, "Relief valve"); symbols.put(11527, "Steam blow off"); symbols.put(553, "Air pump"); symbols.put(1321, "Water pump"); symbols.put(11783, "Sand"); symbols.put(1799, "Drain valve"); symbols.put(12039, "Set barke"); symbols.put(1029, "Set barke"); symbols.put(772, "Board lighting"); symbols.put(5639, "Diesel Engine Notch Up"); symbols.put(5640, "Diesel Engine Notch Down"); } public static synchronized FunctionSymbol getInstance(){ if (INSTANCE == null){ INSTANCE = new FunctionSymbol(); } return INSTANCE; } public SparseArray<String> getSymbols() { return symbols; } }
2,142
Java
.java
rk4an/ecos-controller
9
2
0
2012-04-22T11:06:55Z
2017-04-16T19:02:10Z
SiteswapTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/SiteswapTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class SiteswapTest { @Test public void testCreateSynchronousFromString() { String expected = new String("6p"); NumberFilter filter = new NumberFilter(expected, NumberFilter.Type.EQUAL, 1, 2); } @Test public void testParseString() { String siteswap_str_1 = "v1.0.0/86277.2.1.0"; String siteswap_str_1_substring = "86277.2.1.0"; Siteswap siteswap_1 = new Siteswap(siteswap_str_1); assertEquals("86277", siteswap_1.toAsyncString()); assertEquals(2, siteswap_1.getNumberOfJugglers()); assertEquals(1, siteswap_1.getNumberOfSynchronousHands()); assertEquals(0, siteswap_1.getSynchronousStartPosition()); assertEquals(siteswap_str_1_substring, siteswap_1.toParsableString()); String siteswap_str_2 = "c9ec99bc39ac99a.3.3.1"; Siteswap siteswap_2 = new Siteswap(siteswap_str_2); assertEquals("c9ec99bc39ac99a", siteswap_2.toAsyncString()); assertEquals(3, siteswap_2.getNumberOfJugglers()); assertEquals(3, siteswap_2.getNumberOfSynchronousHands()); assertEquals(1, siteswap_2.getSynchronousStartPosition()); assertEquals(siteswap_str_2, siteswap_2.toParsableString()); String siteswap_str_3 = "86277.2.1"; Siteswap siteswap_3 = new Siteswap(siteswap_str_3); assertEquals("86277", siteswap_3.toAsyncString()); assertEquals(2, siteswap_3.getNumberOfJugglers()); assertEquals(1, siteswap_3.getNumberOfSynchronousHands()); assertEquals(0, siteswap_3.getSynchronousStartPosition()); assertEquals(siteswap_str_1_substring, siteswap_3.toParsableString()); String siteswap_str_4 = "86277.2"; Siteswap siteswap_4 = new Siteswap(siteswap_str_4); assertEquals("86277", siteswap_4.toAsyncString()); assertEquals(2, siteswap_4.getNumberOfJugglers()); assertEquals(1, siteswap_4.getNumberOfSynchronousHands()); assertEquals(0, siteswap_4.getSynchronousStartPosition()); assertEquals(siteswap_str_1_substring, siteswap_4.toParsableString()); String siteswap_str_5 = "86277"; Siteswap siteswap_5 = new Siteswap(siteswap_str_5); assertEquals("86277", siteswap_5.toAsyncString()); assertEquals(2, siteswap_5.getNumberOfJugglers()); assertEquals(1, siteswap_5.getNumberOfSynchronousHands()); assertEquals(0, siteswap_5.getSynchronousStartPosition()); assertEquals(siteswap_str_1_substring, siteswap_5.toParsableString()); } @Test public void testMergeSyncSiteswapsFailOnInvalidSiteswap() { Siteswap s1 = new Siteswap("86277"); Siteswap s2 = new Siteswap("6787a"); Siteswap merged = Siteswap.mergeCompatible(s1, s2); assertEquals(merged, null); } @Test public void testMergeSyncSiteswapsFailOnIncompatibility() { Siteswap s1 = new Siteswap("86277"); Siteswap s2 = new Siteswap("86727"); Siteswap merged = Siteswap.mergeCompatible(s1, s2); assertEquals(merged, null); } }
4,013
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
SiteswapGeneratorTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/SiteswapGeneratorTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import java.util.LinkedList; import static org.junit.Assert.assertEquals; import static siteswaplib.SiteswapGenerator.Status.ALL_SITESWAPS_FOUND; public class SiteswapGeneratorTest { @Test public void testGeneration() { int numberOfJugglers = 2; int period = 7; int minThrow = 2; int maxThrow = 10; int numberOfObjects = 6; int numberOfSynchronousHands = 1; FilterList filters = new FilterList(); filters.addDefaultFilters(numberOfJugglers, minThrow, numberOfSynchronousHands); filters.add(new LocalInterfaceFilter( new Siteswap("ppspsps"), PatternFilter.Type.INCLUDE, numberOfJugglers)); filters.add(new LocalPatternFilter( new Siteswap("22"), PatternFilter.Type.EXCLUDE, numberOfJugglers)); filters.add(new LocalPatternFilter( new Siteswap("44"), PatternFilter.Type.EXCLUDE, numberOfJugglers)); SiteswapGenerator gen = new SiteswapGenerator(period, maxThrow, minThrow, numberOfObjects, numberOfJugglers, filters); gen.setSyncPattern(false); SiteswapGenerator.Status status = gen.generateSiteswaps(); assertEquals(ALL_SITESWAPS_FOUND, status); String expected = new String("[7567566, 7746675, 7746756, 7747746, 8456757, 8457567, 8457747, 8556756, 8557566, 8557746, 8557845, 8558556, 8627577, 8852757, 9245778, 9457467, 9458457, 9525678, 9527478, 9527892, 9529458, 9557466, 9557862, 9558456, 9558852, 9625677, 9627477, 9629457, 9645675, 9645774, 9685275, 9695274, 9724677, 9729627, 9744675, 9744774, 9749625, 9749724, 9784275, 9789225, 9794274, 9922497, 9924477, 9924972, 9929427, 9929922, 9952467, 9952962, a524579, a525578, a529529, a625577, a645575, a675275, a724577, a729527, a744575, a749525, a756275, a759245, a774275, a779225, a855275]"); assertEquals(expected, gen.getSiteswaps().toString()); return; } }
2,715
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
FilterListTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/FilterListTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FilterListTest { @Test public void testParsableStringConversion() { FilterList list1 = new FilterList(); list1.addDefaultFilters(5, 1); FilterList list2 = new FilterList(); list2.addDefaultFilters(3, 3); list1.add(new NumberFilter("9p", NumberFilter.Type.EQUAL, 1, 3)); list1.add(new NumberFilter("9", NumberFilter.Type.EQUAL, 1, 3)); list1.add(new LocalInterfaceFilter(new Siteswap("ppsps"), LocalInterfaceFilter.Type.EXCLUDE, 3)); String list1str = list1.toParsableString(); String list2str = list2.toParsableString(); FilterList list1conv = new FilterList().fromParsableString(list1str); FilterList list2conv = new FilterList().fromParsableString(list2str); assertEquals(list1, list1conv); assertEquals(list2, list2conv); } }
1,703
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
LocalPatternFilterTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/LocalPatternFilterTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LocalPatternFilterTest { @Test public void testParsableStringConversion() { LocalPatternFilter filter1 = new LocalPatternFilter(new Siteswap("ppsps"), LocalPatternFilter.Type.EXCLUDE, 3); LocalPatternFilter filter2 = new LocalPatternFilter(new Siteswap("972"), LocalPatternFilter.Type.INCLUDE, 5); String filter1str = filter1.toParsableString(); String filter2str = filter2.toParsableString(); LocalPatternFilter filter1conv = new LocalPatternFilter().fromParsableString(filter1str); LocalPatternFilter filter2conv = new LocalPatternFilter().fromParsableString(filter2str); assertEquals(filter1, filter1conv); assertEquals(filter2, filter2conv); } }
1,583
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
PatternFilterTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/PatternFilterTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class PatternFilterTest { @Test public void testParsableStringConversion() { PatternFilter filter1 = new PatternFilter(new Siteswap("ppsps"), PatternFilter.Type.EXCLUDE); PatternFilter filter2 = new PatternFilter(new Siteswap("972"), PatternFilter.Type.INCLUDE); String filter1str = filter1.toParsableString(); String filter2str = filter2.toParsableString(); PatternFilter filter1conv = new PatternFilter(filter1str); PatternFilter filter2conv = new PatternFilter(filter2str); assertEquals(filter1, filter1conv); assertEquals(filter2, filter2conv); } }
1,578
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NumberFilterTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/NumberFilterTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import static org.junit.Assert.*; public class NumberFilterTest { @Test public void testCreateSynchronousFromString() { String expected = new String("6p"); NumberFilter filter = new NumberFilter(expected, NumberFilter.Type.EQUAL, 1, 2); assertEquals(expected, filter.getFilterValue().toString()); } @Test public void testEquals() { NumberFilter filter1 = new NumberFilter("6p", NumberFilter.Type.EQUAL, 1, 2); NumberFilter filter2 = new NumberFilter("6p", NumberFilter.Type.EQUAL, 1, 2); NumberFilter filter3 = new NumberFilter("6", NumberFilter.Type.EQUAL, 1, 2); NumberFilter filter4 = new NumberFilter("8p", NumberFilter.Type.EQUAL, 1, 2); assertEquals(filter1, filter2); assertNotEquals(filter1, filter3); assertNotEquals(filter1, filter4); } @Test public void testSynchronousPassConversion() { NumberFilter filter = new NumberFilter("9p", NumberFilter.Type.EQUAL, 1, 3); assertArrayEquals(new int[]{10, 11}, filter.getFilterValue().getValues(0)); assertArrayEquals(new int[]{8, 10}, filter.getFilterValue().getValues(1)); assertArrayEquals(new int[]{7, 8}, filter.getFilterValue().getValues(2)); } @Test public void testCountValue() { NumberFilter filter1 = new NumberFilter("9p", NumberFilter.Type.EQUAL, 1, 3); NumberFilter filter2 = new NumberFilter("9", NumberFilter.Type.EQUAL, 1, 3); Siteswap siteswap1 = new Siteswap("89a4945", 3); Siteswap siteswap2 = new Siteswap("8859a57889a059a49a5919a3783", 3); siteswap1.setNumberOfSynchronousHands(3); siteswap2.setNumberOfSynchronousHands(3); siteswap2.setSynchronousStartPosition(2); int expected1 = 4; int expected2 = 9; int expected3 = 6; // Attention: counted over global period length int expected4 = 6; assertEquals(expected1, siteswap1.countFilterValue(filter1.getFilterValue())); assertEquals(expected2, siteswap2.countFilterValue(filter1.getFilterValue())); assertEquals(expected3, siteswap1.countFilterValue(filter2.getFilterValue())); assertEquals(expected4, siteswap2.countFilterValue(filter2.getFilterValue())); } @Test public void testParsableStringConversion() { NumberFilter filter1 = new NumberFilter("9p", NumberFilter.Type.EQUAL, 1, 3); NumberFilter filter2 = new NumberFilter("9", NumberFilter.Type.EQUAL, 1, 3); NumberFilter filter3 = new NumberFilter("5", NumberFilter.Type.GREATER_EQUAL, 3, 1); NumberFilter filter4 = new NumberFilter("a", NumberFilter.Type.SMALLER_EQUAL, 15, 1); String filter1str = filter1.toParsableString(); String filter2str = filter2.toParsableString(); String filter3str = filter3.toParsableString(); String filter4str = filter4.toParsableString(); NumberFilter filter1conv = new NumberFilter().fromParsableString(filter1str); NumberFilter filter2conv = new NumberFilter().fromParsableString(filter2str); NumberFilter filter3conv = new NumberFilter().fromParsableString(filter3str); NumberFilter filter4conv = new NumberFilter().fromParsableString(filter4str); assertEquals(filter1, filter1conv); assertEquals(filter2, filter2conv); assertEquals(filter3, filter3conv); assertEquals(filter4, filter4conv); } }
4,336
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
InterfaceFilterTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/InterfaceFilterTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import static org.junit.Assert.assertEquals; public class InterfaceFilterTest { @Test public void testParsableStringConversion() { InterfaceFilter filter1 = new InterfaceFilter(new Siteswap("ppsps"), InterfaceFilter.Type.EXCLUDE); InterfaceFilter filter2 = new InterfaceFilter(new Siteswap("972"), InterfaceFilter.Type.INCLUDE); String filter1str = filter1.toParsableString(); String filter2str = filter2.toParsableString(); InterfaceFilter filter1conv = new InterfaceFilter().fromParsableString(filter1str); InterfaceFilter filter2conv = new InterfaceFilter().fromParsableString(filter2str); assertEquals(filter1, filter1conv); assertEquals(filter2, filter2conv); } }
1,544
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
LocalInterfaceFilterTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/siteswaplib/LocalInterfaceFilterTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import org.junit.Test; import static org.junit.Assert.assertEquals; public class LocalInterfaceFilterTest { @Test public void testParsableStringConversion() { LocalInterfaceFilter filter1 = new LocalInterfaceFilter(new Siteswap("ppsps"), LocalInterfaceFilter.Type.EXCLUDE, 3); LocalInterfaceFilter filter2 = new LocalInterfaceFilter(new Siteswap("972"), LocalInterfaceFilter.Type.INCLUDE, 5); String filter1str = filter1.toParsableString(); String filter2str = filter2.toParsableString(); LocalInterfaceFilter filter1conv = new LocalInterfaceFilter().fromParsableString(filter1str); LocalInterfaceFilter filter2conv = new LocalInterfaceFilter().fromParsableString(filter2str); assertEquals(filter1, filter1conv); assertEquals(filter2, filter2conv); } }
1,605
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
ExampleUnitTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/test/java/namlit/siteswapgenerator/ExampleUnitTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
1,148
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
LocalPatternFilter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/LocalPatternFilter.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; /** * Created by tilman on 29.10.17. */ public class LocalPatternFilter extends PatternFilter { static final private String VERSION = "1"; private Siteswap mLocalPattern; public LocalPatternFilter() { } public LocalPatternFilter(String str) { fromParsableString(str); } public LocalPatternFilter(Siteswap pattern, Type type, int numberOfJugglers) { super(pattern, type); mLocalPattern = pattern; byte[] globalPattern = new byte[numberOfJugglers * pattern.period_length() - (numberOfJugglers-1)]; for (int i = 0; i < globalPattern.length; ++i) { if (i % numberOfJugglers == 0) globalPattern[i] = pattern.at(i / numberOfJugglers); else globalPattern[i] = Siteswap.DONT_CARE; } mPattern = new Siteswap(globalPattern); } @Override public String toParsableString() { String str = new String(); str += String.valueOf(VERSION) + ","; str += mLocalPattern.toParsableString() + ","; str += super.toParsableString(); return str; } @Override public LocalPatternFilter fromParsableString(String str) { String[] splits = str.split(","); int begin_index = 0; if (splits.length < 3) { return this; } if (!splits[0].equals(VERSION)) return this; begin_index += splits[0].length() + 1; mLocalPattern = new Siteswap(splits[1]); begin_index += splits[1].length() + 1; super.fromParsableString(str.substring(begin_index)); return this; } @Override public String toString() { String str; if (mType == Type.INCLUDE) str = new String("Include Local: "); else str = new String("Exclude Local: "); str += mLocalPattern.toString(); return str; } @Override public boolean equals(Object obj) { if (! (obj instanceof LocalPatternFilter)) return false; LocalPatternFilter rhs = (LocalPatternFilter) obj; return mLocalPattern.equals(rhs.mLocalPattern) && super.equals(rhs); } public Siteswap getGlobalPattern() { return mPattern; } @Override public Siteswap getPattern() { return mLocalPattern; } }
3,127
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
SiteswapGenerator.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/SiteswapGenerator.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import java.util.*; import java.io.Serializable; import java.util.concurrent.atomic.AtomicBoolean; public class SiteswapGenerator implements Serializable{ public enum Status {GENERATING, ALL_SITESWAPS_FOUND, RANDOM_SITESWAP_FOUND, MAX_RESULTS_REACHED, TIMEOUT_REACHED, MEMORY_FULL, CANCELLED}; private LinkedList<Siteswap> mSiteswaps; private FilterList mFilterList; private int mPeriodLength; private byte mMaxThrow; private byte mMinThrow; private byte mNumberOfObjects; private int mNumberOfJugglers; private int mMaxResults = 1000000000; private long mStartTime = 0; private int mTimeoutSeconds = 100; private boolean mCalculationComplete = false; private AtomicBoolean mIsCanceled; private int mBacktrackingCount = 0; // Just for algorithm performance analysis private int mNumberOfSynchronousHands = 1; private boolean mIsRandomGeneration = false; private Siteswap mCompatibleSiteswap = null; public SiteswapGenerator(int length, int max, int min, int objects, int number_of_jugglers) { this.mPeriodLength = length; if (length < 1) this.mPeriodLength = 1; this.mMaxThrow = (byte) max; this.mMinThrow = (byte) min; this.mNumberOfObjects = (byte) objects; if (objects < 1) { this.mNumberOfObjects = 1; } mIsCanceled = new AtomicBoolean(false); setNumberOfJugglers(number_of_jugglers); mFilterList = new FilterList(); mFilterList.addDefaultFilters(number_of_jugglers, mNumberOfSynchronousHands); } public SiteswapGenerator(int length, int max, int min, int objects, int number_of_jugglers, FilterList filterList) { this(length, max, min, objects, number_of_jugglers); mFilterList = filterList; } public LinkedList<Filter> getFilterList() { return mFilterList; } public void setFilterList(FilterList filterList) { this.mFilterList = filterList; } public Status generateSiteswaps() { mIsCanceled.set(false); mCalculationComplete = false; mBacktrackingCount = 0; mSiteswaps = new LinkedList<Siteswap>(); mStartTime = System.currentTimeMillis(); byte[] siteswapArray = new byte[mPeriodLength]; byte[] interfaceArray = new byte[mPeriodLength]; Arrays.fill(siteswapArray, Siteswap.FREE); Arrays.fill(interfaceArray, Siteswap.FREE); Siteswap siteswap; Siteswap siteswapInterface; Status status = Status.GENERATING; for (int i = 0; i < mNumberOfSynchronousHands; ++i) { siteswap = new Siteswap(siteswapArray, mNumberOfJugglers); siteswap.setNumberOfSynchronousHands(mNumberOfSynchronousHands); siteswap.setSynchronousStartPosition(i); siteswapInterface = new Siteswap(interfaceArray, mNumberOfJugglers); status = backtracking(siteswap, siteswapInterface, 0, 0); if (status != Status.GENERATING || mIsRandomGeneration) { break; } status = Status.ALL_SITESWAPS_FOUND; } if (mIsRandomGeneration) { while (status == Status.GENERATING || status == Status.RANDOM_SITESWAP_FOUND) { Arrays.fill(siteswapArray, Siteswap.FREE); Arrays.fill(interfaceArray, Siteswap.FREE); siteswap = new Siteswap(siteswapArray, mNumberOfJugglers); siteswap.setNumberOfSynchronousHands((mNumberOfSynchronousHands)); siteswap.setSynchronousStartPosition((new Random().nextInt(mNumberOfSynchronousHands))); siteswapInterface = new Siteswap(interfaceArray, mNumberOfJugglers); status = backtracking(siteswap, siteswapInterface, 0, 0); } } mCalculationComplete = true; return status; } public void setNumberOfJugglers(int numberOfJugglers) { this.mNumberOfJugglers = numberOfJugglers; if (numberOfJugglers < 1) this.mNumberOfJugglers = 1; } public void setPeriodLength(int periodLength) { this.mPeriodLength = periodLength; } public void setMaxThrow(int maxThrow) { this.mMaxThrow = (byte) maxThrow; } public void setMinThrow(int minThrow) { this.mMinThrow = (byte) minThrow; } public void setNumberOfObjects(int numberOfObjects) { this.mNumberOfObjects = (byte) numberOfObjects; } public void setMaxResults(int maxResults) { this.mMaxResults = maxResults; } public void setTimeoutSeconds(int timeoutSeconds) { this.mTimeoutSeconds = timeoutSeconds; } public void setSyncPattern(boolean isSyncPattern) { if (isSyncPattern) mNumberOfSynchronousHands = getNumberOfJugglers(); else mNumberOfSynchronousHands = 1; } public void setRandomGeneration(boolean isRandomGeneration) { mIsRandomGeneration = isRandomGeneration; } public void setCompatibleSiteswap(Siteswap siteswap) { mCompatibleSiteswap = siteswap; } public Siteswap getCompatibleSiteswap() { return mCompatibleSiteswap; } public LinkedList<Siteswap> getSiteswaps() { return mSiteswaps; } public int getNumberOfGeneratedSiteswaps() { if (mSiteswaps == null) return 0; return mSiteswaps.size(); } public int getPeriodLength() { return mPeriodLength; } public byte getMaxThrow() { return mMaxThrow; } public byte getMinThrow() { return mMinThrow; } public byte getNumberOfObjects() { return mNumberOfObjects; } public int getNumberOfJugglers() { return mNumberOfJugglers; } public int getMaxResults() { return mMaxResults; } public int getTimeoutSeconds() { return mTimeoutSeconds; } public int getBacktrackingCount() { return mBacktrackingCount; } public boolean isCalculationComplete() { return mCalculationComplete; } public void cancelGeneration() { mIsCanceled.set(true); } private int getMaxSumToGenerate(Siteswap siteswap, Siteswap siteswapInterface, int index) { int maxSum = 0; int interfaceIndex = siteswap.period_length() + mMaxThrow - 2; for(int i = siteswap.period_length() - 1; i >= index; --i) { while (siteswapInterface.at(interfaceIndex) != Siteswap.FREE) { interfaceIndex--; if (interfaceIndex < i) return 0; } maxSum += (interfaceIndex - i); interfaceIndex--; } return maxSum; } private int getMinSumToGenerate(Siteswap siteswap, Siteswap siteswapInterface, int index) { int minSum = 0; int interfaceIndex = index + mMinThrow; for(int i = index; i < siteswap.period_length(); ++i) { while (siteswapInterface.at(interfaceIndex) != Siteswap.FREE) { interfaceIndex++; if ((interfaceIndex - i) > mMaxThrow) return mMaxThrow; } minSum += (interfaceIndex - i); interfaceIndex++; } return minSum; } /** * Returns false, if an timeout occured, the maximum number of siteswaps is * reached or some error occurred. The siteswap calculation is then recursively * aborted. Returns true on normal, to indicate, that the siteswap search * shall be continued. * */ private Status backtracking(Siteswap siteswap, Siteswap siteswapInterface, int currentIndex, int uniqueRepresentationIndex) { mBacktrackingCount++; if (mBacktrackingCount % 1000 == 0 && System.currentTimeMillis() - mStartTime > mTimeoutSeconds * 1000) return Status.TIMEOUT_REACHED; if (mIsCanceled.get()) return Status.CANCELLED; if (currentIndex == mPeriodLength) { if (uniqueRepresentationIndex != 0) { // Representation is not unique or siteswap has shorter period. // Go a step back and continue searching... return Status.GENERATING; } if (matchesFilters(siteswap)) { mSiteswaps.add(new Siteswap(siteswap)); if(Runtime.getRuntime().maxMemory()-(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) < 1000) return Status.MEMORY_FULL; if (mSiteswaps.size() >= mMaxResults) return Status.MAX_RESULTS_REACHED; if (mIsRandomGeneration) return Status.RANDOM_SITESWAP_FOUND; } // A filter did not match. Go a step back and continue searching... return Status.GENERATING; } else { // Not last index if (currentIndex != 0) { if (!matchesFiltersPartialSitswap(siteswap, currentIndex - 1)) { // Go a step back and continue searching... return Status.GENERATING; } } } int min, max, uniqeMax; if (currentIndex == 0) { min = mNumberOfObjects; if (mIsRandomGeneration) min = mMaxThrow; max = mMaxThrow; uniqeMax = mMaxThrow + 1; // same value as max would result in wrong index calculation if (mPeriodLength == 1) { max = mNumberOfObjects; } } else { int partialSum = siteswap.getPartialSum(0, currentIndex - 1); int sum = mPeriodLength * mNumberOfObjects; // calculate minimum throw. The minimum throw must be hight enougth, that // the overall sum can be numberOfOjects * periodLength int minDeterminedByAverage = sum - partialSum - getMaxSumToGenerate(siteswap, siteswapInterface, currentIndex + 1); min = (minDeterminedByAverage > mMinThrow) ? minDeterminedByAverage : mMinThrow; // calculate max throw. The maximum throw can not be higher, than required // by the unique representation property. Additionally it must be possible, // that the overall sum is numberOfOjects * periodLength uniqeMax = siteswap.at(uniqueRepresentationIndex); int maxDeterminedByAverage = sum - partialSum - getMinSumToGenerate(siteswap, siteswapInterface, currentIndex + 1); max = (maxDeterminedByAverage < uniqeMax) ? maxDeterminedByAverage : uniqeMax; } for (int value = min; value <= max; ++value) { if (mIsRandomGeneration) { Random rand = new Random(); value = rand.nextInt(max - min + 1) + min; } if (siteswapInterface.at(currentIndex + value) != Siteswap.FREE) continue; siteswap.set(currentIndex, value); siteswapInterface.set(currentIndex + value, value); int nextUniqueIndex = (value == uniqeMax) ? uniqueRepresentationIndex + 1 : 0; Status status = backtracking(siteswap, siteswapInterface, currentIndex + 1, nextUniqueIndex); if (status != Status.GENERATING) return status; siteswapInterface.set(currentIndex + value, Siteswap.FREE); } siteswap.set(currentIndex, Siteswap.FREE); // reset value for backtracking return Status.GENERATING; } private boolean matchesFilters(Siteswap siteswap) { if (mFilterList == null) return true; for (Filter filter : mFilterList) { if (!filter.isFulfilled(siteswap)) return false; } return true; } private boolean matchesFiltersPartialSitswap(Siteswap siteswap, int index) { if (mFilterList == null) return true; for (Filter filter : mFilterList) { if (!filter.isPartlyFulfilled(siteswap, index)) return false; } return true; } }
11,249
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
PatternFilter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/PatternFilter.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; public class PatternFilter extends Filter { public enum Type {EXCLUDE, INCLUDE} static final private String VERSION = "1"; protected Siteswap mPattern; protected Type mType; public PatternFilter() { } public PatternFilter(String str) { fromParsableString(str); } public PatternFilter(Siteswap pattern, Type type) { this.mPattern = pattern; this.mType = type; } @Override public boolean isFulfilled(Siteswap siteswap) { if (mType == Type.INCLUDE) return siteswap.isPattern(mPattern); return !siteswap.isPattern(mPattern); } @Override public boolean isPartlyFulfilled(Siteswap siteswap, int index) { if (mType == Type.INCLUDE) return true; // TODO return false, if it is impossible to fulfill pattern switch (mType) { case INCLUDE: break; case EXCLUDE: if (index < mPattern.period_length() - 1) return true; return !siteswap.isPattern(mPattern, index + 1 - mPattern.period_length()); } return true; } @Override public String toParsableString() { String str = new String(); str += String.valueOf(VERSION) + ","; str += mPattern.toParsableString() + ","; str += mType.toString() + ","; return str; } @Override public PatternFilter fromParsableString(String str) { String[] splits = str.split(","); if (splits.length < 3) { return this; } if (!splits[0].equals(VERSION)) return this; mPattern = new Siteswap(splits[1]); mType = Type.valueOf(splits[2]); return this; } @Override public String toString() { String str; if (mType == Type.INCLUDE) str = new String("Include: "); else str = new String("Exclude: "); str += mPattern.toString(); return str; } @Override public boolean equals(Object obj) { if (! (obj instanceof PatternFilter)) return false; PatternFilter rhs = (PatternFilter) obj; return mType.equals(rhs.mType) && mPattern.equals(rhs.mPattern); } public Type getType() { return mType; } public Siteswap getPattern() { return mPattern; } }
2,802
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
Filter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/Filter.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import java.io.Serializable; import java.util.LinkedList; import siteswaplib.NumberFilter.Type; public abstract class Filter implements Serializable { public enum FilterType {NUMBER_FILTER, PATTERN_FILTER, INTERFACE_FILTER, LOCAL_PATTERN_FILTER, LOCAL_INTERFACE_FILTER}; public abstract boolean isFulfilled(Siteswap siteswap); /** * The filter is only tested at/up to index position. This function can be * used during siteswap generation to test, if a partly generated siteswap * would fulfill the filter condition. Returns true, if the filter is currently * fulfilled or might be fulfilled later, when the complete siteswap is * generated. Returns False, if it is not possible anymore, to fulfill the filter * condition. * */ public abstract boolean isPartlyFulfilled(Siteswap siteswap, int index); public abstract String toParsableString(); public abstract Filter fromParsableString(String str); }
1,727
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NumberFilter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/NumberFilter.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import java.io.Serializable; public class NumberFilter extends Filter { static final private String VERSION = "1"; public class FilterValue implements Serializable { private int mValue; public FilterValue(int filterValue) { this.mValue = filterValue; } public FilterValue(String filterValue) { fromString(filterValue); } public void setValue(int value) { this.mValue = value; } // A 6p in a synchronous pattern can be either a 5 or a 7 // This function returns all possible numbers at a given // synchronous position index public int[] getValues(int synchronousPosition) { if (isSpecialThrow()) { return new int[]{mValue}; } if (mValue % mNumberOfSynchronousHands == 0) { return new int[]{mValue}; } int landingPosition = 0; int length = mNumberOfSynchronousHands - 1; if (getCorrectedValue() == 0) { length -= synchronousPosition; landingPosition = synchronousPosition + 1; } int values[] = new int[length]; for (int i = 0; i < length; ++i) { if (landingPosition == synchronousPosition) ++landingPosition; values[i] = getCorrectedValue() + (landingPosition - synchronousPosition); ++landingPosition; } return values; } public int getCorrectedValue() { if (isSpecialThrow()) return mValue; int diffToValidThrow = mValue % mNumberOfSynchronousHands; return mValue - diffToValidThrow; } public void fromString(String strValue) { if (mNumberOfSynchronousHands > 1 && strValue.length() == 2 && strValue.charAt(1) == 'p') { mValue = Siteswap.charToInt(strValue.charAt(0)) + 1; if (mValue % mNumberOfSynchronousHands != 1) mValue = Siteswap.INVALID; return; } mValue = Siteswap.stringToInt(strValue); } public String toParsableString() { return String.valueOf(mValue); } void fromParsableString(String str) { try { mValue = Integer.valueOf(str); } catch (NumberFormatException e) { } } @Override public String toString() { if (mValue < 0) { // Pass or Self: use String conversion of Siteswap class return Siteswap.intToString(mValue); } int diffToValidThrow = mValue % mNumberOfSynchronousHands; String str = Siteswap.intToString(mValue - diffToValidThrow); if (diffToValidThrow != 0) str += "p"; return str; } @Override public boolean equals(Object obj) { if (! (obj instanceof FilterValue)) return false; FilterValue rhs = (FilterValue) obj; return toString().equals(rhs.toString()); } @Override public int hashCode() { return toString().hashCode(); } public boolean isGenericPass() { return mValue == Siteswap.PASS; } public boolean isGenericSelf() { return mValue == Siteswap.SELF; } public boolean isSpecialThrow() { return mValue < 0; } } public enum Type {GREATER_EQUAL, SMALLER_EQUAL, EQUAL} private Type mType; private FilterValue mFilterValue; private int mThresholdValue; private int mNumberOfSynchronousHands; public NumberFilter() { } public NumberFilter(String str) { fromParsableString(str); } public NumberFilter(int filterValue, Type type, int threshold, int numberOfSynchronousHands) { this.mType = type; this.mThresholdValue = threshold; this.mNumberOfSynchronousHands = numberOfSynchronousHands; this.mFilterValue = new FilterValue(filterValue); } public NumberFilter(String filterValue, Type type, int threshold, int numberOfSynchronousHands) { this.mType = type; this.mThresholdValue = threshold; this.mNumberOfSynchronousHands = numberOfSynchronousHands; this.mFilterValue = new FilterValue(filterValue); } public void setNumberOfSynchronousHands(int numberOfSynchronousHands) { this.mNumberOfSynchronousHands = numberOfSynchronousHands; } @Override public boolean isFulfilled(Siteswap siteswap) { if (mType == Type.GREATER_EQUAL) return siteswap.countFilterValue(mFilterValue) >= mThresholdValue; if (mType == Type.SMALLER_EQUAL) return siteswap.countFilterValue(mFilterValue) <= mThresholdValue; return siteswap.countFilterValue(mFilterValue) == mThresholdValue; } @Override public boolean isPartlyFulfilled(Siteswap siteswap, int index) { int currentCount = siteswap.countFilterValuePartitially(mFilterValue, index); switch (mType) { case GREATER_EQUAL: return currentCount + (siteswap.global_period_length() - index) > mThresholdValue; case SMALLER_EQUAL: return currentCount <= mThresholdValue; case EQUAL: return currentCount <= mThresholdValue && currentCount + (siteswap.global_period_length() - index) > mThresholdValue; } return true; } @Override public String toParsableString() { String str = new String(); str += String.valueOf(VERSION) + ","; str += mType.toString() + ","; str += String.valueOf(mFilterValue.mValue) + ","; str += String.valueOf(mNumberOfSynchronousHands) + ","; str += String.valueOf(mThresholdValue) + ","; return str; } @Override public NumberFilter fromParsableString(String str) { String[] splits = str.split(","); if (splits.length < 5) { return this; } if (!splits[0].equals(VERSION)) return this; mType = Type.valueOf(splits[1]); try { mFilterValue = new FilterValue(Integer.valueOf(splits[2])); mNumberOfSynchronousHands = Integer.valueOf(splits[3]); mThresholdValue = Integer.valueOf(splits[4]); } catch (NumberFormatException e) { return this; } return this; } @Override public String toString() { String str = new String(""); if (mType == Type.EQUAL) { if (mThresholdValue == 0) return "no " + mFilterValue.toString(); else str += "exactly " + Siteswap.intToString(mThresholdValue); } else if (mType == Type.GREATER_EQUAL) str += "at least " + Siteswap.intToString(mThresholdValue); else if (mType == Type.SMALLER_EQUAL) str += "not more than " + Siteswap.intToString(mThresholdValue); else return ""; if (mFilterValue.isSpecialThrow()) { // Pass or Self: use String conversion of Siteswap class str += " " + mFilterValue.toString(); if (mThresholdValue != 1) { // Plural s on string representation needed if (mFilterValue.isGenericPass()) str += "es"; else str += "s"; } } else { // throw with height >= 0 if (mThresholdValue == 1) str += " throw"; else str += " throws"; str += " with height " + mFilterValue.toString(); } return str; } @Override public boolean equals(Object obj) { if (! (obj instanceof NumberFilter)) return false; NumberFilter rhs = (NumberFilter) obj; return toString().equals(rhs.toString()); } @Override public int hashCode() { return toString().hashCode(); } public Type getType() { return mType; } public FilterValue getFilterValue() { return mFilterValue; } public int getThresholdValue() { return mThresholdValue; } static public String[] getPossibleValues(int minThrow, int maxThrow, int numberOfSynchronousHands) { if (minThrow > maxThrow) { return new String[0]; } if (numberOfSynchronousHands == 1) { int length = maxThrow - minThrow + 1; String arr[] = new String[length]; for(int i = 0; i < length; ++i) { arr[i] = Siteswap.intToString(i + minThrow); } return arr; } int distMinToValidThrow = minThrow % numberOfSynchronousHands; int distMaxToValidThrow = maxThrow % numberOfSynchronousHands; int length = 2 * ((maxThrow - distMaxToValidThrow - minThrow) / numberOfSynchronousHands + 1); if (distMinToValidThrow != 0) { length += 1; } if (distMaxToValidThrow != 0) { length += 1; } String[] arr = new String[length]; int i = 0; int currentThrow = minThrow; if (distMinToValidThrow != 0) { arr[i] = Siteswap.intToString(minThrow - distMinToValidThrow) + "p"; currentThrow = minThrow + (numberOfSynchronousHands - distMinToValidThrow); ++i; } for(; i < length - 1; i += 2) { arr[i] = Siteswap.intToString(currentThrow); arr[i+1] = Siteswap.intToString(currentThrow) + "p"; currentThrow += numberOfSynchronousHands; } if (distMaxToValidThrow != 0) { arr[i] = Siteswap.intToString(currentThrow) + "p"; } return arr; } }
9,087
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NamedSiteswaps.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/NamedSiteswaps.java
package siteswaplib; import java.util.Arrays; import java.util.List; public class NamedSiteswaps { static final private List<NamedSiteswap> namedSiteswapsList = Arrays.asList( new NamedSiteswap("86722", 2, "5 club not why"), new NamedSiteswap("86227", 2, "5 club why not"), new NamedSiteswap("86867", 2, "5 count popcorn (44)"), new NamedSiteswap("a6667", 2, "5 count popcorn"), new NamedSiteswap("9964966", 2, "7 club Jim's 2 count"), new NamedSiteswap("9964786", 2, "7 club Jim's 2 count (variation)"), new NamedSiteswap("9784966", 2, "7 club Jim's 2 count (variation)"), new NamedSiteswap("9784786", 2, "7 club Jim's 2 count (variation)"), new NamedSiteswap("9969268", 2, "7 club maybe (1)"), new NamedSiteswap("9968296", 2, "7 club maybe (2)"), new NamedSiteswap("9968278", 2, "7 club maybe (variation)"), new NamedSiteswap("7", 2, "7 club one count"), new NamedSiteswap("9962968", 2, "7 club not why"), new NamedSiteswap("9962788", 2, "7 club not why (variation)"), new NamedSiteswap("9782968", 2, "7 club not why (variation)"), new NamedSiteswap("9782788", 2, "7 club not why (variation)"), new NamedSiteswap("966", 2, "7 club three count"), new NamedSiteswap("7786867", 2, "7 club Vitoria"), new NamedSiteswap("9968926", 2, "7 club why not"), new NamedSiteswap("9788926", 2, "7 club why not (variation)"), new NamedSiteswap("8686867", 2, "7 count popcorn"), new NamedSiteswap("9668686", 2, "7 count popcorn (variation)"), new NamedSiteswap("a666786", 2, "7 count popcorn (variation)"), new NamedSiteswap("a666867", 2, "7 count popcorn (variation)"), new NamedSiteswap("a666966", 2, "7 count popcorn (variation)"), new NamedSiteswap("996", 2, "8 club pps"), new NamedSiteswap("9797888", 2, "8 club Vitoria"), new NamedSiteswap("9", 2, "9 club one count"), new NamedSiteswap("a2747", 2, "aa7 Warmup Pattern"), new NamedSiteswap("9667867", 2, "Aspirin"), new NamedSiteswap("756", 2, "baby dragon; zap opus 1; holy hand-grenade"), new NamedSiteswap("9968978", 2, "Clean Finish"), new NamedSiteswap("726", 2, "coconut laden swallow"), new NamedSiteswap("9789268", 2, "Das Schirche"), new NamedSiteswap("7796686", 2, "Das Schöne"), new NamedSiteswap("945", 2, "dragon; black beast of aaaarg..."), new NamedSiteswap("7742744", 2, "Flipalot"), new NamedSiteswap("867", 2, "French 3 count"), new NamedSiteswap("86777", 2, "Funky Bookends"), new NamedSiteswap("942", 2, "glass elevator"), new NamedSiteswap("9792688", 2, "Good Morning"), new NamedSiteswap("996882777", 2, "Great Chaos"), new NamedSiteswap("8882225", 2, "Heffalot"), new NamedSiteswap("975", 2, "Holy Grail; zap opus two"), new NamedSiteswap("77222", 2, "inverted parsnip"), new NamedSiteswap("75724", 2, "Kaatzi"), new NamedSiteswap("645", 2, "killer bunny"), new NamedSiteswap("774", 2, "Jim's 1 count (async)"), new NamedSiteswap("77466", 2, "Jim's 2 count (async)"), new NamedSiteswap("77772", 2, "Martin's one count (async)"), new NamedSiteswap("86727", 2, "maybe"), new NamedSiteswap("96627", 2, "maybe not"), new NamedSiteswap("7777266", 2, "Mild Madness (async)"), new NamedSiteswap("9789788", 2, "Milk Duds"), new NamedSiteswap("9647772", 2, "Odnom"), new NamedSiteswap("9969968", 2, "Ollerup"), new NamedSiteswap("96672", 2, "not likely"), new NamedSiteswap("86772", 2, "not why"), new NamedSiteswap("77722", 2, "parsnip"), new NamedSiteswap("99494", 2, "Peanut Flips"), new NamedSiteswap("9669667", 2, "Placebo"), new NamedSiteswap("9969788", 2, "Poem"), new NamedSiteswap("9968897", 2, "Real Fake Clean Finish"), new NamedSiteswap("7284554", 2, "The forgotten Flip"), new NamedSiteswap("7788289247772", 2, "The missing elevator button"), new NamedSiteswap("97428", 2, "The One to Concentrate"), new NamedSiteswap("86277", 2, "why not") ); static public List<NamedSiteswap> getListOfNamedSiteswaps() { return namedSiteswapsList; } }
4,642
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
LocalInterfaceFilter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/LocalInterfaceFilter.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; /** * Created by tilman on 29.10.17. */ public class LocalInterfaceFilter extends InterfaceFilter { static final private String VERSION = "1"; private Siteswap mLocalPattern; public LocalInterfaceFilter() { } public LocalInterfaceFilter(String str) { fromParsableString(str); } public LocalInterfaceFilter(Siteswap pattern, Type type, int numberOfJugglers) { super(pattern, type); mLocalPattern = pattern; byte[] globalPattern = new byte[numberOfJugglers * pattern.period_length() - (numberOfJugglers-1)]; for (int i = 0; i < globalPattern.length; ++i) { if (i % numberOfJugglers == 0) globalPattern[i] = pattern.at(i / numberOfJugglers); else globalPattern[i] = Siteswap.DONT_CARE; } mPattern = new Siteswap(globalPattern); } @Override public String toParsableString() { String str = new String(); str += String.valueOf(VERSION) + ","; str += mLocalPattern.toParsableString() + ","; str += super.toParsableString(); return str; } @Override public LocalInterfaceFilter fromParsableString(String str) { String[] splits = str.split(","); int begin_index = 0; if (splits.length < 3) { return this; } if (!splits[0].equals(VERSION)) return this; begin_index += splits[0].length() + 1; mLocalPattern = new Siteswap(splits[1]); begin_index += splits[1].length() + 1; super.fromParsableString(str.substring(begin_index)); return this; } @Override public String toString() { String str; if (mType == Type.INCLUDE) str = new String("Include Local Interface: "); else str = new String("Exclude Local Interface: "); str += mLocalPattern.toString(); return str; } public Siteswap getGlobalPattern() { return mPattern; } @Override public Siteswap getPattern() { return mLocalPattern; } }
2,885
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
CyclicByteArray.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/CyclicByteArray.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import java.util.*; import java.io.Serializable; public class CyclicByteArray implements Iterable<Byte>, Iterator<Byte>, Serializable{ private int first_element_index = 0; private int iterator_count = 0; private byte[] data; public CyclicByteArray(byte[] data) { this.data = new byte[data.length]; for(int i = 0; i < data.length; ++i) this.data[i] = data[i]; } public CyclicByteArray(CyclicByteArray array) { this(array.data); this.first_element_index = array.first_element_index; } public byte at(int index) { if (length() == 0) return 0; return data[((first_element_index + index) % length() + length()) % length()]; } public void modify(int index, byte value) { if (length() == 0) return; data[((first_element_index + index) % length() + length()) % length()] = value; } public int length() { return data.length; } public void rotateRight(int positions) { if (length() == 0) return; first_element_index = (first_element_index - positions) % length(); if (first_element_index < 0) first_element_index += length(); } public void rotateLeft(int positions) { if (length() == 0) return; first_element_index = (first_element_index + positions) % length(); if (first_element_index < 0) first_element_index += length(); } @Override public Iterator<Byte> iterator() { iterator_count = 0; return this; } @Override public boolean hasNext() { return iterator_count != length(); } @Override public Byte next() { if (iterator_count >= length()) throw new NoSuchElementException(); return at(iterator_count++); } @Override public void remove() { // not implemented } }
2,443
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NamedSiteswap.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/NamedSiteswap.java
package siteswaplib; import androidx.annotation.NonNull; public class NamedSiteswap extends Siteswap { public NamedSiteswap(String siteswap, int numJugglers, String name) { super(siteswap, numJugglers, name); } public NamedSiteswap(Siteswap siteswap) { super(siteswap); } @NonNull @Override public String toString() { String name = getSiteswapName() == "" ? "" : getSiteswapName() + ": "; return name + super.toString(); } }
495
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
FilterList.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/FilterList.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import siteswaplib.NumberFilter.Type; public class FilterList extends LinkedList<Filter> implements Serializable { public FilterList() { } public FilterList(int numberOfJugglers, int numberOfSynchronousHands) { addDefaultFilters(numberOfJugglers, numberOfSynchronousHands); } // TODO add and use method updateNumberOfJugglersAndSynchronousHands public void addDefaultFilters(int numberOfJugglers, int minThrow, int numberOfSynchronousHands) { if (numberOfJugglers <= 1) return; // remove Filters first, to avoid duplicate filters removeDefaultFilters(numberOfJugglers, minThrow, numberOfSynchronousHands); addFirst(new NumberFilter(Siteswap.PASS, Type.GREATER_EQUAL, 1, numberOfSynchronousHands)); for (int i = minThrow; i < 2*numberOfJugglers; ++i) { if ( Siteswap.isPass(i, numberOfJugglers)) { NumberFilter filter = new NumberFilter(i, Type.EQUAL, 0, numberOfSynchronousHands); if (!contains(filter)) addFirst(filter); } } } public void addDefaultFilters(int numberOfJugglers, int numberOfSynchronousHands) { addDefaultFilters(numberOfJugglers, 0, numberOfSynchronousHands); } public void addZips(int numberOfJugglers, int numberOfSynchronousHands) { while (remove(new NumberFilter(numberOfJugglers, Type.EQUAL, 0, numberOfSynchronousHands))) ; } public void addZaps(int numberOfJugglers, int numberOfSynchronousHands) { int max = 3*numberOfJugglers; if (numberOfSynchronousHands > 1 && numberOfJugglers > 1) max = 2 * numberOfJugglers + 2; // Where is just one zap in synchronous patters "2p" for (int i = 2 * numberOfJugglers + 1; i < max; ++i) { if ( Siteswap.isPass(i, numberOfJugglers)) while (remove(new NumberFilter(i, Type.EQUAL, 0, numberOfSynchronousHands))) ; } } public void addHolds(int numberOfJugglers, int numberOfSynchronousHands) { remove(new NumberFilter(2 * numberOfJugglers, Type.EQUAL, 0, numberOfSynchronousHands)); } public void removeDefaultFilters(int numberOfJugglers, int minThrow, int numberOfSynchronousHands) { if (numberOfJugglers <= 1) return; while (remove(new NumberFilter(Siteswap.PASS, Type.GREATER_EQUAL, 1, numberOfSynchronousHands))) ; for (int i = minThrow; i < 2*numberOfJugglers; ++i) { if ( Siteswap.isPass(i, numberOfJugglers)) while (remove(new NumberFilter(i, Type.EQUAL, 0, numberOfSynchronousHands))) ; } } public void removeDefaultFilters(int numberOfJugglers, int numberOfSynchronousHands) { removeDefaultFilters(numberOfJugglers, 0, numberOfSynchronousHands); } public void removeZips(int numberOfJugglers, int numberOfSynchronousHands) { addZips(numberOfJugglers, numberOfSynchronousHands); addFirst(new NumberFilter(numberOfJugglers, Type.EQUAL, 0, 1)); } public void removeZaps(int numberOfJugglers, int numberOfSynchronousHands) { addZaps(numberOfJugglers, numberOfSynchronousHands); int max = 3*numberOfJugglers; if (numberOfSynchronousHands > 1 && numberOfJugglers > 1) max = 2 * numberOfJugglers + 2; // Where is just one zap in synchronous patters "2p" for (int i = 2 * numberOfJugglers + 1; i < max; ++i) { if ( Siteswap.isPass(i, numberOfJugglers)) addFirst(new NumberFilter(i, Type.EQUAL, 0, numberOfSynchronousHands)); } } public void removeHolds(int numberOfJugglers, int numberOfSynchronousHands) { addHolds(numberOfJugglers, numberOfSynchronousHands); addFirst(new NumberFilter(2 * numberOfJugglers, Type.EQUAL, 0, 1)); } public String toParsableString() { String str = new String(); for (Filter filter : this) { if (filter instanceof LocalPatternFilter) { str += Filter.FilterType.LOCAL_PATTERN_FILTER.toString() + ":"; str += filter.toParsableString() + ";"; } else if (filter instanceof LocalInterfaceFilter) { str += Filter.FilterType.LOCAL_INTERFACE_FILTER.toString() + ":"; str += filter.toParsableString() + ";"; } else if (filter instanceof PatternFilter) { str += Filter.FilterType.PATTERN_FILTER.toString() + ":"; str += filter.toParsableString() + ";"; } else if (filter instanceof InterfaceFilter) { str += Filter.FilterType.INTERFACE_FILTER.toString() + ":"; str += filter.toParsableString() + ";"; } else if (filter instanceof NumberFilter) { str += Filter.FilterType.NUMBER_FILTER.toString() + ":"; str += filter.toParsableString() + ";"; } } return str; } public FilterList fromParsableString(String str) { clear(); String[] filters = str.split(";"); for (String f : filters) { String[] filter = f.split(":"); if (filter.length != 2) continue; if (Filter.FilterType.valueOf(filter[0]).equals(Filter.FilterType.LOCAL_PATTERN_FILTER)) { add(new LocalPatternFilter(filter[1])); } else if (Filter.FilterType.valueOf(filter[0]).equals(Filter.FilterType.LOCAL_INTERFACE_FILTER)) { add(new LocalInterfaceFilter(filter[1])); } else if (Filter.FilterType.valueOf(filter[0]).equals(Filter.FilterType.PATTERN_FILTER)) { add(new PatternFilter(filter[1])); } else if (Filter.FilterType.valueOf(filter[0]).equals(Filter.FilterType.INTERFACE_FILTER)) { add(new InterfaceFilter(filter[1])); } else if (Filter.FilterType.valueOf(filter[0]).equals(Filter.FilterType.NUMBER_FILTER)) { add(new NumberFilter(filter[1])); } } return this; } }
6,710
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
Siteswap.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/Siteswap.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; import java.text.DecimalFormat; import java.util.*; import java.io.Serializable; public class Siteswap implements Comparable<Siteswap>, Iterable<Byte>, Serializable { public static final byte SELF = -1; public static final byte PASS = -2; public static final byte DONT_CARE = -3; public static final byte FREE = -4; public static final byte INVALID = -5; private CyclicByteArray mData; private int mNumberOfJugglers = 1; private String mSiteswapName = ""; private String mInvalidCharacters = ""; private boolean mIsParsingError = false; private int mNumberOfSynchronousHands = 1; // when there are n throws at the same time, each siteswap number can be at position // 0, ... n-1 within the synchronous throws. The position of siteswap.at(0) is coded // in mSynchronousStartPosition and is adapted on every rotation of the siteswap. private int mSynchronousStartPosition = 0; public Siteswap() { this(new byte[0]); } public Siteswap(Siteswap s) { this.mData = new CyclicByteArray(s.mData); setNumberOfJugglers(s.getNumberOfJugglers()); setSiteswapName(s.getSiteswapName()); setNumberOfSynchronousHands(s.getNumberOfSynchronousHands()); setSynchronousStartPosition(s.getSynchronousStartPosition()); } public Siteswap(byte[] data, int numberOfJugglers) { this.mData = new CyclicByteArray(data); setNumberOfJugglers(numberOfJugglers); } public Siteswap(String siteswap, int numberOfJugglers, String name) { this(siteswap, numberOfJugglers); setSiteswapName(name); } public Siteswap(String siteswap, int numberOfJugglers) { setNumberOfJugglers(numberOfJugglers); fromParsableString(siteswap); } public Siteswap(String siteswap, String host, String query) { // set default value for number of jugglers setNumberOfJugglers(2); if (host.equals("siteswap.de")) { fromParsableString(siteswap); } if (host.equals("passist.org")) { fromPassistString(siteswap, query); } } public Siteswap(String siteswap) { this(siteswap, 2); } public Siteswap(byte[] data) { this(data, 1); } public byte at(int index) { return mData.at(index); } public byte atSyncCorrected(int index) { return (byte) (getNumberOfSynchronousHands() * ((getSynchronousPosition(index) + at(index)) / getNumberOfSynchronousHands())); } public void set(int index, int value) { mData.modify(index, (byte) value); } public int period_length() { return mData.length(); } public int local_period_length() { if (period_length() % getNumberOfJugglers() == 0) return period_length() / getNumberOfJugglers(); return period_length(); } // TODO rename public int global_period_length() { int length = period_length(); if (period_length() % getNumberOfSynchronousHands() != 0) { while (length % getNumberOfSynchronousHands() != 0) { length += period_length(); } } return length; } public int getNonMirroredPeriod() { int length = period_length(); int number_of_hands = getNumberOfHands(); while (length % number_of_hands != 0) { length += period_length(); } return length; } public int getNumberOfHands() { return 2 * getNumberOfJugglers(); } public void swap(int index) { byte temp = mData.at(index + 1); mData.modify(index+1, (byte) (mData.at(index) - 1)); mData.modify(index, (byte) (temp + 1)); } public int getMaxThrow() { int max = 0; for(int i = 0; i < period_length(); ++i) { if (at(i) > max) max = at(i); } return max; } public int getNumberOfObjects() { if (period_length() == 0) return 0; return getPartialSum(0, period_length()-1) / period_length(); } public int getNumberOfJugglers() { return mNumberOfJugglers; } private void setNumberOfJugglers(int numberOfJugglers) { this.mNumberOfJugglers = numberOfJugglers; if (numberOfJugglers < 1) this.mNumberOfJugglers = 1; } public boolean setNumberOfSynchronousHands(int numberOfSynchronousHands) { if (numberOfSynchronousHands < 1) numberOfSynchronousHands = 1; if (getNumberOfHands() % numberOfSynchronousHands != 0) return false; mNumberOfSynchronousHands = numberOfSynchronousHands; return true; } public int getNumberOfSynchronousHands() { return mNumberOfSynchronousHands; } public void setSynchronousStartPosition(int synchronousStartPosition) { mSynchronousStartPosition = synchronousStartPosition % getNumberOfSynchronousHands(); } public int getSynchronousStartPosition() { return mSynchronousStartPosition; } public String getSiteswapName() { return mSiteswapName; } public void setSiteswapName(String name) { mSiteswapName = name; } public int getPartialSum(int startIndex, int stopIndex) { int sum = 0; for (int i = startIndex; i <= stopIndex; ++i) { sum += mData.at(i); } return sum; } public boolean is_in_range(byte min, byte max) { for (Byte value : mData) { if(value < min || value > max) return false; } return true; } public boolean isSynchronous() { return mNumberOfSynchronousHands != 1; } public int getSynchronousPosition(int position) { return (getSynchronousStartPosition() + position) % getNumberOfSynchronousHands(); } public int countFilterValue(NumberFilter.FilterValue siteswapValue) { int counter = 0; for (int i = 0; i < global_period_length(); ++i) { for (int value : siteswapValue.getValues(getSynchronousPosition(i))) { if (isPatternSingleValue((byte) value, at(i))) counter++; } } return counter; } public int countFilterValuePartitially(NumberFilter.FilterValue siteswapValue, int index) { int counter = 0; for (int i = 0; i <= index; ++i) { for (int value : siteswapValue.getValues(getSynchronousPosition(i))) { if (isPatternSingleValue((byte) value, mData.at(i))) counter++; } } return counter; } public void rotateRight(int positions) { mData.rotateRight(positions); mSynchronousStartPosition = (mSynchronousStartPosition - positions) % getNumberOfSynchronousHands(); if (mSynchronousStartPosition < 0) mSynchronousStartPosition += getNumberOfSynchronousHands(); } public void rotateLeft(int positions) { mData.rotateLeft(positions); mSynchronousStartPosition = (mSynchronousStartPosition + positions) % getNumberOfSynchronousHands(); } public void make_unique_representation() { Siteswap temp = new Siteswap(this); int rotate_counter = 0; for(int i = 0; i < period_length(); ++i) { if (compareTo(temp) < 0) { mData.rotateRight(rotate_counter); rotate_counter = 0; } temp.rotateRight(1); rotate_counter++; } } public boolean rotateGetinFree() { for (int i = 0; i < period_length(); ++i) { if (isGetinFree()) return true; rotateRight(1); } return false; } public Siteswap calculateGetin() { Siteswap siteswapInterface = toInterface(Siteswap.FREE, period_length() + getMaxThrow(), period_length() + getMaxThrow()); int getinLength = 0; // calculate getin length for (int i = 0; i < getNumberOfObjects(); ++i) { if (siteswapInterface.at(i) != FREE) { getinLength = getNumberOfObjects() - i; break; } } // create getin Siteswap byte[] getinArray = new byte[getinLength]; Arrays.fill(getinArray, (byte) getNumberOfObjects()); Siteswap getin = new Siteswap(getinArray, mNumberOfJugglers); // calculate getin values for(int i = 0; i < getin.period_length(); ++i) { int offset = i - getin.period_length(); while(siteswapInterface.at(getin.at(i) + offset) != FREE) getin.set(i, getin.at(i) + 1); siteswapInterface.set(getin.at(i) + offset, getin.at(i)); } return getin; } public Siteswap calculateGetout() { Siteswap siteswapInterface = toInterface(Siteswap.FREE, period_length() + getMaxThrow(), period_length()); int getoutLength = 0; // calculate getout length for (int i = 0; i < getMaxThrow() - getNumberOfObjects(); ++i) { int interfaceIndex = period_length() + getMaxThrow() - i - 1; if (siteswapInterface.at(interfaceIndex) != FREE) { getoutLength = getMaxThrow() - getNumberOfObjects() - i; break; } } // create getout Siteswap byte[] getoutArray = new byte[getoutLength]; Arrays.fill(getoutArray, (byte) getNumberOfObjects()); Siteswap getout = new Siteswap(getoutArray, mNumberOfJugglers); // calculate getout values for (int i = getout.period_length() - 1; i >= 0; --i) { int offset = period_length() + i; while (siteswapInterface.at(getout.at(i) + offset) != FREE) getout.set(i, getout.at(i) - 1); siteswapInterface.set(getout.at(i) + offset, getout.at(i)); } return getout; } public boolean isGetinFree() { return calculateGetin().period_length() == 0; } public int calculateMandatoreyGetinLength() { Siteswap getin = calculateGetin(); Siteswap siteswapInterface = toInterface(Siteswap.FREE, period_length() + getMaxThrow(), period_length() + getMaxThrow()); int mandatoryGetinLength = 0; for (int i = 0; i < getin.period_length(); ++i) { int fallDownPosition = getin.at(i) + i - getin.period_length(); int sameHandPreviousPosition = fallDownPosition - 2 * getNumberOfJugglers(); // if Siteswap is Mandatory if( sameHandPreviousPosition >= 0 && siteswapInterface.at(sameHandPreviousPosition) != Siteswap.FREE ) { mandatoryGetinLength = getin.period_length() - i; break; } if(fallDownPosition >= 0) { siteswapInterface.set(fallDownPosition, getin.at(i)); } } return mandatoryGetinLength; } public Siteswap calculateMandatoryGetin() { Siteswap getin = calculateGetin(); int mandatoryGetinLength = calculateMandatoreyGetinLength(); Siteswap mandatorySiteswap = new Siteswap(new byte[mandatoryGetinLength], mNumberOfJugglers); for(int i = 0; i < mandatorySiteswap.period_length(); ++i) { int getinPos = i + getin.period_length() - mandatorySiteswap.period_length(); mandatorySiteswap.set(i, getin.at(getinPos)); } return mandatorySiteswap; } public Siteswap calculateNonMandatoryGetins() { Siteswap getin = calculateGetin(); int mandatoryGetinLength = calculateMandatoreyGetinLength(); int nonMandatoryGetinLength = getin.period_length() - mandatoryGetinLength; Siteswap nonMandatorySiteswap = new Siteswap(new byte[nonMandatoryGetinLength], mNumberOfJugglers); for (int i = 0; i < nonMandatoryGetinLength; ++i) { nonMandatorySiteswap.set(i, getin.at(i)); } return nonMandatorySiteswap; } public Siteswap[] calculateLocalGetins() { Siteswap[] localGetins = new Siteswap[getNumberOfJugglers()]; Siteswap mandatoryGetin = calculateMandatoryGetin(); // initialize getin Siteswaps for(int juggler = 0; juggler < getNumberOfJugglers(); ++juggler) { int localGetinLength = mandatoryGetin.period_length() / getNumberOfJugglers(); if (mandatoryGetin.period_length() % getNumberOfJugglers() >= (getNumberOfJugglers() - juggler)) localGetinLength++; localGetins[juggler] = new Siteswap(new byte[localGetinLength], getNumberOfJugglers()); } int localGetinIndex = 0; for (int i = 0; i < mandatoryGetin.period_length(); ++i) { int juggler = (i + getNumberOfJugglers() - mandatoryGetin.period_length() % getNumberOfJugglers()) % getNumberOfJugglers(); localGetins[juggler].set(localGetinIndex, mandatoryGetin.at(i)); if ((i + 1) % getNumberOfJugglers() == 0) localGetinIndex++; } return localGetins; } public Siteswap[] calculateLocalGetouts() { Siteswap[] localGetouts = new Siteswap[getNumberOfJugglers()]; Siteswap globalGetout = calculateGetout(); // Calculate getout lenght for each juggler and allocate getout Siteswaps for(int i = 0; i < localGetouts.length; ++i) { int startPos = i - period_length() % getNumberOfJugglers(); if (i < period_length() % getNumberOfJugglers()) startPos += getNumberOfJugglers(); int length = (globalGetout.period_length() - startPos - 1) / getNumberOfJugglers() + 1; if (globalGetout.period_length() - startPos <= 0) length = 0; localGetouts[i] = new Siteswap(new byte[length], mNumberOfJugglers); } for (int i = 0; i < globalGetout.period_length(); ++i) { int juggler = (period_length() % getNumberOfJugglers() + i) % getNumberOfJugglers(); localGetouts[juggler].set(i / getNumberOfJugglers(), globalGetout.at(i)); } return localGetouts; } public class ClubDistribution { public int leftHandNumberOfClubs; public int rightHandNumberOfClubs; public ClubDistribution(int left, int right) { leftHandNumberOfClubs = left; rightHandNumberOfClubs = right; } @Override public String toString() { return String.valueOf(leftHandNumberOfClubs) + "|" + String.valueOf(rightHandNumberOfClubs); } @Override public boolean equals(Object obj) { if (! (obj instanceof ClubDistribution)) return false; ClubDistribution rhs = (ClubDistribution) obj; return this.leftHandNumberOfClubs == rhs.leftHandNumberOfClubs && this.rightHandNumberOfClubs == rhs.rightHandNumberOfClubs; } } // Calculates the club Distribution for a pattern started from ground state public ClubDistribution[] calculateGroundStateClubDistribution() { ClubDistribution groundStateClubDistribution[] = new ClubDistribution[getNumberOfJugglers()]; for (int juggler = 0; juggler < getNumberOfJugglers(); ++juggler) { int numberOfClubsForJuggler = getNumberOfObjects() / getNumberOfJugglers(); if (juggler < getNumberOfObjects() % getNumberOfJugglers()) numberOfClubsForJuggler++; int numberOfClubsRightHand = numberOfClubsForJuggler / 2 + numberOfClubsForJuggler % 2; int numberOfClubsLeftHand = numberOfClubsForJuggler / 2; groundStateClubDistribution[juggler] = new ClubDistribution(numberOfClubsLeftHand, numberOfClubsRightHand); } return groundStateClubDistribution; } public ClubDistribution[] calculateInitialClubDistribution() { ClubDistribution initialClubDistribution[] = new ClubDistribution[getNumberOfJugglers()]; Siteswap getin = calculateGetin(); Siteswap localGetins[] = calculateLocalGetins(); Siteswap nonMandatoryGetin = calculateNonMandatoryGetins(); // Calculate initial start position including all getins. It is assumed, // that the regular periodig Siteswap is started from the right Hand // for all jugglers. for(int juggler = 0; juggler < getNumberOfJugglers(); ++juggler) { int numberOfClubsForJuggler = getNumberOfObjects() / getNumberOfJugglers(); int jugglerPosition = (getin.period_length() % getNumberOfJugglers() + juggler) % getNumberOfJugglers(); if( jugglerPosition < getNumberOfObjects() % getNumberOfJugglers()) numberOfClubsForJuggler++; int numberOfClubsStartingHand = numberOfClubsForJuggler / 2 + numberOfClubsForJuggler % 2; int numberOfClubsSecondHand = numberOfClubsForJuggler / 2; int numberOfGetinsForJuggler = getin.period_length() / getNumberOfJugglers(); if (getin.period_length() % getNumberOfJugglers() >= (getNumberOfJugglers() - juggler)) numberOfGetinsForJuggler++; boolean isStartRight = (numberOfGetinsForJuggler % 2) == 0; int right = numberOfClubsStartingHand; int left = numberOfClubsSecondHand; if (!isStartRight) { right = numberOfClubsSecondHand; left = numberOfClubsStartingHand; } initialClubDistribution[juggler] = new ClubDistribution(left, right); } // Calculate new starting position, when only mandatory getins are thrown for (int i = 0; i < nonMandatoryGetin.period_length(); ++i) { int throwingJuggler = (i + getNumberOfJugglers() - getin.period_length() % getNumberOfJugglers()) % getNumberOfJugglers(); int numberOfThrows = (getin.period_length() - i) / getNumberOfJugglers(); if (throwingJuggler >= getNumberOfJugglers() - (getin.period_length()-i) % getNumberOfJugglers()) numberOfThrows++; boolean isRightHandThrowing = (numberOfThrows % 2) == 0; int catchingJuggler = (throwingJuggler + nonMandatoryGetin.at(i)) % getNumberOfJugglers(); boolean isRightHandCatching = ((throwingJuggler + nonMandatoryGetin.at(i)) / getNumberOfJugglers()) % 2 == 0; if (!isRightHandThrowing) isRightHandCatching = !isRightHandCatching; if (isRightHandThrowing) initialClubDistribution[throwingJuggler].rightHandNumberOfClubs--; else initialClubDistribution[throwingJuggler].leftHandNumberOfClubs--; if (isRightHandCatching) initialClubDistribution[catchingJuggler].rightHandNumberOfClubs++; else initialClubDistribution[catchingJuggler].leftHandNumberOfClubs++; } return initialClubDistribution; } public boolean isMandatoryGetin() { return calculateMandatoryGetin().period_length() != 0; } public boolean isGroundStateClubDistribution() { ClubDistribution groundstateClubDistribution[] = calculateGroundStateClubDistribution(); ClubDistribution actualClubDistribution[] = calculateInitialClubDistribution(); for (int i = 0; i < actualClubDistribution.length; ++i) { if (!groundstateClubDistribution[i].equals(actualClubDistribution[i])) return false; } return true; } // The higher the returned integer value, the better the current rotation can be // used as a starting position. public int measureSuitabilityForStartingPosition() { int measure = 0; if (!isMandatoryGetin()) measure += 1000; if (isGroundStateClubDistribution()) measure += 10; if (isGetinFree()) measure += 1; if (Siteswap.isPass(at(0), getNumberOfJugglers())) measure += 100; for(int i = 1; i < getNumberOfJugglers(); ++i) { if (Siteswap.isPass(at(i), getNumberOfJugglers())) measure += 2; } return measure; } public void rotateToBestStartingPosition() { int max = 0; int rot = 0; for (int i = 0; i < period_length(); ++i) { if (measureSuitabilityForStartingPosition() > max) { max = measureSuitabilityForStartingPosition(); rot = i; } rotateRight(1); } rotateRight(rot); } @Override public Iterator<Byte> iterator() { return mData.iterator(); } @Override public int compareTo(Siteswap o) { int length = period_length() < o.period_length() ? period_length() : o.period_length(); for(int i = 0; i < length; ++i) { if(at(i) < o.at(i)) return -1; if(at(i) > o.at(i)) return 1; } if(period_length() < o.period_length()) return -1; if(period_length() > o.period_length()) return 1; return 0; } public byte[] toArray() { byte[] arr = new byte[period_length()]; for (int i = 0; i < period_length(); ++i) { arr[i] = mData.at(i); } return arr; } public Vector<Siteswap> toLocal() { Vector<Siteswap> localSiteswaps = new Vector<Siteswap>(mNumberOfJugglers); for (int i = 0; i < mNumberOfJugglers; ++i) { localSiteswaps.add(new Siteswap(new byte[period_length()])); for(int j = 0; j < period_length(); ++j) { localSiteswaps.elementAt(i).set(j, at(mNumberOfJugglers * j + i)); } } return localSiteswaps; } /** * Returns the Siteswap as a string, where the individual numbers are * divided by the number of jugglers (local notation). The order of the * number is left as is. * @return String representation of the siteswap */ public String toDividedString() { if (mNumberOfJugglers == 1) return toString(); String str = new String(); DecimalFormat formatter = new DecimalFormat("0.#"); for(int i = 0; i < period_length(); ++i) { str += formatter.format(at(i) / (double) mNumberOfJugglers); str += "&ensp;"; } return str; } public Vector<String> toLocalString() { Vector<String> localSiteswapStrings = new Vector<String>(mNumberOfJugglers); if (mNumberOfJugglers == 1) { localSiteswapStrings.add(toString()); return localSiteswapStrings; } for(int juggler = 0; juggler < mNumberOfJugglers; ++juggler) { String str = new String(); DecimalFormat formatter = new DecimalFormat("0.#"); for(int i = 0; i < local_period_length(); ++i) { int position = juggler + i*mNumberOfJugglers; str += formatter.format(atSyncCorrected(position) / (double) mNumberOfJugglers); if (Siteswap.isPass(at(position), mNumberOfJugglers)) { str += "<sub><small>"; if (mNumberOfJugglers >= 3) str += Character.toString((char) ('A' + (position + at(position)) % mNumberOfJugglers)); if (((juggler + at(position)) / mNumberOfJugglers) % 2 == 0) str += "x"; else str += "||"; str += "</small></sub>"; } str += "&ensp;"; } localSiteswapStrings.add(str); } return localSiteswapStrings; } @Override public boolean equals(Object obj) { if (! (obj instanceof Siteswap)) return false; if (getNumberOfSynchronousHands() != ((Siteswap) obj).getNumberOfSynchronousHands()) return false; // TODO synchronous start position: attention: use same rotation for comparison return compareTo((Siteswap) obj) == 0; } @Override public String toString() { if (isSynchronous()) { return toSyncStringLocalVsLocal(); } else { return toAsyncString(); } } public String toGlobalString() { if (isSynchronous()) { return toSyncStringGlobalRepresentation(); } else { return toAsyncString(); } } public String toAsyncString() { String str = new String(); for (byte value : mData) { str += Character.toString(intToChar(value)); } return str; } public String toSyncStringLocalVsLocal() { String str = new String(); for (int juggler = 0; juggler < getNumberOfJugglers(); ++juggler) { str += Character.toString((char) ('A' + juggler)) + ": "; for (int i = 0; i < local_period_length(); ++i) { int index = i*getNumberOfJugglers() + juggler; int value = atSyncCorrected(index) / getNumberOfJugglers(); str += Character.toString(intToChar(value)); if (isPass(at(index), getNumberOfJugglers())) { str += "p"; } } str += " "; } return str; } public String toSyncStringGlobalRepresentation() { String str = new String(); for (int i = 0; i < global_period_length(); ++i) { byte value = atSyncCorrected(i); if (getSynchronousPosition(i) == 0) str += "("; str += Character.toString(intToChar(value)); if (isPass(at(i), getNumberOfJugglers())) str += "p"; if (getSynchronousPosition(i) == (getNumberOfSynchronousHands() - 1)) str += ")"; } return str; } static public String getCurrentStringVersion() { return new String("v1.0.0"); } // str: siteswap/86777 // query: jugglers=2 public boolean fromPassistString(String str, String query) { String[] url_splitted_arr = str.split("/"); if (url_splitted_arr.length != 2 || !url_splitted_arr[0].equals("siteswap")) { return false; } String pattern = url_splitted_arr[1]; String[] query_splitted = query.split("="); if (query_splitted.length != 2 || !query_splitted[0].equals("jugglers") ) { return false; } String number_of_jugglers = query_splitted[1]; String parsableString = pattern + "." + number_of_jugglers + ".1.0"; return fromParsableString(parsableString); } // /v1.0.0/86277.[nr_jugglers].[nr_sync_hands].[sync_start_pos]" // async two jugglers: 86277.2.1.0 public boolean fromParsableString(String str) { String[] version_splitted_arr = str.split("/"); if (version_splitted_arr.length == 0) { return false; } if (version_splitted_arr.length == 1) { return parseStringLatestVersion(version_splitted_arr[0]); } if (version_splitted_arr.length == 2) { return parseVersionedString(version_splitted_arr[0], version_splitted_arr[1]); } return false; // length > 2 } public boolean parseVersionedString(String version, String siteswapStr) { if (version.equals("v1.0.0")) { return parseStringVersion_1_0_0(siteswapStr); } mIsParsingError = true; mInvalidCharacters = version; return false; // invalid version } private boolean parseStringLatestVersion(String str) { return parseStringVersion_1_0_0(str); } private boolean parseStringVersion_1_0_0(String str) { String[] arr = str.split("\\."); int i = 0; try { if (arr.length >= 1) { this.mData = new CyclicByteArray(parseString(arr[0])); } if (arr.length >= 2) { i = 1; setNumberOfJugglers(Integer.valueOf(arr[1])); } if (arr.length >= 3) { i = 2; setNumberOfSynchronousHands(Integer.valueOf(arr[2])); } if (arr.length >= 4) { i = 3; setSynchronousStartPosition(Integer.valueOf(arr[3])); } } catch (NumberFormatException e) { mIsParsingError = true; mInvalidCharacters += arr[i]; return false; } return true; } public String toParsableString() { return toAsyncString() + "." + String.valueOf(getNumberOfJugglers()) + "." + String.valueOf(getNumberOfSynchronousHands()) + "." + String .valueOf(getSynchronousStartPosition()); } public Siteswap toPattern() { Siteswap pattern = new Siteswap(this); for (int i = 0; i < period_length(); ++i) { if(isPass(at(i), mNumberOfJugglers)) pattern.set(i, PASS); if(isSelf(at(i), mNumberOfJugglers)) pattern.set(i, SELF); } return pattern; } public Siteswap toInterface() { return toInterface(Siteswap.FREE); } public Siteswap toInterface(byte defaultValue) { byte[] interfaceArray = new byte[period_length()]; Arrays.fill(interfaceArray, defaultValue); Siteswap siteswapInterface = new Siteswap(interfaceArray, mNumberOfJugglers); for (int i = 0; i < period_length(); ++i) { if (at(i) < 0) continue; siteswapInterface.set(i + at(i), at(i)); } return siteswapInterface; } /** * converts the siteswap to an interface of a specific length. The interface will not be * filled cyclic and throws coming down after the specified length will be ignored. The * length parameters specifies, how many throws of the siteswaps are considered for the * interface. Typically length is the interfaceLength in the context of getin calculation * and the period length of the siteswap in the context of getout calculation. * * * @param defaultValue * @param interfaceLength * @param length * @return */ public Siteswap toInterface(byte defaultValue, int interfaceLength, int length) { byte[] interfaceArray = new byte[interfaceLength]; Arrays.fill(interfaceArray, defaultValue); Siteswap siteswapInterface = new Siteswap(interfaceArray, mNumberOfJugglers); for (int i = 0; i < length; ++i) { if (at(i) < 0 || i + at(i) >= interfaceLength) continue; siteswapInterface.set(i + at(i), at(i)); } return siteswapInterface; } public boolean isValid() { return isValid(this); } public static Siteswap mergeCompatible(Siteswap s1, Siteswap s2) { Siteswap i1 = s1.toInterface().toPattern(); Siteswap i2 = s2.toInterface().toPattern(); if (!s2.rotateToInterface(i1)) { return null; } int length = 2 * s1.period_length(); Siteswap mergedSiteswap = new Siteswap(new byte[length]); mergedSiteswap.setSynchronousStartPosition(s1.getSynchronousStartPosition()); mergedSiteswap.setNumberOfSynchronousHands(s1.getNumberOfSynchronousHands()); mergedSiteswap.setNumberOfJugglers(s1.getNumberOfJugglers()); for (int i = 0; i < s1.period_length(); ++i) { mergedSiteswap.set(2*i, s1.at(2*i)); mergedSiteswap.set(2*i+1, s2.at(2*i+1)); } if (!mergedSiteswap.isValid()) { return null; } return mergedSiteswap; } public static boolean isValid(Siteswap siteswap) { byte[] interfaceArray = new byte[siteswap.period_length()]; Arrays.fill(interfaceArray, Siteswap.FREE); Siteswap siteswapInterface = new Siteswap(interfaceArray); for (int i = 0; i < siteswap.period_length(); ++i) { if (siteswap.at(i) < 0) return false; if (siteswapInterface.at(i + siteswap.at(i)) != Siteswap.FREE) return false; siteswapInterface.set(i + siteswap.at(i), siteswap.at(i)); } return true; } public String stringAt(int index) { return Character.toString(intToChar(atSyncCorrected(index))); } public static String intToString(int value) { if (value == SELF) return "self"; if (value == PASS) return "pass"; if (value == DONT_CARE) return "do not care"; if (value == FREE) return "free"; if (value < 0) return "invalid"; if(value >= 0 && value < 10) return Integer.toString(value); return Character.toString((char) (value - 10 + 'a')); } public static int stringToInt(String value) { if (value == "pass") return PASS; else if (value == "self") return SELF; else if (value == "do not care") return DONT_CARE; else if (value == "free") return FREE; else if (value.length() == 1) return charToInt(value.charAt(0)); return INVALID; } public static char intToChar(int value) { if (value == SELF) return 's'; if (value == PASS) return 'p'; if (value == DONT_CARE) return '?'; if (value == FREE) return '*'; if (value < 0) return '!'; if(value >= 0 && value < 10) return (char) (value + '0'); return (char) (value - 10 + 'a'); } public static int charToInt(char value) { if (value == 'p') return PASS; if (value == 's') return SELF; if (value == '?') return DONT_CARE; if (value == 'O') return FREE; if(value <= '9' && value >= '0') return (int) (value - '0'); if(value <= 'z' && value >= 'a') return (int) (value + 10 - 'a'); return INVALID; } public boolean isPatternSingleValue(byte patternValue, byte siteswapValue) { if (siteswapValue >= 0) { if (patternValue == SELF) return siteswapValue % getNumberOfJugglers() == 0; if (patternValue == PASS) return siteswapValue % getNumberOfJugglers() != 0; if (patternValue == DONT_CARE) return true; // the Pattern should not have any free positions. Therefore false is returned in this case if (patternValue == FREE) return false; } else { if (siteswapValue == DONT_CARE) return true; // When a position in the siteswap is free, it is not known, if the pattern will be // matched. In this case false will be assumed if (siteswapValue == FREE) return false; } return patternValue == siteswapValue; } public boolean isPattern(Siteswap pattern) { if (pattern.period_length() == 0) return true; for(int i = 0; i < period_length(); ++i) { if (isPattern(pattern, i)) return true; } return false; } public boolean isPattern(Siteswap pattern, int patternStartPosition) { for (int i = 0; i < pattern.period_length(); ++i) { if (!isPatternSingleValue(pattern.at(i), at(i + patternStartPosition))) return false; } return true; } public boolean rotateToInterface(Siteswap siteswapInterface) { if (siteswapInterface.period_length() != period_length()) { return false; } for(int i = 0; i < period_length(); ++i) { rotateLeft(1); if (toInterface().isPattern(siteswapInterface, 0)) return true; } return false; } public boolean isParsingError() { return mIsParsingError; } public String getInvalidCharactersFromParsing() { return mInvalidCharacters; } static public boolean isPass(int value, int numberOfJugglers) { return value % numberOfJugglers != 0; } static public boolean isSelf(int value, int numberOfJugglers) { return !isPass(value, numberOfJugglers); } private byte[] parseString(String str) { byte[] siteswap = new byte[str.length()]; mInvalidCharacters = ""; mIsParsingError = false; for (int i = 0; i < str.length(); ++i) { siteswap[i] = (byte) charToInt(str.charAt(i)); if (siteswap[i] == INVALID) { mIsParsingError = true; mInvalidCharacters += str.charAt(i); } } return siteswap; } }
32,512
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
InterfaceFilter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/siteswaplib/InterfaceFilter.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; /** * Created by tilman on 29.10.17. */ public class InterfaceFilter extends PatternFilter { static final private String VERSION = "1"; public InterfaceFilter() { } public InterfaceFilter(String str) { fromParsableString(str); } public InterfaceFilter(Siteswap pattern, Type type) { super(pattern, type); } @Override public String toString() { String str; if (mType == Type.INCLUDE) str = new String("Include Interface: "); else str = new String("Exclude Interface: "); str += mPattern.toString(); return str; } @Override public String toParsableString() { String str = new String(); str += String.valueOf(VERSION) + ","; str += super.toParsableString(); return str; } @Override public InterfaceFilter fromParsableString(String str) { String[] splits = str.split(","); int begin_index = 0; if (splits.length < 3) { return this; } if (!splits[0].equals(VERSION)) return this; begin_index += splits[0].length() + 1; super.fromParsableString(str.substring(begin_index)); return this; } @Override public boolean isFulfilled(Siteswap siteswap) { Siteswap siteswapInterface = siteswap.toInterface(Siteswap.FREE); if (mType == Type.INCLUDE) return siteswapInterface.isPattern(mPattern); return !siteswapInterface.isPattern(mPattern); } @Override public boolean isPartlyFulfilled(Siteswap siteswap, int index) { if (mType == Type.EXCLUDE) { return isFulfilled(siteswap); } // Intefaces that need to be included are not checked for partly generated siteswaps // at the moment return true; } }
2,646
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
EnterSiteswapDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/EnterSiteswapDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import siteswaplib.Siteswap; /** * Created by tilman on 29.10.17. */ public class EnterSiteswapDialog extends DialogFragment { private EditText mSiteswapTextEdit; private EditText mNumberOfJugglersTextEdit; private CheckBox mIsSynchronouscheckbox; private int mNumberOfJugglersDefault; private boolean mIsSyncDefault; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_enter_siteswap) .setTitle(getString(R.string.enter_siteswap__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(getString(R.string.ok), null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (validateAndShowSiteswap()) dialog.dismiss(); } }); } }); return dialog; } @Override public void onStart() { super.onStart(); mSiteswapTextEdit = (EditText) getDialog().findViewById(R.id.enter_siteswap_siteswap_text_edit); mNumberOfJugglersTextEdit = (EditText) getDialog().findViewById(R.id.enter_siteswap_number_of_jugglers_text_edit); mIsSynchronouscheckbox = (CheckBox) getDialog().findViewById(R.id.enter_siteswap_sync_mode_checkbox); mNumberOfJugglersTextEdit.setText(String.valueOf(mNumberOfJugglersDefault)); mIsSynchronouscheckbox.setChecked(mIsSyncDefault); } @Override public void onStop() { super.onStop(); } private boolean validateAndShowSiteswap() { try { int numberOfJugglers = Integer.valueOf(mNumberOfJugglersTextEdit.getText().toString()); boolean isSync = mIsSynchronouscheckbox.isChecked(); int numberOfSynchronousHands = 1; if (isSync) { numberOfSynchronousHands = numberOfJugglers; } Siteswap siteswap = new Siteswap(mSiteswapTextEdit.getText().toString(), numberOfJugglers); siteswap.setNumberOfSynchronousHands(numberOfSynchronousHands); if (!siteswap.isValid() ) throw new IllegalArgumentException(siteswap.toString()); Intent intent = new Intent(getContext(), DetailedSiteswapActivity.class); intent.putExtra(getString(R.string.intent_detailed_siteswap_view__siteswap), siteswap); startActivity(intent); return true; } catch (IllegalArgumentException e) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(getString(R.string.main_activity__invalid_site_swap) + e.getMessage()) .setNeutralButton(getString(R.string.back), null); builder.create().show(); } return false; } public void show(FragmentManager manager, String tag, int numberOfJugglers, boolean isSynchrounous) { mNumberOfJugglersDefault = numberOfJugglers; mIsSyncDefault = isSynchrounous; show(manager, tag); } }
4,925
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
ConfirmDeleteGenerationParametersDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/ConfirmDeleteGenerationParametersDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * Created by tilman on 29.10.17. */ public class ConfirmDeleteGenerationParametersDialog extends DialogFragment { private static final String STATE_GENERATION_PARAMETER_ENTITY = "STATE_GENERATION_PARAMETER_ENTITY"; private TextView mGenerationParametersTextView; private GenerationParameterEntity mGenerationParameterEntity; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mGenerationParameterEntity = (GenerationParameterEntity) savedInstanceState.getSerializable(STATE_GENERATION_PARAMETER_ENTITY); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_confirm_remove_generation_parameter) .setTitle(getString(R.string.confirm_delete_generation_parameters__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(getString(R.string.remove), null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteGenerationParameters(); dialog.dismiss(); } }); } }); return dialog; } @Override public void onStart() { super.onStart(); mGenerationParametersTextView = (TextView) getDialog().findViewById(R.id.generation_parameter_text_view); mGenerationParametersTextView.setText(mGenerationParameterEntity.toString()); } public void deleteGenerationParameters() { new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getContext()); db.generationParameterDao().deleteGenerationParameters(mGenerationParameterEntity); } catch (android.database.sqlite.SQLiteConstraintException e) { } } }).start(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_GENERATION_PARAMETER_ENTITY, mGenerationParameterEntity); } @Override public void onStop() { super.onStop(); } public void show(FragmentManager manager, String tag, GenerationParameterEntity generationParameterEntity) { mGenerationParameterEntity = generationParameterEntity; show(manager, tag); } }
4,175
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
PatternFilterDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/PatternFilterDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.text.Html; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import siteswaplib.Filter; import siteswaplib.InterfaceFilter; import siteswaplib.LocalInterfaceFilter; import siteswaplib.LocalPatternFilter; import siteswaplib.PatternFilter; import siteswaplib.Siteswap; /** * Created by tilman on 29.10.17. */ public class PatternFilterDialog extends AddFilterDialog { private static final String STATE_OLD_FILTER = "STATE_OLD_FILTER"; private static final String STATE_NUMBER_OF_JUGGLERS = "STATE_NUMBER_OF_JUGGLERS"; private RadioButton mPatternRadioButton; private RadioButton mInterfaceRadioButton; private RadioButton mGlobalRadioButton; private RadioButton mLocalRadioButton; private RadioButton mIncludeRadioButton; private RadioButton mExcludeRadioButton; private EditText mPatternEditText; private TextView mDescriptionTextView; private Filter mOldFilter = null; private int mNumberOfJugglers; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mOldFilter = (Filter) savedInstanceState.getSerializable(STATE_OLD_FILTER); mNumberOfJugglers = savedInstanceState.getInt(STATE_NUMBER_OF_JUGGLERS); } int positiveButtonStringId = R.string.filter__add_button; if (mOldFilter != null) positiveButtonStringId = R.string.filter__replace_button; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.pattern_filter_layout) .setPositiveButton(positiveButtonStringId, null) .setNegativeButton(R.string.filter__cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .setNeutralButton(R.string.filter__remove_button, null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Filter filter = readPatternFilter(); if (filter == null) return; if (mOldFilter != null) mListener.onChangeSiteswapFilter(mOldFilter, filter); else mListener.onAddSiteswapFilter(filter); dialog.dismiss(); } }); button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEUTRAL); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Filter filter = readPatternFilter(); if (filter == null) return; mListener.onRemoveSiteswapFilter(filter); dialog.dismiss(); } }); } }); return dialog; } @Override public void onStart() { super.onStart(); mPatternRadioButton = (RadioButton) getDialog().findViewById(R.id.pattern_radio_button); mInterfaceRadioButton = (RadioButton) getDialog().findViewById(R.id.interface_radio_button); mGlobalRadioButton = (RadioButton) getDialog().findViewById(R.id.global_radio_button); mLocalRadioButton = (RadioButton) getDialog().findViewById(R.id.local_radio_button); mIncludeRadioButton = (RadioButton) getDialog().findViewById(R.id.include_radio_button); mExcludeRadioButton = (RadioButton) getDialog().findViewById(R.id.exclude_radio_button); mPatternEditText = (EditText) getDialog().findViewById(R.id.pattern_text_edit); mDescriptionTextView = (TextView) getDialog().findViewById(R.id.description_text_view); mDescriptionTextView.setText(Html.fromHtml(getString(R.string.pattern_filter__description_html))); SharedPreferences sharedPref = getContext().getSharedPreferences( getString(R.string.pattern_filter__shared_preferences), Context.MODE_PRIVATE); boolean isPattern = sharedPref.getBoolean(getString(R.string.pattern_filter__shared_preferences_pattern_checked), true); boolean isInterface = sharedPref.getBoolean(getString(R.string.pattern_filter__shared_preferences_interface_checked), false); boolean isGlobal = sharedPref.getBoolean(getString(R.string.pattern_filter__shared_preferences_global_checked), true); boolean isLocal = sharedPref.getBoolean(getString(R.string.pattern_filter__shared_preferences_local_checked), false); boolean isInclude = sharedPref.getBoolean(getString(R.string.pattern_filter__shared_preferences_include_checked), true); boolean isExclude = sharedPref.getBoolean(getString(R.string.pattern_filter__shared_preferences_exclude_checked), false); if (mOldFilter != null) { if (mOldFilter instanceof PatternFilter) { PatternFilter filter = (PatternFilter) mOldFilter; isPattern = true; isInterface = false; isGlobal = true; isLocal = false; isInclude = filter.getType() == PatternFilter.Type.INCLUDE; isExclude = !isInclude; mPatternEditText.setText(filter.getPattern().toString()); } if (mOldFilter instanceof LocalPatternFilter) { isGlobal = false; isLocal = true; } if (mOldFilter instanceof InterfaceFilter) { isPattern = false; isInterface = true; } if (mOldFilter instanceof LocalInterfaceFilter) { isGlobal = false; isLocal = true; } } mPatternRadioButton.setChecked(isPattern); mInterfaceRadioButton.setChecked(isInterface); mGlobalRadioButton.setChecked(isGlobal); mLocalRadioButton.setChecked(isLocal); mIncludeRadioButton.setChecked(isInclude); mExcludeRadioButton.setChecked(isExclude); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_OLD_FILTER, mOldFilter); outState.putInt(STATE_NUMBER_OF_JUGGLERS, mNumberOfJugglers); } @Override public void onStop() { super.onStop(); SharedPreferences sharedPref = getContext().getSharedPreferences( getString(R.string.pattern_filter__shared_preferences), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); boolean isPattern = mPatternRadioButton.isChecked(); boolean isInterface = mInterfaceRadioButton.isChecked(); boolean isGlobal = mGlobalRadioButton.isChecked(); boolean isLocal = mLocalRadioButton.isChecked(); boolean isInclude = mIncludeRadioButton.isChecked(); boolean isExclude = mExcludeRadioButton.isChecked(); editor.putBoolean(getString(R.string.pattern_filter__shared_preferences_pattern_checked), isPattern); editor.putBoolean(getString(R.string.pattern_filter__shared_preferences_interface_checked), isInterface); editor.putBoolean(getString(R.string.pattern_filter__shared_preferences_global_checked), isGlobal); editor.putBoolean(getString(R.string.pattern_filter__shared_preferences_local_checked), isLocal); editor.putBoolean(getString(R.string.pattern_filter__shared_preferences_include_checked), isInclude); editor.putBoolean(getString(R.string.pattern_filter__shared_preferences_exclude_checked), isExclude); editor.commit(); } Filter readPatternFilter() { boolean isPattern = mPatternRadioButton.isChecked(); boolean isInterface = mInterfaceRadioButton.isChecked(); boolean isGlobal = mGlobalRadioButton.isChecked(); boolean isLocal = mLocalRadioButton.isChecked(); boolean isInclude = mIncludeRadioButton.isChecked(); boolean isExclude = mExcludeRadioButton.isChecked(); PatternFilter.Type filterType = PatternFilter.Type.INCLUDE; Siteswap pattern = new Siteswap( mPatternEditText.getText().toString() ); if (pattern.isParsingError()) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(getString(R.string.pattern_filter__parsing_error) + " " + pattern.getInvalidCharactersFromParsing()) .setNeutralButton(getString(R.string.back), null); builder.create().show(); return null; } if (pattern.period_length() == 0) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(getString(R.string.pattern_filter__toast_no_input)) .setNeutralButton(getString(R.string.back), null); builder.create().show(); return null; } if (isExclude) filterType = PatternFilter.Type.EXCLUDE; if (isPattern) { if (isGlobal) { return new PatternFilter(pattern, filterType); } else { return new LocalPatternFilter(pattern, filterType, mNumberOfJugglers); } } else { // Interface Filter if (isGlobal) { return new InterfaceFilter(pattern, filterType); } else { return new LocalInterfaceFilter(pattern, filterType, mNumberOfJugglers); } } } public void show(FragmentManager manager, String tag, int numberOfJugglers) { mNumberOfJugglers = numberOfJugglers; show(manager, tag); } public void show(FragmentManager manager, String tag, int numberOfJugglers, Filter filter) { mOldFilter = filter; show(manager, tag, numberOfJugglers); } }
11,621
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
AppDatabase.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/AppDatabase.java
package namlit.siteswapgenerator; import androidx.sqlite.db.SupportSQLiteDatabase; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.migration.Migration; import android.content.Context; @Database(entities = {SiteswapEntity.class, GenerationParameterEntity.class}, version = 2) public abstract class AppDatabase extends RoomDatabase { public final static String database_name = "siteswap_generator_app_database"; private static AppDatabase INSTANCE; public abstract FavoriteDao siteswapDao(); public abstract GenerationParameterDao generationParameterDao(); public static AppDatabase getAppDatabase(Context context) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, database_name) .addMigrations(MIGRATION_1_2) .build(); } return INSTANCE; } public static void destroyInstance() { INSTANCE = null; } static final Migration MIGRATION_1_2 = new Migration(1, 2) { @Override public void migrate(SupportSQLiteDatabase database) { database.execSQL("CREATE TABLE `generation_parameters` (" + "`uid` INTEGER NOT NULL, " + "`name` TEXT, " + "`numberOfObjects` INTEGER NOT NULL, " + "`periodLength` INTEGER NOT NULL, " + "`maxThrow` INTEGER NOT NULL, " + "`minThrow` INTEGER NOT NULL, " + "`numberOfJugglers` INTEGER NOT NULL, " + "`maxResults` INTEGER NOT NULL, " + "`timeout` INTEGER NOT NULL, " + "`isSynchronous` INTEGER NOT NULL, " + "`isRandomMode` INTEGER NOT NULL, " + "`isZips` INTEGER NOT NULL, " + "`isZaps` INTEGER NOT NULL, " + "`isHolds` INTEGER NOT NULL, " + "`filterListString` TEXT, " + "PRIMARY KEY(`uid`))"); } }; }
2,200
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
ChooseRemoveFavoriteDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/ChooseRemoveFavoriteDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.Serializable; import java.util.List; /** * Created by tilman on 29.10.17. */ public class ChooseRemoveFavoriteDialog extends DialogFragment { private static final String STATE_SITESWAP_ENTITY_LIST = "STATE_SITESWAP_ENTITY_LIST"; private ListView mListView; private List<SiteswapEntity> mSiteswapEntityList; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mSiteswapEntityList = (List<SiteswapEntity>) savedInstanceState.getSerializable(STATE_SITESWAP_ENTITY_LIST); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_choose_remove_favorite) .setTitle(getString(R.string.choose_remove_favorite__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); final AlertDialog dialog = builder.create(); return dialog; } @Override public void onStart() { super.onStart(); mListView = (ListView) getDialog().findViewById(R.id.favorite_choose_remove_list); ArrayAdapter adapter = new ArrayAdapter<SiteswapEntity>( getContext(), android.R.layout.simple_list_item_1, mSiteswapEntityList); mListView.setAdapter(adapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SiteswapEntity siteswapEntity = ((SiteswapEntity) parent.getItemAtPosition(position)); new ConfirmRemoveFavoriteDialog().show(getFragmentManager(), getString(R.string.confirm_remove_favorite__dialog_tag), siteswapEntity); dismiss(); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_SITESWAP_ENTITY_LIST, (Serializable) mSiteswapEntityList); } @Override public void onStop() { super.onStop(); } public void show(FragmentManager manager, String tag, List<SiteswapEntity> siteswapEntityList) { mSiteswapEntityList = siteswapEntityList; show(manager, tag); } }
3,680
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
FavoritesActivity.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/FavoritesActivity.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SearchView; import java.io.Serializable; import java.util.List; import siteswaplib.Siteswap; public class FavoritesActivity extends AppCompatActivity { private static final String STATE_SITESWAPS = "STATE_SITESWAPS"; private static final String STATE_FILTER_TYPE = "STATE_FILTER_TYPE"; private static final String STATE_DATABASE_SEARCH_KEY = "STATE_DATABASE_SEARCH_KEY"; private static final String STATE_IS_VIEW_SITESWAPS = "STATE_IS_VIEW_SITESWAPS"; ListView mSiteswapListView; private List<SiteswapEntity> mSiteswaps; private List<String> mDatabaseColumnStrings; private enum FilterType {ALL, JUGGLER_NAME, LOCATION, DATE}; private FilterType mFilterType; private String mDatabaseSearchKey; private Boolean mIsViewSiteswaps; SearchView mSearchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null) { mSiteswaps = (List<SiteswapEntity>) savedInstanceState.getSerializable(STATE_SITESWAPS); mFilterType = (FilterType) savedInstanceState.getSerializable(STATE_FILTER_TYPE); mDatabaseSearchKey = savedInstanceState.getString(STATE_DATABASE_SEARCH_KEY); mIsViewSiteswaps = savedInstanceState.getBoolean(STATE_IS_VIEW_SITESWAPS); } SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); mDatabaseSearchKey = sharedPref.getString(getString(R.string.favorites__preference_database_search_key), ""); mIsViewSiteswaps = sharedPref.getBoolean(getString(R.string.favorites__preference_is_view_siteswaps), true); try { mFilterType = FilterType.valueOf(sharedPref.getString(getString(R.string.favorites__preference_filter_type), "")); } catch (Exception ex) { mFilterType = FilterType.ALL; } setContentView(R.layout.activity_show_siteswaps); setTitle(String.format(getString(R.string.favorites__title_waiting_for_database_query))); mSiteswapListView = (ListView) findViewById(R.id.siteswap_list); mSearchView = (SearchView) findViewById(R.id.search_view); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_show_favorites, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_show_all) { mFilterType = FilterType.ALL; } else if (id == R.id.action_show_jugglers) { mFilterType = FilterType.JUGGLER_NAME; } else if (id == R.id.action_show_locations) { mFilterType = FilterType.LOCATION; } else if (id == R.id.action_show_dates) { mFilterType = FilterType.DATE; } mIsViewSiteswaps = false; loadData(); return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_SITESWAPS, (Serializable) mSiteswaps); outState.putSerializable(STATE_FILTER_TYPE, mFilterType); outState.putString(STATE_DATABASE_SEARCH_KEY, mDatabaseSearchKey); outState.putBoolean(STATE_IS_VIEW_SITESWAPS, mIsViewSiteswaps); } @Override protected void onStart () { super.onStart(); loadData(); } @Override protected void onStop() { super.onStop(); SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(getString(R.string.favorites__preference_filter_type), mFilterType.toString()); editor.putString(getString(R.string.favorites__preference_database_search_key), mDatabaseSearchKey); editor.putBoolean(getString(R.string.favorites__preference_is_view_siteswaps), mIsViewSiteswaps); editor.commit(); } private void loadData() { if (mIsViewSiteswaps || mFilterType == FilterType.ALL) { loadSiteswaps(); } else { loadDatabaseColumn(); } } private void loadSiteswaps() { new Thread(new Runnable() { @Override public void run() { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); final String title; switch (mFilterType) { case ALL: mSiteswaps = db.siteswapDao().getAllFavorites(); String.format(getString(R.string.favorites__title_siteswaps)); title = String.format(getString(R.string.favorites__title_siteswaps)); break; case JUGGLER_NAME: mSiteswaps = db.siteswapDao().getSiteswapsOfJuggler(mDatabaseSearchKey); title = mDatabaseSearchKey; break; case LOCATION: mSiteswaps = db.siteswapDao().getSiteswapsOfLocation(mDatabaseSearchKey); title = mDatabaseSearchKey; break; case DATE: mSiteswaps = db.siteswapDao().getSiteswapsOfDate(mDatabaseSearchKey); title = mDatabaseSearchKey; break; default: title = mDatabaseSearchKey; } runOnUiThread(new Runnable() { @Override public void run() { setSiteswaps(title); } }); } }).start(); } private void loadDatabaseColumn() { new Thread(new Runnable() { @Override public void run() { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); final String title; switch (mFilterType) { case JUGGLER_NAME: mDatabaseColumnStrings = db.siteswapDao().getJugglers(); title = String.format(getString(R.string.favorites__title_jugglers)); break; case LOCATION: mDatabaseColumnStrings = db.siteswapDao().getLocations(); title = String.format(getString(R.string.favorites__title_locations)); break; case DATE: mDatabaseColumnStrings = db.siteswapDao().getDates(); title = String.format(getString(R.string.favorites__title_dates)); break; default: title = ""; } runOnUiThread(new Runnable() { @Override public void run() { setDatabaseColumn(title); } }); } }).start(); } private void setSiteswaps(String title) { setTitle(title); ArrayAdapter adapter = new ArrayAdapter( FavoritesActivity.this, android.R.layout.simple_list_item_1, mSiteswaps); mSiteswapListView.setAdapter(adapter); mSiteswapListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SiteswapEntity siteswapEntity = ((SiteswapEntity) parent.getItemAtPosition(position)); Siteswap siteswap = siteswapEntity.toSiteswap(); Intent intent = new Intent(getApplicationContext(), DetailedSiteswapActivity.class); intent.putExtra(getString(R.string.intent_detailed_siteswap_view__siteswap), siteswap); intent.putExtra(getString(R.string.intent_detailed_siteswap_view__skip_rotation_to_starting_position), true); startActivity(intent); } }); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { if (TextUtils.isEmpty(newText)) { adapter.getFilter().filter(null); } else { adapter.getFilter().filter(newText); } return true; } }); } private void setDatabaseColumn(String title) { setTitle(title); ArrayAdapter adapter = new ArrayAdapter( FavoritesActivity.this, android.R.layout.simple_list_item_1, mDatabaseColumnStrings); mSiteswapListView.setAdapter(adapter); mSiteswapListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDatabaseSearchKey = ((String) parent.getItemAtPosition(position)); mIsViewSiteswaps = true; loadSiteswaps(); } }); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { if (TextUtils.isEmpty(newText)) { adapter.getFilter().filter(null); } else { adapter.getFilter().filter(newText); } return true; } }); } }
11,539
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
QRCodeDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/QRCodeDialog.java
package namlit.siteswapgenerator; import android.app.Dialog; import android.graphics.Point; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.view.Display; import android.view.WindowManager; import android.widget.ImageView; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import static android.content.Context.WINDOW_SERVICE; public class QRCodeDialog extends DialogFragment { private static final String STATE_QR_CONTENT = "STATE_QR_CONTENT"; String mQRContent; Bitmap mQRImage; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mQRContent = savedInstanceState.getString(STATE_QR_CONTENT); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(createQRCodeView()); final AlertDialog dialog = builder.create(); return dialog; } @Override public void onStart() { super.onStart(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_QR_CONTENT, mQRContent); } @Override public void onStop() { super.onStop(); } private ImageView createQRCodeView() { QRCodeWriter qrCodeWriter = new QRCodeWriter(); try { WindowManager manager = (WindowManager) getActivity().getSystemService(WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point point = new Point(); display.getSize(point); int width = point.x; int height = point.y; int smallerDimension = width < height ? width : height; smallerDimension = smallerDimension * 3/4; BitMatrix bitMatrix = qrCodeWriter.encode(mQRContent, BarcodeFormat.QR_CODE, smallerDimension, smallerDimension); final int w = bitMatrix.getWidth(); final int h = bitMatrix.getHeight(); final int[] pixels = new int[w * h]; for (int y = 0; y < h; y++) { final int offset = y * w; for (int x = 0; x < w; x++) { pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE; } } mQRImage = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mQRImage.setPixels(pixels, 0, smallerDimension, 0, 0, w, h); ImageView imageView = new ImageView(getActivity()); imageView.setImageBitmap(mQRImage); return imageView; } catch (WriterException e) { dismiss(); return null; } } public void show(FragmentManager manager, String tag, String qrContent) { mQRContent = qrContent; show(manager, tag); } }
3,155
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
SiteswapEntity.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/SiteswapEntity.java
package namlit.siteswapgenerator; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import androidx.annotation.NonNull; import java.io.Serializable; import siteswaplib.Siteswap; @Entity(tableName = "favorites") public class SiteswapEntity implements Serializable { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "uid") private int uid; @ColumnInfo(name = "siteswap") private String siteswap; @ColumnInfo(name = "name") private String name; @ColumnInfo(name = "juggler_names") private String juggerNames; @ColumnInfo(name = "location") private String location; @ColumnInfo(name = "date") private String date; public SiteswapEntity() { } public SiteswapEntity(Siteswap siteswap, String name, String juggerNames, String location, String date) { fromSiteswap(siteswap); setName(name); setJuggerNames(juggerNames); setLocation(location); setDate(date); } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getSiteswap() { return siteswap; } public void setSiteswap(String siteswap) { this.siteswap = siteswap; } public String getName() { return name; } public void setName(String favoriteName) { this.name = favoriteName; } public String getJuggerNames() { return juggerNames; } public void setJuggerNames(String juggerNames) { this.juggerNames = juggerNames; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Siteswap toSiteswap() { Siteswap siteswap = new Siteswap(getSiteswap()); return siteswap; } public void fromSiteswap(Siteswap siteswap) { setSiteswap(siteswap.toParsableString()); setName(siteswap.getSiteswapName()); } @Override public String toString() { return getName() + ", " + getJuggerNames() + ", " + getLocation() + ", " + getDate(); } }
2,394
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
ShowSiteswaps.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/ShowSiteswaps.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.FragmentManager; import android.content.Intent; import androidx.core.view.MenuItemCompat; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.appcompat.widget.ShareActionProvider; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SearchView; import java.util.LinkedList; import siteswaplib.SiteswapGenerator; import siteswaplib.Siteswap; public class ShowSiteswaps extends AppCompatActivity implements SiteswapGenerationFragment.SiteswapGenerationCallbacks { private static final String TAG_SITESWAP_GENERATION_TASK_FRAGMENT = "siteswap_generation_task_fragment"; private SiteswapGenerator mGenerator = null; private LinkedList<Siteswap> mSiteswapList = null; private SiteswapGenerator.Status mGenerationStatus = SiteswapGenerator.Status.GENERATING; private SiteswapGenerationFragment mSiteswapGenerationFragment; ListView mSiteswapListView; SearchView mSearchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_siteswaps); setTitle(String.format(getString(R.string.show_siteswaps__title_generating))); Intent intent = getIntent(); if(intent != null) { mGenerator = (SiteswapGenerator) intent.getSerializableExtra(getString(R.string.intent__siteswap_generator)); } mSiteswapListView = (ListView) findViewById(R.id.siteswap_list); mSearchView = (SearchView) findViewById(R.id.search_view); FragmentManager fm = getFragmentManager(); mSiteswapGenerationFragment = (SiteswapGenerationFragment) fm.findFragmentByTag(TAG_SITESWAP_GENERATION_TASK_FRAGMENT); // If the Fragment is non-null, then it is currently being // retained across a configuration change. if (mSiteswapGenerationFragment == null) { mSiteswapGenerationFragment = new SiteswapGenerationFragment(); fm.beginTransaction().add(mSiteswapGenerationFragment, TAG_SITESWAP_GENERATION_TASK_FRAGMENT).commit(); } else { mSiteswapGenerationFragment.getSiteswapGenerator(); } } @Override protected void onRestart() { super.onRestart(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_siteswap_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.menu_item_share) { Intent shareIntent = createShareIntent(); Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via)); // Check if there are apps available to handle the intent if (shareIntent.resolveActivity(getPackageManager()) != null) { startActivity(chooserIntent); } } return super.onOptionsItemSelected(item); } private Intent createShareIntent() { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); String siteswapString = ""; if (mSiteswapList != null) { StringBuilder stringBuilder = new StringBuilder(); int char_counter = 0; for (Siteswap siteswap: mSiteswapList) { stringBuilder.append(siteswap.toString() + "\n"); char_counter += siteswap.period_length(); if (char_counter >= 1000) { stringBuilder.append(getString( R.string.show_siteswaps__share_to_many_siteswaps)); break; } } siteswapString = stringBuilder.toString(); } shareIntent.putExtra(Intent.EXTRA_TEXT, siteswapString); shareIntent.setType("text/plain"); return shareIntent; } private void loadSiteswaps() { mSiteswapList = mGenerator.getSiteswaps(); ArrayAdapter adapter = new ArrayAdapter<Siteswap>( ShowSiteswaps.this, android.R.layout.simple_list_item_1, mSiteswapList); mSiteswapListView.setAdapter(adapter); mSiteswapListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Siteswap siteswap = (Siteswap) parent.getItemAtPosition(position); Siteswap compatible_siteswap = mGenerator.getCompatibleSiteswap(); if (compatible_siteswap != null) { siteswap = Siteswap.mergeCompatible(compatible_siteswap, siteswap); if (siteswap == null) { siteswap = (Siteswap) parent.getItemAtPosition(position); } } Intent intent = new Intent(getApplicationContext(), DetailedSiteswapActivity.class); intent.putExtra(getString(R.string.intent_detailed_siteswap_view__siteswap), siteswap); startActivity(intent); } }); switch (mGenerationStatus) { case GENERATING: setTitle(String.format(getString(R.string.show_siteswaps__title_generating))); break; case ALL_SITESWAPS_FOUND: setTitle(String.format(getString(R.string.show_siteswaps__title_found_all), mSiteswapList.size())); break; case MAX_RESULTS_REACHED: setTitle(String.format(getString(R.string.show_siteswaps__title_limit_reached), mSiteswapList.size())); break; case TIMEOUT_REACHED: setTitle(String.format(getString(R.string.show_siteswaps__title_timeout_reached), mSiteswapList.size())); break; case MEMORY_FULL: setTitle(String.format(getString(R.string.show_siteswaps__title_memory_full), mSiteswapList.size())); break; case CANCELLED: setTitle(String.format(getString(R.string.show_siteswaps__title_cancelled))); break; } mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { if (TextUtils.isEmpty(newText)) { adapter.getFilter().filter(null); } else { adapter.getFilter().filter(newText); } return true; } }); } public SiteswapGenerator getSiteswapGenerator() { return mGenerator; } public void onGenerationComplete(SiteswapGenerator generator, SiteswapGenerator.Status status) { mGenerator = generator; mGenerationStatus = status; loadSiteswaps(); } }
8,281
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
ConfirmRemoveFavoriteDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/ConfirmRemoveFavoriteDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Created by tilman on 29.10.17. */ public class ConfirmRemoveFavoriteDialog extends DialogFragment { private static final String STATE_SITESWAP_ENTIIY = "STATE_SITESWAP_ENTIIY"; private TextView mFavoriteTextView; private SiteswapEntity mSiteswapEntity; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mSiteswapEntity = (SiteswapEntity) savedInstanceState.getSerializable(STATE_SITESWAP_ENTIIY); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_confirm_remove_favorite) .setTitle(getString(R.string.confirm_remove_favorite__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(getString(R.string.remove), null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deleteSiteswapFromFavorites(); dialog.dismiss(); } }); } }); return dialog; } @Override public void onStart() { super.onStart(); mFavoriteTextView = (TextView) getDialog().findViewById(R.id.favorite_text_view); mFavoriteTextView.setText( getString(R.string.confirm_remove_favorite__name) + " " + mSiteswapEntity.getName() + "\n" + getString(R.string.confirm_remove_favorite__jugglers) + " " + mSiteswapEntity.getJuggerNames() + "\n" + getString(R.string.confirm_remove_favorite__location) + " " + mSiteswapEntity.getLocation() + "\n" + getString(R.string.confirm_remove_favorite__date) + " " + mSiteswapEntity.getDate()); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_SITESWAP_ENTIIY, mSiteswapEntity); } @Override public void onStop() { super.onStop(); } private void deleteSiteswapFromFavorites() { new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getContext()); FavoriteDao dao = db.siteswapDao(); dao.deleteFavorite(mSiteswapEntity); getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getContext(), getString(R.string.detailed_siteswap__toast_favorite_removed), Toast.LENGTH_LONG).show(); } }); } catch (android.database.sqlite.SQLiteConstraintException e) { } catch (NullPointerException e) { } } }).start(); } public void show(FragmentManager manager, String tag, SiteswapEntity siteswapEntity) { mSiteswapEntity = siteswapEntity; show(manager, tag); } }
4,788
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
GenerationParameterEntity.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/GenerationParameterEntity.java
package namlit.siteswapgenerator; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import androidx.annotation.NonNull; import java.io.Serializable; import siteswaplib.FilterList; import siteswaplib.Siteswap; @Entity(tableName = "generation_parameters") public class GenerationParameterEntity implements Serializable { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "uid") private int uid; @ColumnInfo(name = "name") private String name; @ColumnInfo(name = "numberOfObjects") private int numberOfObjects; @ColumnInfo(name = "periodLength") private int periodLength; @ColumnInfo(name = "maxThrow") private int maxThrow; @ColumnInfo(name = "minThrow") private int minThrow; @ColumnInfo(name = "numberOfJugglers") private int numberOfJugglers; @ColumnInfo(name = "maxResults") private int maxResults; @ColumnInfo(name = "timeout") private int timeout; @ColumnInfo(name = "isSynchronous") private boolean isSynchronous; @ColumnInfo(name = "isRandomMode") private boolean isRandomMode; @ColumnInfo(name = "isZips") private boolean isZips; @ColumnInfo(name = "isZaps") private boolean isZaps; @ColumnInfo(name = "isHolds") private boolean isHolds; @ColumnInfo(name = "filterListString") private String filterListString; public GenerationParameterEntity() { name = ""; numberOfObjects = 7; periodLength = 5; maxThrow = 10; minThrow = 2; numberOfJugglers = 2; maxResults = 100; timeout = 5; isSynchronous = false; isRandomMode = false; isZips = false; isZaps = false; isHolds = false; setFilterList(new FilterList(numberOfJugglers, 1)); } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public int getNumberOfObjects() { return numberOfObjects; } public void setNumberOfObjects(int numberOfObjects) { this.numberOfObjects = numberOfObjects; } public int getPeriodLength() { return periodLength; } public void setPeriodLength(int periodLength) { this.periodLength = periodLength; } public int getMaxThrow() { return maxThrow; } public void setMaxThrow(int maxThrow) { this.maxThrow = maxThrow; } public int getMinThrow() { return minThrow; } public void setMinThrow(int minThrow) { this.minThrow = minThrow; } public int getNumberOfJugglers() { return numberOfJugglers; } public void setNumberOfJugglers(int numberOfJugglers) { this.numberOfJugglers = numberOfJugglers; } public int getMaxResults() { return maxResults; } public void setMaxResults(int maxResults) { this.maxResults = maxResults; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public boolean isSynchronous() { return isSynchronous; } public void setSynchronous(boolean is_synchronous) { this.isSynchronous = is_synchronous; } public boolean isRandomMode() { return isRandomMode; } public void setRandomMode(boolean is_random_mode) { this.isRandomMode = is_random_mode; } public boolean isZips() { return isZips; } public void setZips(boolean zips) { isZips = zips; } public boolean isZaps() { return isZaps; } public void setZaps(boolean zaps) { isZaps = zaps; } public boolean isHolds() { return isHolds; } public void setHolds(boolean holds) { isHolds = holds; } public void setFilterListString(String filterListString) { this.filterListString = filterListString; } public String getFilterListString() { return filterListString; } public void setFilterList(FilterList filter_list) { setFilterListString(filter_list.toParsableString()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Siteswap toSiteswap() { Siteswap siteswap = new Siteswap(getName()); return siteswap; } @Override public String toString() { return getName(); } }
4,533
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
AddFilterDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/AddFilterDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.content.Context; import androidx.fragment.app.DialogFragment; import siteswaplib.Filter; /** * Created by tilman on 29.10.17. */ public class AddFilterDialog extends DialogFragment { public interface FilterDialogListener { public void onAddSiteswapFilter(Filter filter); public void onRemoveSiteswapFilter(Filter filter); public void onChangeSiteswapFilter(Filter oldFilter, Filter newFilter); } // Use this instance of the interface to deliver action events FilterDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Context context) { super.onAttach(context); try { mListener = (FilterDialogListener) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement NoticeDialogListener"); } } }
1,769
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NonScrollListView.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/NonScrollListView.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.util.AttributeSet; import android.widget.ListView; import android.content.Context; import android.view.ViewGroup; /** * Created by tilman on 07.10.17. */ public class NonScrollListView extends ListView { public NonScrollListView(Context context) { super(context); } public NonScrollListView(Context context, AttributeSet attrs) { super(context, attrs); } public NonScrollListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom); ViewGroup.LayoutParams params = getLayoutParams(); params.height = getMeasuredHeight(); } }
1,714
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
GenerateCompatibleSiteswapDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/GenerateCompatibleSiteswapDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.widget.CheckBox; import android.widget.EditText; import siteswaplib.FilterList; import siteswaplib.InterfaceFilter; import siteswaplib.PatternFilter; import siteswaplib.Siteswap; import siteswaplib.SiteswapGenerator; /** * Created by tilman on 22.07.18. */ public class GenerateCompatibleSiteswapDialog extends DialogFragment { public interface DatabaseTransactionComplete { public void databaseTransactionComplete(); } private static final String STATE_SITESWAP = "STATE_SITESWAP"; private EditText mNumberOfObjectsTextEdit; private EditText mMinThrow; private EditText mMaxThrow; private CheckBox mIsZipsCheckbox; private CheckBox mIsZapscheckbox; private CheckBox mIsHoldsCheckbox; private Siteswap mSiteswap; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mSiteswap = (Siteswap) savedInstanceState.getSerializable(STATE_SITESWAP); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_generate_compatible_siteswap_dialog) .setTitle(getString(R.string.detailed_siteswap__dialog_generate_compatible_title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton(getString(R.string.generate), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { generateCompatibleSiteswaps(); } }); return builder.create(); } @Override public void onStart() { super.onStart(); mNumberOfObjectsTextEdit = (EditText) getDialog().findViewById(R.id.number_of_objects_compatible_text_edit); mMinThrow = (EditText) getDialog().findViewById(R.id.min_throw_compatible_text_edit); mMaxThrow = (EditText) getDialog().findViewById(R.id.max_throw_compatible_text_edit); mIsZipsCheckbox = (CheckBox) getDialog().findViewById(R.id.include_zips_compatible_checkbox); mIsZapscheckbox = (CheckBox) getDialog().findViewById(R.id.include_zaps_compatible_checkbox); mIsHoldsCheckbox = (CheckBox) getDialog().findViewById(R.id.include_holds_compatible_checkbox); mNumberOfObjectsTextEdit.setText(String.valueOf(mSiteswap.getNumberOfObjects())); mMinThrow.setText(String.valueOf(mSiteswap.getNumberOfJugglers())); mMaxThrow.setText(String.valueOf(mSiteswap.getMaxThrow())); mIsZipsCheckbox.setChecked(true); mIsZapscheckbox.setChecked(false); mIsHoldsCheckbox.setChecked(false); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_SITESWAP, mSiteswap); } @Override public void onStop() { super.onStop(); } private void generateCompatibleSiteswaps() { try { int numberOfObjects = Integer.valueOf(mNumberOfObjectsTextEdit.getText().toString()); int minThrow = Integer.valueOf(mMinThrow.getText().toString()); int maxThrow = Integer.valueOf(mMaxThrow.getText().toString()); int numberOfJugglers = mSiteswap.getNumberOfJugglers(); int periodLength = mSiteswap.period_length(); int maxResults = 1000; int timeout = 10; boolean isSyncPattern = mSiteswap.isSynchronous(); int numberOfSynchronousHands = 1; if (isSyncPattern) { numberOfSynchronousHands = numberOfJugglers; } boolean isZips = mIsZipsCheckbox.isChecked(); boolean isZaps = mIsZapscheckbox.isChecked(); boolean isHolds = mIsHoldsCheckbox.isChecked(); if (periodLength < 1) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_period_length)); if (numberOfObjects < 1) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_number_of_objects)); if (numberOfJugglers < 1 || numberOfJugglers > 10) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_number_of_jugglers)); if (maxThrow < numberOfObjects) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_max_throw_smaller_average)); if (minThrow > numberOfObjects) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_min_throw_greater_average)); if ((numberOfObjects + mSiteswap.getNumberOfObjects()) % numberOfJugglers != 0) throw new IllegalArgumentException(getString(R.string.generate_compatible__invalid_number_of_objects)); FilterList filters = new FilterList(); filters.addDefaultFilters(numberOfJugglers, minThrow, numberOfSynchronousHands); if (!isZips) { filters.removeZips(numberOfJugglers, numberOfSynchronousHands); } if (!isZaps) { filters.removeZaps(numberOfJugglers, numberOfSynchronousHands); } if (!isHolds) { filters.removeHolds(numberOfJugglers, numberOfSynchronousHands); } filters.add(new InterfaceFilter(mSiteswap.toInterface().toPattern(), PatternFilter.Type.INCLUDE)); SiteswapGenerator siteswapGenerator = new SiteswapGenerator(periodLength, maxThrow, minThrow, numberOfObjects, numberOfJugglers, filters); siteswapGenerator.setMaxResults(maxResults); siteswapGenerator.setTimeoutSeconds(timeout); siteswapGenerator.setSyncPattern(isSyncPattern); siteswapGenerator.setRandomGeneration(false); siteswapGenerator.setCompatibleSiteswap(mSiteswap); Intent intent = new Intent(getContext(), ShowSiteswaps.class); intent.putExtra(getString(R.string.intent__siteswap_generator), siteswapGenerator); startActivity(intent); } catch (NumberFormatException e) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(getString(R.string.main_activity__invalid_input_value) + " " + String.format(getString(R.string.main_activity__could_not_convert_to_int), e.getMessage())) .setNeutralButton(getString(R.string.back), null); builder.create().show(); return; } catch (IllegalArgumentException e) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setMessage(getString(R.string.main_activity__invalid_input_value) + " " + e.getMessage()) .setNeutralButton(getString(R.string.back), null); builder.create().show(); return; } } public void show(FragmentManager manager, String tag, Siteswap siteswap) { mSiteswap = siteswap; show(manager, tag); } }
8,436
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
SiteswapGenerationFragment.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/SiteswapGenerationFragment.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.app.Fragment; import siteswaplib.SiteswapGenerator; /** * Created by tilman on 22.11.17. */ public class SiteswapGenerationFragment extends Fragment { interface SiteswapGenerationCallbacks { SiteswapGenerator getSiteswapGenerator(); void onGenerationComplete(SiteswapGenerator generator, SiteswapGenerator.Status status); } private SiteswapGenerationCallbacks mCallbacks; private SiteswapGenerationTask mTask; @Override public void onAttach(Context context) { super.onAttach(context); mCallbacks = (SiteswapGenerationCallbacks) context; } @Override public void onAttach(Activity context) { super.onAttach(context); mCallbacks = (SiteswapGenerationCallbacks) context; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); // Create and execute the background task. mTask = new SiteswapGenerationTask(); mTask.execute(); } /** * Set the callback to null so we don't accidentally leak the * Activity instance. */ @Override public void onDetach() { super.onDetach(); mCallbacks = null; } @Override public void onDestroy() { super.onDestroy(); mTask.mGenerator.cancelGeneration(); mTask.cancel(true); mTask.mGenerator = null; mTask = null; } public void getSiteswapGenerator() { if (isError()) { mTask = new SiteswapGenerationTask(); mTask.execute(); return; } if (mTask.getStatus() == AsyncTask.Status.FINISHED) { mTask.generationComplete(); } } public boolean isError() { if(mTask.mGenerator == null) return true; return mTask.mIsError; } private class SiteswapGenerationTask extends AsyncTask<Void, Integer, Void> { private SiteswapGenerator mGenerator; private SiteswapGenerator.Status mGenerationStatus; private boolean mIsError = false; @Override protected void onPreExecute() { if (mCallbacks != null) { mGenerator = mCallbacks.getSiteswapGenerator(); } } @Override protected Void doInBackground(Void... ignore) { try { mGenerationStatus = mGenerator.generateSiteswaps(); } catch (java.lang.RuntimeException e) { mIsError = true; // This exceptions occurs, if the Andoid system recycles the memory of the // activity, but doInBackgound is still executed in background. } return null; } @Override protected void onPostExecute(Void ignore) { generationComplete(); } private void generationComplete() { if (mIsError) { return; } if (mCallbacks != null) { mCallbacks.onGenerationComplete(mGenerator, mGenerationStatus); } } } }
4,069
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
MainActivity.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/MainActivity.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.Manifest; import android.app.AlertDialog; import androidx.sqlite.db.SimpleSQLiteQuery; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.util.Base64; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.CheckBox; import android.text.TextWatcher; import android.text.Editable; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.channels.FileChannel; import java.util.List; import siteswaplib.*; public class MainActivity extends AppCompatActivity implements AddFilterDialog.FilterDialogListener, LoadGenerationParametersDialog.UpdateGenerationParameters { final static int PATTERN_FILTER_ITEM_NUMBER = 0; final static int PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1; final static int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 2; private FilterList mFilterList; private int mNumberOfObjects; private int mPeriodLength; private int mMaxThrow; private int mMinThrow; private int mNumberOfJugglers; private int mMaxResults; private int mTimeout; private boolean mIsSyncPattern; private boolean mIsRandomGenerationMode; private boolean mIsZips; private boolean mIsZaps; private boolean mIsHolds; private int mFilterSpinnerPosition; private EditText mNumberOfObjectsEditText; private EditText mPeriodLengthEditText; private EditText mMaxThrowEditText; private EditText mMinThrowEditText; private EditText mNumberOfJugglersEditText; private EditText mMaxResultsEditText; private EditText mTimeoutEditText; private CheckBox mSyncModeCheckbox; private CheckBox mRandomGenerationModeCheckbox; private CheckBox mZipsCheckbox; private CheckBox mZapsCheckbox; private CheckBox mHoldsCheckbox; private Spinner mFilterTypeSpinner; private NonScrollListView mFilterListView; private ArrayAdapter<Filter> mFilterListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); populateDatabaseWithDefaultGenerationParameters(); mNumberOfObjectsEditText = (EditText) findViewById(R.id.number_of_objects); mPeriodLengthEditText = (EditText) findViewById(R.id.period_length); mMaxThrowEditText = (EditText) findViewById(R.id.max_throw); mMinThrowEditText = (EditText) findViewById(R.id.min_throw); mNumberOfJugglersEditText = (EditText) findViewById(R.id.number_of_jugglers); mMaxResultsEditText = (EditText) findViewById(R.id.max_results); mTimeoutEditText = (EditText) findViewById(R.id.timeout); mZipsCheckbox = (CheckBox) findViewById(R.id.include_zips_checkbox); mZapsCheckbox = (CheckBox) findViewById(R.id.include_zaps_checkbox); mHoldsCheckbox = (CheckBox) findViewById(R.id.include_holds_checkbox); mFilterTypeSpinner = (Spinner) findViewById(R.id.filter_type_spinner); mFilterListView = (NonScrollListView) findViewById(R.id.filter_list); mSyncModeCheckbox = (CheckBox) findViewById(R.id.sync_mode_checkbox); mRandomGenerationModeCheckbox = (CheckBox) findViewById(R.id.random_generation_mode_checkbox); mFilterList = new FilterList(); SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); mNumberOfObjects = sharedPref.getInt(getString(R.string.main_activity__settings_number_of_objects), 7); mPeriodLength = sharedPref.getInt(getString(R.string.main_activity__settings_period_length), 5); mMaxThrow = sharedPref.getInt(getString(R.string.main_activity__settings_max_throw), 10); mMinThrow = sharedPref.getInt(getString(R.string.main_activity__settings_min_throw), 2); mNumberOfJugglers = sharedPref.getInt(getString(R.string.main_activity__settings_number_of_jugglers), 2); mMaxResults = sharedPref.getInt(getString(R.string.main_activity__settings_max_results), 100); mTimeout = sharedPref.getInt(getString(R.string.main_activity__settings_timeout), 5); mIsZips = sharedPref.getBoolean(getString(R.string.main_activity__settings_is_zips), true); mIsZaps = sharedPref.getBoolean(getString(R.string.main_activity__settings_is_zaps), false); mIsHolds = sharedPref.getBoolean(getString(R.string.main_activity__settings_is_holds), false); mIsSyncPattern = sharedPref.getBoolean( getString(R.string.main_activity__settings_is_sync_pattern), false); mIsRandomGenerationMode = sharedPref.getBoolean( getString(R.string.main_activity__settings_is_random_generation_mode), false); mFilterSpinnerPosition = sharedPref.getInt(getString(R.string.main_activity__settings_filter_spinner_position), 0); String serializedFilterList = sharedPref.getString(getString(R.string.main_activity__settings_filter_list), ""); if (serializedFilterList != "") { try { byte b[] = Base64.decode(serializedFilterList, Base64.DEFAULT); ByteArrayInputStream bi = new ByteArrayInputStream(b); ObjectInputStream si = new ObjectInputStream(bi); mFilterList = (FilterList) si.readObject(); si.close(); } catch (Exception e) { Toast.makeText(this, getString(R.string.main_activity__deserialization_error_toast), Toast.LENGTH_SHORT).show(); } } mNumberOfObjectsEditText.setText(String.valueOf(mNumberOfObjects)); mPeriodLengthEditText.setText(String.valueOf(mPeriodLength)); mMaxThrowEditText.setText(String.valueOf(mMaxThrow)); mMinThrowEditText.setText(String.valueOf(mMinThrow)); mNumberOfJugglersEditText.setText(String.valueOf(mNumberOfJugglers)); mMaxResultsEditText.setText(String.valueOf(mMaxResults)); mTimeoutEditText.setText(String.valueOf(mTimeout)); mSyncModeCheckbox.setChecked(mIsSyncPattern); mRandomGenerationModeCheckbox.setChecked(mIsRandomGenerationMode); mZipsCheckbox.setChecked(mIsZips); mZapsCheckbox.setChecked(mIsZaps); mHoldsCheckbox.setChecked(mIsHolds); mFilterTypeSpinner.setSelection(mFilterSpinnerPosition); mFilterListAdapter = new ArrayAdapter<Filter>( this, android.R.layout.simple_list_item_1, mFilterList); mFilterListView.setAdapter(mFilterListAdapter); mFilterListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Filter filter = (Filter) parent.getItemAtPosition(position); if (!updateFromTextEdits()) return; if (filter instanceof NumberFilter) { new NumberFilterDialog().show(getSupportFragmentManager(), getString(R.string.number_filter__dialog_tag), mMinThrow, mMaxThrow, mPeriodLength, getNumberOfSynchronousHands(), filter); } else if (filter instanceof PatternFilter) new PatternFilterDialog().show(getSupportFragmentManager(), getString(R.string.pattern_filter__dialog_tag), mNumberOfJugglers, filter); } }); updateAutoFilters(); mNumberOfJugglersEditText.addTextChangedListener(new TextWatcher() { private boolean was_invalid = false; private int invalid_filter_list_length = 0; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Add Default Filters, if new text is not empty if (count != 0 || start != 0) updateAutoFilters(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Remove Default Filters, if old text was not empty if (count == 0 && start == 0) { return; } updateFromTextEdits(); mFilterList.removeDefaultFilters(mNumberOfJugglers, getNumberOfSynchronousHands()); mFilterList.addZips(mNumberOfJugglers, getNumberOfSynchronousHands()); mFilterList.addZaps(mNumberOfJugglers, getNumberOfSynchronousHands()); mFilterList.addHolds(mNumberOfJugglers, getNumberOfSynchronousHands()); mFilterListAdapter.notifyDataSetChanged(); } @Override public void afterTextChanged(Editable s) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public GenerationParameterEntity build7ClubDefaultGenerationEntity() { GenerationParameterEntity entity = new GenerationParameterEntity(); entity.setName("Default: 7 clubs period 5"); entity.setNumberOfObjects(7); entity.setPeriodLength(5); entity.setMaxThrow(10); entity.setMinThrow(2); entity.setNumberOfJugglers(2); entity.setMaxResults(100); entity.setTimeout(5); entity.setSynchronous(false); entity.setRandomMode(false); entity.setZips(true); entity.setZaps(false); entity.setHolds(false); FilterList list = new FilterList(); list.addDefaultFilters(2, 2, 1); list.removeZaps(2, 1); list.removeHolds(2, 1); entity.setFilterList(list); return entity; } public void populateDatabaseWithDefaultGenerationParameters() { new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); List<GenerationParameterEntity> entities = db.generationParameterDao().getAllGenerationParameters(); if (entities.isEmpty()) { db.generationParameterDao().insertGenerationParameters( build7ClubDefaultGenerationEntity() ); } } catch (android.database.sqlite.SQLiteConstraintException e) { } } }).start(); } public void saveGenerationParameters() { GenerationParameterEntity entity = new GenerationParameterEntity(); if (!updateFromTextEdits()) return; entity.setNumberOfObjects(mNumberOfObjects); entity.setPeriodLength(mPeriodLength); entity.setMaxThrow(mMaxThrow); entity.setMinThrow(mMinThrow); entity.setNumberOfJugglers(mNumberOfJugglers); entity.setMaxResults(mMaxResults); entity.setTimeout(mTimeout); entity.setSynchronous(mIsSyncPattern); entity.setRandomMode(mIsRandomGenerationMode); entity.setZips(mIsZips); entity.setZaps(mIsZaps); entity.setHolds(mIsHolds); entity.setFilterList(mFilterList); new SaveGenerationParametersDialog().show(getSupportFragmentManager(), getString(R.string.save_generation_parameters__dialog_tag), entity); } public void updateGenerationParameters(GenerationParameterEntity generationParameters) { mNumberOfObjectsEditText.setText(String.valueOf(generationParameters.getNumberOfObjects())); mPeriodLengthEditText.setText(String.valueOf(generationParameters.getPeriodLength())); mMaxThrowEditText.setText(String.valueOf(generationParameters.getMaxThrow())); mMinThrowEditText.setText(String.valueOf(generationParameters.getMinThrow())); mNumberOfJugglersEditText.setText(String.valueOf(generationParameters.getNumberOfJugglers())); mMaxResultsEditText.setText(String.valueOf(generationParameters.getMaxResults())); mTimeoutEditText.setText(String.valueOf(generationParameters.getTimeout())); mSyncModeCheckbox.setChecked(generationParameters.isSynchronous()); mRandomGenerationModeCheckbox.setChecked(generationParameters.isRandomMode()); mZipsCheckbox.setChecked(generationParameters.isZips()); mZapsCheckbox.setChecked(generationParameters.isZaps()); mHoldsCheckbox.setChecked(generationParameters.isHolds()); mFilterList.fromParsableString(generationParameters.getFilterListString()); mFilterListAdapter.notifyDataSetChanged(); } public void loadGenerationParameters() { new Thread(new Runnable() { @Override public void run() { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); final List<GenerationParameterEntity> entities = db.generationParameterDao().getAllGenerationParameters(); runOnUiThread(new Runnable() { @Override public void run() { new LoadGenerationParametersDialog().show(getSupportFragmentManager(), getString(R.string.load_generation_parameters__dialog_tag), entities); } }); } }).start(); } public void deleteGenerationParameters() { new Thread(new Runnable() { @Override public void run() { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); final List<GenerationParameterEntity> entities = db.generationParameterDao().getAllGenerationParameters(); runOnUiThread(new Runnable() { @Override public void run() { new DeleteGenerationParametersDialog().show(getSupportFragmentManager(), getString(R.string.delete_generation_parameters__dialog_tag), entities); } }); } }).start(); } private File getDatabaseBackupFile() { return new File(getExternalFilesDir(null), "backup_" + AppDatabase.database_name); } public void exportAppDatabase() { new Thread(new Runnable() { @Override public void run() { AppDatabase.getAppDatabase(getApplicationContext()).siteswapDao().checkpoint(new SimpleSQLiteQuery("pragma wal_checkpoint(full)")); File source_path = getDatabasePath(AppDatabase.database_name); File dest_path = getDatabaseBackupFile(); COPY_FILE_STATE status = copyFile(source_path, dest_path); final String user_msg; switch (status) { case SUCCESS: user_msg = String.format(getString( R.string.main_activity__successfully_exported_database_msg), dest_path.toString()); break; case FILE_NOT_FOUND: user_msg = String.format(getString(R.string.main_activity__file_not_found_toast), dest_path.toString()); break; case IO_ERROR: user_msg = getString(R.string.main_activity__io_exeption_toast); break; default: user_msg = "Error: unknown return value of copy_file"; } runOnUiThread(new Runnable() { @Override public void run() { showMessageDialog(user_msg); } }); } }).start(); } public void importAppDatabase() { confirmDatabaseImportDialog(); } private void copyAppDatabaseFromExternalStorage() { new Thread(new Runnable() { @Override public void run() { AppDatabase.getAppDatabase(getApplicationContext()).siteswapDao().checkpoint(new SimpleSQLiteQuery("pragma wal_checkpoint(full)")); AppDatabase.destroyInstance(); File source_path = getDatabaseBackupFile(); File dest_path = getDatabasePath(AppDatabase.database_name); File dbwal = new File(getDatabasePath(AppDatabase.database_name).getAbsolutePath() + "-wal"); File dbshm = new File(getDatabasePath(AppDatabase.database_name).getAbsolutePath() + "-shm"); dbwal.delete(); dbshm.delete(); COPY_FILE_STATE status = copyFile(source_path, dest_path); final String user_msg; switch (status) { case SUCCESS: user_msg = String.format(getString( R.string.main_activity__successfully_imported_database_msg), source_path.toString()); break; case FILE_NOT_FOUND: user_msg = String.format(getString(R.string.main_activity__file_not_found_toast), source_path.toString()); break; case IO_ERROR: user_msg = getString(R.string.main_activity__io_exeption_toast); break; default: user_msg = "Error: unknown return value of copy_file"; } runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), user_msg, Toast.LENGTH_LONG).show(); } }); } }).start(); } private enum COPY_FILE_STATE {SUCCESS, IO_ERROR, FILE_NOT_FOUND}; public COPY_FILE_STATE copyFile(File source, File destination) { //Toast.makeText(this, source.toString() + "\n" + destination.toString(), // Toast.LENGTH_LONG).show(); FileChannel sourceChannel; FileChannel destinationChannel; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); try { destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); destinationChannel.close(); sourceChannel.close(); } catch (IOException e) { return COPY_FILE_STATE.IO_ERROR; } } catch (FileNotFoundException e) { return COPY_FILE_STATE.FILE_NOT_FOUND; } return COPY_FILE_STATE.SUCCESS; } private void showMessageDialog(String message) { try { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); } catch (Throwable t) { t.printStackTrace(); } } private void confirmDatabaseImportDialog() { try { AlertDialog.Builder builder = new AlertDialog.Builder(this); String source = getDatabaseBackupFile().toString(); builder.setMessage(getString(R.string.main_activity__import_database_confirmation, source)); builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { copyAppDatabaseFromExternalStorage(); } }); AlertDialog dialog = builder.create(); dialog.show(); } catch (Throwable t) { t.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_load_generation_parameters) { loadGenerationParameters(); } else if (id == R.id.action_save_generation_parameters) { saveGenerationParameters(); } else if (id == R.id.action_delete_generation_parameters) { deleteGenerationParameters(); } else if (id == R.id.action_named_siteswaps) { showNamedSiteswaps(); } else if (id == R.id.action_export_database) { exportAppDatabase(); } else if (id == R.id.action_import_database) { importAppDatabase(); } else if (id == R.id.action_favorites) { favorites(); } else if (id == R.id.action_about) { showAboutDialog(); } else if (id == R.id.action_help) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(Html.fromHtml(getString(R.string.help_activity__help_html_text))) .setNeutralButton(getString(R.string.back), null); builder.create().show(); } return super.onOptionsItemSelected(item); } private boolean updateFromTextEdits() { try { mNumberOfObjects = Integer.valueOf(mNumberOfObjectsEditText.getText().toString()); mPeriodLength = Integer.valueOf(mPeriodLengthEditText.getText().toString()); mMaxThrow = Integer.valueOf(mMaxThrowEditText.getText().toString()); mMinThrow = Integer.valueOf(mMinThrowEditText.getText().toString()); mNumberOfJugglers = Integer.valueOf(mNumberOfJugglersEditText.getText().toString()); mMaxResults = Integer.valueOf(mMaxResultsEditText.getText().toString()); mTimeout = Integer.valueOf(mTimeoutEditText.getText().toString()); mIsSyncPattern = mSyncModeCheckbox.isChecked(); mIsRandomGenerationMode = mRandomGenerationModeCheckbox.isChecked(); mIsZips = mZipsCheckbox.isChecked(); mIsZaps = mZapsCheckbox.isChecked(); mIsHolds = mHoldsCheckbox.isChecked(); mFilterSpinnerPosition = mFilterTypeSpinner.getSelectedItemPosition(); if (mPeriodLength < 1) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_period_length)); if (mNumberOfObjects < 1) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_number_of_objects)); if (mNumberOfJugglers < 1 || mNumberOfJugglers > 10) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_number_of_jugglers)); if (mMaxThrow < mNumberOfObjects) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_max_throw_smaller_average)); if (mMinThrow > mNumberOfObjects) throw new IllegalArgumentException(getString(R.string.main_activity__invalid_min_throw_greater_average)); } catch (NumberFormatException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.main_activity__invalid_input_value) + " " + String.format(getString(R.string.main_activity__could_not_convert_to_int), e.getMessage())) .setNeutralButton(getString(R.string.back), null); builder.create().show(); return false; } catch (IllegalArgumentException e) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.main_activity__invalid_input_value) + " " + e.getMessage()) .setNeutralButton(getString(R.string.back), null); builder.create().show(); return false; } return true; } @Override protected void onStop() { super.onStop(); SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); updateFromTextEdits(); editor.putInt(getString(R.string.main_activity__settings_number_of_objects), mNumberOfObjects); editor.putInt(getString(R.string.main_activity__settings_period_length), mPeriodLength); editor.putInt(getString(R.string.main_activity__settings_max_throw), mMaxThrow); editor.putInt(getString(R.string.main_activity__settings_min_throw), mMinThrow); editor.putInt(getString(R.string.main_activity__settings_number_of_jugglers), mNumberOfJugglers); editor.putInt(getString(R.string.main_activity__settings_max_results), mMaxResults); editor.putInt(getString(R.string.main_activity__settings_timeout), mTimeout); editor.putBoolean(getString(R.string.main_activity__settings_is_sync_pattern), mIsSyncPattern); editor.putBoolean(getString(R.string.main_activity__settings_is_random_generation_mode), mIsRandomGenerationMode); editor.putBoolean(getString(R.string.main_activity__settings_is_zips), mIsZips); editor.putBoolean(getString(R.string.main_activity__settings_is_zaps), mIsZaps); editor.putBoolean(getString(R.string.main_activity__settings_is_holds), mIsHolds); editor.putInt(getString(R.string.main_activity__settings_filter_spinner_position), mFilterSpinnerPosition); try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream so = new ObjectOutputStream(bo); so.writeObject(mFilterList); so.close(); editor.putString(getString(R.string.main_activity__settings_filter_list), Base64.encodeToString(bo.toByteArray(), Base64.DEFAULT)); } catch (Exception e) { Toast.makeText(this, getString(R.string.main_activity__serialization_error_toast), Toast.LENGTH_SHORT).show(); } editor.commit(); } public int getNumberOfSynchronousHands() { if (mIsSyncPattern) { return mNumberOfJugglers; } return 1; } public void addFilter(View view) { if (!updateFromTextEdits()) return; if (mFilterTypeSpinner.getSelectedItemPosition() == PATTERN_FILTER_ITEM_NUMBER) { new PatternFilterDialog().show(getSupportFragmentManager(), getString(R.string.pattern_filter__dialog_tag), mNumberOfJugglers); } else { new NumberFilterDialog().show(getSupportFragmentManager(), getString(R.string.number_filter__dialog_tag), mMinThrow, mMaxThrow, mPeriodLength, getNumberOfSynchronousHands()); } } public void resetFilters(View view) { mFilterList.clear(); updateAutoFilters(); } public void onAddSiteswapFilter(Filter filter) { if (!mFilterList.contains(filter)) mFilterList.add(filter); mFilterListAdapter.notifyDataSetChanged(); } public void onRemoveSiteswapFilter(Filter filter) { // Remove all occurences of Filter while (mFilterList.remove(filter)) ; mFilterListAdapter.notifyDataSetChanged(); } public void onChangeSiteswapFilter(Filter oldFilter, Filter newFilter) { onRemoveSiteswapFilter(oldFilter); onAddSiteswapFilter(newFilter); } public void enterSiteswap(View button) { if (!updateFromTextEdits()) return; new EnterSiteswapDialog().show(getSupportFragmentManager(), getString(R.string.enter_siteswap__dialog_tag), mNumberOfJugglers, mIsSyncPattern); } public void generateSiteswaps(View view) { if (!updateFromTextEdits()) return; SiteswapGenerator siteswapGenerator = new SiteswapGenerator(mPeriodLength, mMaxThrow, mMinThrow, mNumberOfObjects, mNumberOfJugglers, mFilterList); siteswapGenerator.setMaxResults(mMaxResults); siteswapGenerator.setTimeoutSeconds(mTimeout); siteswapGenerator.setSyncPattern(mIsSyncPattern); siteswapGenerator.setRandomGeneration(mIsRandomGenerationMode); Intent intent = new Intent(this, ShowSiteswaps.class); intent.putExtra(getString(R.string.intent__siteswap_generator), siteswapGenerator); startActivity(intent); } public void onCheckboxClicked(View view) { boolean checked = ((CheckBox) view).isChecked(); int oldNumberOfSynchronousHands = getNumberOfSynchronousHands(); if (!updateFromTextEdits()) { ((CheckBox) view).setChecked(!checked); return; } switch (view.getId()) { case R.id.include_zips_checkbox: if (checked) mFilterList.addZips(mNumberOfJugglers, getNumberOfSynchronousHands()); else mFilterList.removeZips(mNumberOfJugglers, getNumberOfSynchronousHands()); break; case R.id.include_zaps_checkbox: if (checked) mFilterList.addZaps(mNumberOfJugglers, getNumberOfSynchronousHands()); else mFilterList.removeZaps(mNumberOfJugglers, getNumberOfSynchronousHands()); break; case R.id.include_holds_checkbox: if (checked) mFilterList.addHolds(mNumberOfJugglers, getNumberOfSynchronousHands()); else mFilterList.removeHolds(mNumberOfJugglers, getNumberOfSynchronousHands()); break; case R.id.sync_mode_checkbox: removeAutoFilters(oldNumberOfSynchronousHands); updateFiltersWithNumberOfSynchronousHands(getNumberOfSynchronousHands()); addAutoFilters(); break; } mFilterListAdapter.notifyDataSetChanged(); } private boolean updateAutoFilters() { if (!updateFromTextEdits()) return false; removeAutoFilters(getNumberOfSynchronousHands()); addAutoFilters(); mFilterListAdapter.notifyDataSetChanged(); return true; } private void removeAutoFilters(int numberOfSynchronousHands) { mFilterList.removeDefaultFilters(mNumberOfJugglers, mMinThrow, numberOfSynchronousHands); mFilterList.addZips(mNumberOfJugglers, numberOfSynchronousHands); mFilterList.addZaps(mNumberOfJugglers, numberOfSynchronousHands); mFilterList.addHolds(mNumberOfJugglers, numberOfSynchronousHands); } private void addAutoFilters() { mFilterList.addDefaultFilters(mNumberOfJugglers, mMinThrow, getNumberOfSynchronousHands()); if (!mIsZips) mFilterList.removeZips(mNumberOfJugglers, getNumberOfSynchronousHands()); if (!mIsZaps) mFilterList.removeZaps(mNumberOfJugglers, getNumberOfSynchronousHands()); if (!mIsHolds) mFilterList.removeHolds(mNumberOfJugglers, getNumberOfSynchronousHands()); } private void updateFiltersWithNumberOfSynchronousHands(int numberOfSynchronousHands) { for (Filter filter : mFilterList) { if (filter instanceof NumberFilter) { ((NumberFilter) filter).setNumberOfSynchronousHands(numberOfSynchronousHands); } } } private void showNamedSiteswaps() { Intent intent = new Intent(this, NamedSiteswapActivity.class); startActivity(intent); } private void favorites() { Intent intent = new Intent(this, FavoritesActivity.class); startActivity(intent); } private void showAboutDialog() { try { PackageManager manager = getPackageManager(); PackageInfo info = manager.getPackageInfo(getPackageName(), 0); String appVersion = info.versionName; AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = getLayoutInflater().inflate(R.layout.layout_about_page, null); TextView appNameVersion = (TextView) view.findViewById(R.id.appNameVersion); appNameVersion.setText(getString(R.string.app_name) + " " + appVersion); builder.setView(view); builder.setNeutralButton(getString(R.string.back), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); dialog.show(); } catch (Throwable t) { t.printStackTrace(); } } }
35,650
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
DetailedSiteswapActivity.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/DetailedSiteswapActivity.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.content.Intent; import android.net.Uri; import androidx.core.view.MenuItemCompat; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.appcompat.widget.ShareActionProvider; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.List; import java.util.Vector; import siteswaplib.NamedSiteswaps; import siteswaplib.Siteswap; public class DetailedSiteswapActivity extends AppCompatActivity implements AddToFavoritesDialog.DatabaseTransactionComplete { private static final String STATE_SITESWAP = "STATE_SITESWAP"; private Siteswap mSiteswap; private TextView mGlobalSiteswapTextview; private TextView mLocalSiteswapTextview; private TextView mNameTextview; private TextView mInterfacePatternTextview; private TextView mNumberOfObjectsTextview; private TextView mPeriodLengthTextview; private TextView mLocalSiteswapLegendTextview; private CausalDiagram mCausalDiagram; private CausalDiagram mLadderDiagram; private SiteswapEntity mFavorite; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detailed_siteswap); setTitle(R.string.detailed_siteswap__title); if (savedInstanceState != null) { mSiteswap = (Siteswap) savedInstanceState.getSerializable(STATE_SITESWAP); } else { Intent intent = getIntent(); if (Intent.ACTION_VIEW.equals(intent.getAction())) { createFromImplicitIntent(intent); } else { createFromExplicitIntent(intent); } loadNameFromFavorites(); } mGlobalSiteswapTextview = (TextView) findViewById(R.id.global_siteswap_textview); mLocalSiteswapTextview = (TextView) findViewById(R.id.local_siteswap_textview); mNameTextview = (TextView) findViewById(R.id.name_textview); mInterfacePatternTextview = (TextView) findViewById(R.id.interface_pattern_text_view); mNumberOfObjectsTextview = (TextView) findViewById(R.id.number_of_objects_textview); mPeriodLengthTextview = (TextView) findViewById(R.id.period_length_textview); mLocalSiteswapLegendTextview = (TextView) findViewById(R.id.local_siteswap_legend_textview); mCausalDiagram = (CausalDiagram) findViewById(R.id.causal_diagram_view); mCausalDiagram.setSiteswap(mSiteswap); mLadderDiagram = (CausalDiagram) findViewById(R.id.ladder_diagram_view); mLadderDiagram.setSiteswap(mSiteswap); new Thread(new Runnable() { @Override public void run() { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); mFavorite = db.siteswapDao().getSiteswap(mSiteswap.toParsableString()); runOnUiThread(new Runnable() { @Override public void run() { if (mFavorite != null) { mSiteswap.setSiteswapName(mFavorite.getName()); } else { } updateTextViews(); } }); } }).start(); updateTextViews(); } @Override protected void onRestart() { super.onRestart(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_SITESWAP, mSiteswap); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_detailed_siteswap, menu); if (mSiteswap.getNumberOfJugglers() == 2) { menu.add(0, R.id.action_generate_compatible, 0, R.string.detailed_siteswap__option_generate_compatible); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.menu_item_share_detailed) { Intent shareIntent = createShareIntent(); Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via)); // Check if there are apps available to handle the intent if (shareIntent.resolveActivity(getPackageManager()) != null) { startActivity(chooserIntent); } } else if (id == R.id.action_rotate_default) { mSiteswap.rotateToBestStartingPosition(); updateTextViews(); } else if (id == R.id.action_generate_compatible) { generate_compatible_siteswap(); } else if (id == R.id.action_add_to_favorites) { addToFavorites(); updateTextViews(); } else if (id == R.id.action_remove_from_favorites) { removeFromFavorites(); updateTextViews(); } else if (id == R.id.action_show_qr_code) { showQRCode(); } else if (id == R.id.action_open_in_passist) { openInPassist(); } return super.onOptionsItemSelected(item); } private void showQRCode() { new QRCodeDialog().show(getSupportFragmentManager(), getString(R.string.show_qr_code__dialog_tag), getSiteswapLink()); } private void openInPassist() { if (mSiteswap.isSynchronous()) { Toast.makeText(getApplicationContext(), getString(R.string.detailed_siteswap__toast_synchronous_siteswap), Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://passist.org/siteswap/" + mSiteswap.toString() + "?jugglers=" + mSiteswap.getNumberOfJugglers())); startActivity(intent); } public void generate_compatible_siteswap() { new GenerateCompatibleSiteswapDialog().show(getSupportFragmentManager(), getString(R.string.generate_compatible_siteswaps__dialog_tag), mSiteswap); } private void createFromExplicitIntent(Intent intent) { mSiteswap = (Siteswap) intent.getSerializableExtra(getString(R.string.intent_detailed_siteswap_view__siteswap)); boolean skipRotationToStartingPosition = intent.getBooleanExtra(getString(R.string.intent_detailed_siteswap_view__skip_rotation_to_starting_position), false); if (mSiteswap == null) mSiteswap = new Siteswap(); if (!skipRotationToStartingPosition) { mSiteswap.rotateToBestStartingPosition(); } } private void createFromImplicitIntent(Intent intent) { Uri uri = intent.getData(); String siteswapString = null; String host = null; String query = null; if (uri != null) { siteswapString = uri.getPath(); host = uri.getHost(); query = uri.getQuery(); } if (siteswapString == null) { siteswapString = ""; } if (siteswapString.length() != 0 && siteswapString.charAt(0) == '/') { siteswapString = siteswapString.substring(1); // Starting / is ommited } mSiteswap = new Siteswap(siteswapString, host, query); if (mSiteswap.isParsingError()) { Toast.makeText(getApplicationContext(), getString(R.string.detailed_siteswap__parsing_error) + " " + mSiteswap.getInvalidCharactersFromParsing(), Toast.LENGTH_LONG).show(); mSiteswap = new Siteswap(); } if (!mSiteswap.isValid()) { Toast.makeText(getApplicationContext(), getString(R.string.detailed_siteswap__invalid_siteswap) + " " + siteswapString, Toast.LENGTH_LONG).show(); mSiteswap = new Siteswap(); } } private void loadNameFromFavorites() { if (mSiteswap.getSiteswapName() == "") { Siteswap normalizedSiteswap = new Siteswap(mSiteswap); normalizedSiteswap.make_unique_representation(); int index = NamedSiteswaps.getListOfNamedSiteswaps().indexOf(normalizedSiteswap); if (index != -1) { mSiteswap.setSiteswapName(((Siteswap) NamedSiteswaps.getListOfNamedSiteswaps().get(index)).getSiteswapName()); } } } private String getSiteswapLink() { return "https://siteswap.de/" + mSiteswap.getCurrentStringVersion() + "/" + mSiteswap.toParsableString(); } private Intent createShareIntent() { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); String siteswapString = ""; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(getSiteswapLink() + "\n"); stringBuilder.append(getString(R.string.detailed_siteswap__share_global) + " "); Siteswap getin = mSiteswap.calculateGetin(); if (getin.period_length() != 0) { stringBuilder.append(getin.toString()); stringBuilder.append(" | "); } stringBuilder.append(mSiteswap.toString()); Siteswap getout = mSiteswap.calculateGetout(); if (getout.period_length() != 0) { stringBuilder.append(" | "); stringBuilder.append(getout.toString()); } stringBuilder.append("\n"); stringBuilder.append(Html.fromHtml(createLocalHtmlString("|")).toString()); siteswapString = stringBuilder.toString(); shareIntent.putExtra(Intent.EXTRA_TEXT, siteswapString); shareIntent.setType("text/plain"); return shareIntent; } public void updateTextViews() { String name = (mSiteswap.getSiteswapName() == "") ? "Unnamed" : mSiteswap.getSiteswapName(); mNameTextview.setText(name); mInterfacePatternTextview.setText(mSiteswap.toInterface().toPattern().toString()); mNumberOfObjectsTextview.setText(String.valueOf(mSiteswap.getNumberOfObjects())); mPeriodLengthTextview.setText(String.valueOf(mSiteswap.period_length())); String globalHtmlString = "<font color=\"grey\">" + mSiteswap.calculateGetin().toString() + "</font> " + " <big>" + mSiteswap.toGlobalString() + " </big> " + "<font color=\"grey\">" + mSiteswap.calculateGetout().toString() + "</font> "; mGlobalSiteswapTextview.setText(Html.fromHtml(globalHtmlString)); String localHtmlString = createLocalHtmlString(); mLocalSiteswapTextview.setText(Html.fromHtml(localHtmlString)); //mLocalSiteswapTextview.setText(Html.fromHtml("Juggler A: 4 2.5 3.5")); mCausalDiagram.invalidate(); mLadderDiagram.invalidate(); mLocalSiteswapLegendTextview.setText(Html.fromHtml(getString(R.string.detailed_siteswap__legend_html))); } private String createLocalHtmlString() { return createLocalHtmlString(""); } private String createLocalHtmlString(String getinoutSeparation) { String localHtmlString = "<big>Local Siteswap:</big><br>"; Vector<String> localSiteswapStrings = mSiteswap.toLocalString(); Siteswap[] localGetins = mSiteswap.calculateLocalGetins(); Siteswap[] localGetouts = mSiteswap.calculateLocalGetouts(); Siteswap.ClubDistribution initialClubDistribution[] = mSiteswap.calculateInitialClubDistribution(); for(int juggler = 0; juggler < mSiteswap.getNumberOfJugglers(); ++juggler) { localHtmlString += Character.toString((char) ('A' + juggler)) + " "; localHtmlString += "<small>" + initialClubDistribution[juggler].toString() + "</small>"; // initial clubs in hands localHtmlString += ": "; localHtmlString += "<font color=\"grey\"><small>" + localGetins[juggler].toDividedString() + "</small></font> "; if (localGetins[juggler].period_length() != 0) localHtmlString += getinoutSeparation + "&ensp;"; localHtmlString += localSiteswapStrings.elementAt(juggler); if (localGetouts[juggler].period_length() != 0) localHtmlString += getinoutSeparation + "&ensp;"; localHtmlString += "<font color=\"grey\"><small>" + localGetouts[juggler].toDividedString() + "</small></font> "; localHtmlString += "<br>"; } return localHtmlString; } public void rotateLeft(View view) { mSiteswap.rotateLeft(1); updateTextViews(); } public void rotateRight(View view) { mSiteswap.rotateRight(1); updateTextViews(); } private void addToFavorites() { new AddToFavoritesDialog().show(getSupportFragmentManager(), getString(R.string.add_to_favorites__dialog_tag), mSiteswap); } private void removeFromFavorites() { new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getApplicationContext()); FavoriteDao dao = db.siteswapDao(); final List<SiteswapEntity> siteswapEntityList = dao.getSiteswaps(mSiteswap.toParsableString()); runOnUiThread(new Runnable() { @Override public void run() { if (siteswapEntityList.size() > 1) { new ChooseRemoveFavoriteDialog().show(getSupportFragmentManager(), getString(R.string.confirm_remove_favorite__dialog_tag), siteswapEntityList); } else if (siteswapEntityList.size() == 1) { new ConfirmRemoveFavoriteDialog().show(getSupportFragmentManager(), getString(R.string.confirm_remove_favorite__dialog_tag), siteswapEntityList.get(0)); } else { Toast.makeText(getApplicationContext(), getString(R.string.detailed_siteswap__toast_not_in_favorites), Toast.LENGTH_LONG).show(); } } }); } catch (android.database.sqlite.SQLiteConstraintException e) { } } }).start(); } @Override public void databaseTransactionComplete() { updateTextViews(); } }
15,955
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
LoadGenerationParametersDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/LoadGenerationParametersDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.Serializable; import java.util.List; /** * Created by tilman on 29.10.17. */ public class LoadGenerationParametersDialog extends DialogFragment { private static final String STATE_GENERATION_PARAMETER_ENTITY = "STATE_GENERATION_PARAMETER_ENTITY"; private ListView mListView; private List<GenerationParameterEntity> mGenerationParameterEntityList; private UpdateGenerationParameters updateGenerationParameters; public interface UpdateGenerationParameters { public void updateGenerationParameters(GenerationParameterEntity entity); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mGenerationParameterEntityList = (List<GenerationParameterEntity>) savedInstanceState.getSerializable(STATE_GENERATION_PARAMETER_ENTITY); } updateGenerationParameters = (UpdateGenerationParameters) getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_generation_parameters_list) .setTitle(getString(R.string.load_generation_parameters__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); final AlertDialog dialog = builder.create(); return dialog; } @Override public void onStart() { super.onStart(); mListView = (ListView) getDialog().findViewById(R.id.generation_parameters_list); ArrayAdapter adapter = new ArrayAdapter<GenerationParameterEntity>( getContext(), android.R.layout.simple_list_item_1, mGenerationParameterEntityList); mListView.setAdapter(adapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { GenerationParameterEntity generationParameterEntity = ((GenerationParameterEntity) parent.getItemAtPosition(position)); updateGenerationParameters.updateGenerationParameters(generationParameterEntity); dismiss(); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_GENERATION_PARAMETER_ENTITY, (Serializable) mGenerationParameterEntityList); } @Override public void onStop() { super.onStop(); } public void show(FragmentManager manager, String tag, List<GenerationParameterEntity> siteswapEntityList) { mGenerationParameterEntityList = siteswapEntityList; show(manager, tag); } }
4,036
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
SaveGenerationParametersDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/SaveGenerationParametersDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.Button; import android.widget.EditText; /** * Created by tilman on 29.10.17. */ public class SaveGenerationParametersDialog extends DialogFragment { private static final String STATE_GENERATION_PARAMETER_ENTITY = "STATE_GENERATION_PARAMETER_ENTITY"; private EditText mGenerationParameterNameTextEdit; private GenerationParameterEntity mGenerationParameterEntity; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mGenerationParameterEntity = (GenerationParameterEntity) savedInstanceState.getSerializable(STATE_GENERATION_PARAMETER_ENTITY); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_save_generation_parameters) .setTitle(getString(R.string.save_generation_parameters__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setPositiveButton(getString(R.string.ok), null); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(final DialogInterface dialog) { Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mGenerationParameterEntity.setName(mGenerationParameterNameTextEdit.getText().toString()); insertEntityInDatabase(); dialog.dismiss(); } }); } }); return dialog; } public void insertEntityInDatabase() { new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getContext()); db.generationParameterDao().insertGenerationParameters(mGenerationParameterEntity); } catch (android.database.sqlite.SQLiteConstraintException e) { } } }).start(); } @Override public void onStart() { super.onStart(); mGenerationParameterNameTextEdit = (EditText) getDialog().findViewById(R.id.generation_parameter_name_text_edit_text_edit); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_GENERATION_PARAMETER_ENTITY, mGenerationParameterEntity); } @Override public void onStop() { super.onStop(); } public void show(FragmentManager manager, String tag, GenerationParameterEntity entity) { mGenerationParameterEntity = entity; show(manager, tag); } }
4,148
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NamedSiteswapActivity.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/NamedSiteswapActivity.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; import java.util.List; import siteswaplib.NamedSiteswap; import siteswaplib.NamedSiteswaps; import siteswaplib.Siteswap; public class NamedSiteswapActivity extends AppCompatActivity { static final private List<NamedSiteswap> mSiteswapList = NamedSiteswaps.getListOfNamedSiteswaps(); SearchView mSearchView; ListView mSiteswapListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show_siteswaps); setTitle(String.format(getString(R.string.named_siteswaps__title))); mSiteswapListView = (ListView) findViewById(R.id.siteswap_list); mSearchView = (SearchView) findViewById(R.id.search_view); SiteswapArrayAdapter adapter = new SiteswapArrayAdapter( NamedSiteswapActivity.this, android.R.layout.simple_list_item_1, mSiteswapList); mSiteswapListView.setAdapter(adapter); mSiteswapListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Siteswap siteswap = ((Siteswap) parent.getItemAtPosition(position)); Intent intent = new Intent(getApplicationContext(), DetailedSiteswapActivity.class); intent.putExtra(getString(R.string.intent_detailed_siteswap_view__siteswap), siteswap); startActivity(intent); } }); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { if (TextUtils.isEmpty(newText)) { adapter.getFilter().filter(null); } else { adapter.getFilter().filter(newText); } return true; } }); } }
3,128
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
FavoriteDao.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/FavoriteDao.java
package namlit.siteswapgenerator; import androidx.sqlite.db.SupportSQLiteQuery; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.RawQuery; import java.util.List; @Dao public interface FavoriteDao { @Query("SELECT * FROM favorites ORDER BY name") List<SiteswapEntity> getAllFavorites(); @Query("SELECT * FROM favorites WHERE siteswap IS :siteswap") List<SiteswapEntity> getSiteswaps(String siteswap); @Query("SELECT * FROM favorites WHERE siteswap IS :siteswap") SiteswapEntity getSiteswap(String siteswap); @Query("SELECT DISTINCT juggler_names FROM favorites ORDER BY juggler_names") List<String> getJugglers(); @Query("SELECT DISTINCT location FROM favorites ORDER BY location") List<String> getLocations(); @Query("SELECT DISTINCT date FROM favorites ORDER BY date") List<String> getDates(); @Query("SELECT * FROM favorites WHERE juggler_names IS :juggler") List<SiteswapEntity> getSiteswapsOfJuggler(String juggler); @Query("SELECT * FROM favorites WHERE location IS :location") List<SiteswapEntity> getSiteswapsOfLocation(String location); @Query("SELECT * FROM favorites WHERE date IS :date") List<SiteswapEntity> getSiteswapsOfDate(String date); @RawQuery int checkpoint(SupportSQLiteQuery supportSQLiteQuery); @Insert void insertFavorites(SiteswapEntity... siteswap); @Delete void deleteFavorite(SiteswapEntity siteswap); }
1,527
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
CausalDiagram.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/CausalDiagram.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.PointF; import android.util.AttributeSet; import android.view.View; import siteswaplib.Siteswap; /** * Created by tilman on 11.04.18. */ public class CausalDiagram extends View { private boolean mIsLadderDiagram; private Paint mTextPaint; private Paint mHandTextPaint; private Paint mJugglerNamePaint; private Paint mCirclePaint; private Paint mConnectionPaint; private Paint mArrowHeadPaint; private Path mArrowHeadPath; private Siteswap mSiteswap = null; private float mDensity; private float mSmallTextSize; private float mMediumTextSize; private float mLargeTextSize; private float mNodeRadius; private float mNodeLocalBeatXDistance; private float mNodeYDistance; private float mStrokeWidth; private float mJugglerNameDist; private float mArrowHeadSize; private int mNumberOfNodes; public CausalDiagram(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CausalDiagram, 0, 0); try { mIsLadderDiagram = a.getBoolean(R.styleable.CausalDiagram_isLadderDiagram, false); } finally { a.recycle(); } init(); } public void setSiteswap(Siteswap siteswap) { this.mSiteswap = siteswap; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mNumberOfNodes = mSiteswap.getNonMirroredPeriod(); int parentWidth = MeasureSpec.getSize(widthMeasureSpec); int rowLengthCenterPoints = (mNumberOfNodes / mSiteswap.getNumberOfJugglers()) * (int) mNodeLocalBeatXDistance; int circleSize = 2 * (int) mNodeRadius + (int) mStrokeWidth; int rowOffset = (int) mNodeLocalBeatXDistance / mSiteswap.getNumberOfJugglers(); if (mSiteswap.isSynchronous()) { if (mSiteswap.getSynchronousStartPosition() == 0) rowOffset = (int) mNodeLocalBeatXDistance; else rowOffset = 0; } int minw = getPaddingLeft() + getPaddingRight() + (int) mJugglerNameDist + rowLengthCenterPoints + circleSize - rowOffset; if (minw < parentWidth) { minw = parentWidth; mNumberOfNodes = (int) ((minw / mNodeLocalBeatXDistance * mSiteswap.getNumberOfJugglers()) - 1); } int w = resolveSizeAndState(minw, widthMeasureSpec, 1); int minh = getPaddingTop() + getPaddingBottom() + 2 * (int) (mNodeRadius + mHandTextPaint.descent() - mHandTextPaint.ascent()) + (mSiteswap.getNumberOfJugglers() - 1) * (int) mNodeYDistance; int h = resolveSizeAndState(minh, heightMeasureSpec, 0); setMeasuredDimension(w, h); } protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < mSiteswap.getNumberOfJugglers(); ++i) { float numberTextPosY = getNodePosition(i).y - (mJugglerNamePaint.ascent() + mJugglerNamePaint.descent()) / 2; canvas.drawText(Character.toString((char) ('A' + i)) + ":", getPaddingLeft(), numberTextPosY, mJugglerNamePaint); } for(int i = 0; i < mNumberOfNodes; ++i) { boolean isRightHand = (i / mSiteswap.getNumberOfJugglers()) % 2 == 0; drawNode(canvas, getNodePosition(i).x, getNodePosition(i).y, mSiteswap.stringAt(i), isRightHand, isTextAbove(i)); drawConnection(canvas, i); } } private boolean isTextAbove(int index) { int row = index % mSiteswap.getNumberOfJugglers(); return row == 0 ? true : false; } private void drawNode(Canvas canvas, int x, int y, String number, boolean isRightHand, boolean isTextAbove) { String handText = isRightHand ? new String("R") : new String("L"); float handTextPosY = isTextAbove? y - mHandTextPaint.descent() - mNodeRadius : y - mHandTextPaint.ascent() + mNodeRadius; float numberTextPosY = y - (mTextPaint.ascent() + mTextPaint.descent()) / 2; canvas.drawText(number, x, numberTextPosY, mTextPaint); canvas.drawCircle(x, y, mNodeRadius, mCirclePaint); canvas.drawText(handText, x, handTextPosY, mHandTextPaint); } private int getStepIndex(int startNodeIndex){ if (mIsLadderDiagram) { return mSiteswap.at(startNodeIndex); } return mSiteswap.at(startNodeIndex) - 2 * mSiteswap.getNumberOfJugglers(); } private void drawConnection(Canvas canvas, int startNodeIndex) { int stepIndex = getStepIndex(startNodeIndex); int stopNodeIndex = startNodeIndex + stepIndex; if (stopNodeIndex < 0) return; int row_distance = Math.abs(stopNodeIndex % mSiteswap.getNumberOfJugglers() - startNodeIndex % mSiteswap.getNumberOfJugglers()); float offsetFromNode = mNodeRadius + mStrokeWidth / 2; if (stepIndex == 0) { } if (row_distance == 1 || stepIndex == mSiteswap.getNumberOfJugglers()) drawStraightConnection(canvas, startNodeIndex, stopNodeIndex, offsetFromNode); else drawBezierConnection(canvas, startNodeIndex, stopNodeIndex, offsetFromNode); } private void drawBezierConnection(Canvas canvas, int startNodeIndex, int stopNodeIndex, float offsetFromNode) { float startNodeX = getNodePosition(startNodeIndex).x; float startNodeY = getNodePosition(startNodeIndex).y; float stopNodeX = getNodePosition(stopNodeIndex).x; float stopNodeY = getNodePosition(stopNodeIndex).y; float x_direction_start = 1 / (float) Math.sqrt(2); if (stopNodeIndex < startNodeIndex) x_direction_start *= -1; float y_direction_start = 1 / (float) Math.sqrt(2); if (!isTextAbove(startNodeIndex)) y_direction_start *= -1; if (stopNodeIndex - startNodeIndex == -mSiteswap.getNumberOfJugglers()) y_direction_start *= -1; float x_direction_stop = 1 / (float) Math.sqrt(2); if (stopNodeIndex < startNodeIndex) x_direction_stop *= -1; float y_direction_stop = 1 / (float) Math.sqrt(2); if (!isTextAbove(stopNodeIndex)) y_direction_stop *= -1; if (stopNodeIndex - startNodeIndex == -mSiteswap.getNumberOfJugglers()) y_direction_stop *= -1; float rotation = (float) Math.toDegrees(Math.atan2(-y_direction_stop, x_direction_stop)); float startX = startNodeX + x_direction_start * offsetFromNode; float startY = startNodeY + y_direction_start * offsetFromNode; float stopX = stopNodeX - x_direction_stop * (mArrowHeadSize + offsetFromNode); float stopY = stopNodeY + y_direction_stop * (mArrowHeadSize + offsetFromNode); float control_point_factor = mNodeRadius; if (Math.abs(stopNodeIndex - startNodeIndex) == mSiteswap.getNumberOfJugglers()) { control_point_factor *= 1.2; y_direction_stop /= 2; } else if (stopNodeIndex == startNodeIndex) { control_point_factor *= 1.5; y_direction_start *= 1.5; } else control_point_factor *= 3; Path path = new Path(); path.moveTo(startX, startY); path.cubicTo(startX + x_direction_start * control_point_factor, startY + y_direction_start * control_point_factor, stopX - x_direction_stop * control_point_factor, stopY + y_direction_stop * control_point_factor, stopX, stopY); canvas.drawPath(path, mConnectionPaint); drawArrowHead(canvas, stopX, stopY, rotation); } private void drawStraightConnection(Canvas canvas, int startNodeIndex, int stopNodeIndex, float offsetFromNode) { float startNodeX = getNodePosition(startNodeIndex).x; float startNodeY = getNodePosition(startNodeIndex).y; float stopNodeX = getNodePosition(stopNodeIndex).x; float stopNodeY = getNodePosition(stopNodeIndex).y; float length = new PointF(stopNodeX - startNodeX, stopNodeY - startNodeY).length(); float dxStart = (stopNodeX - startNodeX) / length * offsetFromNode; float dyStart = (stopNodeY - startNodeY) / length * offsetFromNode; float dxEnd = (stopNodeX - startNodeX) / length * (offsetFromNode + mArrowHeadSize); float dyEnd = (stopNodeY - startNodeY) / length * (offsetFromNode + mArrowHeadSize); float rotation = (float) Math.toDegrees(Math.atan2(dyStart, dxStart)); canvas.drawLine(startNodeX + dxStart, startNodeY + dyStart, stopNodeX - dxEnd, stopNodeY - dyEnd, mConnectionPaint); drawArrowHead(canvas, stopNodeX - dxEnd, stopNodeY - dyEnd, rotation); } private void drawArrowHead(Canvas canvas, float x, float y, float rotationDegree) { Matrix transform = new Matrix(); transform.setRotate(rotationDegree); transform.postTranslate(x, y); Path arrowHead = new Path(); mArrowHeadPath.transform(transform, arrowHead); canvas.drawPath(arrowHead, mArrowHeadPaint); } private Point getNodePosition(int nodeIndex) { int yPosFirstRow = getPaddingTop() + (int) (mNodeRadius - mHandTextPaint.ascent() + mHandTextPaint.descent() + mStrokeWidth / 2); int xPosStart = (int) (mNodeRadius + mStrokeWidth / 2) + getPaddingLeft() + (int) mJugglerNameDist; int row = nodeIndex % mSiteswap.getNumberOfJugglers(); int column = nodeIndex; column += mSiteswap.getSynchronousStartPosition(); column -= mSiteswap.getSynchronousPosition(nodeIndex); float columnXDistance = mNodeLocalBeatXDistance / mSiteswap.getNumberOfJugglers(); int xPos = xPosStart + column * (int) columnXDistance; int yPos = yPosFirstRow + row * (int) mNodeYDistance; return new Point(xPos, yPos); } private void init() { mSiteswap = new Siteswap(); mDensity = getResources().getDisplayMetrics().density; mSmallTextSize = mDensity * 20; mMediumTextSize = mDensity * 25; mLargeTextSize = mDensity * 30; mNodeRadius = mSmallTextSize * 2 / 3; mNodeLocalBeatXDistance = mDensity * 60; mNodeYDistance = mDensity * 80; mStrokeWidth = mDensity * 2; mArrowHeadSize = mDensity * 12; mJugglerNameDist = mDensity * 40; mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setColor(Color.BLACK); mTextPaint.setTextSize(mSmallTextSize); mTextPaint.setTextAlign(Paint.Align.CENTER); mHandTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mHandTextPaint.setColor(Color.BLACK); mHandTextPaint.setTextSize(mMediumTextSize); mHandTextPaint.setTextAlign(Paint.Align.CENTER); mJugglerNamePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mJugglerNamePaint.setColor(Color.BLACK); mJugglerNamePaint.setTextSize(mLargeTextSize); mJugglerNamePaint.setTextAlign(Paint.Align.LEFT); mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(Color.BLACK); mCirclePaint.setStyle(Paint.Style.STROKE); mCirclePaint.setStrokeWidth(mStrokeWidth); mConnectionPaint = new Paint(Paint.ANTI_ALIAS_FLAG); if(mIsLadderDiagram) { mConnectionPaint.setColor(0xff00aa00); } else { mConnectionPaint.setColor(Color.BLUE); } mConnectionPaint.setStyle(Paint.Style.STROKE); mConnectionPaint.setStrokeWidth(mStrokeWidth); mArrowHeadPaint = new Paint(Paint.ANTI_ALIAS_FLAG); if(mIsLadderDiagram) { mArrowHeadPaint.setColor(0xff00aa00); } else { mArrowHeadPaint.setColor(Color.BLUE); } mArrowHeadPaint.setStyle(Paint.Style.FILL); mArrowHeadPaint.setStrokeWidth(mStrokeWidth); mArrowHeadPath = new Path(); mArrowHeadPath.moveTo(mArrowHeadSize, 0); mArrowHeadPath.lineTo(0, -0.4f * mArrowHeadSize); mArrowHeadPath.lineTo(0, +0.4f * mArrowHeadSize); mArrowHeadPath.close(); } }
13,639
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
NumberFilterDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/NumberFilterDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.widget.ArrayAdapter; import android.widget.RadioButton; import android.widget.Spinner; import java.util.ArrayList; import java.util.List; import siteswaplib.Filter; import siteswaplib.NumberFilter; import siteswaplib.Siteswap; /** * Created by tilman on 29.10.17. */ public class NumberFilterDialog extends AddFilterDialog { private static final String STATE_OLD_FILTER = "STATE_OLD_FILTER"; private static final String STATE_MIN_THROW = "STATE_MIN_THROW"; private static final String STATE_MAX_THROW = "STATE_MAX_THROW"; private static final String STATE_PERIOD_LENGTH = "STATE_PERIOD_LENGTH"; private static final String STATE_NUMBER_OF_SYNCHRONOUS_HANDS = "STATE_NUMBER_OF_SYNCHRONOUS_HANDS"; private RadioButton mAtLeastRadioButton; private RadioButton mNotMoreRadioButton; private RadioButton mExactlyRadioButton; private Spinner mNumberSpinner; private Spinner mHeightSpinner; Filter mOldFilter = null; int mMinThrow = 0; int mMaxThrow = 0; int mPeriodLength = 0; int mNumberOfSynchronousHands = 1; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mOldFilter = (Filter) savedInstanceState.getSerializable(STATE_OLD_FILTER); mMinThrow = savedInstanceState.getInt(STATE_MIN_THROW); mMaxThrow = savedInstanceState.getInt(STATE_MAX_THROW); mPeriodLength = savedInstanceState.getInt(STATE_PERIOD_LENGTH); mNumberOfSynchronousHands = savedInstanceState.getInt(STATE_NUMBER_OF_SYNCHRONOUS_HANDS); } int positiveButtonStringId = R.string.filter__add_button; if (mOldFilter != null) positiveButtonStringId = R.string.filter__replace_button; AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.number_filter_layout) .setPositiveButton(positiveButtonStringId, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which ) { Filter filter = readNumberFilter(); if (filter != null) { if (mOldFilter != null) mListener.onChangeSiteswapFilter(mOldFilter, filter); else mListener.onAddSiteswapFilter(filter); } } }) .setNegativeButton(R.string.filter__cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .setNeutralButton(R.string.filter__remove_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Filter filter = readNumberFilter(); if (filter != null) mListener.onRemoveSiteswapFilter(filter); } }); return builder.create(); } @Override public void onStart() { super.onStart(); mAtLeastRadioButton = (RadioButton) getDialog().findViewById(R.id.at_least_radio_button); mNotMoreRadioButton = (RadioButton) getDialog().findViewById(R.id.not_more_radio_button); mExactlyRadioButton = (RadioButton) getDialog().findViewById(R.id.exactly_radio_button); mNumberSpinner = (Spinner) getDialog().findViewById(R.id.number_spinner); mHeightSpinner = (Spinner) getDialog().findViewById(R.id.height_spinner); SharedPreferences sharedPref = getContext().getSharedPreferences( getString(R.string.number_filter__shared_preferences), Context.MODE_PRIVATE); boolean isAtLeast = sharedPref.getBoolean(getString(R.string.number_filter__at_least), true); boolean isNotMore = sharedPref.getBoolean(getString(R.string.number_filter__not_more), false); boolean isExactly = sharedPref.getBoolean(getString(R.string.number_filter__exactly), false); int throwHeightIndex = sharedPref.getInt(getString(R.string.number_filter__shared_preferences_throw_height_index), 0); int numberIndex = sharedPref.getInt(getString(R.string.number_filter__shared_preferences_number_index), 1); List<String> throwHeightArray = new ArrayList<String>(); if (mOldFilter != null) { if (mOldFilter instanceof NumberFilter) { NumberFilter filter = (NumberFilter) mOldFilter; isAtLeast = false; isNotMore = false; isExactly = false; switch (filter.getType()) { case GREATER_EQUAL: isAtLeast = true; break; case SMALLER_EQUAL: isNotMore = true; break; case EQUAL: isExactly = true; break; } NumberFilter.FilterValue throwHeight = filter.getFilterValue(); int threshold = filter.getThresholdValue(); if(throwHeight.isGenericPass()) throwHeightIndex = 0; else if(throwHeight.isGenericSelf()) throwHeightIndex = 1; else { throwHeightArray.add(throwHeight.toString()); throwHeightIndex = 0; } numberIndex = threshold; } } throwHeightArray.add(Siteswap.intToString(Siteswap.PASS)); throwHeightArray.add(Siteswap.intToString(Siteswap.SELF)); for (String str : NumberFilter.getPossibleValues(mMinThrow, mMaxThrow, mNumberOfSynchronousHands)) { throwHeightArray.add(str); } ArrayAdapter<String> throwHeightAdapter = new ArrayAdapter<String>( getActivity(), android.R.layout.simple_spinner_item, throwHeightArray); throwHeightAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mHeightSpinner.setAdapter(throwHeightAdapter); List<String> numberArray = new ArrayList<String>(); for (int i = 0; i <= mPeriodLength; ++i) { numberArray.add(Integer.toString(i)); } ArrayAdapter<String> NumberAdapter = new ArrayAdapter<String>( getActivity(), android.R.layout.simple_spinner_item, numberArray); NumberAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mNumberSpinner.setAdapter(NumberAdapter); if (throwHeightIndex >= mHeightSpinner.getCount() || throwHeightIndex < 0) throwHeightIndex = 0; if (numberIndex >= mNumberSpinner.getCount() || numberIndex < 0) numberIndex = 0; mAtLeastRadioButton.setChecked(isAtLeast); mNotMoreRadioButton.setChecked(isNotMore); mExactlyRadioButton.setChecked(isExactly); mHeightSpinner.setSelection(throwHeightIndex); mNumberSpinner.setSelection(numberIndex); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_OLD_FILTER, mOldFilter); outState.putInt(STATE_MIN_THROW, mMinThrow); outState.putInt(STATE_MAX_THROW, mMaxThrow); outState.putInt(STATE_PERIOD_LENGTH, mPeriodLength); outState.putInt(STATE_NUMBER_OF_SYNCHRONOUS_HANDS, mNumberOfSynchronousHands); } @Override public void onStop() { super.onStop(); SharedPreferences sharedPref = getContext().getSharedPreferences( getString(R.string.number_filter__shared_preferences), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); boolean isAtLeast = mAtLeastRadioButton.isChecked(); boolean isNotMore = mNotMoreRadioButton.isChecked(); boolean isExactly = mExactlyRadioButton.isChecked(); int throwHeightIndex = mHeightSpinner.getSelectedItemPosition(); int numberIndex = mNumberSpinner.getSelectedItemPosition(); editor.putBoolean(getString(R.string.number_filter__at_least), isAtLeast); editor.putBoolean(getString(R.string.number_filter__not_more), isNotMore); editor.putBoolean(getString(R.string.number_filter__exactly), isExactly); editor.putInt(getString(R.string.number_filter__shared_preferences_throw_height_index), throwHeightIndex); editor.putInt(getString(R.string.number_filter__shared_preferences_number_index), numberIndex); editor.commit(); } Filter readNumberFilter() { boolean isAtLeast = mAtLeastRadioButton.isChecked(); boolean isNotMore = mNotMoreRadioButton.isChecked(); boolean isExactly = mExactlyRadioButton.isChecked(); String height = (String) mHeightSpinner.getSelectedItem(); int threshold = Integer.valueOf((String) mNumberSpinner.getSelectedItem()); NumberFilter.Type type = NumberFilter.Type.GREATER_EQUAL; if (isNotMore) type = NumberFilter.Type.SMALLER_EQUAL; if (isExactly) type = NumberFilter.Type.EQUAL; return new NumberFilter(height, type, threshold, mNumberOfSynchronousHands); } public void show(FragmentManager manager, String tag, int minThrow, int maxThrow, int periodLength, int numberOfSynchronousHands, Filter filter) { mOldFilter = filter; show(manager, tag, minThrow, maxThrow, periodLength, numberOfSynchronousHands); } public void show(FragmentManager manager, String tag, int minThrow, int maxThrow, int periodLength, int numberOfSynchronousHands) { mMinThrow = minThrow; mMaxThrow = maxThrow; mPeriodLength = periodLength; mNumberOfSynchronousHands = numberOfSynchronousHands; show(manager, tag); } }
11,249
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
SiteswapArrayAdapter.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/SiteswapArrayAdapter.java
package namlit.siteswapgenerator; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import siteswaplib.NamedSiteswap; import siteswaplib.Siteswap; public class SiteswapArrayAdapter extends ArrayAdapter<NamedSiteswap> { private final LayoutInflater mInflater; private final int mResource; public SiteswapArrayAdapter (Context context, int resource, List<NamedSiteswap> siteswaps) { super(context, resource, siteswaps); mInflater = LayoutInflater.from(context); mResource = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { final View view; final TextView text; LayoutInflater inflater = mInflater; int resource = mResource; if (convertView == null) { view = inflater.inflate(resource, parent, false); } else { view = convertView; } try { text = (TextView) view; } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); } final NamedSiteswap siteswap = getItem(position); text.setText(siteswap.toString()); return view; } }
1,545
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
AddToFavoritesDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/AddToFavoritesDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import java.util.Date; import java.text.DateFormat; import java.util.List; import siteswaplib.Siteswap; /** * Created by tilman on 22.07.18. */ public class AddToFavoritesDialog extends DialogFragment { public interface DatabaseTransactionComplete { public void databaseTransactionComplete(); } private static final String STATE_SITESWAP = "STATE_SITESWAP"; private EditText mSiteswapNameTextEdit; private AutoCompleteTextView mJugglerNameTextEdit; private AutoCompleteTextView mLocationTextEdit; private EditText mDateTextEdit; private Siteswap mSiteswap; private String mSiteswapName; private String mJugglerName; private String mLocation; private String mDate; private DatabaseTransactionComplete mDatabaseTransactionComplete; private Activity mActivity; private ArrayAdapter mJugglerAdapter; private ArrayAdapter mLocationAdapter; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mSiteswap = (Siteswap) savedInstanceState.getSerializable(STATE_SITESWAP); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); mDatabaseTransactionComplete = (DatabaseTransactionComplete) getActivity(); mActivity = getActivity(); builder.setView(R.layout.layout_add_to_favorites) .setTitle(getString(R.string.add_to_favorites__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton(getString(R.string.add), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { addSiteswapToFavorites(); } }); return builder.create(); } @Override public void onStart() { super.onStart(); mSiteswapNameTextEdit = (EditText) getDialog().findViewById(R.id.siteswap_name_text_edit); mJugglerNameTextEdit = (AutoCompleteTextView) getDialog().findViewById(R.id.juggler_name_text_edit); mLocationTextEdit = (AutoCompleteTextView) getDialog().findViewById(R.id.location_text_edit); mDateTextEdit= (EditText) getDialog().findViewById(R.id.date_text_edit); setupAutocomplete(); if (mSiteswap.getSiteswapName() == "") mSiteswapNameTextEdit.setText(mSiteswap.toString()); else mSiteswapNameTextEdit.setText(mSiteswap.getSiteswapName() + ": " + mSiteswap.toString()); mDateTextEdit.setText(DateFormat.getDateInstance().format(new Date())); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_SITESWAP, mSiteswap); } @Override public void onStop() { super.onStop(); } private void addSiteswapToFavorites() { mSiteswapName = mSiteswapNameTextEdit.getText().toString(); mSiteswap.setSiteswapName(mSiteswapName); mJugglerName = mJugglerNameTextEdit.getText().toString(); mLocation = mLocationTextEdit.getText().toString(); mDate = mDateTextEdit.getText().toString(); new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getContext()); db.siteswapDao().insertFavorites(new SiteswapEntity(mSiteswap, mSiteswapName, mJugglerName, mLocation, mDate)); mActivity.runOnUiThread(new Runnable() { @Override public void run() { mDatabaseTransactionComplete.databaseTransactionComplete(); } }); } catch (android.database.sqlite.SQLiteConstraintException e) { } } }).start(); } private void setupAutocomplete() { new Thread(new Runnable() { @Override public void run() { try { AppDatabase db = AppDatabase.getAppDatabase(getContext()); List<String> jugglers = db.siteswapDao().getJugglers(); List<String> locations = db.siteswapDao().getLocations(); mJugglerAdapter = new ArrayAdapter( getContext(), android.R.layout.simple_list_item_1, jugglers); mLocationAdapter = new ArrayAdapter( getContext(), android.R.layout.simple_list_item_1, locations); mActivity.runOnUiThread(new Runnable() { @Override public void run() { mJugglerNameTextEdit.setAdapter(mJugglerAdapter); mJugglerNameTextEdit.setThreshold(1); mLocationTextEdit.setAdapter(mLocationAdapter); mLocationTextEdit.setThreshold(1); } }); } catch (android.database.sqlite.SQLiteConstraintException e) { } } }).start(); } public void show(FragmentManager manager, String tag, Siteswap siteswap) { mSiteswap = siteswap; show(manager, tag); } }
6,812
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
DeleteGenerationParametersDialog.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/DeleteGenerationParametersDialog.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2018 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.FragmentManager; import androidx.appcompat.app.AlertDialog; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.Serializable; import java.util.List; /** * Created by tilman on 29.10.17. */ public class DeleteGenerationParametersDialog extends DialogFragment { private static final String STATE_GENERATION_PARAMETER_ENTITY = "STATE_GENERATION_PARAMETER_ENTITY"; private ListView mListView; private List<GenerationParameterEntity> mGenerationParameterEntityList; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if(savedInstanceState != null) { mGenerationParameterEntityList = (List<GenerationParameterEntity>) savedInstanceState.getSerializable(STATE_GENERATION_PARAMETER_ENTITY); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(R.layout.layout_generation_parameters_list) .setTitle(getString(R.string.delete_generation_parameters__title)) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); final AlertDialog dialog = builder.create(); return dialog; } @Override public void onStart() { super.onStart(); mListView = (ListView) getDialog().findViewById(R.id.generation_parameters_list); ArrayAdapter adapter = new ArrayAdapter<GenerationParameterEntity>( getContext(), android.R.layout.simple_list_item_1, mGenerationParameterEntityList); mListView.setAdapter(adapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { GenerationParameterEntity generationParameterEntity = ((GenerationParameterEntity) parent.getItemAtPosition(position)); new ConfirmDeleteGenerationParametersDialog().show(getFragmentManager(), getString(R.string.confirm_delete_generation_parameters__dialog_tag), generationParameterEntity); dismiss(); } }); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_GENERATION_PARAMETER_ENTITY, (Serializable) mGenerationParameterEntityList); } @Override public void onStop() { super.onStop(); } public void show(FragmentManager manager, String tag, List<GenerationParameterEntity> siteswapEntityList) { mGenerationParameterEntityList = siteswapEntityList; show(manager, tag); } }
3,887
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
GenerationParameterDao.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/main/java/namlit/siteswapgenerator/GenerationParameterDao.java
package namlit.siteswapgenerator; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import java.util.List; @Dao public interface GenerationParameterDao { @Query("SELECT * FROM generation_parameters ORDER BY name") List<GenerationParameterEntity> getAllGenerationParameters(); @Query("SELECT * FROM generation_parameters WHERE name IS :name") GenerationParameterEntity getGenerationParamenters(String name); @Insert void insertGenerationParameters(GenerationParameterEntity... generationParameters); @Delete void deleteGenerationParameters(GenerationParameterEntity generationParameters); }
691
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
ExampleInstrumentedTest.java
/FileExtraction/Java_unseen/namlit_siteswap_generator/app/src/androidTest/java/namlit/siteswapgenerator/ExampleInstrumentedTest.java
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("namlit.siteswapgenerator", appContext.getPackageName()); } }
1,508
Java
.java
namlit/siteswap_generator
15
6
11
2017-10-03T19:11:33Z
2023-12-30T16:50:25Z
PortalResourceLifecycle.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecm-wcm-extension/src/main/java/org/exoplatform/ecms/application/PortalResourceLifecycle.java
/* * Copyright (C) 2003-2012 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecms.application; import org.apache.commons.lang3.StringUtils; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.mop.SiteType; import org.exoplatform.web.application.Application; import org.exoplatform.web.application.ApplicationLifecycle; import org.exoplatform.web.application.RequestFailure; /** * Created by The eXo Platform SAS * Author : Dang Viet Ha * hadv@exoplatform.com * Feb 20, 2012 */ public class PortalResourceLifecycle implements ApplicationLifecycle<PortalRequestContext> { /** The PATH. */ final private String PATH = "/{portalName}/javascript/live"; @Override public void onInit(Application app) throws Exception { } @Override public void onStartRequest(Application app, PortalRequestContext context) throws Exception { if (SiteType.PORTAL == context.getSiteType()) { // add current site js data String javascriptPath = StringUtils.replaceOnce(PATH, "{portalName}", context.getSiteName()); context.getJavascriptManager().addExtendedScriptURLs(context.getPortalContextPath() + javascriptPath); // add shared JS data for current site javascriptPath = StringUtils.replaceOnce(PATH, "{portalName}", "shared"); context.getJavascriptManager().addExtendedScriptURLs(context.getPortalContextPath() + javascriptPath); } } @Override public void onFailRequest(Application app, PortalRequestContext context, RequestFailure failureType) { } @Override public void onEndRequest(Application app, PortalRequestContext context) throws Exception { } @Override public void onDestroy(Application app) throws Exception { } }
2,614
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockWCMPublicationService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/social/addons/rdbms/listener/MockWCMPublicationService.java
package org.exoplatform.social.addons.rdbms.listener; import java.util.Map; import javax.jcr.Node; import org.exoplatform.services.ecm.publication.NotInPublicationLifecycleException; import org.exoplatform.services.wcm.publication.WCMPublicationService; import org.exoplatform.services.wcm.publication.WebpagePublicationPlugin; public class MockWCMPublicationService implements WCMPublicationService { @Override public void addPublicationPlugin(WebpagePublicationPlugin p) { } @Override public Map<String, WebpagePublicationPlugin> getWebpagePublicationPlugins() { return null; } @Override public boolean isEnrolledInWCMLifecycle(Node node) throws NotInPublicationLifecycleException, Exception { return false; } @Override public void enrollNodeInLifecycle(Node node, String lifecycleName) throws Exception { } @Override public void enrollNodeInLifecycle(Node node, String siteName, String remoteUser) throws Exception { } @Override public void unsubcribeLifecycle(Node node) throws NotInPublicationLifecycleException, Exception { } @Override public void updateLifecyleOnChangeContent(Node node, String siteName, String remoteUser) throws Exception { } @Override public void updateLifecyleOnChangeContent(Node node, String siteName, String remoteUser, String newState) throws Exception { } @Override public String getContentState(Node node) throws Exception { return null; } }
1,455
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockUploadService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/social/addons/rdbms/listener/MockUploadService.java
package org.exoplatform.social.addons.rdbms.listener; import java.util.HashMap; import java.util.Map; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; public class MockUploadService extends UploadService { Map<String, UploadResource> uploadResources = new HashMap<>(); public MockUploadService(PortalContainerInfo pinfo, InitParams params) throws Exception { super(pinfo, params); } public void createUploadResource(String uploadId, String filePath, String fileName, String mimeType) throws Exception { UploadResource uploadResource = new UploadResource(uploadId, fileName); uploadResource.setMimeType(mimeType); uploadResource.setStatus(UploadResource.UPLOADED_STATUS); uploadResource.setStoreLocation(filePath); uploadResources.put(uploadId, uploadResource); } @Override public UploadResource getUploadResource(String uploadId) { return uploadResources.get(uploadId); } @Override public void removeUploadResource(String uploadId) { uploadResources.remove(uploadId); } public void removeUpload(String uploadId) { uploadResources.remove(uploadId); } public Map<String, UploadResource> getUploadResources() { return uploadResources; } }
1,364
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
HTMLUploadImageProcessorTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/social/ckeditor/HTMLUploadImageProcessorTest.java
package org.exoplatform.social.ckeditor; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.Session; import javax.jcr.Workspace; import org.apache.commons.io.IOUtils; import org.exoplatform.ecms.uploads.HTMLUploadImageProcessorImpl; import org.exoplatform.services.jcr.config.RepositoryEntry; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.wcm.core.WCMService; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.exoplatform.container.PortalContainer; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; import java.io.*; import java.nio.file.Files; @RunWith(MockitoJUnitRunner.class) public class HTMLUploadImageProcessorTest { @Rule public TemporaryFolder uploadFolder = new TemporaryFolder(); @Mock private PortalContainer portalContainer; @Mock private UploadService uploadService; @Mock private RepositoryService repositoryService; @Mock private ManageableRepository repository; @Mock private RepositoryEntry repositoryEntry; @Mock private Session session; @Mock private SessionProvider sessionProvider; @Mock private LinkManager linkManager; @Mock private SessionProviderService sessionProviderService; @Mock private NodeHierarchyCreator nodeHierarchyCreator; @Mock private WCMService wcmService; @Test public void shouldReturnSameContentWhenNoEmbeddedImage() throws Exception { // Given HTMLUploadImageProcessorImpl imageProcessor = new HTMLUploadImageProcessorImpl(portalContainer, uploadService, repositoryService, linkManager, sessionProviderService,nodeHierarchyCreator,wcmService); String content = "<p>content with no images</p>"; Node node = mock(Node.class); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(sessionProviderService.getSystemSessionProvider(null)).thenReturn(sessionProvider); when(sessionProvider.getSession(null,repository)).thenReturn(session); when(session.getNodeByUUID(anyString())).thenReturn(node); // When String processedContent = imageProcessor.processImages(content, "nodeParent", null); // Then assertEquals(content, processedContent); } @Test public void shouldReturnUpdatedContentWhenEmbeddedImage() throws Exception { // Given HTMLUploadImageProcessorImpl imageProcessor = new HTMLUploadImageProcessorImpl(portalContainer, uploadService, repositoryService, linkManager, sessionProviderService,nodeHierarchyCreator,wcmService); String content = "<p>content with image: <img src=\"/portal/image?uploadId=123456\" /></p>"; Node node = mock(Node.class); File imageFile = uploadFolder.newFile("image.png"); UploadResource uploadImage = new UploadResource("123456", "image.png"); uploadImage.setStoreLocation(imageFile.getPath()); when(uploadService.getUploadResource(eq("123456"))).thenReturn(uploadImage); when(node.hasNode(eq("image.png"))).thenReturn(false); when(node.addNode(anyString(), anyString())).thenReturn(node); when(portalContainer.getName()).thenReturn("portal"); when(portalContainer.getRestContextName()).thenReturn("rest"); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(sessionProviderService.getSystemSessionProvider(null)).thenReturn(sessionProvider); when(repositoryEntry.getName()).thenReturn("repository"); when(sessionProvider.getSession(null,repository)).thenReturn(session); when(node.getSession()).thenReturn(session); Workspace workspace = mock(Workspace.class); when(session.getWorkspace()).thenReturn(workspace); when(session.getNodeByUUID(anyString())).thenReturn(node); when(workspace.getName()).thenReturn("collaboration"); lenient().when(node.getPath()).thenReturn("/path/to/image.png"); // When String processedContent = imageProcessor.processImages(content, "nodeParent", null); // Then assertTrue(processedContent.matches("<p>content with image: <img src=\"/portal/rest/images/repository/collaboration/[a-z0-9]+\" /></p>")); } @Test public void shouldReturnUpdatedContentWhenEmbeddedImageForSpace() throws Exception { // Given HTMLUploadImageProcessorImpl imageProcessor = new HTMLUploadImageProcessorImpl(portalContainer, uploadService, repositoryService, linkManager, sessionProviderService,nodeHierarchyCreator,wcmService); String content = "<p>content with image: <img src=\"/portal/image?uploadId=123456\" /></p>"; Node node = mock(Node.class); File imageFile = uploadFolder.newFile("image.png"); UploadResource uploadImage = new UploadResource("123456", "image.png"); uploadImage.setStoreLocation(imageFile.getPath()); when(uploadService.getUploadResource(eq("123456"))).thenReturn(uploadImage); when(node.hasNode(eq("image.png"))).thenReturn(false); when(node.addNode(anyString(), anyString())).thenReturn(node); when(portalContainer.getName()).thenReturn("portal"); when(portalContainer.getRestContextName()).thenReturn("rest"); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(sessionProviderService.getSystemSessionProvider(null)).thenReturn(sessionProvider); when(repositoryEntry.getName()).thenReturn("repository"); when(sessionProvider.getSession("collaboration",repository)).thenReturn(session); when(node.getSession()).thenReturn(session); Workspace workspace = mock(Workspace.class); when(session.getWorkspace()).thenReturn(workspace); when(session.getRootNode()).thenReturn(node); when(node.getNode(anyString())).thenReturn(node); when(workspace.getName()).thenReturn("collaboration"); lenient().when(node.getPath()).thenReturn("/path/to/image.png"); // When String processedContent = imageProcessor.processSpaceImages(content, "nodeParent", null); // Then assertTrue(processedContent.matches("<p>content with image: <img src=\"/portal/rest/images/repository/collaboration/[a-z0-9]+\" /></p>")); } @Test public void shouldReturnUpdatedContentWhenEmbeddedImportedImageForSpace() throws Exception { // Given HTMLUploadImageProcessorImpl imageProcessor = new HTMLUploadImageProcessorImpl(portalContainer, uploadService, repositoryService, linkManager, sessionProviderService,nodeHierarchyCreator,wcmService); String content = "<p>content with image: <img src=\"//-image.png-//\" /></p>"; Node node = mock(Node.class); when(node.hasNode(eq("image.png"))).thenReturn(false); when(node.addNode(anyString(), anyString())).thenReturn(node); when(portalContainer.getName()).thenReturn("portal"); when(portalContainer.getRestContextName()).thenReturn("rest"); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(sessionProviderService.getSystemSessionProvider(null)).thenReturn(sessionProvider); when(repositoryEntry.getName()).thenReturn("repository"); when(sessionProvider.getSession("collaboration",repository)).thenReturn(session); when(node.getSession()).thenReturn(session); when(node.getUUID()).thenReturn("123524"); Workspace workspace = mock(Workspace.class); when(session.getWorkspace()).thenReturn(workspace); when(session.getRootNode()).thenReturn(node); when(node.getNode(anyString())).thenReturn(node); when(workspace.getName()).thenReturn("collaboration"); lenient().when(node.getPath()).thenReturn("/path/to/image.png"); File file = new File(System.getProperty("java.io.tmpdir") + File.separator +"image.png"); try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(new ByteArrayInputStream("test data".getBytes()), outputStream); } catch (Exception e) { throw new IllegalArgumentException("Cannot create the file", e); } // When String processedContent = imageProcessor.processSpaceImages(content, "nodeParent", null); // Then assertTrue(processedContent.matches("<p>content with image: <img src=\"/portal/rest/images/repository/collaboration/[a-z0-9]+\" /></p>")); } @Test public void shouldReturnUpdatedContentWhenEmbeddedImageForUser() throws Exception { // Given HTMLUploadImageProcessorImpl imageProcessor = new HTMLUploadImageProcessorImpl(portalContainer, uploadService, repositoryService, linkManager, sessionProviderService,nodeHierarchyCreator,wcmService); String content = "<p>content with image: <img src=\"/portal/image?uploadId=123456\" /></p>"; Node node = mock(Node.class); File imageFile = uploadFolder.newFile("image.png"); UploadResource uploadImage = new UploadResource("123456", "image.png"); uploadImage.setStoreLocation(imageFile.getPath()); when(uploadService.getUploadResource(eq("123456"))).thenReturn(uploadImage); when(node.hasNode(eq("image.png"))).thenReturn(false); when(node.addNode(anyString(), anyString())).thenReturn(node); when(portalContainer.getName()).thenReturn("portal"); when(portalContainer.getRestContextName()).thenReturn("rest"); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(sessionProviderService.getSystemSessionProvider(null)).thenReturn(sessionProvider); when(repositoryEntry.getName()).thenReturn("repository"); when(nodeHierarchyCreator.getUserNode(sessionProvider, "userId")).thenReturn(node); when(node.getSession()).thenReturn(session); Workspace workspace = mock(Workspace.class); when(session.getWorkspace()).thenReturn(workspace); when(workspace.getName()).thenReturn("collaboration"); lenient().when(node.getPath()).thenReturn("/path/to/image.png"); // When String processedContent = imageProcessor.processUserImages(content, "userId", null); // Then assertTrue(processedContent.matches("<p>content with image: <img src=\"/portal/rest/images/repository/collaboration/[a-z0-9]+\" /></p>")); } @Test public void shouldReturnUpdatedContentForExport() throws Exception { // Given HTMLUploadImageProcessorImpl imageProcessor = new HTMLUploadImageProcessorImpl(portalContainer, uploadService, repositoryService, linkManager, sessionProviderService,nodeHierarchyCreator,wcmService); String content = "<p>content with image: <img src=\"/portal/rest/images/repository/collaboration/123456\" /></p>"; Node node = mock(Node.class); Property property = mock(Property.class); when(portalContainer.getName()).thenReturn("portal"); when(portalContainer.getRestContextName()).thenReturn("rest"); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(repositoryEntry.getName()).thenReturn("repository"); when(wcmService.getReferencedContent(anyObject(), anyString(),anyString() )).thenReturn(node); when(node.getNode(anyString())).thenReturn(node); when(node.getName()).thenReturn("image.png"); when(node.getProperty(anyString())).thenReturn(property); when(property.getStream()).thenReturn(new ByteArrayInputStream("test data".getBytes())); // When String processedContent = imageProcessor.processImagesForExport(content); // Then assertTrue(processedContent.matches("<p>content with image: <img src=\"//-image.png-//\" /></p>")); } }
12,229
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ECMSActivityFileStoragePluginTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/wcm/ext/component/activity/ECMSActivityFileStoragePluginTest.java
package org.exoplatform.wcm.ext.component.activity; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValueParam; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.config.RepositoryEntry; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.social.core.activity.model.ActivityFile; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.activity.model.ExoSocialActivityImpl; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.Session; import javax.jcr.nodetype.NodeDefinition; import java.io.File; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ECMSActivityFileStoragePluginTest { static private String TEXT_PLAIN = "text/plain"; @Mock UploadService uploadService; @Mock SessionProviderService sessionProviderService; @Mock SpaceService spaceService; @Mock RepositoryService repositoryService; @Mock NodeHierarchyCreator nodeHierarchyCreator; @Mock SessionProvider sessionProvider; @Mock ManageableRepository repository; @Mock RepositoryEntry repositoryEntry; @Mock Session session; @Mock AutoVersionService autoVersionService; @Test public void storeAttachments() throws Exception { // Given ConversationState.setCurrent(new ConversationState(new org.exoplatform.services.security.Identity("root"))); InitParams initParams = new InitParams(); ValueParam datasource = new ValueParam(); datasource.setName("datasource"); datasource.setValue("jcr"); ValueParam priority = new ValueParam(); priority.setName("priority"); priority.setValue("1"); initParams.addParameter(datasource); initParams.addParameter(priority); ECMSActivityFileStoragePlugin ecmsActivityFileStoragePlugin = new ECMSActivityFileStoragePlugin(spaceService,nodeHierarchyCreator,repositoryService,uploadService,sessionProviderService,initParams,autoVersionService); ExoSocialActivity activity = new ExoSocialActivityImpl(); activity.setTitle("test"); activity.setStreamOwner("root"); Identity streamOwner = new Identity(OrganizationIdentityProvider.NAME,"root"); streamOwner.setId("root"); ActivityFile activityFile = new ActivityFile(); activityFile.setUploadId("1234"); activityFile.setName("testFileUpload"); UploadResource uploadResource = new UploadResource("1234"); uploadResource.setFileName("testFileUpload"); File file = File.createTempFile("testFileUpload", ".xml"); uploadResource.setStoreLocation(file.getPath()); uploadResource.setMimeType(TEXT_PLAIN); when(sessionProviderService.getSystemSessionProvider(any())).thenReturn(sessionProvider); lenient().when(sessionProviderService.getSessionProvider(any())).thenReturn(sessionProvider); when(repositoryService.getCurrentRepository()).thenReturn(repository); when(repository.getConfiguration()).thenReturn(repositoryEntry); lenient().when(repositoryEntry.getName()).thenReturn("workspace"); when(repositoryEntry.getDefaultWorkspaceName()).thenReturn("collaboration"); when(sessionProvider.getSession(any(), any())).thenReturn(session); Node userNode = mock(Node.class); Node parentNode = mock(Node.class); Node parentUploadNode = mock(Node.class); Node node = mock(Node.class); Node resourceNode = mock(Node.class); NodeDefinition nodeDefinition = mock(NodeDefinition.class); Property property = mock(Property.class); when(nodeHierarchyCreator.getUserNode(any(), any())).thenReturn(userNode); when(nodeHierarchyCreator.getJcrPath(any())).thenReturn("/Users"); when(userNode.hasNode(any())).thenReturn(true); when(userNode.getNode(any())).thenReturn(parentNode); when(parentNode.hasNode(any())).thenReturn(true); when(parentNode.getNode(any())).thenReturn(parentUploadNode); when(parentUploadNode.getDefinition()).thenReturn(nodeDefinition); when(parentUploadNode.addNode(any(),any())).thenReturn(node); when(node.addNode(any(),any())).thenReturn(resourceNode); when(uploadService.getUploadResource(any())).thenReturn(uploadResource); when(session.getItem(any())).thenReturn(node); when(node.getPath()).thenReturn("/test/node_B/node_1"); when(resourceNode.getProperty(any())).thenReturn(property); when(property.getString()).thenReturn("testProperty"); when(node.isNodeType(any())).thenReturn(false); when(autoVersionService.autoVersion(node)).thenReturn(any()); // when ecmsActivityFileStoragePlugin.storeAttachments(activity,streamOwner,activityFile); // then verify(uploadService, times(1)).removeUploadResource(any()); verify(uploadService, times(1)).getUploadResource(any()); verify(session, times(1)).save(); verify(autoVersionService, times(1)).autoVersion(any()); } }
5,772
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UtilsTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/wcm/ext/component/activity/listener/UtilsTest.java
package org.exoplatform.wcm.ext.component.activity.listener; import static org.exoplatform.services.jcr.ext.ActivityTypeUtils.EXO_ACTIVITY_INFO; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Mockito.*; import java.util.Arrays; import javax.jcr.Node; import javax.jcr.Property; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.security.ConversationState; import org.exoplatform.social.core.activity.model.ExoSocialActivityImpl; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.space.model.Space; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.MockitoJUnitRunner; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.access.AccessControlList; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.spi.SpaceService; /** * Test class for org.exoplatform.wcm.ext.component.activity.listener.Utils */ @RunWith(MockitoJUnitRunner.class) public class UtilsTest { @Mock ActivityManager activityManager; @Mock IdentityManager identityManager; @Mock ActivityCommonService activityCommonService; @Mock SpaceService spaceService; MockedStatic<CommonsUtils> COMMONS_UTILS; MockedStatic<Utils> UTILS; @Before public void setUp() throws Exception { COMMONS_UTILS = mockStatic(CommonsUtils.class); UTILS = mockStatic(Utils.class); COMMONS_UTILS.when(() -> activityManager.isActivityTypeEnabled(nullable(String.class))).thenReturn(true); COMMONS_UTILS.when(() -> CommonsUtils.getService(eq(ActivityManager.class))).thenReturn(activityManager); COMMONS_UTILS.when(() -> CommonsUtils.getService(eq(IdentityManager.class))).thenReturn(identityManager); COMMONS_UTILS.when(() -> CommonsUtils.getService(eq(ActivityCommonService.class))).thenReturn(activityCommonService); COMMONS_UTILS.when(() -> CommonsUtils.getService(eq(SpaceService.class))).thenReturn(spaceService); when(spaceService.getSpaceByGroupId(nullable(String.class))).thenReturn(new Space()); UTILS.when(() -> Utils.postFileActivity(any(), nullable(String.class), anyBoolean(), anyBoolean(), nullable(String.class), nullable(String.class))).thenCallRealMethod(); UTILS.when(() -> Utils.getActivityOwnerId(any())) .thenReturn("john"); UTILS.when(() -> Utils.isPublic(any())).thenCallRealMethod(); ExoSocialActivity activity = new ExoSocialActivityImpl(); activity.setId("123"); UTILS.when(() -> Utils.createActivity(any(), nullable(String.class), any(), nullable(String.class), nullable(String.class), anyBoolean(), nullable(String.class), nullable(String.class))) .thenReturn(activity); when(activityManager.getActivity(anyString())).thenReturn(activity); when(identityManager.getOrCreateIdentity(eq(OrganizationIdentityProvider.NAME), any())).thenReturn(new Identity()); } @After public void tearDown() throws Exception { COMMONS_UTILS.close(); UTILS.close(); } @Test public void shouldPostFileActivityWhenFileIsPublic() throws Exception { // Given ExtendedNode node = mock(ExtendedNode.class); when(node.isCheckedOut()).thenReturn(true); when(node.isNodeType(EXO_ACTIVITY_INFO)).thenReturn(false); when(node.canAddMixin(EXO_ACTIVITY_INFO)).thenReturn(true); lenient().when(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(false); AccessControlList acl = new AccessControlList("john", Arrays.asList(new AccessControlEntry("any", "read"))); when(node.getACL()).thenReturn(acl); // When Utils.postFileActivity(node, null, false, false, "", ""); // Then verify(activityManager, times(1)).saveActivityNoReturn(nullable(Identity.class), any(ExoSocialActivity.class)); } @Test public void shouldNotPostFileActivityWhenFileIsNotPublic() throws Exception { ExtendedNode node = mock(ExtendedNode.class); lenient().when(node.isCheckedOut()).thenReturn(true); when(node.isNodeType(EXO_ACTIVITY_INFO)).thenReturn(false); lenient().when(node.canAddMixin(EXO_ACTIVITY_INFO)).thenReturn(true); lenient().when(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(false); AccessControlList acl = new AccessControlList("john", Arrays.asList(new AccessControlEntry("*:/spaces/space1", "read"))); when(node.getACL()).thenReturn(acl); // When ExoSocialActivity activity = Utils.postFileActivity(node, null, false, false, "", ""); // Then verify(activityManager, never()).saveActivityNoReturn(any(), any(ExoSocialActivity.class)); } @Test public void checkPostActivityIfActivityTypeIsEnabled() throws Exception { ExtendedNode node = mock(ExtendedNode.class); when(node.isCheckedOut()).thenReturn(true); when(node.isNodeType(EXO_ACTIVITY_INFO)).thenReturn(false); when(node.canAddMixin(EXO_ACTIVITY_INFO)).thenReturn(true); lenient().when(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(false); AccessControlList acl = new AccessControlList("john", Arrays.asList(new AccessControlEntry("any", "read"))); when(node.getACL()).thenReturn(acl); //Enable activity type ActivityManager activityManager = mock(ActivityManager.class); when(activityManager.isActivityTypeEnabled(nullable(String.class))).thenReturn(true); COMMONS_UTILS.when(() -> CommonsUtils.getService(eq(ActivityManager.class))).thenReturn(activityManager); // Check File activity when it is disabled // When Utils.postFileActivity(node, null, false, false, "", ""); // Then verify(activityManager, times(1)).saveActivityNoReturn(nullable(Identity.class), any(ExoSocialActivity.class)); // Check Content activity when it is disabled // When lenient().when(activityManager.isActivityTypeEnabled(nullable(String.class))).thenReturn(true); Utils.postActivity(node, null, false, false, "", ""); // Then verify(activityManager, times(1)).saveActivityNoReturn(nullable(Identity.class), any(ExoSocialActivity.class)); } @Test public void checkPostActivityIfActivityTypeIsDisabled() throws Exception { ExtendedNode node = mock(ExtendedNode.class); lenient().when(node.isCheckedOut()).thenReturn(true); lenient().when(node.isNodeType(EXO_ACTIVITY_INFO)).thenReturn(false); lenient().when(node.canAddMixin(EXO_ACTIVITY_INFO)).thenReturn(true); lenient().when(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(false); AccessControlList acl = new AccessControlList("john", Arrays.asList(new AccessControlEntry("any", "read"))); lenient().when(node.getACL()).thenReturn(acl); //Disable activity type ActivityManager activityManager = mock(ActivityManager.class); when(activityManager.isActivityTypeEnabled(nullable(String.class))).thenReturn(false); COMMONS_UTILS.when(() -> CommonsUtils.getService(eq(ActivityManager.class))).thenReturn(activityManager); // Check File activity when it is disabled // When Utils.postFileActivity(node, null, false, false, "", ""); // Then verify(activityManager, never()).saveActivityNoReturn(any(), any(ExoSocialActivity.class)); // Check Content activity when it is disabled // When Utils.postActivity(node, null, false, false, "", ""); // Then verify(activityManager, never()).saveActivityNoReturn(any(), any(ExoSocialActivity.class)); } @Test public void testAddVersionComment() { UTILS.when(() -> Utils.addVersionComment(any(Node.class), anyString(), anyString())).thenCallRealMethod(); UTILS.when(() -> Utils.getSpaceName(any())).thenReturn("/spaces/spaceOne"); ConversationState conversionState = ConversationState.getCurrent(); if(conversionState == null) { conversionState = new ConversationState(new org.exoplatform.services.security.Identity("root")); ConversationState.setCurrent(conversionState); } Node node = mock(Node.class); String commentText = "this is a comment"; String userName = "root"; try { when(node.isCheckedOut()).thenReturn(true); when(node.isNodeType(EXO_ACTIVITY_INFO)).thenReturn(false); when(node.canAddMixin(EXO_ACTIVITY_INFO)).thenReturn(true); lenient().when(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(false); Utils.addVersionComment(node, commentText, userName); verify(activityManager,times(1)).saveComment(any(), any()); } catch (Exception e) { fail(); } try { when(node.isNodeType(EXO_ACTIVITY_INFO)).thenReturn(true); Property property = mock(Property.class); when(property.getString()).thenReturn("444"); when(node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(property); when(activityManager.getActivity(eq("444"))).thenReturn(null); lenient().when(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)).thenReturn(true); Utils.addVersionComment(node, commentText, userName); verify(activityManager,times(2)).saveComment(any(), any()); } catch (Exception e) { fail(); } } }
9,713
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TestService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/ecm/webui/component/explorer/popup/service/TestService.java
/* * Copyright (C) 2003-2014 eXo Platform SEA. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecm.webui.component.explorer.popup.service; import javax.jcr.*; import org.junit.Ignore; import org.exoplatform.component.test.*; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.context.DocumentContext; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.rest.impl.ProviderBinder; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.Identity; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.SpaceUtils; import org.exoplatform.social.core.space.impl.DefaultSpaceApplicationHandler; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.wcm.ext.component.document.service.IShareDocumentService; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Aug 7, 2014 */ @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.ROOT, path = "conf/configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/ecms-test-configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/standalone/test-configuration.xml"), }) @Ignore public class TestService extends AbstractKernelTest { //private Log log = ExoLogger.getExoLogger(TestService.class); protected final String REPO_NAME = "repository"; protected final String DEFAULT_WS = "collaboration"; protected static PortalContainer container; private RepositoryService repositoryService; protected ManageableRepository repository; protected SessionProvider sessionProvider; protected Session session; protected SessionProviderService sessionProviderService_; protected ProviderBinder providers; private org.exoplatform.social.core.identity.model.Identity rootIdentity; private String perm = PermissionType.READ+","+PermissionType.ADD_NODE+","+PermissionType.SET_PROPERTY; private String comment = "Comment"; private String spaceName = "/spaces/space1"; private String userName = "john"; private String nodePath = "nodeToShare"; private String activityId; private NodeLocation nodeLocation; private String spaceId; private LinkManager linkManager; /** * Clear current container */ protected void tearDown() throws Exception { //delete node this.session.getRootNode().getNode(nodePath).remove(); this.session.save(); //delete activity ActivityManager manager = (ActivityManager)container.getComponentInstanceOfType(ActivityManager.class); manager.deleteActivity(activityId); //delete space SpaceService spaceService = (SpaceService) container.getComponentInstanceOfType(SpaceService.class); spaceService.deleteSpace(spaceId); RequestLifeCycle.end(); } private void initContainer() { container = PortalContainer.getInstance(); repositoryService = (RepositoryService) container.getComponentInstanceOfType(RepositoryService.class); sessionProviderService_ = (SessionProviderService) container.getComponentInstanceOfType(SessionProviderService.class); String loginConf = this.getClass().getResource("/conf/standalone/login.conf").toString(); System.setProperty("java.security.auth.login.config", loginConf); try { applySystemSession(); } catch (Exception e) { fail(); throw new RuntimeException("Failed to initialize standalone container: " + e.getMessage(), e); } } @Override protected void setUp() throws Exception { begin(); ConversationState conversionState = ConversationState.getCurrent(); if(conversionState == null) { conversionState = new ConversationState(new Identity("root")); ConversationState.setCurrent(conversionState); } initContainer(); IdentityManager identityManager = container.getComponentInstanceOfType(IdentityManager.class); rootIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, "root", false); linkManager =(LinkManager) container.getComponentInstanceOfType(LinkManager.class); this.nodeLocation = NodeLocation.getNodeLocationByNode(this.session.getRootNode().addNode(nodePath)); session.save(); SpaceService spaceService = (SpaceService)container.getComponentInstanceOfType(SpaceService.class); Space sp = getSpaceInstance(spaceService, "space1"); spaceId = sp.getId(); //init space node Node group = null; if(!session.getRootNode().hasNode("Groups"))group = session.getRootNode().addNode("Groups"); else group = session.getRootNode().getNode("Groups"); Node spaces = null; if(!group.hasNode("spaces"))spaces = group.addNode("spaces"); else spaces = group.getNode("spaces"); Node space = spaces.addNode(spaceName.split("/")[2]); space.addNode("Documents"); session.save(); } public void testShare() throws Exception { //share node DocumentContext.getCurrent().getAttributes().put(DocumentContext.IS_SKIP_RAISE_ACT, false); IShareDocumentService temp = (IShareDocumentService) container.getComponentInstanceOfType(IShareDocumentService.class); activityId = temp.publishDocumentToSpace(spaceName, NodeLocation.getNodeByLocation(nodeLocation), comment, perm); //Test symbolic link NodeIterator nodeIterator = session.getRootNode().getNode("Groups/spaces/space1/Documents/Shared").getNodes(); assertEquals(1, nodeIterator.getSize()); Node target = nodeIterator.nextNode(); assertEquals("exo:symlink", target.getPrimaryNodeType().getName()); Node origin = linkManager.getTarget(target,true); assertEquals("/" + nodePath, origin.getPath()); //Test permission ExtendedNode extendedNode = (ExtendedNode) origin; assertTrue(!extendedNode.getACL().getPermissions("*:" + spaceName).isEmpty()); //Test activity ActivityManager manager = (ActivityManager) container.getComponentInstanceOfType(ActivityManager.class); ExoSocialActivity activity = manager.getActivity(this.activityId); assertEquals(this.comment, activity.getTitle()); } public void testShareUser() throws Exception { //share node DocumentContext.getCurrent().getAttributes().put(DocumentContext.IS_SKIP_RAISE_ACT, false); IShareDocumentService temp = (IShareDocumentService) container.getComponentInstanceOfType(IShareDocumentService.class); temp.publishDocumentToUser(userName, NodeLocation.getNodeByLocation(nodeLocation), comment, perm); //Test symbolic link NodeIterator nodeIterator = session.getRootNode().getNode("Users/j___/jo___/joh___/john/Private/Documents/Shared").getNodes(); assertEquals(1, nodeIterator.getSize()); Node target = nodeIterator.nextNode(); assertEquals("exo:symlink", target.getPrimaryNodeType().getName()); Node origin = linkManager.getTarget(target,true); assertEquals("/" + nodePath, origin.getPath()); //Test permission ExtendedNode extendedNode = (ExtendedNode) origin; assertTrue(!extendedNode.getACL().getPermissions(userName).isEmpty()); } public void applySystemSession() throws Exception{ System.setProperty("gatein.tenant.repository.name", REPO_NAME); container = PortalContainer.getInstance(); repositoryService.setCurrentRepositoryName(REPO_NAME); repository = repositoryService.getCurrentRepository(); closeOldSession(); sessionProvider = sessionProviderService_.getSystemSessionProvider(null); session = sessionProvider.getSession(DEFAULT_WS, repository); sessionProvider.setCurrentRepository(repository); sessionProvider.setCurrentWorkspace(DEFAULT_WS); } /** * Close current session */ private void closeOldSession() { if (session != null && session.isLive()) { session.logout(); } } private Space getSpaceInstance(SpaceService spaceService, String spaceName) throws Exception { Space space = new Space(); space.setDisplayName(spaceName); space.setPrettyName(space.getDisplayName()); space.setRegistration(Space.OPEN); space.setDescription("add new space " + spaceName); space.setType(DefaultSpaceApplicationHandler.NAME); space.setVisibility(Space.OPEN); space.setRegistration(Space.VALIDATION); space.setPriority(Space.INTERMEDIATE_PRIORITY); space.setGroupId(SpaceUtils.SPACE_GROUP + "/" + space.getPrettyName()); space.setUrl(space.getPrettyName()); String[] managers = new String[] { "root"}; String[] members = new String[] { "root" }; String[] invitedUsers = new String[] {}; String[] pendingUsers = new String[] {}; space.setInvitedUsers(invitedUsers); space.setPendingUsers(pendingUsers); space.setManagers(managers); space.setMembers(members); spaceService.saveSpace(space, true); return space; } }
10,482
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TaskAttachmentEntityTypePluginTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/services/attachments/plugins/TaskAttachmentEntityTypePluginTest.java
/* * Copyright (C) 2022 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.services.attachments.plugins; import junit.framework.TestCase; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.config.RepositoryEntry; import org.exoplatform.services.jcr.core.ExtendedSession; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.jcr.impl.core.SessionImpl; import org.exoplatform.services.jcr.impl.core.WorkspaceImpl; import org.exoplatform.task.dto.ProjectDto; import org.exoplatform.task.dto.StatusDto; import org.exoplatform.task.dto.TaskDto; import org.exoplatform.task.service.ProjectService; import org.exoplatform.task.service.TaskService; import javax.jcr.nodetype.NodeType; import java.util.Arrays; import java.util.HashSet; import static org.exoplatform.services.wcm.core.NodetypeConstant.NT_FOLDER; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TaskAttachmentEntityTypePluginTest extends TestCase { public void testGetAttachmentOrLinkId() throws Exception { long entityId = 1; // Mock services TaskService taskService = mock(TaskService.class); ProjectService projectService = mock(ProjectService.class); NodeHierarchyCreator nodeHierarchyCreator = mock(NodeHierarchyCreator.class); RepositoryService repositoryService = mock(RepositoryService.class); SessionProviderService sessionProviderService = mock(SessionProviderService.class); // Mock SessionProvider SessionProvider sessionProvider = mock(SessionProvider.class); when(sessionProviderService.getSessionProvider(null)).thenReturn(sessionProvider); // Mock Repository service and JCR session ManageableRepository repository = mock(ManageableRepository.class); when(repositoryService.getCurrentRepository()).thenReturn(repository); RepositoryEntry repositoryEntry = mock(RepositoryEntry.class); when(repository.getConfiguration()).thenReturn(repositoryEntry); when(repository.getConfiguration().getDefaultWorkspaceName()).thenReturn("collaboration"); ExtendedSession extendedSession = mock(ExtendedSession.class); when(sessionProvider.getSession(any(), any())).thenReturn(extendedSession); // Mock Task TaskDto task = new TaskDto(); task.setId(1); ProjectDto project = new ProjectDto(); project.setId(1); StatusDto status = new StatusDto(); status.setProject(project); task.setStatus(status); when(taskService.getTask(1)).thenReturn(task); when(projectService.getParticipator(anyLong())).thenReturn(new HashSet<>(Arrays.asList("user1", "/platform/users", "member:/spaces/space1"))); // Instantiate the TaskAttachmentEntityTypePlugin TaskAttachmentEntityTypePlugin taskAttachmentEntityTypePlugin = new TaskAttachmentEntityTypePlugin(taskService, projectService, nodeHierarchyCreator, sessionProviderService, repositoryService); // Node does not exist, we return the same attachmentId String attachmentId = "123456789Azerty"; String attachmentName = "testFile.docx"; assertEquals(1, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", entityId, attachmentId).size()); assertEquals(attachmentId, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", entityId, attachmentId).get(0)); // Node exist NodeImpl node = mock(NodeImpl.class); when(node.getIdentifier()).thenReturn(attachmentId); when(node.getName()).thenReturn(attachmentName); NodeType nodeType = mock(NodeType.class); when(nodeType.getName()).thenReturn("nt:file"); when(node.getPrimaryNodeType()).thenReturn(nodeType); when(extendedSession.getNodeByIdentifier(anyString())).thenReturn(node); when(extendedSession.itemExists(anyString())).thenReturn(true); // Return original node ID if it is not under space and user can not access the group's target folder when(node.getPath()).thenReturn("/Users/user1/documents/testFile.docx"); assertEquals(1, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).size()); assertEquals(attachmentId, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).get(0)); // Create different nodes NodeImpl rootNode = mock(NodeImpl.class); NodeImpl taskParentNode = mock(NodeImpl.class); NodeImpl taskNode = mock(NodeImpl.class); NodeImpl linkNode = mock(NodeImpl.class); String linkNodeIdentifier = "link_identifier_123456789Azerty"; SessionImpl session = mock(SessionImpl.class); WorkspaceImpl workspace = mock(WorkspaceImpl.class); when(workspace.getName()).thenReturn("collaboration"); when(session.getWorkspace()).thenReturn(workspace); when(node.getSession()).thenReturn(session); when(node.getPath()).thenReturn("/Groups/spaces/spaceOne/documents/testFile.docx"); when(linkNode.getIdentifier()).thenReturn(linkNodeIdentifier); when(taskNode.addNode(anyString(), anyString())).thenReturn(linkNode); when(taskParentNode.getNode(String.valueOf(anyLong()))).thenReturn(taskNode); when(taskParentNode.addNode(String.valueOf(entityId), NT_FOLDER)).thenReturn(taskNode); when(rootNode.addNode("task", NT_FOLDER)).thenReturn(taskParentNode); when(extendedSession.getItem(anyString())).thenReturn(rootNode); // Will return link ID instead of the original attached file assertEquals(1, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).size()); assertEquals(linkNodeIdentifier, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).get(0)); when(projectService.getParticipator(anyLong())).thenReturn(new HashSet<>(Arrays.asList("user1", "/platform/users", "member:/spaces/space1", "member:/spaces/spaceOne"))); // Will return link ID instead of the original attached file assertEquals(2, taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).size()); assertTrue(taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).contains(attachmentId)); assertTrue(taskAttachmentEntityTypePlugin.getlinkedAttachments("task", 1, attachmentId).contains(linkNodeIdentifier)); } }
7,620
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockSpacesAdministrationService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/ecms/mock/MockSpacesAdministrationService.java
package org.exoplatform.ecms.mock; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.social.core.space.SpacesAdministrationService; import java.util.List; public class MockSpacesAdministrationService implements SpacesAdministrationService { @Override public List<MembershipEntry> getSpacesAdministratorsMemberships() { return null; } @Override public void updateSpacesAdministratorsMemberships(List<MembershipEntry> permissionsExpressions) { } @Override public List<MembershipEntry> getSpacesCreatorsMemberships() { return null; } @Override public void updateSpacesCreatorsMemberships(List<MembershipEntry> permissionsExpressions) { } @Override public boolean canCreateSpace(String username) { return false; } }
794
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
MockFileService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/ecms/mock/MockFileService.java
package org.exoplatform.ecms.mock; import org.exoplatform.commons.file.model.FileInfo; import org.exoplatform.commons.file.model.FileItem; import org.exoplatform.commons.file.services.FileService; import org.exoplatform.commons.file.services.FileStorageException; import java.io.IOException; public class MockFileService implements FileService { @Override public FileInfo getFileInfo(long l) { return null; } @Override public FileItem getFile(long l) throws FileStorageException { return null; } @Override public FileItem writeFile(FileItem fileItem) throws FileStorageException, IOException { return null; } @Override public FileItem updateFile(FileItem fileItem) throws FileStorageException, IOException { return null; } @Override public FileInfo deleteFile(long l) { return null; } }
844
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ActivityAttachmentProcessorTest.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/ecms/activity/processor/ActivityAttachmentProcessorTest.java
package org.exoplatform.ecms.activity.processor; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.activity.model.ExoSocialActivityImpl; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.runners.MockitoJUnitRunner; import javax.jcr.Node; import java.util.HashMap; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ActivityAttachmentProcessorTest { @Mock private ActivityAttachmentProcessor activityAttachmentProcessor; @Test public void processActivity() { ExoSocialActivity activity = new ExoSocialActivityImpl(); activity.setType("sharefiles:spaces"); HashMap<String, String> templateParams = new HashMap<>(); templateParams.put("workspace", "collaboration"); templateParams.put("author", "root"); templateParams.put("permission", "read"); templateParams.put("nodePath", "/Groups/spaces/new/Documents/Shared/sample.pdf"); templateParams.put("docTitle", "sample.pdf"); templateParams.put("mimeType", "application/pdf"); templateParams.put("message", ""); templateParams.put("repository", "repository"); templateParams.put("contentName", "sample.pdf"); templateParams.put("nodeUUID", "736ec0d07f0001015e91bad4c1d582e1"); templateParams.put("id", "736ec0d07f0001015e91bad4c1d582e1"); activity.setTemplateParams(templateParams); NodeLocation nodeLocation = new NodeLocation(templateParams.get("repository"), templateParams.get("workspace"), templateParams.get("nodePath"), templateParams.get("nodeUUID"), true); Node currentNode = mock(Node.class); doCallRealMethod().when(activityAttachmentProcessor).processActivity(activity); MockedStatic<NodeLocation> NODE_LOCATION = mockStatic(NodeLocation.class); NODE_LOCATION.when(() -> NodeLocation.getNodeByLocation(ArgumentMatchers.refEq(nodeLocation))).thenReturn(currentNode); activityAttachmentProcessor.processActivity(activity); assertEquals(1, activity.getFiles().size()); } }
2,342
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FakeIdentityProvider.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/ecms/ext/provider/FakeIdentityProvider.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecms.ext.provider; import java.util.HashMap; import java.util.Map; import org.exoplatform.social.core.identity.IdentityProvider; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.model.Profile; public class FakeIdentityProvider extends IdentityProvider<Application> { /** The Constant NAME. */ public final static String NAME = "apps"; private static Map<String,Application> appsByUrl = new HashMap<String,Application>(); @Override public Application findByRemoteId(String remoteId) { return appsByUrl.get(remoteId); } @Override public String getName() { return NAME; } @Override public Identity createIdentity(Application app) { Identity identity = new Identity(NAME, app.getId()); return identity; } public void addApplication(Application app) { appsByUrl.put(app.getId(), app); } @Override public void populateProfile(Profile profile, Application app) { profile.setProperty(Profile.USERNAME, app.getName()); profile.setProperty(Profile.FIRST_NAME, app.getName()); profile.setAvatarUrl(app.getIcon()); profile.setUrl(app.getUrl()); } }
1,906
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
Application.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/test/java/org/exoplatform/ecms/ext/provider/Application.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.ecms.ext.provider; /** * represents an external application interacting with Social * @author <a href="mailto:patrice.lamarque@exoplatform.com">Patrice Lamarque</a> * @version $Revision$ */ public class Application { private String name; private String description; private String id; private String url; private String icon; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
1,659
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocActivityUpdaterListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/addons/rdbms/listener/DocActivityUpdaterListener.java
package org.exoplatform.social.addons.rdbms.listener; import javax.jcr.*; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.plugin.doc.UIDocActivity; public class DocActivityUpdaterListener extends Listener<ExoSocialActivity, String> { private static final Log LOG = ExoLogger.getLogger(DocActivityUpdaterListener.class); public static final String ACTIVITY_TYPE = "DOC_ACTIVITY"; @Override public void onEvent(Event<ExoSocialActivity, String> event) throws Exception { ExoSocialActivity activity = event.getSource(); if (ACTIVITY_TYPE.equals(activity.getType())) { String workspace = activity.getTemplateParams().get(UIDocActivity.WORKSPACE); if(workspace == null) { workspace = activity.getTemplateParams().get(UIDocActivity.WORKSPACE.toLowerCase()); } String docId = activity.getTemplateParams().get(UIDocActivity.ID); Node docNode = getDocNode(workspace, activity.getUrl(), docId); if (docNode != null && docNode.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { ActivityTypeUtils.attachActivityId(docNode, event.getData()); docNode.save(); } catch (RepositoryException e) { LOG.warn("Updates the document activity is unsuccessful!"); LOG.debug("Updates the document activity is unsuccessful!", e); } } } } /** * This method is target to get the Document node. * * @param workspace * @param path * @param nodeId * @return */ private Node getDocNode(String workspace, String path, String nodeId) { if (workspace == null || (nodeId == null && path == null)) { return null; } try { Session session = SessionProviderService.getSystemSessionProvider().getSession(workspace, SessionProviderService.getRepository()); try { return session.getNodeByUUID(nodeId); } catch (Exception e) { return (Node) session.getItem(path); } } catch (RepositoryException e) { return null; } } }
2,385
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocViewer.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/plugin/doc/UIDocViewer.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.social.plugin.doc; import java.util.*; import javax.jcr.Node; import javax.jcr.RepositoryException; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation; import org.exoplatform.ecm.webui.utils.Utils; import org.exoplatform.portal.webui.util.Util; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.web.application.JavascriptManager; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.UIPopupContainer; import org.exoplatform.webui.core.lifecycle.Lifecycle; import org.exoplatform.webui.event.Event; import org.exoplatform.webui.event.EventListener; import org.exoplatform.webui.ext.UIExtension; import org.exoplatform.webui.ext.UIExtensionManager; /** * UIDocViewer <p></p> * * @author Zuanoc * @since Aug 10, 2010 */ @ComponentConfig( lifecycle = Lifecycle.class, events = { @EventConfig(listeners = UIDocViewer.DownloadActionListener.class), @EventConfig(listeners = UIBaseNodePresentation.OpenDocInDesktopActionListener.class) } ) public class UIDocViewer extends UIBaseNodePresentation { private static final String UIDocViewerPopup = "UIDocViewerPopup"; /** * The logger. */ private static final Log LOG = ExoLogger.getLogger(UIDocViewer.class); protected Node originalNode; public String docPath; public String repository; public String workspace; /** * Sets the original node. * * @param originalNode */ public void setOriginalNode(Node originalNode) { this.originalNode = originalNode; } /** * Gets the original node. * * @return * @throws Exception */ public Node getOriginalNode() throws Exception { // return originalNode; return getDocNode(); } /** * Sets the node. * * @param node */ public void setNode(Node node) { originalNode = node; } @Override public Node getNode() throws Exception { // return originalNode; return getDocNode(); } public String getTemplate() { Node docNode = getDocNode(); if(docNode == null) return null; TemplateService templateService = getApplicationComponent(TemplateService.class); String userName = Util.getPortalRequestContext().getRemoteUser() ; try { if (docNode.isNodeType("nt:frozenNode")) { String uuid = docNode.getProperty("jcr:frozenUuid").getString(); docNode = docNode.getSession().getNodeByUUID(uuid); } String nodeType = docNode.getPrimaryNodeType().getName(); if(templateService.isManagedNodeType(nodeType)) { return templateService.getTemplatePathByUser(false, nodeType, userName); } }catch (RepositoryException re){ if (LOG.isDebugEnabled() || LOG.isWarnEnabled()) LOG.error("Get template catch RepositoryException: ", re); } catch (Exception e) { //TemplateService LOG.warn(e.getMessage(), e); } return null; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.presentation.UIBaseNodePresentation#getTemplatePath() */ public String getTemplatePath() throws Exception { return getRepository(); } public ResourceResolver getTemplateResourceResolver(WebuiRequestContext context, String template) { DMSConfiguration dmsConfiguration = getApplicationComponent(DMSConfiguration.class); String workspace = dmsConfiguration.getConfig().getSystemWorkspace(); return new JCRResourceResolver(workspace); } public String getNodeType() { return null; } public boolean isNodeTypeSupported() { return false; } public UIComponent getCommentComponent() { return null; } public UIComponent getRemoveAttach() { return null; } public UIComponent getRemoveComment() { return null; } public UIComponent getUIComponent(String mimeType) throws Exception { UIExtensionManager manager = getApplicationComponent(UIExtensionManager.class); List<UIExtension> extensions = manager.getUIExtensions(Utils.FILE_VIEWER_EXTENSION_TYPE); Map<String, Object> context = new HashMap<String, Object>(); context.put(Utils.MIME_TYPE, mimeType); for (UIExtension extension : extensions) { UIComponent uiComponent = manager.addUIExtension(extension, context, this); if (uiComponent != null) { return uiComponent; } } return null; } public String getRepositoryName() { return UIDocActivity.REPOSITORY_NAME; } static public class DownloadActionListener extends EventListener<UIDocViewer> { public void execute(Event<UIDocViewer> event) throws Exception { UIDocViewer uiComp = event.getSource(); String downloadLink = uiComp.getDownloadLink(org.exoplatform.wcm.webui.Utils.getFileLangNode(uiComp.getDocNode())); JavascriptManager jsManager = event.getRequestContext().getJavascriptManager(); downloadLink = downloadLink.replaceAll("&amp;", "&") ; jsManager.addJavascript("window.location.href = " + downloadLink + ";"); } } private Node getDocNode() { NodeLocation nodeLocation = new NodeLocation(repository, workspace, docPath); return NodeLocation.getNodeByLocation(nodeLocation); } @Override public UIPopupContainer getPopupContainer() throws Exception { UIPopupContainer pContainer1 = getAncestorOfType(UIPopupContainer.class); UIPopupContainer pContainer2 = pContainer1.getChildById(UIDocViewerPopup); if (pContainer2 == null) { pContainer2 = pContainer1.addChild(UIPopupContainer.class, null, UIDocViewerPopup); } return pContainer2; } }
6,777
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
UIDocActivity.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/plugin/doc/UIDocActivity.java
/* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.social.plugin.doc; /** * Created by The eXo Platform SAS * Author : Zun * exo@exoplatform.com * Jul 23, 2010 */ public class UIDocActivity { private static final String IMAGE_PREFIX = "image/"; private static final String DOCUMENT_POSTFIX = "/pdf"; public static final String DOCLINK = "DOCLINK"; public static final String MESSAGE = "MESSAGE"; public static final String REPOSITORY = "REPOSITORY"; public static final String WORKSPACE = "WORKSPACE"; public static final String DOCNAME = "DOCNAME"; public static final String ID = "id"; public static final String DOCPATH = "DOCPATH"; public static final String LINK_PARAM = "link"; public static final String CONTENT_NAME = "contentName"; public static final String CONTENT_LINK = "contenLink"; public static final String IMAGE_PATH = "imagePath"; public static final String MIME_TYPE = "mimeType"; public static final String STATE = "state"; public static final String AUTHOR = "author"; public static final String DATE_CREATED = "dateCreated"; public static final String LAST_MODIFIED = "lastModified"; public static final String DOCUMENT_TYPE_LABEL= "docTypeLabel"; public static final String DOCUMENT_TITLE = "docTitle"; public static final String DOCUMENT_VERSION = "docVersion"; public static final String DOCUMENT_SUMMARY = "docSummary"; public static final String IS_SYMLINK = "isSymlink"; public static final String REPOSITORY_NAME = "repository"; public static final String WORKSPACE_NAME = "collaboration"; }
2,364
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocActivityChildPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/plugin/doc/notification/plugin/DocActivityChildPlugin.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.social.plugin.doc.notification.plugin; import java.util.Map; import org.exoplatform.commons.api.notification.NotificationContext; import org.exoplatform.commons.api.notification.model.ArgumentLiteral; import org.exoplatform.commons.api.notification.model.NotificationInfo; import org.exoplatform.commons.api.notification.plugin.AbstractNotificationChildPlugin; import org.exoplatform.commons.api.notification.service.template.TemplateContext; import org.exoplatform.commons.notification.template.TemplateUtils; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; public class DocActivityChildPlugin extends AbstractNotificationChildPlugin { public final static ArgumentLiteral<String> ACTIVITY_ID = new ArgumentLiteral<String>(String.class, "activityId"); public static final String ID = "DOC_ACTIVITY"; private ExoSocialActivity activity = null; public DocActivityChildPlugin(InitParams initParams) { super(initParams); } @Override public String makeContent(NotificationContext ctx) { try { ActivityManager activityM = CommonsUtils.getService(ActivityManager.class); NotificationInfo notification = ctx.getNotificationInfo(); String language = getLanguage(notification); TemplateContext templateContext = new TemplateContext(ID, language); String activityId = notification.getValueOwnerParameter(ACTIVITY_ID.getKey()); activity = activityM.getActivity(activityId); if (activity.isComment()) { activity = activityM.getParentActivity(activity); } templateContext.put("ACTIVITY", activity.getTitle()); // String content = TemplateUtils.processGroovy(templateContext); return content; } catch (Exception e) { return (activity != null) ? activity.getTitle() : ""; } } public String getActivityParamValue(String key) { Map<String, String> params = activity.getTemplateParams(); if (params != null) { return params.get(key) != null ? params.get(key) : ""; } return ""; } @Override public String getId() { return ID; } @Override public boolean isValid(NotificationContext ctx) { return false; } }
3,061
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
SpaceCustomizationService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/space/customization/SpaceCustomizationService.java
package org.exoplatform.social.space.customization; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.jcr.ImportUUIDBehavior; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.commons.utils.ExoProperties; import org.exoplatform.container.PortalContainer; import org.exoplatform.container.component.RequestLifeCycle; import org.exoplatform.container.configuration.ConfigurationManager; import org.exoplatform.portal.config.DataStorage; import org.exoplatform.portal.config.UserACL; import org.exoplatform.portal.config.UserPortalConfigService; import org.exoplatform.portal.config.model.Application; import org.exoplatform.portal.config.model.ApplicationType; import org.exoplatform.portal.config.model.Container; import org.exoplatform.portal.config.model.ModelObject; import org.exoplatform.portal.config.model.Page; import org.exoplatform.portal.config.model.PortalConfig; import org.exoplatform.portal.mop.SiteKey; import org.exoplatform.portal.mop.navigation.NavigationContext; import org.exoplatform.portal.mop.page.PageContext; import org.exoplatform.portal.mop.page.PageKey; import org.exoplatform.portal.mop.page.PageService; import org.exoplatform.portal.mop.page.PageState; import org.exoplatform.portal.pom.spi.portlet.Portlet; import org.exoplatform.portal.pom.spi.portlet.Preference; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.impl.DMSConfiguration; import org.exoplatform.services.cms.impl.DMSRepositoryConfiguration; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.deployment.DeploymentDescriptor; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.IdentityConstants; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.space.SpaceApplication; import org.exoplatform.social.core.space.SpaceTemplate; import org.exoplatform.social.core.space.SpaceUtils; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.social.core.space.spi.SpaceTemplateService; public class SpaceCustomizationService { final static private Log LOG = ExoLogger.getExoLogger(SpaceCustomizationService.class); final static private String GROUPS_PATH = "groupsPath"; private static final String SPACE_GROUP_ID_PREFERENCE = "{spaceGroupId}"; private static final String SPACE_NEW_HOME_PAGE_TEMPLATE = "custom space"; private static final String SCV_PORTLEt_NAME = "SingleContentViewer"; private static final String ACTIVITY_FOLDER_UPLOAD_NAME = "Activity Stream Documents"; private SessionProviderService sessionProviderService; private NodeHierarchyCreator nodeHierarchyCreator = null; private DMSConfiguration dmsConfiguration = null; private RepositoryService repositoryService = null; private ConfigurationManager configurationManager = null; private DataStorage dataStorageService = null; PageService pageService = null; private UserPortalConfigService userPortalConfigService = null; private SpaceService spaceService = null; private SpaceTemplateService spaceTemplateService = null; private UserACL userACL = null; private String groupsPath; public SpaceCustomizationService(DataStorage dataStorageService_, PageService pageService_, UserPortalConfigService userPortalConfigService_, SessionProviderService sessionProviderService_, NodeHierarchyCreator nodeHierarchyCreator_, DMSConfiguration dmsConfiguration_, RepositoryService repositoryService_, ConfigurationManager configurationManager_, UserACL userACL_) { this.nodeHierarchyCreator = nodeHierarchyCreator_; this.dmsConfiguration = dmsConfiguration_; this.repositoryService = repositoryService_; this.userACL = userACL_; this.configurationManager = configurationManager_; this.sessionProviderService = sessionProviderService_; this.dataStorageService = dataStorageService_; this.pageService = pageService_; this.userPortalConfigService = userPortalConfigService_; groupsPath = nodeHierarchyCreator.getJcrPath(GROUPS_PATH); if (groupsPath.lastIndexOf("/") == groupsPath.length() - 1) { groupsPath = groupsPath.substring(0, groupsPath.lastIndexOf("/")); } } public void editSpaceDriveViewPermissions(String viewNodeName, String permission) throws RepositoryException { if (LOG.isDebugEnabled()) { LOG.debug("Trying to add permission " + permission + " for ECMS view " + viewNodeName); } String viewsPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_VIEWS_PATH); ManageableRepository manageableRepository = repositoryService.getCurrentRepository(); DMSRepositoryConfiguration dmsRepoConfig = dmsConfiguration.getConfig(); Session session = manageableRepository.getSystemSession(dmsRepoConfig.getSystemWorkspace()); Node viewHomeNode = (Node) session.getItem(viewsPath); if (viewHomeNode.hasNode(viewNodeName)) { Node contentNode = viewHomeNode.getNode(viewNodeName); String contentNodePermissions = contentNode.getProperty("exo:accessPermissions").getString(); contentNode.setProperty("exo:accessPermissions", contentNodePermissions.concat(",").concat(permission)); viewHomeNode.save(); if (LOG.isDebugEnabled()) { LOG.debug("Permission " + permission + " added with success to ECMS view " + viewNodeName); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Can not find view node: " + viewNodeName); } } } /* * (non-Javadoc) * @see org.exoplatform.services.deployment.DeploymentPlugin#deploy(org. * exoplatform.services.jcr.ext.common.SessionProvider) */ public void deployContentToSpaceDrive(SessionProvider sessionProvider, String spaceId, DeploymentDescriptor deploymentDescriptor) throws Exception { String sourcePath = deploymentDescriptor.getSourcePath(); LOG.info("Deploying '" + sourcePath + "'content to '" + spaceId + "' Space JCR location"); // sourcePath should start with: war:/, jar:/, classpath:/, file:/ Boolean cleanupPublication = deploymentDescriptor.getCleanupPublication(); InputStream inputStream = configurationManager.getInputStream(sourcePath); ManageableRepository repository = repositoryService.getCurrentRepository(); Session session = sessionProvider.getSession(deploymentDescriptor.getTarget().getWorkspace(), repository); String targetNodePath = deploymentDescriptor.getTarget().getNodePath(); if (targetNodePath.indexOf("/") == 0) { targetNodePath = targetNodePath.replaceFirst("/", ""); } if (targetNodePath.lastIndexOf("/") == targetNodePath.length() - 1) { targetNodePath = targetNodePath.substring(0, targetNodePath.lastIndexOf("/")); } // if target path contains folders, then create them if (!targetNodePath.equals("")) { Node spaceRootNode = (Node) session.getItem(groupsPath + spaceId); Utils.makePath(spaceRootNode, targetNodePath, NodetypeConstant.NT_UNSTRUCTURED); } String fullTargetNodePath = groupsPath + spaceId + "/" + targetNodePath; Node parentTargetNode = (Node) session.getItem(fullTargetNodePath); NodeIterator nodeIterator = parentTargetNode.getNodes(); List<String> initialChildNodesUUID = new ArrayList<String>(); List<String> initialChildNodesNames = new ArrayList<String>(); while (nodeIterator.hasNext()) { Node node = nodeIterator.nextNode(); String uuid = null; try { uuid = node.getUUID(); } catch (Exception exception) { // node is not referenceable continue; } initialChildNodesUUID.add(uuid); initialChildNodesNames.add(node.getName()); } session.importXML(fullTargetNodePath, inputStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW); parentTargetNode = (Node) session.getItem(fullTargetNodePath); nodeIterator = parentTargetNode.getNodes(); List<ExtendedNode> newChildNodesUUID = new ArrayList<ExtendedNode>(); while (nodeIterator.hasNext()) { ExtendedNode childNode = (ExtendedNode) nodeIterator.nextNode(); String uuid = null; try { uuid = childNode.getUUID(); } catch (Exception exception) { // node is not referenceable continue; } // determines wether this is a new node or not if (!initialChildNodesUUID.contains(uuid)) { if (initialChildNodesNames.contains(childNode.getName())) { LOG.info(childNode.getName() + " already exists under " + fullTargetNodePath + ". This node will not be imported!"); childNode.remove(); } else { newChildNodesUUID.add(childNode); } } } String spaceMembershipManager = userACL.getAdminMSType() + ":" + spaceId; for (ExtendedNode extendedNode : newChildNodesUUID) { if (extendedNode.isNodeType(NodetypeConstant.EXO_PRIVILEGEABLE)) { extendedNode.clearACL(); } else if (extendedNode.canAddMixin(NodetypeConstant.EXO_PRIVILEGEABLE)) { extendedNode.addMixin("exo:privilegeable"); extendedNode.clearACL(); } else { throw new IllegalStateException("Can't change permissions on node imported to the added Space."); } extendedNode.setPermission(IdentityConstants.ANY, new String[] { PermissionType.READ }); extendedNode.setPermission(spaceMembershipManager, PermissionType.ALL); if (cleanupPublication) { /** * This code allows to cleanup the publication lifecycle in the target * folder after importing the data. By using this, the publication live * revision property will be re-initialized and the content will be set * as published directly. Thus, the content will be visible in front * side. */ if (extendedNode.hasProperty("publication:liveRevision") && extendedNode.hasProperty("publication:currentState")) { LOG.info("\"" + extendedNode.getName() + "\" publication lifecycle has been cleaned up"); extendedNode.setProperty("publication:liveRevision", ""); extendedNode.setProperty("publication:currentState", "published"); } } } session.save(); session.logout(); LOG.info(deploymentDescriptor.getSourcePath() + " is deployed succesfully into " + fullTargetNodePath); } public void createSpaceHomePage(String spacePrettyName, String spaceGroupId, ExoProperties welcomeSCVCustomPreferences) { RequestLifeCycle.begin(PortalContainer.getInstance()); try { LOG.info("Updating '" + spaceGroupId + "' Space Home Page"); // creates the new home page Space space = getSpaceService().getSpaceByGroupId(spaceGroupId); if (space == null) { throw new IllegalStateException("Can't find space with group id " + spaceGroupId); } String spaceType = space.getType(); SpaceTemplateService spaceTemplateService = getSpaceTemplateService(); SpaceTemplate spaceTemplate = spaceTemplateService.getSpaceTemplateByName(spaceType); if (spaceTemplate == null) { LOG.warn("Could not find space template:{}. Space home page will not be created for space:{}.", spaceType, spacePrettyName); return; } SpaceApplication homeApplication = spaceTemplate.getSpaceHomeApplication(); if (homeApplication == null) { LOG.warn("Could not find home application for template:{}. Space home page will not be created for space:{}.", spaceType, spacePrettyName); return; } String portletName = homeApplication.getPortletName(); String pageName = PortalConfig.GROUP_TYPE + "::" + spaceGroupId + "::" + portletName; Page oldSpaceHomePage = dataStorageService.getPage(pageName); PageContext pageContext = pageService.loadPage(PageKey.parse(oldSpaceHomePage.getPageId())); pageContext.update(oldSpaceHomePage); // creates the customized home page for the space and set few fields // with values from the old home page Page customSpaceHomePage = userPortalConfigService.createPageTemplate(SPACE_NEW_HOME_PAGE_TEMPLATE, PortalConfig.GROUP_TYPE, spaceGroupId); customSpaceHomePage.setTitle(oldSpaceHomePage.getTitle()); customSpaceHomePage.setName(oldSpaceHomePage.getName()); customSpaceHomePage.setAccessPermissions(oldSpaceHomePage.getAccessPermissions()); customSpaceHomePage.setEditPermission(oldSpaceHomePage.getEditPermission()); customSpaceHomePage.setOwnerType(PortalConfig.GROUP_TYPE); customSpaceHomePage.setOwnerId(spaceGroupId); // needs to populate the accessPermissions list to all children: // containers and applications editChildrenAccesPermisions(customSpaceHomePage.getChildren(), customSpaceHomePage.getAccessPermissions()); // dataStorageService.save(customSpaceHomePage); // mandatory preference "Space_URL" should be added to the home page // applications editSpaceURLPreference(customSpaceHomePage.getChildren(), spacePrettyName); // gets the welcome SingleContentViewer Portlet Application<Portlet> welcomeSCVPortlet = getPortletApplication(customSpaceHomePage.getChildren(), SCV_PORTLEt_NAME); // configures the welcome SingleContentViewer Portlet editSCVPreference(welcomeSCVPortlet, spaceGroupId, welcomeSCVCustomPreferences); // NavigationContext navContext = SpaceUtils.createGroupNavigation(spaceGroupId); SiteKey siteKey = navContext.getKey(); PageKey pageKey = new PageKey(siteKey, customSpaceHomePage.getName()); PageState pageState = new PageState( customSpaceHomePage.getTitle(), customSpaceHomePage.getDescription(), customSpaceHomePage.isShowMaxWindow(), customSpaceHomePage.getFactoryId(), customSpaceHomePage.getAccessPermissions() != null ? Arrays.asList(customSpaceHomePage.getAccessPermissions()) : null, customSpaceHomePage.getEditPermission(), customSpaceHomePage.getMoveAppsPermissions() != null ? Arrays.asList(customSpaceHomePage.getMoveAppsPermissions()) : null, customSpaceHomePage.getMoveContainersPermissions() != null ? Arrays.asList(customSpaceHomePage.getMoveContainersPermissions()) : null); pageService.savePage(new PageContext(pageKey, pageState)); dataStorageService.save(customSpaceHomePage); } catch (Exception e) { LOG.error("Error while customizing the Space home page for space: " + spaceGroupId, e); } finally { try { RequestLifeCycle.end(); } catch (Exception e) { LOG.warn("An exception has occurred while proceed RequestLifeCycle.end() : " + e.getMessage()); } } } public SpaceService getSpaceService() { if (this.spaceService == null) { this.spaceService = (SpaceService) PortalContainer.getInstance().getComponentInstanceOfType(SpaceService.class); } return this.spaceService; } public SpaceTemplateService getSpaceTemplateService() { if (this.spaceTemplateService == null) { this.spaceTemplateService = CommonsUtils.getService(SpaceTemplateService.class); } return this.spaceTemplateService; } public void createSpaceDefaultFolders(String groupId) throws Exception { Node parentNode; SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); ManageableRepository currentRepository = repositoryService.getCurrentRepository(); String workspaceName = currentRepository.getConfiguration().getDefaultWorkspaceName(); Session session = sessionProvider.getSession(workspaceName, currentRepository); String groupPath = nodeHierarchyCreator.getJcrPath("groupsPath"); String spaceParentPath = groupPath + groupId + "/Documents"; if (!session.itemExists(spaceParentPath)) { throw new IllegalStateException("Root node of space '" + spaceParentPath + "' doesn't exist"); } parentNode = (Node) session.getItem(spaceParentPath); if (!parentNode.hasNode(ACTIVITY_FOLDER_UPLOAD_NAME)) { parentNode.addNode(ACTIVITY_FOLDER_UPLOAD_NAME); session.save(); } } private void editSCVPreference(Application<Portlet> selectedPortlet, String prefValue, ExoProperties welcomeSCVCustomPreferences) throws Exception { // loads the scv preferences Portlet prefs = dataStorageService.load(selectedPortlet.getState(), ApplicationType.PORTLET); if (prefs == null) { if (LOG.isDebugEnabled()) { LOG.debug("The portlet prefs == null : portlet application " + selectedPortlet.getId()); } prefs = new Portlet(); } // edits the nodeIdentifier preference for (String preferenceName : welcomeSCVCustomPreferences.keySet()) { String preferenceValue = welcomeSCVCustomPreferences.get(preferenceName); if (preferenceValue.contains(SPACE_GROUP_ID_PREFERENCE)) { preferenceValue = preferenceValue.replace(SPACE_GROUP_ID_PREFERENCE, prefValue); } prefs.putPreference(new Preference(preferenceName, preferenceValue, false)); } } @SuppressWarnings("unchecked") private void editSpaceURLPreference(List<ModelObject> children, String prefValue) throws Exception { if (children == null || children.size() == 0) { if (LOG.isDebugEnabled()) { LOG.debug("Can not get a portlet application from children.\nChildren == null or have no items"); } } // parses the children list for (ModelObject modelObject : children) { // if a container, check for its children if (modelObject instanceof Container) { editSpaceURLPreference(((Container) modelObject).getChildren(), prefValue); } else { // if a portlet application, set the preference value if (modelObject instanceof Application && ((Application<?>) modelObject).getType().equals(ApplicationType.PORTLET)) { Application<Portlet> application = (Application<Portlet>) modelObject; Portlet portletPreference = dataStorageService.load(application.getState(), ApplicationType.PORTLET); if (portletPreference == null) { portletPreference = new Portlet(); } portletPreference.putPreference(new Preference(SpaceUtils.SPACE_URL, prefValue, false)); } } } } @SuppressWarnings("unchecked") private Application<Portlet> getPortletApplication(List<ModelObject> children, String portletName) throws Exception { if (children == null || children.size() == 0) { if (LOG.isDebugEnabled()) { LOG.debug("Can not get a portlet application from children.\nChildren == null or have no items"); } } for (ModelObject modelObject : children) { Application<Portlet> selectedApplication = null; if (modelObject instanceof Container) { selectedApplication = getPortletApplication(((Container) modelObject).getChildren(), portletName); } else { if (modelObject instanceof Application && ((Application<?>) modelObject).getType().equals(ApplicationType.PORTLET)) { Application<Portlet> application = (Application<Portlet>) modelObject; String portletId = this.dataStorageService.getId(application.getState()); if (portletId.endsWith("/" + portletName)) { selectedApplication = application; } } } if (selectedApplication != null) { return selectedApplication; } } return null; } @SuppressWarnings("unchecked") private void editChildrenAccesPermisions(List<ModelObject> children, String[] accessPermissions) { if (children != null && children.size() > 0) { for (ModelObject modelObject : children) { if (modelObject instanceof Container) { ((Container) modelObject).setAccessPermissions(accessPermissions); editChildrenAccesPermisions(((Container) modelObject).getChildren(), accessPermissions); } else { if (modelObject instanceof Application && ((Application<?>) modelObject).getType().equals(ApplicationType.PORTLET)) { Application<Portlet> application = (Application<Portlet>) modelObject; application.setAccessPermissions(accessPermissions); } } } } } }
22,600
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
XMLDeploymentPlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/space/customization/plugin/XMLDeploymentPlugin.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.social.space.customization.plugin; import java.util.Iterator; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ObjectParameter; import org.exoplatform.services.deployment.DeploymentDescriptor; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.space.SpaceListenerPlugin; import org.exoplatform.social.core.space.spi.SpaceLifeCycleEvent; import org.exoplatform.social.space.customization.SpaceCustomizationService; public class XMLDeploymentPlugin extends SpaceListenerPlugin { /** The init params. */ private InitParams initParams; private SpaceCustomizationService spaceCustomizationService = null; /** The log. */ private static final Log LOG = ExoLogger.getLogger(XMLDeploymentPlugin.class); /** * Instantiates a new XML deployment plugin. * * @param initParams * the init params * @param spaceCustomizationService * the space customization service * @param nodeHierarchyCreator * the nodeHierarchyCreator service */ public XMLDeploymentPlugin(InitParams initParams, SpaceCustomizationService spaceCustomizationService, NodeHierarchyCreator nodeHierarchyCreator) { this.spaceCustomizationService = spaceCustomizationService; this.initParams = initParams; } @Override public void spaceCreated(SpaceLifeCycleEvent lifeCycleEvent) { SessionProvider sessionProvider = SessionProvider.createSystemProvider(); try { Iterator<?> iterator = initParams.getObjectParamIterator(); while (iterator.hasNext()) { ObjectParameter objectParameter = (ObjectParameter) iterator.next(); DeploymentDescriptor deploymentDescriptor = (DeploymentDescriptor) objectParameter.getObject(); spaceCustomizationService.deployContentToSpaceDrive(sessionProvider, lifeCycleEvent.getSpace().getGroupId(), deploymentDescriptor); } } catch (Exception e) { LOG.error("An unexpected problem occurs while deploying contents", e); } finally { sessionProvider.close(); } } @Override public void applicationActivated(SpaceLifeCycleEvent arg0) {} @Override public void applicationAdded(SpaceLifeCycleEvent arg0) {} @Override public void applicationDeactivated(SpaceLifeCycleEvent arg0) {} @Override public void applicationRemoved(SpaceLifeCycleEvent arg0) {} @Override public void grantedLead(SpaceLifeCycleEvent arg0) {} @Override public void joined(SpaceLifeCycleEvent arg0) {} @Override public void left(SpaceLifeCycleEvent arg0) {} @Override public void revokedLead(SpaceLifeCycleEvent arg0) {} @Override public void spaceRemoved(SpaceLifeCycleEvent arg0) {} @Override public void spaceRenamed(SpaceLifeCycleEvent event) {} @Override public void spaceDescriptionEdited(SpaceLifeCycleEvent event) {} @Override public void spaceAvatarEdited(SpaceLifeCycleEvent event) {} @Override public void spaceAccessEdited(SpaceLifeCycleEvent event) { } @Override public void addInvitedUser(SpaceLifeCycleEvent event) { } @Override public void addPendingUser(SpaceLifeCycleEvent event) { } @Override public void spaceBannerEdited(SpaceLifeCycleEvent event) { } }
4,173
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CustomizeSpaceFolderListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/space/customization/listeners/CustomizeSpaceFolderListener.java
package org.exoplatform.social.space.customization.listeners; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.space.SpaceListenerPlugin; import org.exoplatform.social.core.space.spi.SpaceLifeCycleEvent; import org.exoplatform.social.space.customization.SpaceCustomizationService; public class CustomizeSpaceFolderListener extends SpaceListenerPlugin { private SpaceCustomizationService spaceCustomizationService; private static final Log LOG = ExoLogger.getExoLogger(CustomizeSpaceDriveListener.class); public CustomizeSpaceFolderListener(SpaceCustomizationService spaceCustomizationService) { this.spaceCustomizationService = spaceCustomizationService; } @Override public void spaceCreated(SpaceLifeCycleEvent event) { String groupId = event.getSpace().getGroupId(); try { spaceCustomizationService.createSpaceDefaultFolders(groupId); } catch (Exception e) { LOG.error("Can not create default folder for space : " + groupId, e); } } @Override public void applicationActivated(SpaceLifeCycleEvent event) { } @Override public void applicationAdded(SpaceLifeCycleEvent event) { } @Override public void applicationDeactivated(SpaceLifeCycleEvent event) { } @Override public void applicationRemoved(SpaceLifeCycleEvent event) { } @Override public void grantedLead(SpaceLifeCycleEvent event) { } @Override public void joined(SpaceLifeCycleEvent event) { } @Override public void left(SpaceLifeCycleEvent event) { } @Override public void revokedLead(SpaceLifeCycleEvent event) { } @Override public void spaceRemoved(SpaceLifeCycleEvent event) { } @Override public void spaceRenamed(SpaceLifeCycleEvent event) { } @Override public void spaceDescriptionEdited(SpaceLifeCycleEvent event) { } @Override public void spaceAvatarEdited(SpaceLifeCycleEvent event) { } @Override public void spaceAccessEdited(SpaceLifeCycleEvent event) { } @Override public void addInvitedUser(SpaceLifeCycleEvent event) { } @Override public void addPendingUser(SpaceLifeCycleEvent event) { } @Override public void spaceBannerEdited(SpaceLifeCycleEvent event) { } }
2,308
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CustomizeSpaceDriveListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/space/customization/listeners/CustomizeSpaceDriveListener.java
package org.exoplatform.social.space.customization.listeners; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValueParam; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.space.SpaceListenerPlugin; import org.exoplatform.social.core.space.impl.SpaceServiceImpl; import org.exoplatform.social.core.space.spi.SpaceLifeCycleEvent; import org.exoplatform.social.space.customization.SpaceCustomizationService; public class CustomizeSpaceDriveListener extends SpaceListenerPlugin { private static final String SPACE_DRIVE_VIEW = "space.drive.view"; private SpaceCustomizationService spaceCustomizationService = null; private String viewNodeName = null; private static final Log LOG = ExoLogger.getExoLogger(CustomizeSpaceDriveListener.class); public CustomizeSpaceDriveListener(SpaceCustomizationService spaceCustomizationService_, InitParams params) { this.spaceCustomizationService = spaceCustomizationService_; ValueParam viewParamName = params.getValueParam(SPACE_DRIVE_VIEW); if (viewParamName != null) { viewNodeName = viewParamName.getValue(); } else { LOG.warn("No such property found: " + SPACE_DRIVE_VIEW + "\nPlease make sure to have the correct ECMS view name."); } } @Override public void spaceCreated(SpaceLifeCycleEvent event) { String groupId = event.getSpace().getGroupId(); String permission = SpaceServiceImpl.MANAGER + ":" + groupId; try { if (viewNodeName != null) { spaceCustomizationService.editSpaceDriveViewPermissions(viewNodeName, permission); } else { if (LOG.isDebugEnabled()) { LOG.debug("Can not edit view's permissions for view node: null"); } } } catch (Exception e) { LOG.error("Can not edit view's permission for space drive: " + groupId, e); } } @Override public void applicationActivated(SpaceLifeCycleEvent event) {} @Override public void applicationAdded(SpaceLifeCycleEvent event) {} @Override public void applicationDeactivated(SpaceLifeCycleEvent event) {} @Override public void applicationRemoved(SpaceLifeCycleEvent event) {} @Override public void grantedLead(SpaceLifeCycleEvent event) {} @Override public void joined(SpaceLifeCycleEvent event) {} @Override public void left(SpaceLifeCycleEvent event) {} @Override public void revokedLead(SpaceLifeCycleEvent event) {} @Override public void spaceRemoved(SpaceLifeCycleEvent event) {} @Override public void spaceRenamed(SpaceLifeCycleEvent event) {} @Override public void spaceDescriptionEdited(SpaceLifeCycleEvent event) {} @Override public void spaceAvatarEdited(SpaceLifeCycleEvent event) {} @Override public void spaceAccessEdited(SpaceLifeCycleEvent event) { } @Override public void addInvitedUser(SpaceLifeCycleEvent event) { } @Override public void addPendingUser(SpaceLifeCycleEvent event) { } @Override public void spaceBannerEdited(SpaceLifeCycleEvent event) { } }
3,108
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CustomizeSpaceHomePageListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/space/customization/listeners/CustomizeSpaceHomePageListener.java
package org.exoplatform.social.space.customization.listeners; import java.util.HashMap; import java.util.Map; import org.exoplatform.commons.utils.ExoProperties; import org.exoplatform.container.xml.InitParams; import org.exoplatform.social.core.space.SpaceListenerPlugin; import org.exoplatform.social.core.space.spi.SpaceLifeCycleEvent; import org.exoplatform.social.space.customization.SpaceCustomizationService; /** * @author <a href="mailto:anouar.chattouna@exoplatform.com">Anouar * Chattouna</a> * @version $Revision$ */ public class CustomizeSpaceHomePageListener extends SpaceListenerPlugin { private ExoProperties welcomeSCVCustomPreferences = null; private SpaceCustomizationService spaceCustomizationService = null; private Map<String, Boolean> spaceIds = new HashMap<String, Boolean>(); public CustomizeSpaceHomePageListener(SpaceCustomizationService spaceCustomizationService_, InitParams params) { this.spaceCustomizationService = spaceCustomizationService_; this.welcomeSCVCustomPreferences = params.getPropertiesParam("welcomeSCVCustomPreferences").getProperties(); } @Override public void spaceCreated(SpaceLifeCycleEvent spaceLifeCycleEvent) { spaceIds.put(spaceLifeCycleEvent.getSpace().getGroupId(), true); } @Override public void applicationActivated(SpaceLifeCycleEvent event) {} @Override public void applicationAdded(SpaceLifeCycleEvent spaceLifeCycleEvent) { // Workaround : Unfortunately the 'spaceCreated' listener is called // before the creation of space's pages&navigations, so the Home page // isn't accessible and couldn't be modified there. // To be sure that pages are created when calling // 'spaceCustomizationService.createSpaceHomePage', we have added this // instruction in 'applicationAdded'. // To be sure that this will be called once, when space is created, we // used 'spaceIds' map String spaceGroupId = spaceLifeCycleEvent.getSpace().getGroupId(); Boolean spaceCreated = spaceIds.get(spaceGroupId); if (spaceCreated == null || !spaceCreated) { return; } spaceIds.put(spaceGroupId, false); String spacePrettyName = spaceLifeCycleEvent.getSpace().getPrettyName(); spaceCustomizationService.createSpaceHomePage(spacePrettyName, spaceGroupId, welcomeSCVCustomPreferences); } @Override public void applicationDeactivated(SpaceLifeCycleEvent event) {} @Override public void applicationRemoved(SpaceLifeCycleEvent event) {} @Override public void grantedLead(SpaceLifeCycleEvent event) {} @Override public void joined(SpaceLifeCycleEvent event) {} @Override public void left(SpaceLifeCycleEvent event) {} @Override public void revokedLead(SpaceLifeCycleEvent event) {} @Override public void spaceRemoved(SpaceLifeCycleEvent event) {} @Override public void spaceRenamed(SpaceLifeCycleEvent event) {} @Override public void spaceDescriptionEdited(SpaceLifeCycleEvent event) {} @Override public void spaceAvatarEdited(SpaceLifeCycleEvent event) {} @Override public void spaceAccessEdited(SpaceLifeCycleEvent event) { } @Override public void addInvitedUser(SpaceLifeCycleEvent event) { } @Override public void addPendingUser(SpaceLifeCycleEvent event) { } @Override public void spaceBannerEdited(SpaceLifeCycleEvent event) { } }
3,378
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ComposerImageControllerRest.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/social/ckeditor/rest/ComposerImageControllerRest.java
package org.exoplatform.social.ckeditor.rest; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.annotation.security.RolesAllowed; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.service.rest.RestChecker; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; @Path("/composer/image") public class ComposerImageControllerRest implements ResourceContainer { private static final Log LOG = ExoLogger.getLogger(ComposerImageControllerRest.class); private UploadService uploadService; private ActivityManager activityManager; public ComposerImageControllerRest(UploadService uploadService, ActivityManager activityManager, InitParams params) { this.uploadService = uploadService; this.activityManager = activityManager; } @GET @Path("new") @RolesAllowed("users") public Response createNewUploadId(@QueryParam("uploadId") String uploadId) { RestChecker.checkAuthenticatedRequest(); uploadService.addUploadLimit(uploadId, activityManager.getMaxUploadSize()); return Response.ok(String.valueOf(activityManager.getMaxUploadSize())).build(); } @GET @Path("thumbnail") @RolesAllowed("users") public Response getUploadedImageThumbnail(@Context Request request, @QueryParam("uploadId") String uploadId) { RestChecker.checkAuthenticatedRequest(); UploadResource uploadResource = uploadService.getUploadResource(uploadId); if (uploadResource == null) { return Response.status(404).build(); } EntityTag eTag = new EntityTag(uploadId); Response.ResponseBuilder builder = request.evaluatePreconditions(eTag); if (builder == null) { String storeLocation = uploadResource.getStoreLocation(); File file = new File(storeLocation); if (!file.exists()) { LOG.warn("File doesn't exists " + storeLocation); return Response.serverError().build(); } InputStream stream = null; try { stream = new FileInputStream(file); builder = Response.ok(stream, uploadResource.getMimeType()) .header(HttpHeaders.CONTENT_LENGTH, stream.available()); } catch (FileNotFoundException e) { LOG.warn("File {} doesn't exists " + storeLocation); return Response.serverError().build(); } catch (IOException e) { LOG.warn("Error reading file {} content", storeLocation, e); return Response.serverError().build(); } } builder.tag(eTag); CacheControl cc = new CacheControl(); cc.setMaxAge(86400); return builder.cacheControl(cc).build(); } }
3,222
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ECMSActivityFileStoragePlugin.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/ECMSActivityFileStoragePlugin.java
package org.exoplatform.wcm.ext.component.activity; import java.io.FileInputStream; import java.io.InputStream; import java.util.Calendar; import java.util.HashMap; import javax.jcr.ItemExistsException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.xml.InitParams; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.documents.AutoVersionService; import org.exoplatform.services.cms.impl.Utils; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodeLocation; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.activity.model.ActivityFile; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.provider.SpaceIdentityProvider; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.social.core.storage.ActivityFileStoragePlugin; import org.exoplatform.upload.UploadResource; import org.exoplatform.upload.UploadService; /** * This plugin will store activity attachment files in JCR */ public class ECMSActivityFileStoragePlugin extends ActivityFileStoragePlugin { private static final String ACTIVITY_FOLDER_UPLOAD_NAME = "Activity Stream Documents"; private NodeHierarchyCreator nodeHierarchyCreator; private RepositoryService repositoryService; private SpaceService spaceService; private UploadService uploadService; private SessionProviderService sessionProviderService; private AutoVersionService autoVersionService; public ECMSActivityFileStoragePlugin(SpaceService spaceService, NodeHierarchyCreator nodeHierarchyCreator, RepositoryService repositoryService, UploadService uploadService, SessionProviderService sessionProviderService, InitParams initParams, AutoVersionService autoVersionService) { super(initParams); this.spaceService = spaceService; this.nodeHierarchyCreator = nodeHierarchyCreator; this.repositoryService = repositoryService; this.uploadService = uploadService; this.sessionProviderService = sessionProviderService; this.autoVersionService = autoVersionService; } @Override public void storeAttachments(ExoSocialActivity activity, Identity streamOwner, ActivityFile... attachments) throws Exception { if (attachments == null || attachments.length == 0) { return; } for (ActivityFile activityFile : attachments) { UploadResource uploadedResource = uploadService.getUploadResource(activityFile.getUploadId()); if (uploadedResource == null) { throw new IllegalStateException("Cannot attach uploaded file " + activityFile.getUploadId() + ", it may not exist"); } Node parentNode; SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); ManageableRepository currentRepository = repositoryService.getCurrentRepository(); String workspaceName = currentRepository.getConfiguration().getDefaultWorkspaceName(); Session session = sessionProvider.getSession(workspaceName, currentRepository); if (streamOwner.getProviderId().equals(SpaceIdentityProvider.NAME)) { Space space = spaceService.getSpaceByPrettyName(streamOwner.getRemoteId()); String groupPath = nodeHierarchyCreator.getJcrPath("groupsPath"); String spaceParentPath = groupPath + space.getGroupId() + "/Documents"; if (!session.itemExists(spaceParentPath)) { throw new IllegalStateException("Root node of space '" + spaceParentPath + "' doesn't exist"); } parentNode = (Node) session.getItem(spaceParentPath); if (!parentNode.hasNode(ACTIVITY_FOLDER_UPLOAD_NAME)) { parentNode.addNode(ACTIVITY_FOLDER_UPLOAD_NAME); session.save(); } } else { String remoteUser = ConversationState.getCurrent().getIdentity().getUserId(); if (org.apache.commons.lang3.StringUtils.isBlank(remoteUser)) { throw new IllegalStateException("Remote user is empty"); } Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, remoteUser); String publicPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_USER_PUBLIC_ALIAS); if (userNode == null || !userNode.hasNode(publicPath)) { throw new IllegalStateException("User '" + remoteUser + "' hasn't public folder"); } parentNode = userNode.getNode(publicPath); if (!parentNode.hasNode(ACTIVITY_FOLDER_UPLOAD_NAME)) { parentNode.addNode(ACTIVITY_FOLDER_UPLOAD_NAME); session.save(); } } Node parentUploadNode = null; if (StringUtils.isNotBlank(activityFile.getDestinationFolder())) { SessionProvider sessionProviderUser = sessionProviderService.getSessionProvider(null); session = sessionProviderUser.getSession(workspaceName, currentRepository); StringBuilder folderExpression = new StringBuilder(); folderExpression.append("repository").append(":").append(workspaceName).append(":").append(activityFile.getDestinationFolder()); parentUploadNode = NodeLocation.getNodeByExpression(folderExpression.toString()); }else { parentUploadNode = parentNode.getNode(ACTIVITY_FOLDER_UPLOAD_NAME); } String nodeName = Utils.cleanName(uploadedResource.getFileName()); if (!parentUploadNode.getDefinition().allowsSameNameSiblings()) { nodeName = getFileName(parentUploadNode, nodeName, nodeName, 1); } Node node = null; try { node = parentUploadNode.addNode(nodeName, NodetypeConstant.NT_FILE); } catch (ItemExistsException e) { nodeName = getFileName(parentUploadNode, nodeName, nodeName, 1); node = parentUploadNode.addNode(nodeName, NodetypeConstant.NT_FILE); } node.setProperty("exo:title", uploadedResource.getFileName()); Node resourceNode = node.addNode("jcr:content", "nt:resource"); resourceNode.setProperty("jcr:mimeType", uploadedResource.getMimeType()); resourceNode.setProperty("jcr:lastModified", Calendar.getInstance()); String fileDiskLocation = uploadedResource.getStoreLocation(); try (InputStream inputStream = new FileInputStream(fileDiskLocation)) { resourceNode.setProperty("jcr:data", inputStream); session.save(); node = (Node) session.getItem(node.getPath()); } autoVersionService.autoVersion(node); if (activity.getTemplateParams() == null) { activity.setTemplateParams(new HashMap<>()); } concatenateParam(activity.getTemplateParams(), "REPOSITORY", "repository"); concatenateParam(activity.getTemplateParams(), "WORKSPACE", "collaboration"); concatenateParam(activity.getTemplateParams(), "DOCPATH", node.getPath()); concatenateParam(activity.getTemplateParams(), "docTitle", uploadedResource.getFileName()); concatenateParam(activity.getTemplateParams(), "mimeType", resourceNode.getProperty("jcr:mimeType").getString()); concatenateParam(activity.getTemplateParams(), "id", node.isNodeType("mix:referenceable") ? node.getUUID() : ""); uploadService.removeUploadResource(activityFile.getUploadId()); } } public void attachExistingFile(ExoSocialActivity activity, Identity streamOwner, ActivityFile attachment) throws Exception { if (attachment == null || attachment.getId() == null) { return; } SessionProvider sessionProvider = SessionProviderService.getSystemSessionProvider(); ManageableRepository currentRepository = repositoryService.getCurrentRepository(); String workspaceName = currentRepository.getConfiguration().getDefaultWorkspaceName(); Session session = sessionProvider.getSession(workspaceName, currentRepository); Node attachmentNode = session.getNodeByUUID(attachment.getId()); Node resourceNode = attachmentNode.getNode("jcr:content"); if (activity.getTemplateParams() == null) { activity.setTemplateParams(new HashMap<>()); } String nodeTitle; try { nodeTitle = org.exoplatform.ecm.webui.utils.Utils.getTitle(attachmentNode); } catch (Exception e1) { nodeTitle = attachmentNode.getName(); } concatenateParam(activity.getTemplateParams(), "REPOSITORY", "repository"); concatenateParam(activity.getTemplateParams(), "WORKSPACE", "collaboration"); concatenateParam(activity.getTemplateParams(), "DOCPATH", attachmentNode.getPath()); concatenateParam(activity.getTemplateParams(), "docTitle", nodeTitle); concatenateParam(activity.getTemplateParams(), "mimeType", resourceNode.getProperty("jcr:mimeType").getString()); concatenateParam(activity.getTemplateParams(), "id", attachmentNode.isNodeType("mix:referenceable") ? attachmentNode.getUUID() : ""); } private String getFileName(Node parentUploadNode, String originalNodeName, String nodeName, int fileIndex) throws RepositoryException { if (parentUploadNode.hasNode(nodeName)) { int pointIndex = originalNodeName.lastIndexOf('.'); if (pointIndex > 0) { nodeName = originalNodeName.substring(0, pointIndex) + "(" + fileIndex + ")" + originalNodeName.substring(pointIndex); } else { nodeName = originalNodeName + "(" + fileIndex + ")"; } return getFileName(parentUploadNode, originalNodeName, nodeName, ++fileIndex); } return nodeName; } }
10,309
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileUIActivity.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/FileUIActivity.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity; public class FileUIActivity { public static final String[] EMPTY_ARRAY = new String[0]; public static final String SEPARATOR_REGEX = "\\|@\\|"; private static final String NEW_DATE_FORMAT = "hh:mm:ss MMM d, yyyy"; public static final String ID = "id"; public static final String CONTENT_LINK = "contenLink"; public static final String MESSAGE = "MESSAGE"; public static final String ACTIVITY_STATUS = "description"; public static final String IMAGE_PATH = "imagePath"; public static final String MIME_TYPE = "mimeType"; public static final String STATE = "state"; public static final String AUTHOR = "author"; public static final String DATE_CREATED = "dateCreated"; public static final String LAST_MODIFIED = "lastModified"; public static final String DOCUMENT_TYPE_LABEL = "docTypeLabel"; public static final String DOCUMENT_TITLE = "docTitle"; public static final String DOCUMENT_VERSION = "docVersion"; public static final String DOCUMENT_SUMMARY = "docSummary"; public static final String IS_SYSTEM_COMMENT = "isSystemComment"; public static final String SYSTEM_COMMENT = "systemComment"; public static final String NODE_PATH = "nodePath"; public static final String ONE_DRIVE_PROVIDER_ID = "onedrive"; public static final String GOOGLE_DRIVE_PROVIDER_ID = "gdrive"; public static final String ONE_DRIVE_ICON = "uiIcon-onedrive"; public static final String GOOGLE_DRIVE_ICON = "uiIcon-gdrive"; }
2,541
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentUIActivity.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/ContentUIActivity.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; public class ContentUIActivity { private static final String NEW_DATE_FORMAT = "hh:mm:ss MMM d, yyyy"; private static final Log LOG = ExoLogger.getLogger(ContentUIActivity.class); public static final String ID = "id"; public static final String CONTENT_LINK = "contenLink"; public static final String MESSAGE = "MESSAGE"; public static final String REPOSITORY = "REPOSITORY"; public static final String WORKSPACE = "WORKSPACE"; public static final String CONTENT_NAME = "contentName"; public static final String IMAGE_PATH = "imagePath"; public static final String MIME_TYPE = "mimeType"; public static final String STATE = "state"; public static final String AUTHOR = "author"; public static final String DATE_CREATED = "dateCreated"; public static final String LAST_MODIFIED = "lastModified"; public static final String DOCUMENT_TYPE_LABEL = "docTypeLabel"; public static final String DOCUMENT_TITLE = "docTitle"; public static final String DOCUMENT_VERSION = "docVersion"; public static final String DOCUMENT_SUMMARY = "docSummary"; public static final String IS_SYSTEM_COMMENT = "isSystemComment"; public static final String SYSTEM_COMMENT = "systemComment"; public static final String MIX_VERSION = "mix:versionable"; public static final String NODE_PATH = "nodePath"; public static final String NODE_UUID = "nodeUUID"; public static final String PERMISSION = "permission"; public static final String COMMENT = "comment"; public static final String THUMBNAIL = "thumbnail"; }
2,653
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
TagActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/TagActivityListener.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import java.util.List; import javax.jcr.Node; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; public class TagActivityListener extends Listener<Node, String>{ private static String TAG_ADDED_BUNDLE = "SocialIntegration.messages.tagAdded"; private static String TAG_REMOVED_BUNDLE = "SocialIntegration.messages.tagRemoved"; private static String TAGS_ADDED_BUNDLE = "SocialIntegration.messages.tagsAdded"; private static String TAGS_REMOVED_BUNDLE = "SocialIntegration.messages.tagsRemoved"; private static String DOCUMENT_TAG_REMOVED = "Document.event.TagRemoved"; private static String DOCUMENT_TAG_ADDED = "Document.event.TagAdded"; private static final String TAG_ACTION_COMMENT = "files:spaces.TAG_ACTION_COMMENT"; @Override public void onEvent(Event<Node, String> event) throws Exception { ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); String eventName = event.getEventName(); if (! (eventName.equals(DOCUMENT_TAG_ADDED) || eventName.equals(DOCUMENT_TAG_REMOVED)) || !activityManager.isActivityTypeEnabled(TAG_ACTION_COMMENT)) { return; } Node currentNode = event.getSource(); String tagValue = event.getData(); int tagSepIndex = tagValue.indexOf(","); boolean isMultiple = tagSepIndex>0 && !tagValue.endsWith(","); String bundleMessage ; if (isMultiple) { bundleMessage = DOCUMENT_TAG_ADDED.equals(eventName)?TAGS_ADDED_BUNDLE:TAGS_REMOVED_BUNDLE; }else { bundleMessage = DOCUMENT_TAG_ADDED.equals(eventName)?TAG_ADDED_BUNDLE:TAG_REMOVED_BUNDLE; } Utils.postActivity(currentNode, bundleMessage, false, true, tagValue, ""); LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); List<Node> links = linkManager.getAllLinks(currentNode, NodetypeConstant.EXO_SYMLINK); for(Node link: links){ if(link.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)){ ExoSocialActivity linkTagActivity = Utils.postActivity(link, bundleMessage, false, true, tagValue, ""); if (linkTagActivity!=null) { ActivityTypeUtils.attachActivityId(link, linkTagActivity.getId()); } } } } }
3,564
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
AttachmentActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/AttachmentActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; /* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import javax.jcr.Node; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler Attachment Add/Remove event * 14 Jan 2013 */ public class AttachmentActivityListener extends Listener<Node, Node> { private static String ATTACH_ADDED_BUNDLE = "SocialIntegration.messages.attachmentAdded"; private static String ATTACH_REMOVED_BUNDLE = "SocialIntegration.messages.attachmentRemoved"; @Override public void onEvent(Event<Node, Node> event) throws Exception { String eventName = event.getEventName(); //Consider the attachment is added or removed String messageBundle = eventName.equals(ActivityCommonService.ATTACH_ADDED_ACTIVITY)?ATTACH_ADDED_BUNDLE:ATTACH_REMOVED_BUNDLE; Node currentNode = event.getSource(); Utils.postActivity(currentNode, messageBundle, false, true, "", ""); } }
1,871
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileCreateActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/FileCreateActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.social.core.manager.ActivityManager; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class FileCreateActivityListener extends Listener<Object, Node> { private static final String RESOURCE_BUNDLE_KEY_CREATED_BY = "SocialIntegration.messages.createdBy"; private static final String FILES_SPACES = "files:spaces"; private static final String CREATION_COMMENT = "files:spaces.CREATION_COMMENT"; /** * Instantiates a new post create content event listener. */ public FileCreateActivityListener() { } @Override public void onEvent(Event<Object, Node> event) throws Exception { Node currentNode = event.getData(); ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); if(activityManager.isActivityTypeEnabled(FILES_SPACES) && activityManager.isActivityTypeEnabled(CREATION_COMMENT)) { Utils.postFileActivity(currentNode, RESOURCE_BUNDLE_KEY_CREATED_BY, true, true, "", ""); } } }
1,977
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocumentUpdateActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/DocumentUpdateActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.chain.Context; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.documents.DocumentUpdateActivityHandler; import org.exoplatform.services.listener.Event; public class DocumentUpdateActivityListener extends FileUpdateActivityListener { protected final DocumentService documentService; /** * Instantiates a new document update activity listener. */ public DocumentUpdateActivityListener() { documentService = (DocumentService) ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(DocumentService.class); } @Override public void onEvent(Event<Context, String> event) throws Exception { List<DocumentUpdateActivityHandler> handlers = documentService.getDocumentEditorProviders().stream().map(p -> p.getDocumentUpdateHandler()).collect(Collectors.toList()); for(DocumentUpdateActivityHandler handler : handlers) { if(handler.handleDocumentUpdateEvent(event)) { return; } } super.onEvent(event); } }
1,296
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileUpdateActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/FileUpdateActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import java.util.Arrays; import java.util.List; import javax.jcr.*; import org.apache.commons.chain.Context; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.ext.action.InvocationContext; import org.exoplatform.services.jcr.dataflow.persistent.PersistedPropertyData; import org.exoplatform.services.jcr.datamodel.ValueData; import org.exoplatform.services.jcr.impl.core.AuditPropertyImpl; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class FileUpdateActivityListener extends Listener<Context, String> { private static final Log LOG = ExoLogger.getLogger(FileUpdateActivityListener.class); private static final String UPDATE_COMMENT = "files:spaces.UPDATE_COMMENT"; private String[] editedField = {"exo:title", "exo:summary", "exo:language", "dc:title", "dc:description", "dc:creator", "dc:source", "jcr:data"}; private String[] bundleMessage = {"SocialIntegration.messages.rename", "SocialIntegration.messages.editSummary", "SocialIntegration.messages.editLanguage", "SocialIntegration.messages.editTitle", "SocialIntegration.messages.editDescription", "SocialIntegration.messages.singleCreator", "SocialIntegration.messages.addSource", "SocialIntegration.messages.editFile"}; private String[] bundleRemoveMessage = {"SocialIntegration.messages.removeName", "SocialIntegration.messages.removeSummary", "SocialIntegration.messages.removeLanguage", "SocialIntegration.messages.removeTitle", "SocialIntegration.messages.removeDescription", "SocialIntegration.messages.removeCreator", "SocialIntegration.messages.addSource", "SocialIntegration.messages.editFile"}; private boolean[] needUpdate = {true, true, false, true, true, false, false, true}; private int consideredFieldCount = editedField.length; /** * Instantiates a new post edit content event listener. */ public FileUpdateActivityListener() { } @Override public void onEvent(Event<Context, String> event) throws Exception { ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); if(!activityManager.isActivityTypeEnabled(UPDATE_COMMENT)) { return; } Context context = event.getSource(); Property currentProperty = (Property) context.get(InvocationContext.CURRENT_ITEM); Property previousProperty = (Property) context.get(InvocationContext.PREVIOUS_ITEM); String propertyName = event.getData(); StringBuilder oldValueBuilder = new StringBuilder(); StringBuilder newValueBuilder = new StringBuilder(); StringBuilder commentValueBuilder = new StringBuilder(); Node currentNode = currentProperty.getParent(); try { if(!propertyName.equals(NodetypeConstant.JCR_DATA)) { if(currentProperty.getDefinition().isMultiple()){ Value[] values = currentProperty.getValues(); if(values != null && values.length > 0) { for (Value value : values) { newValueBuilder.append(value.getString()).append(ActivityCommonService.METADATA_VALUE_SEPERATOR); commentValueBuilder.append(value.getString()).append(", "); } if(newValueBuilder.length() >= ActivityCommonService.METADATA_VALUE_SEPERATOR.length()) newValueBuilder.delete(newValueBuilder.length() - ActivityCommonService.METADATA_VALUE_SEPERATOR.length(), newValueBuilder.length()); if(commentValueBuilder.length() >=2) commentValueBuilder.delete(commentValueBuilder.length() - 2, commentValueBuilder.length()); } List<ValueData> valueList = ((PersistedPropertyData) ((AuditPropertyImpl) previousProperty).getData()).getValues(); if(valueList != null) { for (ValueData value : valueList) { oldValueBuilder.append(value.toString()).append(ActivityCommonService.METADATA_VALUE_SEPERATOR); } if(oldValueBuilder.length() >= ActivityCommonService.METADATA_VALUE_SEPERATOR.length()) oldValueBuilder.delete(oldValueBuilder.length() - ActivityCommonService.METADATA_VALUE_SEPERATOR.length(), oldValueBuilder.length()); } } else { newValueBuilder = new StringBuilder(currentProperty.getString()); commentValueBuilder = newValueBuilder; if(previousProperty != null && previousProperty.getValue() != null) oldValueBuilder = new StringBuilder(previousProperty.getValue().getString()); } } }catch (Exception e) { LOG.info("Cannot get old value"); } String newValue = newValueBuilder.toString().trim(); String oldValue = oldValueBuilder.toString().trim(); String commentValue = commentValueBuilder.toString().trim(); if(currentNode.isNodeType(NodetypeConstant.NT_RESOURCE)) currentNode = currentNode.getParent(); String resourceBundle = ""; boolean hit = false; for (int i=0; i< consideredFieldCount; i++) { if (propertyName.equals(editedField[i])) { hit = true; if(newValue.length() > 0) { resourceBundle = bundleMessage[i]; //Post activity when update dc:creator property if(propertyName.equals(NodetypeConstant.DC_CREATOR)) { List<String> lstOld = Arrays.asList(oldValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR)); List<String> lstNew = Arrays.asList(newValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR)); String itemsRemoved = ""; int removedCount = 0; int addedCount = 0; StringBuffer sb = new StringBuffer(); for (String item : lstOld) { if(!lstNew.contains(item)) { sb.append(item).append(", "); removedCount++; } } if(sb.length() > 0) { itemsRemoved = sb.toString(); itemsRemoved = itemsRemoved.substring(0, itemsRemoved.length()-2); } sb.delete(0, sb.length()); String itemsAdded = ""; for (String item : lstNew) { if(!lstOld.contains(item)) { sb.append(item).append(", "); addedCount++; } } if(sb.length() > 0) { itemsAdded = sb.toString(); itemsAdded = itemsAdded.substring(0, itemsAdded.length()-2); } if(itemsRemoved.length() > 0 && itemsAdded.length() > 0){ resourceBundle = (removedCount > 1) ? "SocialIntegration.messages.removeMultiCreator" : "SocialIntegration.messages.removeCreator"; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, itemsRemoved, ""); resourceBundle = (lstNew.size() > 1) ? "SocialIntegration.messages.multiCreator" : "SocialIntegration.messages.singleCreator"; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, commentValue, ""); break; } else if(itemsRemoved.length() > 0) { resourceBundle = (removedCount > 1) ? "SocialIntegration.messages.removeMultiCreator" : "SocialIntegration.messages.removeCreator"; newValue = itemsRemoved; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, newValue, ""); break; } else if(itemsAdded.length() > 0) { resourceBundle = (commentValue.split(",").length > 1) ? "SocialIntegration.messages.multiCreator" : "SocialIntegration.messages.singleCreator"; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, commentValue, ""); break; } } //Post activity when update dc:source property if(propertyName.equals(NodetypeConstant.DC_SOURCE)) { List<String> lstOld = Arrays.asList(oldValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR)); List<String> lstNew = Arrays.asList(newValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR)); String itemsRemoved = ""; int removedCount = 0; int addedCount = 0; StringBuffer sb = new StringBuffer(); for (String item : lstOld) { if(!lstNew.contains(item)) { sb.append(item).append(", "); removedCount++; } } if(sb.length() > 0) { itemsRemoved = sb.toString(); itemsRemoved = itemsRemoved.substring(0, itemsRemoved.length()-2); } sb.delete(0, sb.length()); String itemsAdded = ""; for (String item : lstNew) { if(!lstOld.contains(item)) { sb.append(item).append(", "); addedCount++; } } if(sb.length() > 0) { itemsAdded = sb.toString(); itemsAdded = itemsAdded.substring(0, itemsAdded.length()-2); } if(itemsRemoved.length() > 0 && itemsAdded.length() > 0){ resourceBundle = (removedCount > 1) ? "SocialIntegration.messages.removeMultiSource" : "SocialIntegration.messages.removeSource"; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, itemsRemoved, ""); resourceBundle = (addedCount > 1) ? "SocialIntegration.messages.addMultiSource" : "SocialIntegration.messages.addSource"; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, itemsAdded, ""); break; } else if(itemsRemoved.length() > 0) { resourceBundle = (removedCount > 1) ? "SocialIntegration.messages.removeMultiSource" : "SocialIntegration.messages.removeSource"; newValue = itemsRemoved; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, newValue, ""); break; } else if(itemsAdded.length() > 0) { resourceBundle = (addedCount > 1) ? "SocialIntegration.messages.addMultiSource" : "SocialIntegration.messages.addSource"; newValue = itemsAdded; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, newValue, ""); break; } } Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, commentValue, ""); break; } else if(!propertyName.equals(NodetypeConstant.EXO_LANGUAGE)){ //Remove the property resourceBundle = bundleRemoveMessage[i]; if(propertyName.equals(NodetypeConstant.DC_CREATOR)) { resourceBundle = (oldValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR).length > 1) ? "SocialIntegration.messages.removeMultiCreator" : "SocialIntegration.messages.removeCreator"; } else if(propertyName.equals(NodetypeConstant.DC_SOURCE)) { resourceBundle = (oldValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR).length > 1) ? "SocialIntegration.messages.removeMultiSource" : "SocialIntegration.messages.removeSource"; } if(propertyName.equals(NodetypeConstant.DC_SOURCE) || propertyName.equals(NodetypeConstant.DC_CREATOR)) { commentValue = oldValue.replaceAll(ActivityCommonService.METADATA_VALUE_SEPERATOR, ", "); } Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, commentValue, ""); break; } else break; } } if(!hit && propertyName.startsWith("dc:") && !propertyName.equals("dc:date")) { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); String dcProperty = propertyName; try { dcProperty = portletRequestContext.getApplicationResourceBundle().getString("ElementSet.dialog.label." + propertyName.substring(propertyName.lastIndexOf(":") + 1, propertyName.length())); } catch(Exception ex) { LOG.info("Cannot get propertyName"); } if (newValue.length() > 0) { resourceBundle = "SocialIntegration.messages.updateMetadata"; } else { resourceBundle = "SocialIntegration.messages.removeMetadata"; } commentValue = dcProperty + ActivityCommonService.METADATA_VALUE_SEPERATOR + commentValue; Utils.postFileActivity(currentNode, resourceBundle, false, true, commentValue, ""); } } }
14,140
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentMovedActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/ContentMovedActivityListener.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.manager.ActivityManager; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler for ContentMoved event * 21 Jan 2013 */ public class ContentMovedActivityListener extends Listener<Node, String>{ private static final String CONTENT_MOVED_BUNDLE = "SocialIntegration.messages.contentMoved"; private static final String FILE_MOVED_BUNDLE = "SocialIntegration.messages.fileMoved"; private static final String MOVE_CONTENT = "files:spaces.MOVE_COMMENT"; @Override public void onEvent(Event<Node, String> event) throws Exception { ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); if(!activityManager.isActivityTypeEnabled(MOVE_CONTENT)) { return; } Node currentNode = event.getSource(); String target = event.getData(); if(!currentNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) Utils.postActivity(currentNode, CONTENT_MOVED_BUNDLE, false, true, target, ""); else Utils.postFileActivity(currentNode, FILE_MOVED_BUNDLE, false, true, target, ""); } }
2,203
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CategoryActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/CategoryActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; /* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import javax.jcr.Node; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler Category Add/Remove event * 15 Jan 2013 */ public class CategoryActivityListener extends Listener<Node, String> { private static String CATEGORY_ADDED_BUNDLE = "SocialIntegration.messages.categoryAdded"; private static String CATEGORY_REMOVED_BUNDLE = "SocialIntegration.messages.categoryRemoved"; @Override public void onEvent(Event<Node, String> event) throws Exception { Node currentNode = event.getSource(); String categoryName = event.getData(); String eventName = event.getEventName(); String bundleMessage = eventName.equals(ActivityCommonService.CATEGORY_ADDED_ACTIVITY) ? CATEGORY_ADDED_BUNDLE:CATEGORY_REMOVED_BUNDLE; if (eventName.equals(ActivityCommonService.CATEGORY_ADDED_ACTIVITY) || eventName.equals(ActivityCommonService.CATEGORY_REMOVED_ACTIVITY)) { Utils.postActivity(currentNode, bundleMessage, false, true, categoryName, ""); } } }
2,063
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CommentUpdatedActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/CommentUpdatedActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; import java.util.Map; import javax.jcr.Node; /* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.wcm.ext.component.activity.ContentUIActivity; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler Comment Updated event * 30 Jan 2013 */ public class CommentUpdatedActivityListener extends Listener<Node, Node> { @Override public void onEvent(Event<Node, Node> event) throws Exception { Node commentNode = event.getData(); String commentContent = ""; if (commentNode.hasProperty("exo:commentContent")) { try { commentContent = commentNode.getProperty("exo:commentContent").getValue().getString(); }catch (Exception e) { commentContent =null; } } if (commentContent==null) return; try { Utils.setAvatarUrl(commentNode); }catch (Exception e) { commentNode.setProperty("exo:commentorAvatar", Utils.DEFAULT_AVATAR); } commentContent = commentContent.replaceAll("&#64;","@"); String activityID = ActivityTypeUtils.getActivityId(commentNode); ExoContainer container = ExoContainerContext.getCurrentContainer(); ActivityManager activityManager = (ActivityManager) container.getComponentInstanceOfType(ActivityManager.class); ExoSocialActivity commentActivity =null; try { commentActivity = activityManager.getActivity(activityID); }catch (Exception e) { //CommentActivity's deleted do not update anymore return; } Map<String, String> paramsMap = commentActivity.getTemplateParams(); commentActivity.setTitle(commentContent); paramsMap.put(ContentUIActivity.SYSTEM_COMMENT, commentContent); commentActivity.setTemplateParams(paramsMap); activityManager.updateActivity(commentActivity); commentContent = Utils.processMentions(commentContent); commentNode.setProperty("exo:commentContent", commentContent); commentNode.save(); commentNode.getSession().save(); } }
3,157
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/ActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; import org.apache.commons.lang3.StringUtils; import org.exoplatform.ecm.webui.utils.PermissionUtil; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.organization.Membership; import org.exoplatform.services.organization.OrganizationService; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.social.core.activity.ActivityLifeCycleEvent; import org.exoplatform.social.core.activity.ActivityListenerPlugin; import org.exoplatform.social.core.activity.model.ActivityFile; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.wcm.ext.component.document.service.IShareDocumentService; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import java.util.Collection; import java.util.List; public class ActivityListener extends ActivityListenerPlugin { private static final Log LOG = ExoLogger.getLogger(ActivityListener.class); /** The constant COMMENT. */ private static final String COMMENT = ""; /** The constant POST_ACTIVITY. */ private static final Boolean POST_ACTIVITY = false; /** The constant ACTIVITY PARAMS. */ private static final String SEPARATOR_REGEX = "\\|@\\|"; private static final String NODE_UUID_PARAM = "id"; private final SpaceService spaceService; private final SessionProviderService sessionProviderService; private final RepositoryService repositoryService; private final IShareDocumentService shareDocumentService; private final OrganizationService organizationService; public ActivityListener(SpaceService spaceService, SessionProviderService sessionProviderService, RepositoryService repositoryService, IShareDocumentService shareDocumentService, OrganizationService organizationService) { this.spaceService = spaceService; this.sessionProviderService = sessionProviderService; this.repositoryService = repositoryService; this.shareDocumentService = shareDocumentService; this.organizationService = organizationService; } @Override public void saveActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { shareActivityFilesToSpace(activityLifeCycleEvent); } private void shareActivityFilesToSpace(ActivityLifeCycleEvent activityLifeCycleEvent) { ExoSocialActivity activity = activityLifeCycleEvent.getActivity(); List<ActivityFile> filesToShare = activity.getFiles(); String ids = activity.getTemplateParams().get(NODE_UUID_PARAM); if (StringUtils.isBlank(ids)){ return; } String[] uuidNodes = ids.split(SEPARATOR_REGEX); String streamOwner = activity.getStreamOwner(); Space targetSpace = spaceService.getSpaceByPrettyName(streamOwner); if (targetSpace != null) { Node node; String[] permissions = new String[] { PermissionType.READ }; String organizationalIdentity; SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); ManageableRepository currentRepository; String workspaceName; Session session = null; try { currentRepository = repositoryService.getCurrentRepository(); workspaceName = currentRepository.getConfiguration().getDefaultWorkspaceName(); session = sessionProvider.getSession(workspaceName, currentRepository); if (session != null) { Collection<Membership> memberships = null; String currentUserId = ConversationState.getCurrent().getIdentity().getUserId(); try { memberships = organizationService.getMembershipHandler() .findMembershipsByUserAndGroup(currentUserId, targetSpace.getGroupId()); } catch (Exception e) { LOG.warn("Error getting memberships by user (" + currentUserId + ") and group (" + targetSpace.getGroupId() + ")", e); } if (memberships != null) { for (String nodeUuid : uuidNodes) { try { node = session.getNodeByUUID(nodeUuid); for (Membership membership : memberships) { organizationalIdentity = new MembershipEntry(membership.getGroupId(), membership.getMembershipType()).toString(); if (!PermissionUtil.hasPermissions(node, organizationalIdentity, permissions)) { // publish to shared folder shareDocumentService.publishDocumentToSpace(targetSpace.getGroupId(), node, COMMENT, PermissionType.READ, POST_ACTIVITY); break; } } } catch (RepositoryException e) { LOG.error("Error while sharing document to space. Node uuid: " + nodeUuid, e); } } } } } catch (RepositoryException e) { LOG.warn("Error while getting session for sharing files to the space: " + targetSpace.getGroupId(), e); } } } @Override public void updateActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { } @Override public void saveComment(ActivityLifeCycleEvent activityLifeCycleEvent) { } @Override public void updateComment(ActivityLifeCycleEvent activityLifeCycleEvent) { } @Override public void likeActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { } @Override public void likeComment(ActivityLifeCycleEvent activityLifeCycleEvent) { } }
6,387
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileRemovePropertyActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/FileRemovePropertyActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.manager.ActivityManager; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class FileRemovePropertyActivityListener extends Listener<Node, String> { private String[] removedField = {"exo:title", "dc:title", "dc:description", "dc:creator", "dc:source"}; private String[] bundleMessage = {"SocialIntegration.messages.removeName", "SocialIntegration.messages.removeTitle", "SocialIntegration.messages.removeDescription", "SocialIntegration.messages.removeCreator", "SocialIntegration.messages.removeSource"}; private boolean[] needUpdate = {true, true, false, false, false}; private int consideredFieldCount = removedField.length; private static final String REMOVE_PROPERTY = "files:spaces.REMOVE_PROPERTY"; /** * Instantiates a new post edit content event listener. */ public FileRemovePropertyActivityListener() { } @Override public void onEvent(Event<Node, String> event) throws Exception { ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); if(!activityManager.isActivityTypeEnabled(REMOVE_PROPERTY)) { return; } Node currentNode = event.getSource(); String propertyName = event.getData(); if(currentNode.isNodeType(NodetypeConstant.NT_RESOURCE)) currentNode = currentNode.getParent(); String resourceBundle = ""; for (int i=0; i< consideredFieldCount; i++) { if (propertyName.equals(removedField[i])) { resourceBundle = bundleMessage[i]; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, "", ""); break; } } } }
2,857
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentRevisionActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/ContentRevisionActivityListener.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler for Content's Revision changed event * 21 Jan 2013 */ public class ContentRevisionActivityListener extends Listener<Node, String>{ private static String REVISION_CHANGED_BUNDLE = "SocialIntegration.messages.revisionChanged"; @Override public void onEvent(Event<Node, String> event) throws Exception { Node currentNode = event.getSource(); String versionName = event.getData(); Utils.postActivity(currentNode, REVISION_CHANGED_BUNDLE, true, true, versionName, ""); } }
1,547
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CommentRemovedActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/CommentRemovedActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; /* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import javax.jcr.Node; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.social.core.manager.ActivityManager; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler Comment Removed event * 30 Jan 2013 */ public class CommentRemovedActivityListener extends Listener<Node, String> { @Override public void onEvent(Event<Node, String> event) throws Exception { Node commentNode = event.getSource(); Node sourceNode = commentNode.getParent().getParent(); String activityID = ActivityTypeUtils.getActivityId(sourceNode); String commentNodeActivityID = ActivityTypeUtils.getActivityId(commentNode); ExoContainer container = ExoContainerContext.getCurrentContainer(); ActivityManager activityManager = container.getComponentInstanceOfType(ActivityManager.class); try { activityManager.deleteComment(activityID, commentNodeActivityID); }catch (Exception e) { //CommentActivity's deleted do not update anymore return; } } }
2,083
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
PublicationStateActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/PublicationStateActivityListener.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * 17 Jan 2013 */ public class PublicationStateActivityListener extends Listener<Node, String> { private String[] handledState = {"pending", "approved", "staged", "published"}; private String bundlePrefix = "SocialIntegration.messages.stateChange."; @Override public void onEvent(Event<Node, String> event) throws Exception { String stateName = event.getData(); ActivityCommonService activityService = WCMCoreUtils.getService(ActivityCommonService.class); Node currentNode = event.getSource(); Node parent = currentNode.getParent(); for (int i=0; i< handledState.length; i++) { if (handledState[i].equals(stateName)) { if(!currentNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE) || (currentNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE) && activityService.isBroadcastNTFileEvents(currentNode))) Utils.postActivity(currentNode, bundlePrefix + handledState[i], true, true, "", ""); } } } }
2,246
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileAddPropertyActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/FileAddPropertyActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.*; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.application.portlet.PortletRequestContext; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class FileAddPropertyActivityListener extends Listener<Node, String> { private static final Log LOG = ExoLogger.getExoLogger(FileAddPropertyActivityListener.class); private static final String ADD_PROPERTY = "files:spaces.ADD_PROPERTY"; private String[] editedField = {"dc:title", "dc:description", "dc:creator", "dc:source"}; private String[] bundleMessage = {"SocialIntegration.messages.editTitle", "SocialIntegration.messages.editDescription", "SocialIntegration.messages.singleCreator", "SocialIntegration.messages.addSource"}; private boolean[] needUpdate = {false, false, false, false}; private int consideredFieldCount = editedField.length; /** * Instantiates a new post edit content event listener. */ public FileAddPropertyActivityListener() { } @Override public void onEvent(Event<Node, String> event) throws Exception { ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); if(!activityManager.isActivityTypeEnabled(ADD_PROPERTY)) { return; } Node currentNode = event.getSource(); String propertyName = event.getData(); StringBuilder newValueBuilder = new StringBuilder(); StringBuilder commentValueBuilder = new StringBuilder(); try { if(currentNode.getProperty(propertyName).getDefinition().isMultiple()){ Value[] values = currentNode.getProperty(propertyName).getValues(); if(values != null) { for (Value value : values) { newValueBuilder.append(value.getString()).append(ActivityCommonService.METADATA_VALUE_SEPERATOR); commentValueBuilder.append(value.getString()).append(", "); } if(newValueBuilder.length() >= ActivityCommonService.METADATA_VALUE_SEPERATOR.length()) newValueBuilder.delete(newValueBuilder.length() - ActivityCommonService.METADATA_VALUE_SEPERATOR.length(), newValueBuilder.length()); if(commentValueBuilder.length() >=2) commentValueBuilder.delete(commentValueBuilder.length() - 2, commentValueBuilder.length()); } } else { Property prop = currentNode.getProperty(propertyName); if (prop.getDefinition().getRequiredType() == PropertyType.BINARY) { newValueBuilder = new StringBuilder(); } else { newValueBuilder = new StringBuilder(currentNode.getProperty(propertyName).getString()); } } }catch (Exception e) { newValueBuilder = new StringBuilder(); commentValueBuilder = new StringBuilder(); } String newValue = newValueBuilder.toString().trim(); String commentValue = commentValueBuilder.toString().trim(); if(newValue != null && newValue.length() > 0) { if(currentNode.isNodeType(NodetypeConstant.NT_RESOURCE)) currentNode = currentNode.getParent(); String resourceBundle = ""; boolean hit = false; for (int i=0; i< consideredFieldCount; i++) { if (propertyName.equals(editedField[i])) { resourceBundle = bundleMessage[i]; if(propertyName.equals(NodetypeConstant.DC_CREATOR) && newValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR).length > 1) resourceBundle = "SocialIntegration.messages.multiCreator"; if(propertyName.equals(NodetypeConstant.DC_SOURCE) && newValue.split(ActivityCommonService.METADATA_VALUE_SEPERATOR).length > 1) resourceBundle = "SocialIntegration.messages.addMultiSource"; Utils.postFileActivity(currentNode, resourceBundle, needUpdate[i], true, commentValue, ""); hit = true; break; } } if(!hit && propertyName.startsWith("dc:") && !propertyName.equals("dc:date")) { PortletRequestContext portletRequestContext = WebuiRequestContext.getCurrentInstance(); String dcProperty = propertyName; try { dcProperty = portletRequestContext.getApplicationResourceBundle().getString("ElementSet.dialog.label." + propertyName.substring(propertyName.lastIndexOf(":") + 1, propertyName.length())); } catch(Exception ex) { LOG.info("cannot get property name"); } resourceBundle = "SocialIntegration.messages.updateMetadata"; resourceBundle = portletRequestContext.getApplicationResourceBundle().getString(resourceBundle); resourceBundle = resourceBundle.replace("{0}", dcProperty); resourceBundle = resourceBundle.replace("{1}", commentValue); Utils.postFileActivity(currentNode, resourceBundle, false, true, commentValue, ""); } } } }
6,142
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
CommentAddedActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/CommentAddedActivityListener.java
package org.exoplatform.wcm.ext.component.activity.listener; /* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.List; import javax.jcr.Node; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.activity.model.ExoSocialActivity; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler Comment Added event * 16 Jan 2013 */ public class CommentAddedActivityListener extends Listener<Node, Node> { @Override public void onEvent(Event<Node, Node> event) throws Exception { Node currentNode = event.getSource(); Node commentNode = event.getData(); String commentContent = ""; if (commentNode.hasProperty("exo:commentContent")) { try { commentContent = commentNode.getProperty("exo:commentContent").getValue().getString(); }catch (Exception e) { commentContent =null; } } if (commentContent==null) return; try { Utils.setAvatarUrl(commentNode); }catch (Exception e) { commentNode.setProperty("exo:commentorAvatar", Utils.DEFAULT_AVATAR); } commentContent = commentContent.replaceAll("&#64;","@"); ExoSocialActivity commentActivity; if(currentNode.isNodeType(NodetypeConstant.NT_FILE)) { commentActivity = Utils.postFileActivity(currentNode, commentContent, false, true, null, null); }else{ commentActivity= Utils.postActivity(currentNode, commentContent, false, false, null, null); } LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class); List<Node> links = linkManager.getAllLinks(currentNode, NodetypeConstant.EXO_SYMLINK); for(Node link: links){ if(link.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)){ ExoSocialActivity linkCommentActivity = Utils.postActivity(link, commentContent, false, false, null, null); if (commentActivity!=null) { ActivityTypeUtils.attachActivityId(link, linkCommentActivity.getId()); } } } if (commentActivity!=null) { ActivityTypeUtils.attachActivityId(commentNode, commentActivity.getId()); commentNode.getSession().save(); } commentContent = Utils.processMentions(commentContent); commentNode.setProperty("exo:commentContent", commentContent); commentNode.save(); commentNode.getSession().save(); } }
3,357
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
Utils.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/Utils.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import java.io.InputStream; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import javax.jcr.*; import org.apache.commons.lang3.StringUtils; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.commons.utils.ISO8601; import org.exoplatform.container.*; import org.exoplatform.container.xml.PortalContainerInfo; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.context.DocumentContext; import org.exoplatform.services.jcr.access.AccessControlEntry; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.jcr.impl.core.NodeImpl; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.resources.ResourceBundleService; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.*; import org.exoplatform.services.wcm.friendly.FriendlyService; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.services.wcm.webcontent.WebContentSchemaHandler; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.activity.model.ExoSocialActivityImpl; import org.exoplatform.social.core.application.SpaceActivityPublisher; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.model.Profile; import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; import org.exoplatform.social.core.identity.provider.SpaceIdentityProvider; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.service.LinkProvider; import org.exoplatform.social.core.space.SpaceUtils; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.wcm.ext.component.activity.ContentUIActivity; import org.exoplatform.wcm.ext.component.activity.FileUIActivity; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.ecms.css.*; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 18, 2011 */ public class Utils { private static final Log LOG = ExoLogger.getLogger(Utils.class); /** The Constant Activity Type */ public static final String CONTENT_SPACES = "contents:spaces"; public static final String FILE_SPACES = "files:spaces"; public static final String SHARE_FILE = "sharefiles:spaces"; public static final String SHARE_CONTENT = "sharecontents:spaces"; /** the publication:currentState property name */ public static final String CURRENT_STATE_PROP = "publication:currentState"; public static final String EXO_RESOURCES_URI = "/eXoSkin/skin/images/themes/default/Icons/TypeIcons/EmailNotificationIcons/"; public static final String ICON_FILE_EXTENSION = ".png"; public static final String DEFAULT_AVATAR = "/eXoSkin/skin/images/themes/default/social/skin/ShareImages/UserAvtDefault.png"; public static int MAX_SUMMARY_LINES_COUNT = 4; private static String MIX_COMMENT = "exo:activityComment"; private static String MIX_COMMENT_ID = "exo:activityCommentID"; public static int MAX_SUMMARY_CHAR_COUNT = 430; private static String activityType; private static final String CREATION_MESSAGE = "files:spaces.CREATION_COMMENT"; private static final String RENAME_COMMENT = "files:spaces.RENAME_COMMENT"; private static final String MOVE_COMMENT = "files:spaces.MOVE_COMMENT"; private static final String RESOURCE_BUNDLE_KEY_CREATED_BY = "SocialIntegration.messages.createdBy"; private static final String RESOURCE_BUNDLE_KEY_FILE_RENAMED = "SocialIntegration.messages.rename"; private static final String RESOURCE_BUNDLE_KEY_FILE_MOVED = "SocialIntegration.messages.fileMoved"; public static String getActivityType() { return activityType; } public static void setActivityType(String activityType) { Utils.activityType = activityType; } /** * Populate activity data with the data from Node * * @param node the node * @param activityOwnerId the owner id of the activity * @param activityMsgBundleKey the message bundle key of the activity * @return Map the mapped data */ public static Map<String, String> populateActivityData(Node node, String activityOwnerId, String activityMsgBundleKey) throws Exception { return populateActivityData(node, activityOwnerId, activityMsgBundleKey, false, null, null); } public static Map<String, String> populateActivityData(Node node, String activityOwnerId, String activityMsgBundleKey, boolean isComment, String systemComment, String perm) throws Exception { /** The date formatter. */ DateFormat dateFormatter = null; dateFormatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT); LinkManager linkManager = CommonsUtils.getService(LinkManager.class); if(node.canAddMixin(NodetypeConstant.MIX_REFERENCEABLE)){ node.addMixin(NodetypeConstant.MIX_REFERENCEABLE); node.save(); } // get activity data String repository = ((ManageableRepository) node.getSession().getRepository()).getConfiguration() .getName(); String workspace = node.getSession().getWorkspace().getName(); String illustrationImg; try{ illustrationImg = Utils.getIllustrativeImage(node); }catch(Exception ex){ illustrationImg=""; } String strDateCreated = ""; if (node.hasProperty(NodetypeConstant.EXO_DATE_CREATED)) { Calendar dateCreated = node.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate(); strDateCreated = dateFormatter.format(dateCreated.getTime()); } String strLastModified = ""; if (node.hasNode(NodetypeConstant.JCR_CONTENT)) { Node contentNode = node.getNode(NodetypeConstant.JCR_CONTENT); if (contentNode.hasProperty(NodetypeConstant.JCR_LAST_MODIFIED)) { Calendar lastModified = contentNode.getProperty(NodetypeConstant.JCR_LAST_MODIFIED) .getDate(); strLastModified = dateFormatter.format(lastModified.getTime()); } } activityOwnerId = activityOwnerId != null ? activityOwnerId : ""; // populate data to map object Map<String, String> activityParams = new HashMap<String, String>(); activityParams.put(ContentUIActivity.NODE_UUID, node.getUUID()); activityParams.put(ContentUIActivity.CONTENT_NAME, node.getName()); activityParams.put(ContentUIActivity.AUTHOR, activityOwnerId); activityParams.put(ContentUIActivity.DATE_CREATED, strDateCreated); activityParams.put(ContentUIActivity.LAST_MODIFIED, strLastModified); activityParams.put(ContentUIActivity.CONTENT_LINK, getContentLink(node)); activityParams.put(ContentUIActivity.ID, node.isNodeType(NodetypeConstant.MIX_REFERENCEABLE) ? node.getUUID() : ""); activityParams.put(ContentUIActivity.REPOSITORY, repository); activityParams.put(ContentUIActivity.WORKSPACE, workspace); activityParams.put(ContentUIActivity.MESSAGE, activityMsgBundleKey); activityParams.put(ContentUIActivity.MIME_TYPE, getMimeType(linkManager.isLink(node)?linkManager.getTarget(node, true):node)); activityParams.put(ContentUIActivity.IMAGE_PATH, illustrationImg); activityParams.put(ContentUIActivity.IMAGE_PATH, illustrationImg); if (isComment && StringUtils.isNotBlank(systemComment)) { activityParams.put(ContentUIActivity.IS_SYSTEM_COMMENT, String.valueOf(isComment)); activityParams.put(ContentUIActivity.SYSTEM_COMMENT, systemComment); } else { activityParams.put(ContentUIActivity.IS_SYSTEM_COMMENT, String.valueOf(false)); activityParams.put(ContentUIActivity.SYSTEM_COMMENT, ""); } activityParams.put(ContentUIActivity.PERMISSION, perm); activityParams.put(ContentUIActivity.COMMENT, systemComment); activityParams.put(ContentUIActivity.THUMBNAIL, getThumbnailUrl(node, repository, workspace) != null ? getThumbnailUrl(node, repository, workspace) : getDefaultThumbnailUrl(node)); activityParams.put(ContentUIActivity.NODE_PATH, node.getPath()); String nodeTitle = node.getName(); try { nodeTitle = org.exoplatform.ecm.webui.utils.Utils.getTitle(node); } catch (Exception e) { // Nothing to do } activityParams.put(ContentUIActivity.DOCUMENT_TITLE, nodeTitle); return activityParams; } private static String getDefaultThumbnailUrl(Node node) throws RepositoryException { LinkManager linkManager = CommonsUtils.getService(LinkManager.class); String cssClass = CssClassUtils.getCSSClassByFileNameAndFileType( node.getName(), getMimeType(linkManager.isLink(node)?linkManager.getTarget(node, true):node), CssClassManager.ICON_SIZE.ICON_64); if (cssClass.indexOf(CssClassIconFile.DEFAULT_CSS) > 0) { return CommonsUtils.getCurrentDomain() + EXO_RESOURCES_URI + "uiIcon64x64Templatent_file.png"; } return CommonsUtils.getCurrentDomain() + EXO_RESOURCES_URI + cssClass.split(" ")[0] + ICON_FILE_EXTENSION; } private static String getThumbnailUrl(Node node, String repository, String workspace) { try { LinkManager linkManager = CommonsUtils.getService(LinkManager.class); String mimeType = getMimeType(linkManager.isLink(node)?linkManager.getTarget(node, true):node); ExoContainer container = ExoContainerContext.getCurrentContainer(); PortalContainerInfo containerInfo = (PortalContainerInfo) container.getComponentInstanceOfType(PortalContainerInfo.class); String portalName = containerInfo.getContainerName(); String restContextName = org.exoplatform.ecm.webui.utils.Utils.getRestContextName(portalName); String preferenceWS = node.getSession().getWorkspace().getName(); String encodedPath = URLEncoder.encode(node.getPath(), "utf-8"); encodedPath = encodedPath.replaceAll ("%2F", "/"); if (mimeType.startsWith("image")) { return CommonsUtils.getCurrentDomain() + "/" + portalName + "/" + restContextName + "/thumbnailImage/custom/300x300/" + repository + "/" + preferenceWS + encodedPath; } else if (mimeType.indexOf("icon") >=0) { return getWebdavURL(node, repository, workspace); } else if (org.exoplatform.services.cms.impl.Utils.isSupportThumbnailView(mimeType)) { return CommonsUtils.getCurrentDomain() + "/" + portalName + "/" + restContextName + "/thumbnailImage/big/" + repository + "/" + preferenceWS + encodedPath; } else { return null; } } catch (Exception e) { LOG.debug("Cannot get thumbnail url"); } return StringUtils.EMPTY; } private static String getWebdavURL(Node contentNode, String repository, String workspace) throws Exception { FriendlyService friendlyService = CommonsUtils.getService(FriendlyService.class); String link = "#"; String portalName = PortalContainer.getCurrentPortalContainerName(); String restContextName = PortalContainer.getCurrentRestContextName(); if (contentNode.isNodeType("nt:frozenNode")) { String uuid = contentNode.getProperty("jcr:frozenUuid").getString(); Node originalNode = contentNode.getSession().getNodeByUUID(uuid); link = CommonsUtils.getCurrentDomain() + "/" + portalName + "/" + restContextName + "/jcr/" + repository + "/" + workspace + originalNode.getPath() + "?version=" + contentNode.getParent().getName(); } else { link = CommonsUtils.getCurrentDomain() + "/" + portalName + "/" + restContextName + "/jcr/" + repository + "/" + workspace + contentNode.getPath(); } return friendlyService.getFriendlyUri(link); } /** * see the postActivity(Node node, String activityMsgBundleKey, Boolean isSystemComment, String systemComment, String perm) */ public static void postActivity(Node node, String activityMsgBundleKey) throws Exception { postActivity(node, activityMsgBundleKey, false, false, null, null); } public static ExoSocialActivity createShareActivity(Node node, String activityMsgBundleKey, String activityType, String comments, String perm) throws Exception{ setActivityType(activityType); if(SHARE_FILE.equals(activityType)){ return postFileActivity(node,activityMsgBundleKey,false,false,comments, perm); }else if(SHARE_CONTENT.equals(activityType)){ return postActivity(node,activityMsgBundleKey,false,false,comments, perm); }else{ setActivityType(null); return postFileActivity(node,activityMsgBundleKey,false,false,comments, perm); } } /** * see the postFileActivity(Node node, String activityMsgBundleKey, Boolean isSystemComment, String systemComment, String perm) */ public static void postFileActivity(Node node, String activityMsgBundleKey) throws Exception { postFileActivity(node, activityMsgBundleKey, false, false, null, null); } /** * * @param node : activity raised from this source * @param activityMsgBundleKey * @param needUpdate * @param isSystemComment * @param systemComment the new value of System Posted activity, * if (isSystemComment) systemComment can not be set to null, set to empty string instead of. * @param perm the permission accorded for sharing file/content * @throws Exception */ public static ExoSocialActivity postActivity(Node node, String activityMsgBundleKey, boolean needUpdate, boolean isSystemComment, String systemComment, String perm) throws Exception { Object isSkipRaiseAct = DocumentContext.getCurrent() .getAttributes() .get(DocumentContext.IS_SKIP_RAISE_ACT); if (isSkipRaiseAct != null && Boolean.valueOf(isSkipRaiseAct.toString())) { return null; } ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); activityType = StringUtils.isNotEmpty(activityType) ? activityType : CONTENT_SPACES; if(! activityManager.isActivityTypeEnabled(activityType)) { return null; } // get services IdentityManager identityManager = CommonsUtils.getService(IdentityManager.class); ActivityCommonService activityCommonService = CommonsUtils.getService(ActivityCommonService.class); SpaceService spaceService = CommonsUtils.getService(SpaceService.class); // refine to get the valid node refineNode(node); // get owner String activityOwnerId = getActivityOwnerId(node); String nodeActivityID; ExoSocialActivity exa =null; if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); exa = activityManager.getActivity(nodeActivityID); }catch (Exception e){ LOG.info("No activity is deleted, return no related activity"); } } ExoSocialActivity activity = null ; String commentID; boolean commentFlag = false; if (node.isNodeType(MIX_COMMENT) && node.hasProperty(MIX_COMMENT_ID) && activityCommonService.isEditing(node)) { commentID = node.getProperty(MIX_COMMENT_ID).getString(); if (StringUtils.isNotBlank(commentID)) activity = activityManager.getActivity(commentID); commentFlag = (activity != null); } if (activity==null) { activity = createActivity(identityManager, activityOwnerId, node, activityMsgBundleKey, activityType, isSystemComment, systemComment, perm); setActivityType(null); } if (exa!=null) { if (commentFlag) { Map<String, String> paramsMap = activity.getTemplateParams(); String paramMessage = paramsMap.get(ContentUIActivity.MESSAGE); String paramContent = paramsMap.get(ContentUIActivity.SYSTEM_COMMENT); if (!StringUtils.isEmpty(paramMessage)) { paramMessage += ActivityCommonService.VALUE_SEPERATOR + activityMsgBundleKey; if (StringUtils.isEmpty(systemComment)) { paramContent += ActivityCommonService.VALUE_SEPERATOR + " "; }else { paramContent += ActivityCommonService.VALUE_SEPERATOR + systemComment; } } else { paramMessage = activityMsgBundleKey; paramContent = systemComment; } paramsMap.put(ContentUIActivity.MESSAGE, paramMessage); paramsMap.put(ContentUIActivity.SYSTEM_COMMENT, paramContent); activity.setTemplateParams(paramsMap); updateNotifyMessages(activity, activityMsgBundleKey, systemComment); activityManager.updateActivity(activity); } else { updateNotifyMessages(activity, activity.getTemplateParams().get(ContentUIActivity.MESSAGE), activity.getTemplateParams().get(ContentUIActivity.SYSTEM_COMMENT)); activityManager.saveComment(exa, activity); if (activityCommonService.isEditing(node)) { commentID = activity.getId(); if (node.canAddMixin(MIX_COMMENT)) node.addMixin(MIX_COMMENT); if (node.isNodeType(MIX_COMMENT)) node.setProperty(MIX_COMMENT_ID, commentID); } } if (needUpdate) { updateMainActivity(activityManager, node, exa); } return activity; }else { String spaceGroupName = getSpaceName(node); Space space = spaceService.getSpaceByGroupId(SpaceUtils.SPACE_GROUP + "/" + spaceGroupName); if (spaceGroupName != null && spaceGroupName.length() > 0 && space != null) { // post activity to space stream Identity spaceIdentity = identityManager.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName()); activityManager.saveActivityNoReturn(spaceIdentity, activity); } else if (activityOwnerId != null && activityOwnerId.length() > 0) { // post activity to user status stream Identity ownerIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, activityOwnerId); activityManager.saveActivityNoReturn(ownerIdentity, activity); } else { return null; } if (!StringUtils.isEmpty(activity.getId())) { ActivityTypeUtils.attachActivityId(node, activity.getId()); } updateMainActivity(activityManager, node, activity); if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); exa = activityManager.getActivity(nodeActivityID); } catch (Exception e) { LOG.info("No activity is deleted, return no related activity"); } if (exa != null && !commentFlag && isSystemComment) { activityManager.saveComment(exa, activity); if (activityCommonService.isEditing(node)) { commentID = activity.getId(); if (node.canAddMixin(MIX_COMMENT)) node.addMixin(MIX_COMMENT); if (node.isNodeType(MIX_COMMENT)) node.setProperty(MIX_COMMENT_ID, commentID); } } } return activity; } } /** * * @param node : activity raised from this source * @param activityMsgBundleKey * @param isComment * @param systemComment the new value of System Posted activity, * if (isSystemComment) systemComment can not be set to null, set to empty string instead of. * @throws Exception */ public static ExoSocialActivity postFileActivity(Node node, String activityMsgBundleKey, boolean needUpdate, boolean isComment, String systemComment, String perm) throws Exception { Object isSkipRaiseAct = DocumentContext.getCurrent() .getAttributes() .get(DocumentContext.IS_SKIP_RAISE_ACT); if (isSkipRaiseAct != null && Boolean.valueOf(isSkipRaiseAct.toString())) { return null; } ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); activityType = StringUtils.isNotEmpty(activityType) ? activityType : FILE_SPACES; if(! activityManager.isActivityTypeEnabled(activityType)) { return null; } // get services IdentityManager identityManager = CommonsUtils.getService(IdentityManager.class); ActivityCommonService activityCommonService = CommonsUtils.getService(ActivityCommonService.class); SpaceService spaceService = CommonsUtils.getService(SpaceService.class); // refine to get the valid node refineNode(node); // get owner String activityOwnerId = getActivityOwnerId(node); String nodeActivityID; ExoSocialActivity exa =null; if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); exa = activityManager.getActivity(nodeActivityID); }catch (Exception e){ LOG.info("No activity is deleted, return no related activity"); } } ExoSocialActivity activity = null ; String commentID; boolean commentFlag = false; if (node.isNodeType(MIX_COMMENT) && activityCommonService.isEditing(node)) { if (node.hasProperty(MIX_COMMENT_ID)) { commentID = node.getProperty(MIX_COMMENT_ID).getString(); if (StringUtils.isNotBlank(commentID)) activity = activityManager.getActivity(commentID); commentFlag = (activity != null); } } if (activity==null) { activity = createActivity(identityManager, activityOwnerId, node, activityMsgBundleKey, activityType, isComment, systemComment, perm); setActivityType(null); } if (exa != null) { if (commentFlag) { Map<String, String> paramsMap = activity.getTemplateParams(); String paramMessage = paramsMap.get(ContentUIActivity.MESSAGE); String paramContent = paramsMap.get(ContentUIActivity.SYSTEM_COMMENT); if (!StringUtils.isEmpty(paramMessage)) { paramMessage += ActivityCommonService.VALUE_SEPERATOR + activityMsgBundleKey; if (StringUtils.isEmpty(systemComment)) { paramContent += ActivityCommonService.VALUE_SEPERATOR + " "; }else { paramContent += ActivityCommonService.VALUE_SEPERATOR + systemComment; } } else { paramMessage = activityMsgBundleKey; paramContent = systemComment; } paramsMap.put(ContentUIActivity.MESSAGE, paramMessage); paramsMap.put(ContentUIActivity.SYSTEM_COMMENT, paramContent); activity.setTemplateParams(paramsMap); updateNotifyMessages(activity, activityMsgBundleKey, systemComment); activityManager.updateActivity(activity); } else { updateNotifyMessages(activity, activity.getTemplateParams().get(ContentUIActivity.MESSAGE), activity.getTemplateParams().get(ContentUIActivity.SYSTEM_COMMENT)); activityManager.saveComment(exa, activity); if (activityCommonService.isEditing(node)) { commentID = activity.getId(); if (node.canAddMixin(MIX_COMMENT)) node.addMixin(MIX_COMMENT); if (node.isNodeType(MIX_COMMENT)) node.setProperty(MIX_COMMENT_ID, commentID); } } return activity; }else { String spaceGroupName = getSpaceName(node); Space space = spaceService.getSpaceByGroupId(SpaceUtils.SPACE_GROUP + "/" + spaceGroupName); if (spaceGroupName != null && spaceGroupName.length() > 0 && space != null) { // post activity to space stream Identity spaceIdentity = identityManager.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName()); activityManager.saveActivityNoReturn(spaceIdentity, activity); } else if (activityOwnerId != null && activityOwnerId.length() > 0) { if (!isPublic(node)) { // only post activity to user status stream if that upload is public return null; } // post activity to user status stream Identity ownerIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, activityOwnerId); activityManager.saveActivityNoReturn(ownerIdentity, activity); } else { return null; } if (!StringUtils.isEmpty(activity.getId())) { ActivityTypeUtils.attachActivityId(node, activity.getId()); } if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); exa = activityManager.getActivity(nodeActivityID); } catch (Exception e) { LOG.info("No activity is deleted, return no related activity"); } if (exa != null && !commentFlag && isComment) { activity.setId(null); updateNotifyMessages(activity, activity.getTemplateParams().get(ContentUIActivity.MESSAGE), activity.getTemplateParams().get(ContentUIActivity.SYSTEM_COMMENT)); activityManager.saveComment(exa, activity); if (activityCommonService.isEditing(node)) { commentID = activity.getId(); if (node.canAddMixin(MIX_COMMENT)) node.addMixin(MIX_COMMENT); if (node.isNodeType(MIX_COMMENT)) node.setProperty(MIX_COMMENT_ID, commentID); } } } return activity; } } public static void updateNotifyMessages(ExoSocialActivity activity, String activityMsgBundleKey, String systemComment) throws Exception { Locale locale = new Locale("en"); ResourceBundleService resourceBundleService = CommonsUtils.getService(ResourceBundleService.class); ResourceBundle res = resourceBundleService.getResourceBundle("locale.extension.SocialIntegration", locale); StringBuffer sb = new StringBuffer(); String[] keys = activityMsgBundleKey.split(ActivityCommonService.VALUE_SEPERATOR); String[] values = systemComment.split(ActivityCommonService.VALUE_SEPERATOR); String message; for (String key : keys) { try { message = res.getString(key); } catch(MissingResourceException mre) { message = key; } if(values.length > 0) { for(int i = 0; i < values.length; i++) { message = message.replace("{"+i+"}", values[i]); } } sb.append(message).append("\n"); } activity.setTitle(sb.toString()); } private static void updateMainActivity(ActivityManager activityManager, Node contentNode, ExoSocialActivity activity) { Map<String, String> activityParams = activity.getTemplateParams(); String state; String nodeTitle; String nodeType = null; String documentTypeLabel; String currentVersion = null; TemplateService templateService = CommonsUtils.getService(TemplateService.class); try { nodeType = contentNode.getPrimaryNodeType().getName(); documentTypeLabel = templateService.getTemplateLabel(nodeType); }catch (Exception e) { documentTypeLabel = ""; } try { nodeTitle = org.exoplatform.ecm.webui.utils.Utils.getTitle(contentNode); } catch (Exception e1) { nodeTitle =""; } try { state = contentNode.hasProperty(CURRENT_STATE_PROP) ? contentNode.getProperty(CURRENT_STATE_PROP) .getValue() .getString() : ""; } catch (Exception e) { state=""; } try { currentVersion = contentNode.getBaseVersion().getName(); //TODO Must improve this hardcode later, need specification if (currentVersion.contains("jcr:rootVersion")) currentVersion = "0"; }catch (Exception e) { currentVersion =""; } activityParams.put(ContentUIActivity.STATE, state); activityParams.put(ContentUIActivity.DOCUMENT_TYPE_LABEL, documentTypeLabel); activityParams.put(ContentUIActivity.DOCUMENT_TITLE, nodeTitle); activityParams.put(ContentUIActivity.DOCUMENT_VERSION, currentVersion); String summary = getSummary(contentNode); summary =getFirstSummaryLines(summary, MAX_SUMMARY_LINES_COUNT); activityParams.put(ContentUIActivity.DOCUMENT_SUMMARY, summary); activity.setTemplateParams(activityParams); activityManager.updateActivity(activity); } /** * check the nodes that we support to post activities * * @param node for checking * @return result of checking * @throws RepositoryException */ private static boolean isSupportedContent(Node node) throws Exception { if (getActivityOwnerId(node) != null && getActivityOwnerId(node).length() > 0) { NodeHierarchyCreator nodeHierarchyCreator = (NodeHierarchyCreator) ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(NodeHierarchyCreator.class); SessionProvider sessionProvider = WCMCoreUtils.getUserSessionProvider(); if(sessionProvider == null){ sessionProvider = WCMCoreUtils.getSystemSessionProvider(); } Node userNode = nodeHierarchyCreator.getUserNode(sessionProvider, getActivityOwnerId(node)); if (userNode != null && node.getPath().startsWith(userNode.getPath() + "/Private/")) { return false; } } return true; } /** * refine node for validation * * @param currentNode * @throws Exception */ private static void refineNode(Node currentNode) throws Exception { if (currentNode instanceof NodeImpl && !((NodeImpl) currentNode).isValid()) { ExoContainer container = ExoContainerContext.getCurrentContainer(); LinkManager linkManager = (LinkManager) container.getComponentInstanceOfType(LinkManager.class); if (linkManager.isLink(currentNode)) { try { currentNode = linkManager.getTarget(currentNode, false); } catch (RepositoryException ex) { currentNode = linkManager.getTarget(currentNode, true); } } } } /** * get activity owner * * @return activity owner */ public static String getActivityOwnerId(Node node) { String activityOwnerId = ""; ConversationState conversationState = ConversationState.getCurrent(); if (conversationState != null) { activityOwnerId = conversationState.getIdentity().getUserId(); }else{ try { activityOwnerId = node.getProperty("publication:lastUser").getString(); } catch (Exception e) { LOG.info("No lastUser publication"); } } return activityOwnerId; } /** * get the space name of node * * @param node * @return the group name * @throws Exception */ public static String getSpaceName(Node node) throws Exception { NodeHierarchyCreator nodeHierarchyCreator = CommonsUtils.getService(NodeHierarchyCreator.class); String groupPath = nodeHierarchyCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); String spacesFolder = groupPath + "/spaces/"; String spaceName = ""; String nodePath = node.getPath(); if (nodePath.startsWith(spacesFolder)) { spaceName = nodePath.substring(spacesFolder.length()); spaceName = spaceName.substring(0, spaceName.indexOf("/")); } return spaceName; } public static boolean isPublic(Node node) { if (node instanceof ExtendedNode) { ExtendedNode n = (ExtendedNode)node; try { List<String> permissions =n.getACL().getPermissions("any"); if(permissions != null && permissions.size() > 0) { for (String p : permissions) { if ("read".equalsIgnoreCase(p)) { return true; } } } } catch (RepositoryException ex) { return false; } } return false; } /** * Generate the viewer link to site explorer by node * * @param node the node * @return String the viewer link * @throws RepositoryException */ public static String getContentLink(Node node) throws Exception { DocumentService documentService = CommonsUtils.getService(DocumentService.class); return documentService.getShortLinkInDocumentsApp(node.getSession().getWorkspace().getName(), ((NodeImpl)node).getInternalIdentifier()); } /** * Create ExoSocialActivity * * @param identityManager the identity Manager * @param activityOwnerId the remote user name * @param node the node * @param activityMsgBundleKey the message bundle key * @param activityType the activity type * @return the ExoSocialActivity * @throws Exception the activity storage exception */ public static ExoSocialActivity createActivity(IdentityManager identityManager, String activityOwnerId, Node node, String activityMsgBundleKey, String activityType) throws Exception { return createActivity(identityManager, activityOwnerId, node, activityMsgBundleKey, activityType, false, null, null); } public static ExoSocialActivity createActivity(IdentityManager identityManager, String activityOwnerId, Node node, String activityMsgBundleKey, String activityType, boolean isSystemComment, String systemComment, String perm) throws Exception { // Populate activity data Map<String, String> activityParams = populateActivityData(node, activityOwnerId, activityMsgBundleKey, isSystemComment, systemComment, perm); ExoSocialActivity activity = new ExoSocialActivityImpl(); String userId = ""; if(ConversationState.getCurrent() != null) { userId = ConversationState.getCurrent().getIdentity().getUserId(); }else{ userId = activityOwnerId; } Identity identity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false); activity.setUserId(identity.getId()); activity.setType(activityType); activity.setUrl(node.getPath()); if(StringUtils.isNotEmpty(activityMsgBundleKey) && StringUtils.isNotEmpty(systemComment)) { updateNotifyMessages(activity, activityMsgBundleKey, systemComment); } else if(StringUtils.isNotEmpty(systemComment)){ activity.setTitle(systemComment); } else { activity.setTitle(""); } activity.setTemplateParams(activityParams); return activity; } public static void deleteFileActivity(Node node) throws RepositoryException { // get services ExoContainer container = ExoContainerContext.getCurrentContainer(); ActivityManager activityManager = (ActivityManager) container.getComponentInstanceOfType(ActivityManager.class); // get owner String nodeActivityID = StringUtils.EMPTY; if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); if(activityManager.getActivity(nodeActivityID) != null) { activityManager.deleteActivity(nodeActivityID); } } catch (Exception e) { LOG.info("No activity is deleted, return no related activity"); } } } /** * Gets the illustrative image. * * @param node the node * @return the illustrative image */ public static String getIllustrativeImage(Node node) { WebSchemaConfigService schemaConfigService = CommonsUtils.getService(WebSchemaConfigService.class); WebContentSchemaHandler contentSchemaHandler = schemaConfigService.getWebSchemaHandlerByType(WebContentSchemaHandler.class); Node illustrativeImage = null; String uri = ""; try { illustrativeImage = contentSchemaHandler.getIllustrationImage(node); uri = generateThumbnailImageURI(illustrativeImage); } catch (PathNotFoundException ex) { return uri; } catch (Exception e) { // WebContentSchemaHandler LOG.warn(e.getMessage(), e); } return uri; } /** * Generate the Thumbnail Image URI. * * @param file the node * @return the Thumbnail uri with medium size * @throws Exception the exception */ public static String generateThumbnailImageURI(Node file) throws Exception { StringBuilder builder = new StringBuilder(); NodeLocation fielLocation = NodeLocation.getNodeLocationByNode(file); String repository = fielLocation.getRepository(); String workspaceName = fielLocation.getWorkspace(); String nodeIdentifiler = file.getPath().replaceFirst("/", ""); String portalName = PortalContainer.getCurrentPortalContainerName(); String restContextName = PortalContainer.getCurrentRestContextName(); InputStream stream = file.getNode(NodetypeConstant.JCR_CONTENT) .getProperty(NodetypeConstant.JCR_DATA) .getStream(); if (stream.available() == 0) return null; stream.close(); builder.append("/") .append(portalName) .append("/") .append(restContextName) .append("/") .append("thumbnailImage/medium/") .append(repository) .append("/") .append(workspaceName) .append("/") .append(nodeIdentifiler); return builder.toString(); } /** * Get the MimeType * * @param node the node * @return the MimeType */ public static String getMimeType(Node node) { try { if (node.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) { if (node.hasNode(NodetypeConstant.JCR_CONTENT)) return node.getNode(NodetypeConstant.JCR_CONTENT) .getProperty(NodetypeConstant.JCR_MIME_TYPE) .getString(); } } catch (RepositoryException e) { LOG.error(e.getMessage(), e); } return ""; } public static String getSummary(Node node) { String desc = ""; try { if (node != null) { if (node.hasProperty("exo:summary")) { desc = node.getProperty("exo:summary").getValue().getString(); } else if (node.hasNode("jcr:content")) { Node content = node.getNode("jcr:content"); if (content.hasProperty("dc:description") && content.getProperty("dc:description").getValues().length > 0) { desc = content.getProperty("dc:description").getValues()[0].getString(); } } } } catch (RepositoryException re) { if (LOG.isWarnEnabled()) LOG.warn("RepositoryException: ", re); } return desc; } public static String getFirstSummaryLines(String source) { return getFirstSummaryLines(source, MAX_SUMMARY_LINES_COUNT); } private static String convertActivityContent(String source){ String result = source; result = result.replaceAll("(?i)<head>.*</head>", ""); result = result.replaceAll("(?i)<script.*>.*</script>", ""); result = result.replaceAll("(?i)<style.*>.*</style>", ""); result = result.replaceAll("<([a-zA-Z\"]+) *[^/]*?>", ""); result = result.replaceAll("</p>", "<br>"); result = result.replaceAll("</([a-zA-Z]+) *[^/]*?>", ""); result = result.replaceAll("([\r\n\t])+", ""); result = result.replaceAll("^(<br>)", ""); result = result.replaceAll("(<br>[ \r\t\n]+<br>)", "\n"); result = result.replaceAll("(<br>)+", "\n"); return result; } /** * * @param source * @param linesCount * @return first {@code linesCount} without HTML tag */ public static String getFirstSummaryLines(String source, int linesCount) { String result = convertActivityContent(source); int i = 0; int index = -1; while (true) { index = result.indexOf("\n", index+1); if (index<0) break; i++; if (i>=linesCount) break; } if (index <0) { if (result.length()>MAX_SUMMARY_CHAR_COUNT) return result.substring(0, MAX_SUMMARY_CHAR_COUNT-1) + "..."; return result; } if (index>MAX_SUMMARY_CHAR_COUNT) index = MAX_SUMMARY_CHAR_COUNT-1; result = result.substring(0, index) + "\n..."; return result; } public static String[] getSystemCommentTitle(Map<String, String> activityParams) { String[] result; if (activityParams == null) return null; String commentValue = activityParams.get(FileUIActivity.SYSTEM_COMMENT); if (!StringUtils.isEmpty(commentValue)) { if (commentValue.indexOf(ActivityCommonService.VALUE_SEPERATOR) >= 0) { result = commentValue.split(ActivityCommonService.VALUE_SEPERATOR); return result; } else { return new String[]{commentValue}; } } return null; } public static String[] getSystemCommentBundle(Map<String, String> activityParams) { String[] result; if (activityParams == null) return null; String tmp = activityParams.get(FileUIActivity.IS_SYSTEM_COMMENT); String commentMessage; if (tmp == null) return null; try { if (Boolean.parseBoolean(tmp)) { commentMessage = activityParams.get(FileUIActivity.MESSAGE); if (!StringUtils.isEmpty(commentMessage)) { if (commentMessage.indexOf(ActivityCommonService.VALUE_SEPERATOR) >= 0) { result = commentMessage.split(ActivityCommonService.VALUE_SEPERATOR); return result; } else { return new String[]{commentMessage}; } } } } catch (Exception e) { return null; } return null; } public static String getBundleValue(String key) { try { WebuiRequestContext context = WebuiRequestContext.getCurrentInstance(); ResourceBundle res = context.getApplicationResourceBundle(); String value = res.getString(key); return value; } catch (MissingResourceException e) { return key; } } public static String processMentions(String comment) { String excerpts[] = comment.split("@"); comment = excerpts[0]; String mentioned = ""; for (int i=1; i<excerpts.length; i++) { String name = excerpts[i].split(" ")[0]; Identity identity = org.exoplatform.social.notification.Utils.getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, name, true); if (identity != null) { mentioned = addMentioned(name, identity.getProfile().getFullName()); } if (mentioned.isEmpty()) { if (excerpts[i].isEmpty()) comment = comment + " "; else comment = comment + excerpts[i] + " "; } else { comment = comment + mentioned + excerpts[i].substring(name.length(),excerpts[i].length()); mentioned = ""; } } return comment; } private static String addMentioned(String mention, String fullname) { String profileURL = CommonsUtils.getCurrentDomain() + LinkProvider.getProfileUri(mention); return "<a href=" + profileURL + " type=\"mentionedUser\" rel=\"nofollow\">" + fullname + "</a>"; } public static void setAvatarUrl(Node commentNode) throws RepositoryException { String name = commentNode.getProperty("exo:commentor").getString();; Identity identity = org.exoplatform.social.notification.Utils.getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, name, true); Profile profile = identity.getProfile(); if (profile.getAvatarUrl() != null ) { commentNode.setProperty("exo:commentorAvatar", profile.getAvatarUrl()); } else { commentNode.setProperty("exo:commentorAvatar", DEFAULT_AVATAR); } ; } public static String addVersionComment(Node node, String commentText, String userId) throws Exception { String nodeActivityID = null; IdentityManager identityManager = CommonsUtils.getService(IdentityManager.class); SpaceService spaceService = CommonsUtils.getService(SpaceService.class); ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class); String activityOwnerId = getActivityOwnerId(node); boolean deletedActivity = false; if(node.hasProperty(ActivityTypeUtils.EXO_ACTIVITY_ID)) { nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); deletedActivity = activityManager.getActivity(nodeActivityID) == null; } ExoSocialActivity activity = createActivity(identityManager, activityOwnerId, node, commentText, activityType, true, "", ""); setActivityType(null); if (!node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO) || deletedActivity) { String spaceGroupName = getSpaceName(node); Space space = spaceService.getSpaceByGroupId(SpaceUtils.SPACE_GROUP + "/" + spaceGroupName); if (spaceGroupName != null && !spaceGroupName.isEmpty() && space != null) { // post activity to space stream Identity spaceIdentity = identityManager.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName()); activityManager.saveActivityNoReturn(spaceIdentity, activity); } else if (activityOwnerId != null && !activityOwnerId.isEmpty()) { if (!isPublic(node)) { // only post activity to user status stream if that upload is public return null; } // post activity to user status stream Identity ownerIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, activityOwnerId); activityManager.saveActivityNoReturn(ownerIdentity, activity); } else { return null; } if (!StringUtils.isEmpty(activity.getId())) { nodeActivityID = activity.getId(); ActivityTypeUtils.attachActivityId(node, activity.getId()); } } if (nodeActivityID != null && !nodeActivityID.isEmpty() && commentText != null && !commentText.trim().isEmpty()) { org.exoplatform.social.core.identity.model.Identity identity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId); activity = activityManager.getActivity(nodeActivityID); ExoSocialActivity comment = new ExoSocialActivityImpl(identity.getId(), SpaceActivityPublisher.SPACE_APP_ID, commentText, null); activityManager.saveComment(activity, comment); return comment.getId(); } else { LOG.warn("Cannot add comment. ActivityId and comment shouldn't be null or empty. activityId: {}, comment: {}", nodeActivityID, commentText); return null; } } }
48,623
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
FileRemoveActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/FileRemoveActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class FileRemoveActivityListener extends Listener<Object, Node> { public FileRemoveActivityListener() { } @Override public void onEvent(Event<Object, Node> event) throws Exception { Node currentNode = event.getData(); Utils.deleteFileActivity(currentNode); } }
1,280
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentUpdateActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/ContentUpdateActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import javax.jcr.Value; import org.apache.commons.lang3.StringUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class ContentUpdateActivityListener extends Listener<Node, String> { private String[] editedField = {"exo:title", "exo:summary", "dc:title", "dc:description", "exo:text"}; private String[] bundleMessage = {"SocialIntegration.messages.editTitle", "SocialIntegration.messages.editSummary", "SocialIntegration.messages.editTitle", "SocialIntegration.messages.editSummary", "SocialIntegration.messages.editContent"}; private String[] bundleMessageEmpty = {"SocialIntegration.messages.emptyTitle", "SocialIntegration.messages.emptySummary", "SocialIntegration.messages.emptyTitle", "SocialIntegration.messages.emptySummary", "SocialIntegration.messages.emptyContent"}; private boolean[] needUpdate = {true, true, true, true, false}; private int CONTENT_BUNDLE_INDEX = bundleMessage.length-1; private int consideredFieldCount = editedField.length; /** * Instantiates a new post edit content event listener. */ @Override public void onEvent(Event<Node, String> event) throws Exception { Node currentNode = event.getSource(); String propertyName = event.getData(); String newValue; try { if (!currentNode.hasProperty(propertyName)) return; if(currentNode.getProperty(propertyName).getDefinition().isMultiple()){ StringBuffer sb = new StringBuffer(); Value[] values = currentNode.getProperty(propertyName).getValues(); for (int i=0; i<values.length; i++) { if (i==0) { sb.append(values[i].getString()); }else { sb.append(", ").append(values[i].getString()); } } newValue = sb.toString(); }else { newValue= currentNode.getProperty(propertyName).getString(); if (newValue==null) newValue =""; } }catch (Exception e) { newValue = ""; } for (int i=0; i< consideredFieldCount; i++) { if (propertyName.equals(editedField[i])) { if (propertyName.equals("exo:summary")) newValue = Utils.getFirstSummaryLines(newValue); if (StringUtils.isEmpty(newValue)) { Utils.postActivity(currentNode, bundleMessageEmpty[i], needUpdate[i], true, "", ""); } else { Utils.postActivity(currentNode, bundleMessage[i], needUpdate[i], true, newValue, ""); } return; } }//for if (propertyName.endsWith("jcr:data")) { //Special case for text content but store in jcr:content/jcr:data String _resourceBundleKey=""; if (StringUtils.isEmpty(newValue)) { _resourceBundleKey = bundleMessageEmpty[CONTENT_BUNDLE_INDEX]; }else { _resourceBundleKey = bundleMessage[CONTENT_BUNDLE_INDEX]; } Utils.postActivity(currentNode, _resourceBundleKey, needUpdate[CONTENT_BUNDLE_INDEX], true, "", ""); } if (propertyName.endsWith("dc:description")) { //Special case for text content but store in jcr:content/jcr:data try { if (currentNode.hasProperty("exo:summary")) return; //Modify the dc:description but the node have already had the summary property }catch (Exception ex) { return; } newValue = Utils.getFirstSummaryLines(newValue); // get only some first line of dc:description if (StringUtils.isEmpty(newValue)) { Utils.postActivity(currentNode, "SocialIntegration.messages.emptySummary", true, true, "", ""); }else { Utils.postActivity(currentNode, "SocialIntegration.messages.editSummary", true, true, newValue, ""); } } } }
4,917
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentCreateActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/ContentCreateActivityListener.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.wcm.core.NodetypeConstant; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 15, 2011 */ public class ContentCreateActivityListener extends Listener<Object, Node> { private static final String RESOURCE_BUNDLE_KEY_CREATED_BY = "SocialIntegration.messages.createdBy"; /** * Instantiates a new post create content event listener. */ public ContentCreateActivityListener() { } @Override public void onEvent(Event<Object, Node> event) throws Exception { Node currentNode = event.getData(); if(!currentNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) Utils.postActivity(currentNode, RESOURCE_BUNDLE_KEY_CREATED_BY, true, false, "", ""); else Utils.postFileActivity(currentNode, RESOURCE_BUNDLE_KEY_CREATED_BY, true, true, "", ""); } }
1,766
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentRemovedActivityListener.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/activity/listener/ContentRemovedActivityListener.java
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.activity.listener; import javax.jcr.Node; import org.apache.commons.lang3.StringUtils; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.services.jcr.ext.ActivityTypeUtils; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.manager.ActivityManager; /** * Created by The eXo Platform SAS * Author : Nguyen The Vinh From ECM Of eXoPlatform * vinh_nguyen@exoplatform.com * Handler for ContentRemoved event * 26 Feb 2013 */ public class ContentRemovedActivityListener extends Listener<Node, String>{ private static final Log LOG = ExoLogger.getExoLogger(ContentRemovedActivityListener.class); @Override public void onEvent(Event<Node, String> event) throws Exception { Node currentNode = event.getSource(); ExoContainer container = ExoContainerContext.getCurrentContainer(); ActivityManager activityManager = (ActivityManager) container.getComponentInstanceOfType(ActivityManager.class); String nodeActivityID = StringUtils.EMPTY; if (currentNode.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) { try { nodeActivityID = currentNode.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString(); activityManager.deleteActivity(nodeActivityID); }catch (Exception e){ LOG.info("No activity is deleted, return no related activity"); } } } }
2,352
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
DocumentIdentityProvider.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/identity/provider/DocumentIdentityProvider.java
/* * Copyright (C) 2003-2011 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.identity.provider; import javax.jcr.RepositoryException; import org.exoplatform.services.cms.documents.DocumentService; import org.exoplatform.services.cms.documents.model.Document; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.identity.IdentityProvider; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.identity.model.Profile; /** * Created by The eXo Platform SAS Author : eXoPlatform exo@exoplatform.com Mar * 22, 2011 */ public class DocumentIdentityProvider extends IdentityProvider<Document> { private static final Log LOG = ExoLogger.getLogger(DocumentIdentityProvider.class); public static final String NAME = "document"; private DocumentService docService = WCMCoreUtils.getService(DocumentService.class); @Override public Identity createIdentity(Document doc) { Identity identity = new Identity(NAME, doc.getId()); return identity; } @Override public Document findByRemoteId(String id) { try { return docService.findDocById(id); } catch (RepositoryException e) { LOG.error("RepositoryException: ", e); } return null; } @Override public String getName() { return NAME; } @Override public void populateProfile(Profile profile, Document doc) { profile.setProperty(Profile.FIRST_NAME, doc.getName()); profile.setProperty(Profile.USERNAME, doc.getName()); profile.setProperty(Profile.URL, doc.getPath()); } }
2,343
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ShareDocumentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/document/service/ShareDocumentService.java
/* * Copyright (C) 2003-2021 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.document.service; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import javax.jcr.*; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.picocontainer.Startable; import org.exoplatform.commons.utils.ISO8601; import org.exoplatform.ecm.utils.permission.PermissionUtil; import org.exoplatform.services.cms.BasePath; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.access.PermissionType; import org.exoplatform.services.jcr.core.*; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.SpaceUtils; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.social.plugin.doc.UIDocActivity; import org.exoplatform.wcm.ext.component.activity.FileUIActivity; import org.exoplatform.wcm.ext.component.activity.listener.Utils; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Nov 19, 2014 */ public class ShareDocumentService implements IShareDocumentService, Startable{ private static final String SHARED_TEMPLATE_PARAMS_PREFIX = "Shared_"; private static final Log LOG = ExoLogger.getLogger(ShareDocumentService.class); public static final String MIX_PRIVILEGEABLE = "exo:privilegeable"; private static final boolean POST_ACTIVITY = true; public static final String ID = "id"; public static final String REPOSITORY = "REPOSITORY"; public static final String WORKSPACE = "WORKSPACE"; public static final String DOCPATH = "DOCPATH"; public static final String NODEPATH_NAME = "nodePath"; public static final String REPOSITORY_NAME = "repository"; public static final String WORKSPACE_NAME = "collaboration"; private SessionProviderService sessionProviderService; private LinkManager linkManager; private SpaceService spaceService; private RepositoryService repoService; private ActivityManager activityManager; private IdentityManager identityManager; private static final String TEMPLATE_PARAMS_SEPARATOR = "|@|"; public ShareDocumentService(RepositoryService repositoryService, LinkManager linkManager, IdentityManager identityManager, ActivityManager activityManager, SpaceService spaceService, SessionProviderService sessionProviderService){ this.repoService = repositoryService; this.sessionProviderService = sessionProviderService; this.linkManager = linkManager; this.spaceService = spaceService; this.activityManager = activityManager; this.identityManager = identityManager; } /* * {@inheritDoc} */ @Override public String publishDocumentToSpace(String space, Node currentNode, String comment, String perm) { return publishDocumentToSpace(space, currentNode, comment, perm, POST_ACTIVITY); } /* * {@inheritDoc} */ @Override public String publishDocumentToSpace(String space, Node currentNode, String comment, String perm, Boolean postActivity) { Node rootSpace = null; Node shared = null; try { SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); ManageableRepository repository = repoService.getCurrentRepository(); Session session = sessionProvider.getSession(repository.getConfiguration().getDefaultWorkspaceName(), repository); // add symlink to destination space NodeHierarchyCreator nodeCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); nodeCreator.getJcrPath(BasePath.CMS_GROUPS_PATH); rootSpace = (Node) session.getItem(nodeCreator.getJcrPath(BasePath.CMS_GROUPS_PATH) + space); rootSpace = rootSpace.getNode("Documents"); if (!rootSpace.hasNode("Shared")) { shared = rootSpace.addNode("Shared"); } else { shared = rootSpace.getNode("Shared"); } if (currentNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) currentNode = linkManager.getTarget(currentNode); // Update permission String tempPerms = perm.toString();// Avoid ref back to UIFormSelectBox options if (!tempPerms.equals(PermissionType.READ)) tempPerms = PermissionType.READ + "," + PermissionType.ADD_NODE + "," + PermissionType.SET_PROPERTY + "," + PermissionType.REMOVE; if (PermissionUtil.canChangePermission(currentNode)) { setSpacePermission(currentNode, space, tempPerms.split(",")); } else if (PermissionUtil.canRead(currentNode)) { SessionProvider systemSessionProvider = SessionProvider.createSystemProvider(); Session systemSession = systemSessionProvider.getSession(session.getWorkspace().getName(), repository); Node _node = (Node) systemSession.getItem(currentNode.getPath()); setSpacePermission(_node, space, tempPerms.split(",")); } currentNode.getSession().save(); Node link = linkManager.createLink(shared, currentNode); String nodeMimeType = Utils.getMimeType(currentNode); link.addMixin(NodetypeConstant.MIX_FILE_TYPE); link.setProperty(NodetypeConstant.EXO_FILE_TYPE, nodeMimeType); rootSpace.save(); // Share activity if (postActivity) { try { ExoSocialActivity activity = null; if (currentNode.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) { activity = Utils.createShareActivity(link, "", Utils.SHARE_FILE, comment, perm); } else { activity = Utils.createShareActivity(link, "", Utils.SHARE_CONTENT, comment, perm); } link.save(); return activity.getId(); } catch (Exception e1) { if (LOG.isErrorEnabled()) LOG.error(e1.getMessage(), e1); } } if(link.canAddMixin(NodetypeConstant.MIX_REFERENCEABLE)){ link.addMixin(NodetypeConstant.MIX_REFERENCEABLE); link.save(); return link.getUUID(); } } catch (RepositoryException e) { if (LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } catch (Exception e) { if (LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } return ""; } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.component.explorer.popup.service.IShareDocumentService#publishDocumentToUser(java.lang.String, javax.jcr.Node, java.lang.String, java.lang.String) */ @Override public void publishDocumentToUser(String user, Node currentNode, String comment,String perm) { Node userPrivateNode = null; Node shared = null; try { SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); ManageableRepository repository = repoService.getCurrentRepository(); Session session = sessionProvider.getSession(repository.getConfiguration().getDefaultWorkspaceName(), repository); //add symlink to destination user userPrivateNode = getPrivateUserNode(sessionProvider, user); userPrivateNode = userPrivateNode.getNode("Documents"); if(!userPrivateNode.hasNode("Shared")){ shared = userPrivateNode.addNode("Shared"); }else{ shared = userPrivateNode.getNode("Shared"); } if(currentNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) currentNode = linkManager.getTarget(currentNode); //Update permission String tempPerms = perm.toString();//Avoid ref back to UIFormSelectBox options if(!tempPerms.equals(PermissionType.READ)) tempPerms = PermissionType.READ+","+PermissionType.ADD_NODE+","+PermissionType.SET_PROPERTY+","+PermissionType.REMOVE; if(PermissionUtil.canChangePermission(currentNode)){ setUserPermission(currentNode, user, tempPerms.split(",")); }else if(PermissionUtil.canRead(currentNode)){ SessionProvider systemSessionProvider = SessionProvider.createSystemProvider(); Session systemSession = systemSessionProvider.getSession(session.getWorkspace().getName(), repository); Node _node= (Node)systemSession.getItem(currentNode.getPath()); setUserPermission(_node, user, tempPerms.split(",")); } currentNode.getSession().save(); Node link = linkManager.createLink(shared, currentNode); String nodeMimeType = Utils.getMimeType(currentNode); link.addMixin(NodetypeConstant.MIX_FILE_TYPE); link.setProperty(NodetypeConstant.EXO_FILE_TYPE, nodeMimeType); userPrivateNode.save(); } catch (RepositoryException e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } private Node getPrivateUserNode(SessionProvider sessionProvider, String user) throws Exception, PathNotFoundException, RepositoryException { NodeHierarchyCreator nodeCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); String privateRelativePath = nodeCreator.getJcrPath("userPrivate"); Node userNode = nodeCreator.getUserNode(sessionProvider, user); return userNode.getNode(privateRelativePath); } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.component.explorer.popup.service.IShareDocumentService#unpublishDocumentToUser(java.lang.String, javax.jcr.ExtendedNode) */ @Override public void unpublishDocumentToUser(String user, ExtendedNode node) { Node userPrivateNode = null; Node sharedNode = null; try { SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); //remove symlink from destination user userPrivateNode = getPrivateUserNode(sessionProvider, user); userPrivateNode = userPrivateNode.getNode("Documents"); sharedNode = userPrivateNode.getNode("Shared"); sharedNode.getNode(node.getName()).remove(); removeUserPermission(node, user); node.getSession().save(); userPrivateNode.save(); } catch (RepositoryException e) { if (LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } /* (non-Javadoc) * @see org.exoplatform.ecm.webui.component.explorer.popup.service.IShareDocumentService#unpublishDocumentToSpace(java.lang.String, javax.jcr.ExtendedNode) */ @Override public void unpublishDocumentToSpace(String space, ExtendedNode node) { Node rootSpace = null; Node sharedNode = null; try { SessionProvider sessionProvider = sessionProviderService.getSystemSessionProvider(null); ManageableRepository repository = repoService.getCurrentRepository(); Session session = sessionProvider.getSession(repository.getConfiguration().getDefaultWorkspaceName(), repository); //remove symlink to destination space NodeHierarchyCreator nodeCreator = WCMCoreUtils.getService(NodeHierarchyCreator.class); rootSpace = (Node) session.getItem(nodeCreator.getJcrPath(BasePath.CMS_GROUPS_PATH) + space); rootSpace = rootSpace.getNode("Documents"); if (rootSpace.hasNode("Shared")) { sharedNode = rootSpace.getNode("Shared"); sharedNode.getNode(node.getName()).remove(); rootSpace.save(); } removeSpacePermission(node, space); node.getSession().save(); } catch (RepositoryException e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } catch (Exception e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } @Override public void shareDocumentActivityToSpace(ExoSocialActivity sharedActivity) throws Exception { if (sharedActivity == null) { throw new IllegalArgumentException("activity is mandarory"); } if (sharedActivity.isComment() || sharedActivity.getActivityStream() == null) { throw new IllegalArgumentException("comment is not allowed"); } String sharedActivityId = sharedActivity.getId(); String originalActivityId = sharedActivity.getTemplateParams().get("originalActivityId"); String spacePrettyName = sharedActivity.getActivityStream().getPrettyId(); Space targetSpace = spaceService.getSpaceByPrettyName(spacePrettyName); Identity targetSpaceIdentity = identityManager.getOrCreateSpaceIdentity(spacePrettyName); Identity posterIdentity = identityManager.getIdentity(sharedActivity.getPosterId()); String posterUsername = posterIdentity.getRemoteId(); if (targetSpaceIdentity != null && SpaceUtils.isSpaceManagerOrSuperManager(posterUsername, targetSpace.getGroupId()) || (spaceService.isMember(targetSpace, posterUsername) && SpaceUtils.isRedactor(posterUsername, targetSpace.getGroupId()))) { Map<String, String> originalActivityTemplateParams = activityManager.getActivity(originalActivityId).getTemplateParams(); String[] originalActivityFilesWorkspaces = getParameterValues(originalActivityTemplateParams, WORKSPACE); if (originalActivityFilesWorkspaces == null) { originalActivityFilesWorkspaces = getParameterValues(originalActivityTemplateParams, WORKSPACE_NAME); } if (originalActivityFilesWorkspaces == null || originalActivityFilesWorkspaces.length == 0) { LOG.warn("Can't share document of activity {} to space of activity {}, because param {} is empty", originalActivityId, sharedActivityId, WORKSPACE); return; } String[] originalActivityFilesIds = getParameterValues(originalActivityTemplateParams, ID); if (originalActivityFilesIds == null || originalActivityFilesIds.length == 0) { LOG.warn("Can't share document of activity {} to space of activity {}, because param {} is empty", originalActivityId, sharedActivityId, ID); return; } Map<String, String> templateParams = new HashMap<>(); concatenateParam(templateParams, "originalActivityId", originalActivityId); if (originalActivityFilesIds != null && originalActivityFilesIds.length > 0) { for (int i = 0; i < originalActivityFilesIds.length; i++) { String originalActivityFileWorkspace = "collaboration"; if (originalActivityFilesWorkspaces != null && originalActivityFilesWorkspaces.length == originalActivityFilesIds.length && StringUtils.isNotBlank(originalActivityFilesWorkspaces[i])) { originalActivityFileWorkspace = originalActivityFilesWorkspaces[i]; } ExtendedSession originalActivityFileNodeSession = (ExtendedSession) WCMCoreUtils.getSystemSessionProvider() .getSession(originalActivityFileWorkspace, repoService.getCurrentRepository()); Node originalActivityFileNode = originalActivityFileNodeSession.getNodeByIdentifier(originalActivityFilesIds[i]); String targetSpaceFileNodeUUID = publishDocumentToSpace(targetSpace.getGroupId(), originalActivityFileNode, "", PermissionType.READ, false); Node targetSpaceFileNode = originalActivityFileNode.getSession().getNodeByUUID(targetSpaceFileNodeUUID); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.ID, targetSpaceFileNodeUUID); String repository = ((ManageableRepository) targetSpaceFileNode.getSession().getRepository()).getConfiguration() .getName(); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + UIDocActivity.REPOSITORY, repository); String workspace = targetSpaceFileNode.getSession().getWorkspace().getName(); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + UIDocActivity.WORKSPACE, workspace); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.CONTENT_LINK, Utils.getContentLink(targetSpaceFileNode)); String state; try { state = targetSpaceFileNode.hasProperty(Utils.CURRENT_STATE_PROP) ? targetSpaceFileNode.getProperty(Utils.CURRENT_STATE_PROP) .getValue() .getString() : ""; } catch (Exception e) { state = ""; } concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.STATE, state); /** The date formatter. */ DateFormat dateFormatter = null; dateFormatter = new SimpleDateFormat(ISO8601.SIMPLE_DATETIME_FORMAT); String strDateCreated = ""; if (targetSpaceFileNode.hasProperty(NodetypeConstant.EXO_DATE_CREATED)) { Calendar dateCreated = targetSpaceFileNode.getProperty(NodetypeConstant.EXO_DATE_CREATED).getDate(); strDateCreated = dateFormatter.format(dateCreated.getTime()); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.DATE_CREATED, strDateCreated); } String strLastModified = ""; if (targetSpaceFileNode.hasNode(NodetypeConstant.JCR_CONTENT)) { Node contentNode = targetSpaceFileNode.getNode(NodetypeConstant.JCR_CONTENT); if (contentNode.hasProperty(NodetypeConstant.JCR_LAST_MODIFIED)) { Calendar lastModified = contentNode.getProperty(NodetypeConstant.JCR_LAST_MODIFIED) .getDate(); strLastModified = dateFormatter.format(lastModified.getTime()); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.LAST_MODIFIED, strLastModified); } } concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.MIME_TYPE, Utils.getMimeType(originalActivityFileNode)); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.IMAGE_PATH, Utils.getIllustrativeImage(targetSpaceFileNode)); String nodeTitle; try { nodeTitle = org.exoplatform.ecm.webui.utils.Utils.getTitle(targetSpaceFileNode); } catch (Exception e1) { nodeTitle = ""; } concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.DOCUMENT_TITLE, nodeTitle); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.DOCUMENT_VERSION, ""); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + FileUIActivity.DOCUMENT_SUMMARY, Utils.getFirstSummaryLines(Utils.getSummary(targetSpaceFileNode), Utils.MAX_SUMMARY_CHAR_COUNT)); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + UIDocActivity.DOCPATH, targetSpaceFileNode.getPath()); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + UIDocActivity.LINK_PARAM, "");// to // check // if // necessary concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + UIDocActivity.IS_SYMLINK, "true"); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + "originalFileSize", getSize(originalActivityFileNode)); concatenateParam(templateParams, SHARED_TEMPLATE_PARAMS_PREFIX + "originalFileDownloadUrl", org.exoplatform.ecm.webui.utils.Utils.getDownloadRestServiceLink(originalActivityFileNode)); } } // create activity sharedActivity.setTemplateParams(templateParams); activityManager.updateActivity(sharedActivity); } } @Override public void start() { // TODO Auto-generated method stub } @Override public void stop() { // TODO Auto-generated method stub } private void removeSpacePermission(ExtendedNode node, String space) { try { node.removePermission("*:" + space); node.save(); } catch (RepositoryException e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } private void removeUserPermission(ExtendedNode node, String user) { try { node.removePermission(user); node.save(); } catch (RepositoryException e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } } private String getMimeType(Node node) { try { if (node.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) { if (node.hasNode(NodetypeConstant.JCR_CONTENT)) return node.getNode(NodetypeConstant.JCR_CONTENT) .getProperty(NodetypeConstant.JCR_MIME_TYPE) .getString(); } } catch (RepositoryException e) { if(LOG.isErrorEnabled()) LOG.error(e.getMessage(), e); } return ""; } /** * Grant view for parent folder when share a document * We need grant assess right for parent in case editing the shared documents * @param currentNode * @param memberShip * @param permissions * @throws Exception */ private void setSpacePermission(Node currentNode, String memberShip, String[] permissions) throws Exception{ ExtendedNode node = (ExtendedNode) currentNode; if (node.getACL().getPermissions("*:" + memberShip) == null || node.getACL().getPermissions("*:" + memberShip).size() == 0) { if(node.canAddMixin(MIX_PRIVILEGEABLE))node.addMixin(MIX_PRIVILEGEABLE); node.setPermission("*:" + memberShip, permissions); node.save(); } } /** * Grant view for parent folder when share a document * We need grant assess right for parent in case editing the shared documents * @param currentNode * @param username * @param permissions * @throws Exception */ private void setUserPermission(Node currentNode, String username, String[] permissions) throws Exception{ ExtendedNode node = (ExtendedNode) currentNode; if(node.canAddMixin(MIX_PRIVILEGEABLE))node.addMixin(MIX_PRIVILEGEABLE); node.setPermission(username, permissions); node.save(); } private String[] getParameterValues(Map<String, String> activityParams, String paramName) { String[] values = null; String value = activityParams.get(paramName); if (value == null) { value = activityParams.get(paramName.toLowerCase()); } if (value != null) { values = value.split(FileUIActivity.SEPARATOR_REGEX); } return values; } private void concatenateParam(Map<String, String> activityParams, String paramName, String paramValue) { String oldParamValue = activityParams.get(paramName); if (StringUtils.isBlank(oldParamValue)) { activityParams.put(paramName, paramValue); } else { activityParams.put(paramName, oldParamValue + TEMPLATE_PARAMS_SEPARATOR + paramValue); } } private String getSize(Node node) { double size = 0; try { if (node.hasNode(org.exoplatform.ecm.webui.utils.Utils.JCR_CONTENT)) { Node contentNode = node.getNode(org.exoplatform.ecm.webui.utils.Utils.JCR_CONTENT); if (contentNode.hasProperty(org.exoplatform.ecm.webui.utils.Utils.JCR_DATA)) { size = contentNode.getProperty(org.exoplatform.ecm.webui.utils.Utils.JCR_DATA).getLength(); } return FileUtils.byteCountToDisplaySize((long) size); } } catch (PathNotFoundException e) { return StringUtils.EMPTY; } catch (ValueFormatException e) { return StringUtils.EMPTY; } catch (RepositoryException e) { return StringUtils.EMPTY; } catch (NullPointerException e) { return StringUtils.EMPTY; } return StringUtils.EMPTY; } }
26,285
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
IShareDocumentService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/document/service/IShareDocumentService.java
/* * Copyright (C) 2003-2021 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.document.service; import javax.jcr.Node; import org.exoplatform.services.jcr.core.ExtendedNode; import org.exoplatform.social.core.activity.model.ExoSocialActivity; /** * Created by The eXo Platform SAS * Author : eXoPlatform * exo@exoplatform.com * Nov 27, 2014 */ public interface IShareDocumentService { /** * Share a document to a space, permission of space's user also * apply to this document. * <p> * There is a symbolic link of origin document will create * at Documents/Shared folder of destination space. * * @param space destination space will share file in * @param node file will be shared * @param comment message attach with share activity * @param perm permission of destination space's member on origin node * @return return false if have issue */ public String publishDocumentToSpace(String space, Node node, String comment, String perm); /** * Share a document to a space, permission of space's user also apply to this * document. * <p> * There is a symbolic link of origin document will create at Documents/Shared * folder of destination space. * * @param space destination space will share file in * @param node file will be shared * @param comment message attach with share activity * @param perm permission of destination space's member on origin node * @param postActivity define post activity after sharing to a space or not * @return return false if have issue */ public String publishDocumentToSpace(String space, Node node, String comment, String perm, Boolean postActivity); /** * Share a document to a user * <p> * There is a symbolic link of origin document will be created * at Private/Documents/Shared folder of destination user. * * @param user destination user to share file with * @param node file will be shared * @param comment message attach with share activity * @param perm permission of destination space's member on origin node */ public void publishDocumentToUser(String user, Node node, String comment, String perm); /** * Unshare a document to a user * <p> * The symbolic link of origin document will be removed * from Private/Documents/Shared folder of destination user. * * @param username destination user to share file with * @param node file will be shared */ void unpublishDocumentToUser(String username, ExtendedNode node); /** * Unshare a document to a space * <p> * The symbolic link of origin document will be removed * from Documents/Shared folder of destination space. * * @param space destination user to share file with * @param node file will be shared */ void unpublishDocumentToSpace(String space, ExtendedNode node); /** * Share documents of an activity to a space * * @param sharedActivity shared activity * @throws Exception when an error occurred while sharing document to space */ void shareDocumentActivityToSpace(ExoSocialActivity sharedActivity) throws Exception; }
3,843
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z
ContentViewerRESTService.java
/FileExtraction/Java_unseen/exoplatform_ecms/ecms-social-integration/src/main/java/org/exoplatform/wcm/ext/component/document/service/rest/ContentViewerRESTService.java
/* * Copyright (C) 2003-2008 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.wcm.ext.component.document.service.rest; import java.io.StringWriter; import java.io.Writer; import java.util.Locale; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.exoplatform.commons.utils.CommonsUtils; import org.exoplatform.container.ExoContainer; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.ecm.resolver.JCRResourceResolver; import org.exoplatform.groovyscript.text.BindingContext; import org.exoplatform.portal.application.PortalApplication; import org.exoplatform.portal.application.PortalRequestContext; import org.exoplatform.portal.webui.portal.UIPortal; import org.exoplatform.portal.webui.workspace.UIPortalApplication; import org.exoplatform.resolver.ResourceResolver; import org.exoplatform.services.cms.link.LinkManager; import org.exoplatform.services.cms.templates.TemplateService; import org.exoplatform.services.jcr.RepositoryService; import org.exoplatform.services.jcr.core.ExtendedSession; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.app.SessionProviderService; import org.exoplatform.services.jcr.ext.common.SessionProvider; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.rest.resource.ResourceContainer; import org.exoplatform.services.security.ConversationState; import org.exoplatform.services.wcm.core.NodetypeConstant; import org.exoplatform.services.wcm.utils.WCMCoreUtils; import org.exoplatform.social.plugin.doc.UIDocViewer; import org.exoplatform.web.ControllerContext; import org.exoplatform.web.WebAppController; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.core.UIComponent; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** * */ @Path("/contentviewer") public class ContentViewerRESTService implements ResourceContainer { private static final Log LOG = ExoLogger.getLogger(ContentViewerRESTService.class.getName()); private WebAppController webAppController; private RepositoryService repositoryService; private LinkManager linkManager; public ContentViewerRESTService(WebAppController webAppController, RepositoryService repositoryService, LinkManager linkManager) throws Exception { this.webAppController = webAppController; this.repositoryService = repositoryService; this.linkManager = linkManager; } /** * Returns a pdf file for a PDF document. * * @param repoName The repository name. * @param workspaceName The workspace name. * @param uuid The identifier of the document. * @return Response inputstream. * @throws Exception The exception * @anchor PDFViewerRESTService.getPDFFile */ @GET @Path("/{repoName}/{workspaceName}/{uuid}/") public Response getContent(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("uuid") String uuid) throws Exception { String content = null; try { ManageableRepository repository = repositoryService.getCurrentRepository(); ExtendedSession session = (ExtendedSession) getSystemProvider().getSession(workspaceName, repository); Node contentNode = session.getNodeByIdentifier(uuid); if(contentNode != null && contentNode.isNodeType(NodetypeConstant.EXO_SYMLINK)) { contentNode = linkManager.getTarget(contentNode); } StringWriter writer = new StringWriter(); UIDocViewer uiDocViewer = new UIDocViewer(); uiDocViewer.docPath = contentNode.getPath(); uiDocViewer.repository = repository.getConfiguration().getName(); uiDocViewer.workspace = workspaceName; uiDocViewer.setOriginalNode(contentNode); uiDocViewer.setNode(contentNode); ControllerContext controllerContext = new ControllerContext(webAppController, webAppController.getRouter(), request, response, null); PortalApplication application = webAppController.getApplication(PortalApplication.PORTAL_APPLICATION_ID); PortalRequestContext requestContext = new PortalRequestContext(application, controllerContext, org.exoplatform.portal.mop.SiteType.PORTAL.toString(), "", "", null); WebuiRequestContext.setCurrentInstance(requestContext); UIPortalApplication uiApplication = new UIPortalApplication(); uiApplication.setCurrentSite(new UIPortal()); requestContext.setUIApplication(uiApplication); requestContext.setWriter(writer); uiDocViewer.processRender(requestContext); content = writer.toString(); } catch (Exception e) { LOG.error("Cannot render content of document " + repoName + "/" + workspaceName + "/" + uuid, e); } return Response.ok(content).build(); } private SessionProvider getSystemProvider() { SessionProviderService service = WCMCoreUtils.getService(SessionProviderService.class); return service.getSystemSessionProvider(null); } public String getTemplate(Node contentNode) { if(contentNode == null) { return null; } TemplateService templateService = CommonsUtils.getService(TemplateService.class); String userName = ConversationState.getCurrent().getIdentity().getUserId(); try { String nodeType = contentNode.getPrimaryNodeType().getName(); if(templateService.isManagedNodeType(nodeType)) { return templateService.getTemplatePathByUser(false, nodeType, userName); } }catch (RepositoryException re){ if (LOG.isDebugEnabled() || LOG.isWarnEnabled()) LOG.error("Get template catch RepositoryException: ", re); } catch (Exception e) { LOG.warn(e.getMessage(), e); } return null; } public void processRender(String template, UIComponent uiComponent, Writer writer) throws Exception { if(template == null) { throw new IllegalStateException(); } else { ExoContainer container = ExoContainerContext.getCurrentContainer(); ResourceResolver resolver = new JCRResourceResolver("dms-system"); BindingContext bcontext = new BindingContext(resolver, writer); bcontext.put("_ctx", bcontext); bcontext.put("uicomponent", uiComponent); bcontext.put(uiComponent.getUIComponentName(), uiComponent); bcontext.put("locale", new Locale("en")); org.exoplatform.groovyscript.text.TemplateService service = container.getComponentInstanceOfType(org.exoplatform.groovyscript.text.TemplateService.class); service.merge(template, bcontext); } } }
7,618
Java
.java
exoplatform/ecms
25
59
13
2012-04-05T03:17:28Z
2024-05-09T08:26:32Z