answer
stringlengths
17
10.2M
package org.terasology.StructuralResources; import org.joml.RoundingMode; import org.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.audio.events.PlaySoundEvent; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.event.EventPriority; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.characters.events.AttackEvent; import org.terasology.logic.common.ActivateEvent; import org.terasology.logic.inventory.InventoryManager; import org.terasology.logic.inventory.InventoryUtils; import org.terasology.logic.inventory.SelectedInventorySlotComponent; import org.terasology.logic.inventory.events.BeforeItemPutInInventory; import org.terasology.logic.inventory.events.InventorySlotChangedEvent; import org.terasology.logic.inventory.events.InventorySlotStackSizeChangedEvent; import org.terasology.logic.location.LocationComponent; import org.terasology.logic.players.LocalPlayer; import org.terasology.math.ChunkMath; import org.terasology.math.Side; import org.terasology.registry.In; import org.terasology.utilities.Assets; import org.terasology.world.BlockEntityRegistry; import org.terasology.world.WorldProvider; import org.terasology.world.block.Block; import org.terasology.world.block.BlockComponent; import org.terasology.world.block.BlockManager; import org.terasology.world.block.entity.placement.PlaceBlocks; import org.terasology.world.block.family.BlockFamily; import org.terasology.world.block.family.BlockPlacementData; @RegisterSystem public class IngotStackSystem extends BaseComponentSystem { private static final Logger logger = LoggerFactory.getLogger(IngotStackSystem.class); private static final int INGOTS_PER_LAYER = 2; private static final int MAX_LAYERS = 3; private static final int MAX_INGOTS = MAX_LAYERS * INGOTS_PER_LAYER; private static final String LAYER_1_URI = "StructuralResources:IngotStack_01"; private static final String LAYER_2_URI = "StructuralResources:IngotStack_02"; private static final String LAYER_3_URI = "StructuralResources:IngotStack_03"; @In private WorldProvider worldProvider; @In private BlockManager blockManager; @In private BlockEntityRegistry blockEntityRegistry; @In private InventoryManager inventoryManager; @In private LocalPlayer localPlayer; @ReceiveEvent(priority = EventPriority.PRIORITY_HIGH) public void onRightClick(ActivateEvent event, EntityRef entity, IngotComponent ingotComponent) { EntityRef instigator = event.getInstigator(); BlockComponent targetBlockComponent = event.getTarget().getComponent(BlockComponent.class); if (targetBlockComponent == null) { event.consume(); return; } Side surfaceSide = Side.inDirection(event.getHitNormal()); Side secondaryDirection = ChunkMath.getSecondaryPlacementDirection(event.getDirection(), event.getHitNormal()); org.joml.Vector3i blockPos = new org.joml.Vector3i(targetBlockComponent.getPosition(new org.joml.Vector3i())); org.joml.Vector3i targetPos = new org.joml.Vector3i(blockPos).add(surfaceSide.direction()); IngotStackComponent stackComponent = event.getTarget().getComponent(IngotStackComponent.class); if (stackComponent != null && stackComponent.ingots < MAX_INGOTS) { EntityRef stackEntity = event.getTarget(); instigator.send(new PlaySoundEvent(Assets.getSound("engine:PlaceBlock").get(), 0.5f)); SelectedInventorySlotComponent selectedSlot = instigator.getComponent(SelectedInventorySlotComponent.class); inventoryManager.moveItem(instigator, instigator, selectedSlot.slot, stackEntity, 0, 1); } else if (canPlaceBlock(blockPos, targetPos)) { Block newStackBlock = blockManager.getBlockFamily(LAYER_1_URI) .getBlockForPlacement(new BlockPlacementData(targetPos, surfaceSide, secondaryDirection.toDirection().asVector3f())); PlaceBlocks placeNewIngotStack = new PlaceBlocks(targetPos, newStackBlock, instigator); worldProvider.getWorldEntity().send(placeNewIngotStack); instigator.send(new PlaySoundEvent(Assets.getSound("engine:PlaceBlock").get(), 0.5f)); inventoryManager.moveItem(instigator, instigator, findSlot(instigator), blockEntityRegistry.getBlockEntityAt(targetPos), 0, 1); updateIngotStack(targetPos, 1, instigator); } event.consume(); } @ReceiveEvent(priority = EventPriority.PRIORITY_HIGH) public void onLeftClick(AttackEvent event, EntityRef stackEntity, IngotStackComponent stackComponent) { EntityRef instigator = event.getInstigator(); if (stackComponent.ingots > 0) { inventoryManager.moveItem(stackEntity, instigator, 0, instigator, findSlot(instigator), 1); instigator.send(new PlaySoundEvent(Assets.getSound("engine:Loot").get(), 0.5f)); } event.consume(); } // for real-time updates to the stack @ReceiveEvent public void onStackSizeChange(InventorySlotStackSizeChangedEvent event, EntityRef stackEntity, IngotStackComponent stackComponent) { EntityRef instigator = localPlayer.getCharacterEntity(); LocationComponent locationComponent = stackEntity.getComponent(LocationComponent.class); org.joml.Vector3i pos = new org.joml.Vector3i(locationComponent.getWorldPosition(new Vector3f()), RoundingMode.FLOOR); if (event.getNewSize() > MAX_INGOTS) { inventoryManager.moveItem(stackEntity, instigator, 0, instigator, findSlot(instigator), event.getNewSize() - MAX_INGOTS); } updateIngotStack(pos, event.getNewSize(), instigator); } @ReceiveEvent public void onItemPut(BeforeItemPutInInventory event, EntityRef stackEntity, IngotStackComponent stackComponent) { EntityRef item = event.getItem(); // only ingot items allowed in the ingot stack if (!item.hasComponent(IngotComponent.class)) { event.consume(); } } @ReceiveEvent public void onEmpty(InventorySlotChangedEvent event, EntityRef stackEntity, IngotStackComponent stackComponent) { LocationComponent locationComponent = stackEntity.getComponent(LocationComponent.class); org.joml.Vector3i pos = new org.joml.Vector3i(locationComponent.getWorldPosition(new org.joml.Vector3f()), RoundingMode.FLOOR); if (event.getOldItem().hasComponent(IngotComponent.class) && event.getNewItem() == EntityRef.NULL) { updateIngotStack(pos, 0, localPlayer.getCharacterEntity()); } } private void updateIngotStack(org.joml.Vector3i stackPos, int ingots, EntityRef instigator) { EntityRef stackEntity = blockEntityRegistry.getBlockEntityAt(stackPos); Block stackBlock = worldProvider.getBlock(stackPos); String blockUriString = stackBlock.getBlockFamily().getURI().toString(); if (ingots < 0 || ingots > MAX_INGOTS) { return; } if (ingots == 0) { worldProvider.setBlock(stackPos, blockManager.getBlock(BlockManager.AIR_ID)); return; } if (!blockUriString.equalsIgnoreCase(LAYER_1_URI) && !blockUriString.equalsIgnoreCase(LAYER_2_URI) && !blockUriString.equalsIgnoreCase(LAYER_3_URI)) { // not an ingot block return; } IngotStackComponent stackComponent = stackEntity.getComponent(IngotStackComponent.class); int currentLayers = (stackComponent.ingots - 1) / INGOTS_PER_LAYER + 1; int newLayers = (ingots - 1) / INGOTS_PER_LAYER + 1; if (currentLayers != newLayers) { BlockFamily blockFamily; if (newLayers == 2) { blockFamily = blockManager.getBlockFamily(LAYER_2_URI); } else if (newLayers == 3) { blockFamily = blockManager.getBlockFamily(LAYER_3_URI); } else { blockFamily = blockManager.getBlockFamily(LAYER_1_URI); } Block newStackBlock = blockFamily.getBlockForPlacement(new BlockPlacementData(stackPos, Side.TOP, stackBlock.getDirection().toDirection().asVector3f())); PlaceBlocks placeNewIngotStack = new PlaceBlocks(stackPos, newStackBlock, instigator); worldProvider.getWorldEntity().send(placeNewIngotStack); stackEntity = blockEntityRegistry.getBlockEntityAt(stackPos); } stackComponent.ingots = ingots; stackEntity.saveComponent(stackComponent); } private boolean canPlaceBlock(org.joml.Vector3i blockPos, org.joml.Vector3i targetPos) { Block block = worldProvider.getBlock(blockPos); Block targetBlock = worldProvider.getBlock(targetPos); return block.isAttachmentAllowed() && targetBlock.isReplacementAllowed() && !targetBlock.isTargetable(); } private int findSlot(EntityRef entity) { SelectedInventorySlotComponent selectedSlot = entity.getComponent(SelectedInventorySlotComponent.class); if (inventoryManager.getItemInSlot(entity, selectedSlot.slot) == EntityRef.NULL || inventoryManager.getItemInSlot(entity, selectedSlot.slot).hasComponent(IngotComponent.class)) { return selectedSlot.slot; } int emptySlot = -1; int slotCount = InventoryUtils.getSlotCount(entity); for (int i = 0; i < slotCount; i++) { if (InventoryUtils.getItemAt(entity, i).hasComponent(IngotComponent.class)) { return i; } else if (InventoryUtils.getItemAt(entity, i) == EntityRef.NULL && emptySlot == -1) { emptySlot = i; } } return emptySlot; } }
package net.openhft.chronicle.queue; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesUtil; import net.openhft.chronicle.core.time.SetTimeProvider; import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder; import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueExcerpts.InternalAppender; import net.openhft.chronicle.wire.Wires; import org.junit.After; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static java.util.Objects.requireNonNull; import static net.openhft.chronicle.bytes.Bytes.elasticByteBuffer; import static net.openhft.chronicle.bytes.Bytes.fromString; public class ChronicleQueueIndexTest { @Test public void checkTheEOFisWrittenToPreQueueFile() { SetTimeProvider tp = new SetTimeProvider(System.nanoTime()); File firstCQFile = null; File file1 = DirectoryUtils.tempDir("indexQueueTest2"); try { try (ChronicleQueue queue = SingleChronicleQueueBuilder.builder() .path(file1) .rollCycle(RollCycles.DAILY) .timeProvider(tp) .build()) { InternalAppender appender = (InternalAppender) queue.acquireAppender(); appender.writeBytes(RollCycles.DAILY.toIndex(1, 0L), fromString("Hello World 1")); // Simulate the end of the day i.e the queue closes the day rolls // (note the change of index from 18264 to 18265) firstCQFile = queue.file(); firstCQFile = requireNonNull(firstCQFile.listFiles((dir, name) -> name.endsWith(".cq4")))[0]; Assert.assertFalse(hasEOFAtEndOfFile(firstCQFile)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } tp.advanceMillis(TimeUnit.DAYS.toMillis(2)); try (ChronicleQueue queue = SingleChronicleQueueBuilder.builder() .path(file1) .rollCycle(RollCycles.DAILY) .timeProvider(tp) .build();) { InternalAppender appender = (InternalAppender) queue.acquireAppender(); appender.writeBytes(RollCycles.DAILY.toIndex(3, 0L), fromString("Hello World 2")); // Simulate the end of the day i.e the queue closes the day rolls // (note the change of index from 18264 to 18265) Assert.assertTrue(hasEOFAtEndOfFile(firstCQFile)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } finally { file1.deleteOnExit(); } } @Test public void checkTheEOFisWrittenToPreQueueFileAfterPreTouch() { SetTimeProvider tp = new SetTimeProvider(System.nanoTime()); File firstCQFile = null; File file1 = DirectoryUtils.tempDir("indexQueueTest2"); try { try (ChronicleQueue queue = SingleChronicleQueueBuilder.builder() .path(file1) .rollCycle(RollCycles.DAILY) .timeProvider(tp) .build()) { InternalAppender appender = (InternalAppender) queue.acquireAppender(); appender.writeBytes(RollCycles.DAILY.toIndex(1, 0L), fromString("Hello World 1")); // Simulate the end of the day i.e the queue closes the day rolls // (note the change of index from 18264 to 18265) firstCQFile = queue.file(); firstCQFile = requireNonNull(firstCQFile.listFiles((dir, name) -> name.endsWith(".cq4")))[0]; Assert.assertFalse(hasEOFAtEndOfFile(firstCQFile)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } tp.advanceMillis(TimeUnit.DAYS.toMillis(1)); try (ChronicleQueue queue = SingleChronicleQueueBuilder.builder() .path(file1) .rollCycle(RollCycles.DAILY) .timeProvider(tp) .build();) { queue.acquireAppender().pretouch(); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } tp.advanceMillis(TimeUnit.DAYS.toMillis(1)); try (ChronicleQueue queue = SingleChronicleQueueBuilder.builder() .path(file1) .rollCycle(RollCycles.DAILY) .timeProvider(tp) .build();) { InternalAppender appender = (InternalAppender) queue.acquireAppender(); appender.writeBytes(RollCycles.DAILY.toIndex(3, 0L), fromString("Hello World 2")); // Simulate the end of the day i.e the queue closes the day rolls // (note the change of index from 18264 to 18265) Assert.assertTrue(hasEOFAtEndOfFile(firstCQFile)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } } finally { System.out.println(file1.getAbsolutePath()); file1.deleteOnExit(); } } private boolean hasEOFAtEndOfFile(final File file) throws IOException { Bytes bytes = BytesUtil.readFile(file.getAbsolutePath()); // to check that "00 00 00 c0") is the EOF you can run net.openhft.chronicle.queue.ChronicleQueueIndexTest.eofAsHex // eofAsHex(); // check that the EOF is in the last few bytes. String lastFewBytes = bytes.toHexString(131328, 128); //System.out.println(lastFewBytes); // 00 00 00 c0 is the EOF return lastFewBytes.contains("00 00 00 c0"); } private void eofAsHex() { Bytes<ByteBuffer> eof = elasticByteBuffer(4); eof.writeInt(Wires.END_OF_DATA); System.out.println(eof.toHexString()); System.out.println(eof); } @Test public void testIndexQueue() { ChronicleQueue queue = SingleChronicleQueueBuilder.builder() .path("test-chronicle") .rollCycle(RollCycles.DAILY) .build(); InternalAppender appender = (InternalAppender)queue.acquireAppender(); Bytes<byte[]> hello_world = Bytes.fromString("Hello World 1"); appender.writeBytes(RollCycles.DAILY.toIndex(18264, 0L), hello_world); hello_world = Bytes.fromString("Hello World 2"); appender.writeBytes(RollCycles.DAILY.toIndex(18264, 1L), hello_world); // Simulate the end of the day i.e the queue closes the day rolls // (note the change of index from 18264 to 18265) queue.close(); queue = SingleChronicleQueueBuilder.builder() .path("test-chronicle") .rollCycle(RollCycles.DAILY) .build(); appender = (InternalAppender)queue.acquireAppender(); // add a message for the new day hello_world = Bytes.fromString("Hello World 3"); appender.writeBytes(RollCycles.DAILY.toIndex(18265, 0L), hello_world); final ExcerptTailer tailer = queue.createTailer(); final Bytes forRead = Bytes.elasticByteBuffer(); final List<String> results = new ArrayList<>(); while(tailer.readBytes(forRead)) { results.add(forRead.toString()); forRead.clear(); } Assert.assertTrue(results.contains("Hello World 1")); Assert.assertTrue(results.contains("Hello World 2")); // The reader fails to read the third message. The reason for this is // that there was no EOF marker placed at end of the 18264 indexed file // so when the reader started reading through the queues it got stuck on // that file and never progressed to the latest queue file. Assert.assertTrue(results.contains("Hello World 3")); forRead.release(); } @After public void checkRegisteredBytes() { BytesUtil.checkRegisteredBytes(); } }
package com.rmrobotics.library; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.Range; public class Motor { private static final double MAX_POWER = 1.0; private static final double MIN_POWER = 0.1; private DcMotor parent; private DcMotor.Direction defaultDirection; private double minPower; private double maxPower; private double desiredPower; private double currentPower; public Motor (DcMotor dc, DcMotor.Direction d, double min, double max){ parent = dc; defaultDirection = d; minPower = min; maxPower = max; } //Todo add string to send in DbgLog confirming motor settings once configured public void setDesiredPower(double d){ desiredPower = d; } public void updateCurrentPower(){ /** * let it be zero if it needs to be * absolute value and switch direction if needed * clip to be within range * */ if(desiredPower<0){ if(defaultDirection = DcMotor.Direction.FORWARDS;){ defaultDirection = DcMotor.Direction.REVERSE; }else if (defaultDirection = DcMotor.Direction.REVERSE){ defaultDirection = DcMotor.Direction.FORWARDS; } desiredPower = Math.abs(desiredPower); minPower = Math.abs(minPower); maxPower=Math.abs(maxPower); } desiredPower = Range.clip(desiredPower, minPower, maxPower); currentPower = desiredPower; } public void setCurrentPower(){ parent.setPower(currentPower); } }
package ti.modules.titanium.map; import java.util.List; import java.io.IOException; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiDict; import org.appcelerator.titanium.TiProperties; import org.appcelerator.titanium.TiProxy; import org.appcelerator.titanium.TiContext.OnLifecycleEvent; import org.appcelerator.titanium.io.TiBaseFile; import org.appcelerator.titanium.io.TiFileFactory; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.Log; import org.appcelerator.titanium.util.TiConfig; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.view.TiUIView; import org.appcelerator.titanium.util.TiUIHelper; import org.json.JSONObject; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.ViewGroup.LayoutParams; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; interface TitaniumOverlayListener { public void onTap(int index); } public class TiMapView extends TiUIView implements Handler.Callback, TitaniumOverlayListener { private static final String LCAT = "TiMapView"; private static final boolean DBG = TiConfig.LOGD; private static final String TI_DEVELOPMENT_KEY = "0Rq5tT4bUSXcVQ3F0gt8ekVBkqgn05ZJBQMj6uw"; private static final String OLD_API_KEY = "ti.android.google.map.api.key"; private static final String DEVELOPMENT_API_KEY = "ti.android.google.map.api.key.development"; private static final String PRODUCTION_API_KEY = "ti.android.google.map.api.key.production"; public static final String EVENT_CLICK = "click"; public static final String EVENT_REGION_CHANGED = "regionChanged"; public static final int MAP_VIEW_STANDARD = 1; public static final int MAP_VIEW_SATELLITE = 2; public static final int MAP_VIEW_HYBRID = 3; private static final int MSG_SET_LOCATION = 300; private static final int MSG_SET_MAPTYPE = 301; private static final int MSG_SET_REGIONFIT = 302; private static final int MSG_SET_ANIMATE = 303; private static final int MSG_SET_USERLOCATION = 304; private static final int MSG_SET_SCROLLENABLED = 305; private static final int MSG_CHANGE_ZOOM = 306; private static final int MSG_ADD_ANNOTATION = 307; private static final int MSG_REMOVE_ANNOTATION = 308; private static final int MSG_SELECT_ANNOTATION = 309; private static final int MSG_REMOVE_ALL_ANNOTATIONS = 310; //private MapView view; private boolean scrollEnabled; private boolean regionFit; private boolean animate; private boolean userLocation; private LocalMapView view; private Window mapWindow; private TitaniumOverlay overlay; private MyLocationOverlay myLocation; private TiOverlayItemView itemView; private TiDict[] annotations; private Handler handler; class LocalMapView extends MapView { private boolean scrollEnabled; private int lastLongitude; private int lastLatitude; private int lastLatitudeSpan; private int lastLongitudeSpan; public LocalMapView(Context context, String apiKey) { super(context, apiKey); scrollEnabled = false; } public void setScrollable(boolean enable) { scrollEnabled = enable; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (!scrollEnabled && ev.getAction() == MotionEvent.ACTION_MOVE) { return true; } return super.dispatchTouchEvent(ev); } @Override public boolean dispatchTrackballEvent(MotionEvent ev) { if (!scrollEnabled && ev.getAction() == MotionEvent.ACTION_MOVE) { return true; } return super.dispatchTrackballEvent(ev); } @Override public void computeScroll() { super.computeScroll(); GeoPoint center = getMapCenter(); if (lastLatitude != center.getLatitudeE6() || lastLongitude != center.getLongitudeE6() || lastLatitudeSpan != getLatitudeSpan() || lastLongitudeSpan != getLongitudeSpan()) { lastLatitude = center.getLatitudeE6(); lastLongitude = center.getLongitudeE6(); lastLatitudeSpan = getLatitudeSpan(); lastLongitudeSpan = getLongitudeSpan(); TiDict d = new TiDict(); d.put("latitude", scaleFromGoogle(lastLatitude)); d.put("longitude", scaleFromGoogle(lastLongitude)); d.put("latitudeDelta", scaleFromGoogle(lastLatitudeSpan)); d.put("longitudeDelta", scaleFromGoogle(lastLongitudeSpan)); proxy.fireEvent("regionChanged", d); } } } class TitaniumOverlay extends ItemizedOverlay<TiOverlayItem> { TiDict[] annotations; TitaniumOverlayListener listener; public TitaniumOverlay(Drawable defaultDrawable, TitaniumOverlayListener listener) { super(defaultDrawable); this.listener = listener; } public void setAnnotations(TiDict[] annotations) { this.annotations = annotations; populate(); } @Override protected TiOverlayItem createItem(int i) { TiOverlayItem item = null; TiDict a = annotations[i]; if (a.containsKey("latitude") && a.containsKey("longitude")) { String title = a.optString("title", ""); String subtitle = a.optString("subtitle", ""); GeoPoint location = new GeoPoint(scaleToGoogle(a.getDouble("latitude")), scaleToGoogle(a.getDouble("longitude"))); item = new TiOverlayItem(location, title, subtitle); if (a.containsKey("pincolor")) { switch(a.getInt("pincolor")) { case 1 : // RED item.setMarker(makeMarker(Color.RED)); break; case 2 : // GREEN item.setMarker(makeMarker(Color.GREEN)); break; case 3 : // PURPLE item.setMarker(makeMarker(Color.argb(255,192,0,192))); break; } } //If pinimage is set if (a.containsKey("pinimage")) { String imagePath = a.getString("pinimage"); Drawable marker = makeMarker(imagePath); boundCenterBottom(marker); item.setMarker(marker); } if (a.containsKey("leftButton")) { item.setLeftButton(a.getString("leftButton")); } if (a.containsKey("rightButton")) { item.setRightButton(a.getString("rightButton")); } } else { Log.w(LCAT, "Skipping annotation: No coordinates } return item; } @Override public int size() { return (annotations == null) ? 0 : annotations.length; } @Override protected boolean onTap(int index) { boolean handled = super.onTap(index); if(!handled ) { listener.onTap(index); } return handled; } } public TiMapView(TiViewProxy proxy, Window mapWindow) { super(proxy); this.mapWindow = mapWindow; this.handler = new Handler(this); //TODO MapKey TiApplication app = proxy.getTiContext().getTiApp(); TiProperties appProperties = app.getAppProperties(); String oldKey = appProperties.getString(OLD_API_KEY, TI_DEVELOPMENT_KEY); String developmentKey = appProperties.getString(DEVELOPMENT_API_KEY, oldKey); String productionKey = appProperties.getString(PRODUCTION_API_KEY, oldKey); String apiKey = developmentKey; if (app.getDeployType().equals(TiApplication.DEPLOY_TYPE_PRODUCTION)) { apiKey = productionKey; } view = new LocalMapView(mapWindow.getContext(), apiKey); TiMapActivity ma = (TiMapActivity) mapWindow.getContext(); ma.setLifecycleListener(new OnLifecycleEvent() { public void onPause() { if (myLocation != null) { if (DBG) { Log.d(LCAT, "onPause: Disabling My Location"); } myLocation.disableMyLocation(); } } public void onResume() { if (myLocation != null && userLocation) { if (DBG) { Log.d(LCAT, "onResume: Enabling My Location"); } myLocation.enableMyLocation(); } } public void onDestroy() { } public void onStart() { } public void onStop() { } }); view.setBuiltInZoomControls(true); view.setScrollable(true); view.setClickable(true); setNativeView(view); this.regionFit =true; this.animate = false; final TiViewProxy fproxy = proxy; itemView = new TiOverlayItemView(proxy.getContext()); itemView.setOnOverlayClickedListener(new TiOverlayItemView.OnOverlayClicked(){ public void onClick(int lastIndex, String clickedItem) { TiOverlayItem item = overlay.getItem(lastIndex); if (item != null) { TiDict d = new TiDict(); d.put("source", clickedItem); d.put("title", item.getTitle()); d.put("subtitle", item.getSnippet()); d.put("latitude", scaleFromGoogle(item.getPoint().getLatitudeE6())); d.put("longitude", scaleFromGoogle(item.getPoint().getLongitudeE6())); fproxy.fireEvent(EVENT_CLICK, d); } } }); } private LocalMapView getView() { return view; } public boolean handleMessage(Message msg) { switch(msg.what) { case MSG_SET_LOCATION : { doSetLocation((TiDict) msg.obj); return true; } case MSG_SET_MAPTYPE : { doSetMapType(msg.arg1); return true; } case MSG_SET_REGIONFIT : regionFit = msg.arg1 == 1 ? true : false; return true; case MSG_SET_ANIMATE : animate = msg.arg1 == 1 ? true : false; return true; case MSG_SET_SCROLLENABLED : animate = msg.arg1 == 1 ? true : false; if (view != null) { view.setScrollable(scrollEnabled); } return true; case MSG_SET_USERLOCATION : userLocation = msg.arg1 == 1 ? true : false; doUserLocation(userLocation); return true; case MSG_CHANGE_ZOOM : MapController mc = view.getController(); if (mc != null) { mc.setZoom(view.getZoomLevel() + msg.arg1); } return true; case MSG_ADD_ANNOTATION : doAddAnnotation((TiDict) msg.obj); return true; case MSG_REMOVE_ANNOTATION : doRemoveAnnotation((String) msg.obj); return true; case MSG_SELECT_ANNOTATION : boolean select = msg.arg1 == 1 ? true : false; boolean animate = msg.arg2 == 1 ? true : false; String title = (String) msg.obj; doSelectAnnotation(select, title, animate); return true; case MSG_REMOVE_ALL_ANNOTATIONS : doSetAnnotations(new TiDict[0]); return true; } return false; } private void hideAnnotation() { if (view != null && itemView != null) { view.removeView(itemView); itemView.clearLastIndex(); } } private void showAnnotation(int index, TiOverlayItem item) { if (view != null && itemView != null && item != null) { itemView.setItem(index, item); //Make sure the atonnation is always on top of the marker int y = -1*item.getMarker(TiOverlayItem.ITEM_STATE_FOCUSED_MASK).getIntrinsicHeight(); MapView.LayoutParams params = new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, item.getPoint(), 0, y, MapView.LayoutParams.BOTTOM_CENTER); params.mode = MapView.LayoutParams.MODE_MAP; view.addView(itemView, params); } } public void onTap(int index) { if (overlay != null) { synchronized(overlay) { TiOverlayItem item = overlay.getItem(index); if (itemView != null && index == itemView.getLastIndex() && itemView.getVisibility() == View.VISIBLE) { hideAnnotation(); return; } if (item.hasData()) { hideAnnotation(); showAnnotation(index, item); } else { Toast.makeText(proxy.getContext(), "No information for location", Toast.LENGTH_SHORT).show(); } } } } @Override public void processProperties(TiDict d) { LocalMapView view = getView(); if (d.containsKey("mapType")) { doSetMapType(TiConvert.toInt(d, "mapType")); } if (d.containsKey("zoomEnabled")) { view.setBuiltInZoomControls(TiConvert.toBoolean(d,"zoomEnabled")); } if (d.containsKey("scrollEnabled")) { view.setScrollable(TiConvert.toBoolean(d, "scrollEnabled")); } if (d.containsKey("region")) { doSetLocation(d.getTiDict("region")); } if (d.containsKey("regionFit")) { regionFit = d.getBoolean("regionFit"); } if (d.containsKey("animate")) { animate = d.getBoolean("animate"); } if (d.containsKey("userLocation")) { doUserLocation(d.getBoolean("userLocation")); } if (d.containsKey("annotations")) { proxy.internalSetDynamicValue("annotations", d.get("annotations"), false); Object[] annotations = (Object[]) d.get("annotations"); TiDict[] anns = new TiDict[annotations.length]; for(int i = 0; i < annotations.length; i++) { AnnotationProxy ap = (AnnotationProxy) annotations[i]; anns[i] = ap.getDynamicProperties(); } doSetAnnotations(anns); } super.processProperties(d); } @Override public void propertyChanged(String key, Object oldValue, Object newValue, TiProxy proxy) { if (key.equals("location")) { if (newValue != null) { if (newValue instanceof AnnotationProxy) { AnnotationProxy ap = (AnnotationProxy) newValue; doSetLocation(ap.getDynamicProperties()); } else if (newValue instanceof TiDict) { doSetLocation((TiDict) newValue); } } } else if (key.equals("mapType")) { if (newValue == null) { doSetMapType(MAP_VIEW_STANDARD); } else { doSetMapType(TiConvert.toInt(newValue)); } } else { super.propertyChanged(key, oldValue, newValue, proxy); } } public void doSetLocation(TiDict d) { LocalMapView view = getView(); if (d.containsKey("longitude") && d.containsKey("latitude")) { GeoPoint gp = new GeoPoint(scaleToGoogle(d.getDouble("latitude")), scaleToGoogle(d.getDouble("longitude"))); boolean anim = false; if (d.containsKey("animate")) { anim = TiConvert.toBoolean(d, "animate"); } if (anim) { view.getController().animateTo(gp); } else { view.getController().setCenter(gp); } } if (regionFit && d.containsKey("longitudeDelta") && d.containsKey("latitudeDelta")) { view.getController().zoomToSpan(scaleToGoogle(d.getDouble("latitudeDelta")), scaleToGoogle(d.getDouble("longitudeDelta"))); } else { Log.w(LCAT, "span must have longitudeDelta and latitudeDelta"); } } public void doSetMapType(int type) { if (view != null) { switch(type) { case MAP_VIEW_STANDARD : view.setSatellite(false); view.setTraffic(false); view.setStreetView(false); break; case MAP_VIEW_SATELLITE: view.setSatellite(true); view.setTraffic(false); view.setStreetView(false); break; case MAP_VIEW_HYBRID : view.setSatellite(false); view.setTraffic(false); view.setStreetView(true); break; } } } public void doSetAnnotations(TiDict[] annotations) { if (annotations != null) { this.annotations = annotations; List<Overlay> overlays = view.getOverlays(); synchronized(overlays) { if (overlays.contains(overlay)) { overlays.remove(overlay); overlay = null; } int len = annotations.length; if (len > 0) { overlay = new TitaniumOverlay(makeMarker(Color.BLUE), this); overlay.setAnnotations(annotations); overlays.add(overlay); } view.invalidate(); } } } public void addAnnotation(JSONObject annotation) { handler.obtainMessage(MSG_ADD_ANNOTATION, annotation).sendToTarget(); }; public void doAddAnnotation(TiDict annotation) { // if (annotation != null && view != null) { // if (annotations == null) { // annotations = new JSONArray(); // annotations.put(annotation); // doSetAnnotations(annotations); }; public void removeAnnotation(String title) { handler.obtainMessage(MSG_REMOVE_ANNOTATION, title).sendToTarget(); }; public void removeAllAnnotations() { handler.obtainMessage(MSG_REMOVE_ALL_ANNOTATIONS).sendToTarget(); } private int findAnnotation(String title) { int existsIndex = -1; // Check for existence for(int i = 0; i < annotations.length; i++) { TiDict a = annotations[i]; String t = a.optString("title", null); if (t != null) { if (title.equals(t)) { if (DBG) { Log.d(LCAT, "Annotation found at index: " + " with title: " + title); } existsIndex = i; break; } } } return existsIndex; } public void doRemoveAnnotation(String title) { if (title != null && view != null && annotations != null) { int existsIndex = findAnnotation(title); // If found, build a new annotation list if (existsIndex > -1) { TiDict[] a = new TiDict[annotations.length-1]; int j = 0; for(int i = 0; i < annotations.length; i++) { if (i != existsIndex) { a[j++] = (annotations[i]); } } annotations = a; doSetAnnotations(annotations); } } }; public void selectAnnotation(boolean select, String title, boolean animate) { if (title != null) { handler.obtainMessage(MSG_SELECT_ANNOTATION, select ? 1 : 0, animate ? 1 : 0, title).sendToTarget(); } } public void doSelectAnnotation(boolean select, String title, boolean animate) { if (title != null && view != null && annotations != null && overlay != null) { int index = findAnnotation(title); if (index > -1) { if (overlay != null) { synchronized(overlay) { TiOverlayItem item = overlay.getItem(index); if (select) { if (itemView != null && index == itemView.getLastIndex() && itemView.getVisibility() != View.VISIBLE) { showAnnotation(index, item); return; } hideAnnotation(); MapController controller = view.getController(); if (animate) { controller.animateTo(item.getPoint()); } else { controller.setCenter(item.getPoint()); } showAnnotation(index, item); } else { hideAnnotation(); } } } } } } public void doUserLocation(boolean userLocation) { if (view != null) { if (userLocation) { if (myLocation == null) { myLocation = new MyLocationOverlay(proxy.getContext(), view); } List<Overlay> overlays = view.getOverlays(); synchronized(overlays) { if (!overlays.contains(myLocation)) { overlays.add(myLocation); } } myLocation.enableMyLocation(); } else { if (myLocation != null) { List<Overlay> overlays = view.getOverlays(); synchronized(overlays) { if (overlays.contains(myLocation)) { overlays.remove(myLocation); } myLocation.disableMyLocation(); } } } } } public void changeZoomLevel(int delta) { handler.obtainMessage(MSG_CHANGE_ZOOM, delta, 0).sendToTarget(); } private Drawable makeMarker(int c) { OvalShape s = new OvalShape(); s.resize(1.0f, 1.0f); ShapeDrawable d = new ShapeDrawable(s); d.setBounds(0, 0, 15, 15); d.getPaint().setColor(c); return d; } private Drawable makeMarker(String pinimage) { String url = proxy.getTiContext().resolveUrl(null, (String)pinimage); TiBaseFile file = TiFileFactory.createTitaniumFile(proxy.getTiContext(), new String[] { url }, false); try { Drawable d = new BitmapDrawable(TiUIHelper.createBitmap(file.getInputStream())); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } catch (IOException e) { Log.e(LCAT, "Error creating drawable from path: " + pinimage.toString(), e); } return null; } private double scaleFromGoogle(int value) { return (double)value / 1000000.0; } private int scaleToGoogle(double value) { return (int)(value * 1000000); } }
package mathsquared.resultswizard2; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.net.Socket; /** * Main class for the application; runs the administrator GUI that handles result entry. * * @author MathSquared * */ public class ResultsWizard2 { /** * @param args the command-line arguments; unused */ public static void main (String[] args) { // Setup comms ConnectionDetailsFrame cdf = new ConnectionDetailsFrame(true); Socket sock = cdf.call(); InputStream istr; OutputStream ostr; if (sock != null) { // there is a socket; remote try { istr = sock.getInputStream(); ostr = sock.getOutputStream(); } catch (IOException e) { System.out.println("ERROR: I/O error occurred when initializing network communication"); e.printStackTrace(System.out); System.out.println("Exiting..."); System.exit(0); return; } } else { // local istr = new PipedInputStream(); ostr = new PipedOutputStream(); try { new Display(new PipedInputStream((PipedOutputStream) ostr), new PipedOutputStream((PipedInputStream) istr)); } catch (IOException e) { System.out.println("ERROR: I/O error occurred when initializing display"); e.printStackTrace(System.out); System.out.println("Exiting..."); System.exit(0); return; } } // TODO make sure this side calls the ObjectOutputStream constructor first! otherwise, deadlock results (see Javadoc) } }
package com.brentvatne.react; import android.annotation.SuppressLint; import android.content.res.AssetFileDescriptor; import android.graphics.Matrix; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.WindowManager; import android.webkit.CookieManager; import android.widget.MediaController; import com.android.vending.expansion.zipfile.APKExpansionSupport; import com.android.vending.expansion.zipfile.ZipResourceFile; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.LifecycleEventListener; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.events.RCTEventEmitter; import com.yqritc.scalablevideoview.ScalableType; import com.yqritc.scalablevideoview.ScalableVideoView; import com.yqritc.scalablevideoview.ScaleManager; import com.yqritc.scalablevideoview.Size; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.lang.Math; import java.math.BigDecimal; import javax.annotation.Nullable; @SuppressLint("ViewConstructor") public class ReactVideoView extends ScalableVideoView implements MediaPlayer.OnPreparedListener, MediaPlayer .OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnInfoListener, LifecycleEventListener, MediaController.MediaPlayerControl { public enum Events { EVENT_LOAD_START("onVideoLoadStart"), EVENT_LOAD("onVideoLoad"), EVENT_ERROR("onVideoError"), EVENT_PROGRESS("onVideoProgress"), EVENT_SEEK("onVideoSeek"), EVENT_END("onVideoEnd"), EVENT_STALLED("onPlaybackStalled"), EVENT_RESUME("onPlaybackResume"), EVENT_READY_FOR_DISPLAY("onReadyForDisplay"); private final String mName; Events(final String name) { mName = name; } @Override public String toString() { return mName; } } public static final String EVENT_PROP_FAST_FORWARD = "canPlayFastForward"; public static final String EVENT_PROP_SLOW_FORWARD = "canPlaySlowForward"; public static final String EVENT_PROP_SLOW_REVERSE = "canPlaySlowReverse"; public static final String EVENT_PROP_REVERSE = "canPlayReverse"; public static final String EVENT_PROP_STEP_FORWARD = "canStepForward"; public static final String EVENT_PROP_STEP_BACKWARD = "canStepBackward"; public static final String EVENT_PROP_DURATION = "duration"; public static final String EVENT_PROP_PLAYABLE_DURATION = "playableDuration"; public static final String EVENT_PROP_SEEKABLE_DURATION = "seekableDuration"; public static final String EVENT_PROP_CURRENT_TIME = "currentTime"; public static final String EVENT_PROP_SEEK_TIME = "seekTime"; public static final String EVENT_PROP_NATURALSIZE = "naturalSize"; public static final String EVENT_PROP_WIDTH = "width"; public static final String EVENT_PROP_HEIGHT = "height"; public static final String EVENT_PROP_ORIENTATION = "orientation"; public static final String EVENT_PROP_ERROR = "error"; public static final String EVENT_PROP_WHAT = "what"; public static final String EVENT_PROP_EXTRA = "extra"; private ThemedReactContext mThemedReactContext; private RCTEventEmitter mEventEmitter; private Handler mProgressUpdateHandler = new Handler(); private Runnable mProgressUpdateRunnable = null; private Handler videoControlHandler = new Handler(); private MediaController mediaController; private String mSrcUriString = null; private String mSrcType = "mp4"; private ReadableMap mRequestHeaders = null; private boolean mSrcIsNetwork = false; private boolean mSrcIsAsset = false; private ScalableType mResizeMode = ScalableType.LEFT_TOP; private boolean mRepeat = false; private boolean mPaused = false; private boolean mMuted = false; private float mVolume = 1.0f; private float mStereoPan = 0.0f; private float mProgressUpdateInterval = 250.0f; private float mRate = 1.0f; private float mActiveRate = 1.0f; private boolean mPlayInBackground = false; private boolean mBackgroundPaused = false; private int mMainVer = 0; private int mPatchVer = 0; private boolean mMediaPlayerValid = false; // True if mMediaPlayer is in prepared, started, paused or completed state. private int mVideoDuration = 0; private int mVideoBufferedDuration = 0; private boolean isCompleted = false; private boolean mUseNativeControls = false; public ReactVideoView(ThemedReactContext themedReactContext) { super(themedReactContext); mThemedReactContext = themedReactContext; mEventEmitter = themedReactContext.getJSModule(RCTEventEmitter.class); themedReactContext.addLifecycleEventListener(this); initializeMediaPlayerIfNeeded(); setSurfaceTextureListener(this); mProgressUpdateRunnable = new Runnable() { @Override public void run() { if (mMediaPlayerValid && !isCompleted && !mPaused && !mBackgroundPaused) { WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_CURRENT_TIME, mMediaPlayer.getCurrentPosition() / 1000.0); event.putDouble(EVENT_PROP_PLAYABLE_DURATION, mVideoBufferedDuration / 1000.0); //TODO:mBufferUpdateRunnable event.putDouble(EVENT_PROP_SEEKABLE_DURATION, mVideoDuration / 1000.0); mEventEmitter.receiveEvent(getId(), Events.EVENT_PROGRESS.toString(), event); // Check for update after an interval mProgressUpdateHandler.postDelayed(mProgressUpdateRunnable, Math.round(mProgressUpdateInterval)); } } }; } @Override public boolean onTouchEvent(MotionEvent event) { if (mUseNativeControls) { initializeMediaControllerIfNeeded(); mediaController.show(); } return super.onTouchEvent(event); } @Override @SuppressLint("DrawAllocation") protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (!changed || !mMediaPlayerValid) { return; } int videoWidth = getVideoWidth(); int videoHeight = getVideoHeight(); if (videoWidth == 0 || videoHeight == 0) { return; } Size viewSize = new Size(getWidth(), getHeight()); Size videoSize = new Size(videoWidth, videoHeight); ScaleManager scaleManager = new ScaleManager(viewSize, videoSize); Matrix matrix = scaleManager.getScaleMatrix(mScalableType); if (matrix != null) { setTransform(matrix); } } private void initializeMediaPlayerIfNeeded() { if (mMediaPlayer == null) { mMediaPlayerValid = false; mMediaPlayer = new MediaPlayer(); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.setOnVideoSizeChangedListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnBufferingUpdateListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setOnInfoListener(this); } } private void initializeMediaControllerIfNeeded() { if (mediaController == null) { mediaController = new MediaController(this.getContext()); } } public void cleanupMediaPlayerResources() { if ( mediaController != null ) { mediaController.hide(); } if ( mMediaPlayer != null ) { mMediaPlayerValid = false; release(); } } public void setSrc(final String uriString, final String type, final boolean isNetwork, final boolean isAsset, final ReadableMap requestHeaders) { setSrc(uriString, type, isNetwork, isAsset, requestHeaders, 0, 0); } public void setSrc(final String uriString, final String type, final boolean isNetwork, final boolean isAsset, final ReadableMap requestHeaders, final int expansionMainVersion, final int expansionPatchVersion) { mSrcUriString = uriString; mSrcType = type; mSrcIsNetwork = isNetwork; mSrcIsAsset = isAsset; mRequestHeaders = requestHeaders; mMainVer = expansionMainVersion; mPatchVer = expansionPatchVersion; mMediaPlayerValid = false; mVideoDuration = 0; mVideoBufferedDuration = 0; initializeMediaPlayerIfNeeded(); mMediaPlayer.reset(); try { if (isNetwork) { // Use the shared CookieManager to access the cookies // set by WebViews inside the same app CookieManager cookieManager = CookieManager.getInstance(); Uri parsedUrl = Uri.parse(uriString); Uri.Builder builtUrl = parsedUrl.buildUpon(); String cookie = cookieManager.getCookie(builtUrl.build().toString()); Map<String, String> headers = new HashMap<String, String>(); if (cookie != null) { headers.put("Cookie", cookie); } if (mRequestHeaders != null) { headers.putAll(toStringMap(mRequestHeaders)); } setDataSource(mThemedReactContext, parsedUrl, headers); } else if (isAsset) { if (uriString.startsWith("content: Uri parsedUrl = Uri.parse(uriString); setDataSource(mThemedReactContext, parsedUrl); } else { setDataSource(uriString); } } else { ZipResourceFile expansionFile= null; AssetFileDescriptor fd= null; if(mMainVer>0) { try { expansionFile = APKExpansionSupport.getAPKExpansionZipFile(mThemedReactContext, mMainVer, mPatchVer); fd = expansionFile.getAssetFileDescriptor(uriString.replace(".mp4","") + ".mp4"); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } } if(fd==null) { int identifier = mThemedReactContext.getResources().getIdentifier( uriString, "drawable", mThemedReactContext.getPackageName() ); if (identifier == 0) { identifier = mThemedReactContext.getResources().getIdentifier( uriString, "raw", mThemedReactContext.getPackageName() ); } setRawData(identifier); } else { setDataSource(fd.getFileDescriptor(), fd.getStartOffset(),fd.getLength()); } } } catch (Exception e) { e.printStackTrace(); return; } WritableMap src = Arguments.createMap(); WritableMap wRequestHeaders = Arguments.createMap(); wRequestHeaders.merge(mRequestHeaders); src.putString(ReactVideoViewManager.PROP_SRC_URI, uriString); src.putString(ReactVideoViewManager.PROP_SRC_TYPE, type); src.putMap(ReactVideoViewManager.PROP_SRC_HEADERS, wRequestHeaders); src.putBoolean(ReactVideoViewManager.PROP_SRC_IS_NETWORK, isNetwork); if(mMainVer>0) { src.putInt(ReactVideoViewManager.PROP_SRC_MAINVER, mMainVer); if(mPatchVer>0) { src.putInt(ReactVideoViewManager.PROP_SRC_PATCHVER, mPatchVer); } } WritableMap event = Arguments.createMap(); event.putMap(ReactVideoViewManager.PROP_SRC, src); mEventEmitter.receiveEvent(getId(), Events.EVENT_LOAD_START.toString(), event); isCompleted = false; try { prepareAsync(this); } catch (Exception e) { e.printStackTrace(); } } public void setResizeModeModifier(final ScalableType resizeMode) { mResizeMode = resizeMode; if (mMediaPlayerValid) { setScalableType(resizeMode); invalidate(); } } public void setRepeatModifier(final boolean repeat) { mRepeat = repeat; if (mMediaPlayerValid) { setLooping(repeat); } } public void setPausedModifier(final boolean paused) { mPaused = paused; if (!mMediaPlayerValid) { return; } if (mPaused) { if (mMediaPlayer.isPlaying()) { pause(); setPreventScreenFromDimmingFlag(false); } } else { if (!mMediaPlayer.isPlaying()) { start(); setPreventScreenFromDimmingFlag(true); // Setting the rate unpauses, so we have to wait for an unpause if (mRate != mActiveRate) { setRateModifier(mRate); } // Also Start the Progress Update Handler mProgressUpdateHandler.post(mProgressUpdateRunnable); } } } // reduces the volume based on stereoPan private float calulateRelativeVolume() { float relativeVolume = (mVolume * (1 - Math.abs(mStereoPan))); // only one decimal allowed BigDecimal roundRelativeVolume = new BigDecimal(relativeVolume).setScale(1, BigDecimal.ROUND_HALF_UP); return roundRelativeVolume.floatValue(); } public void setMutedModifier(final boolean muted) { mMuted = muted; if (!mMediaPlayerValid) { return; } if (mMuted) { setVolume(0, 0); } else if (mStereoPan < 0) { // louder on the left channel setVolume(mVolume, calulateRelativeVolume()); } else if (mStereoPan > 0) { // louder on the right channel setVolume(calulateRelativeVolume(), mVolume); } else { // same volume on both channels setVolume(mVolume, mVolume); } } public void setVolumeModifier(final float volume) { mVolume = volume; setMutedModifier(mMuted); } public void setStereoPan(final float stereoPan) { mStereoPan = stereoPan; setMutedModifier(mMuted); } public void setProgressUpdateInterval(final float progressUpdateInterval) { mProgressUpdateInterval = progressUpdateInterval; } public void setRateModifier(final float rate) { mRate = rate; if (mMediaPlayerValid) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!mPaused) { // Applying the rate while paused will cause the video to start try { mMediaPlayer.setPlaybackParams(mMediaPlayer.getPlaybackParams().setSpeed(rate)); mActiveRate = rate; } catch (Exception e) { Log.e(ReactVideoViewManager.REACT_CLASS, "Unable to set rate, unsupported on this device"); } } } else { Log.e(ReactVideoViewManager.REACT_CLASS, "Setting playback rate is not yet supported on Android versions below 6.0"); } } } public void applyModifiers() { setResizeModeModifier(mResizeMode); setRepeatModifier(mRepeat); setPausedModifier(mPaused); setMutedModifier(mMuted); setProgressUpdateInterval(mProgressUpdateInterval); setRateModifier(mRate); } public void setPlayInBackground(final boolean playInBackground) { mPlayInBackground = playInBackground; } public void setControls(boolean controls) { this.mUseNativeControls = controls; } public boolean isPreventScreenFromDimmingFlagOn() { int flags = mThemedReactContext.getCurrentActivity().getWindow().getAttributes().flags; if ((flags & WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) == 0) { return false; } return true; } public void setPreventScreenFromDimmingFlag(final boolean state) { if (!mMediaPlayerValid && mThemedReactContext == null) { return; } final boolean isFlagOn = isPreventScreenFromDimmingFlagOn(); if (state && !isFlagOn) { mThemedReactContext.getCurrentActivity().runOnUiThread(new Runnable() { @Override public void run() { mThemedReactContext.getCurrentActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } if (!state && isFlagOn) { mThemedReactContext.getCurrentActivity().runOnUiThread(new Runnable() { @Override public void run() { mThemedReactContext.getCurrentActivity().getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }); } } @Override public void onPrepared(MediaPlayer mp) { mMediaPlayerValid = true; mVideoDuration = mp.getDuration(); WritableMap naturalSize = Arguments.createMap(); naturalSize.putInt(EVENT_PROP_WIDTH, mp.getVideoWidth()); naturalSize.putInt(EVENT_PROP_HEIGHT, mp.getVideoHeight()); if (mp.getVideoWidth() > mp.getVideoHeight()) naturalSize.putString(EVENT_PROP_ORIENTATION, "landscape"); else naturalSize.putString(EVENT_PROP_ORIENTATION, "portrait"); WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_DURATION, mVideoDuration / 1000.0); event.putDouble(EVENT_PROP_CURRENT_TIME, mp.getCurrentPosition() / 1000.0); event.putMap(EVENT_PROP_NATURALSIZE, naturalSize); // TODO: Actually check if you can. event.putBoolean(EVENT_PROP_FAST_FORWARD, true); event.putBoolean(EVENT_PROP_SLOW_FORWARD, true); event.putBoolean(EVENT_PROP_SLOW_REVERSE, true); event.putBoolean(EVENT_PROP_REVERSE, true); event.putBoolean(EVENT_PROP_FAST_FORWARD, true); event.putBoolean(EVENT_PROP_STEP_BACKWARD, true); event.putBoolean(EVENT_PROP_STEP_FORWARD, true); mEventEmitter.receiveEvent(getId(), Events.EVENT_LOAD.toString(), event); applyModifiers(); if (mUseNativeControls) { initializeMediaControllerIfNeeded(); mediaController.setMediaPlayer(this); mediaController.setAnchorView(this); videoControlHandler.post(new Runnable() { @Override public void run() { mediaController.setEnabled(true); mediaController.show(); } }); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { WritableMap error = Arguments.createMap(); error.putInt(EVENT_PROP_WHAT, what); error.putInt(EVENT_PROP_EXTRA, extra); WritableMap event = Arguments.createMap(); event.putMap(EVENT_PROP_ERROR, error); mEventEmitter.receiveEvent(getId(), Events.EVENT_ERROR.toString(), event); return true; } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_INFO_BUFFERING_START: mEventEmitter.receiveEvent(getId(), Events.EVENT_STALLED.toString(), Arguments.createMap()); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: mEventEmitter.receiveEvent(getId(), Events.EVENT_RESUME.toString(), Arguments.createMap()); break; case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START: mEventEmitter.receiveEvent(getId(), Events.EVENT_READY_FOR_DISPLAY.toString(), Arguments.createMap()); break; default: } return false; } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { mVideoBufferedDuration = (int) Math.round((double) (mVideoDuration * percent) / 100.0); } @Override public void seekTo(int msec) { if (mMediaPlayerValid) { WritableMap event = Arguments.createMap(); event.putDouble(EVENT_PROP_CURRENT_TIME, getCurrentPosition() / 1000.0); event.putDouble(EVENT_PROP_SEEK_TIME, msec / 1000.0); mEventEmitter.receiveEvent(getId(), Events.EVENT_SEEK.toString(), event); super.seekTo(msec); if (isCompleted && mVideoDuration != 0 && msec < mVideoDuration) { isCompleted = false; } } } @Override public int getBufferPercentage() { return 0; } @Override public boolean canPause() { return true; } @Override public boolean canSeekBackward() { return true; } @Override public boolean canSeekForward() { return true; } @Override public int getAudioSessionId() { return 0; } @Override public void onCompletion(MediaPlayer mp) { isCompleted = true; mEventEmitter.receiveEvent(getId(), Events.EVENT_END.toString(), null); } @Override protected void onDetachedFromWindow() { mMediaPlayerValid = false; super.onDetachedFromWindow(); setPreventScreenFromDimmingFlag(false); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); setPreventScreenFromDimmingFlag(true); if(mMainVer>0) { setSrc(mSrcUriString, mSrcType, mSrcIsNetwork, mSrcIsAsset, mRequestHeaders, mMainVer, mPatchVer); } else { setSrc(mSrcUriString, mSrcType, mSrcIsNetwork, mSrcIsAsset, mRequestHeaders); } } @Override public void onHostPause() { if (mMediaPlayerValid && !mPaused && !mPlayInBackground) { /* Pause the video in background * Don't update the paused prop, developers should be able to update it on background * so that when you return to the app the video is paused */ mBackgroundPaused = true; mMediaPlayer.pause(); } } @Override public void onHostResume() { mBackgroundPaused = false; if (mMediaPlayerValid && !mPlayInBackground && !mPaused) { new Handler().post(new Runnable() { @Override public void run() { // Restore original state setPausedModifier(false); } }); } } @Override public void onHostDestroy() { } public static Map<String, String> toStringMap(@Nullable ReadableMap readableMap) { Map<String, String> result = new HashMap<>(); if (readableMap == null) return result; com.facebook.react.bridge.ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); result.put(key, readableMap.getString(key)); } return result; } }
package org.sakaiproject.evaluation.utils; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Utils for working with collections and arrays (these are basically convenience methods) * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class ArrayUtils { /** * Remove all duplicate objects from a list * * @param list * @return the original list with the duplicate objects removed */ public static <T> List<T> removeDuplicates(List<T> list) { Set<T> s = new HashSet<T>(); for (Iterator<T> iter = list.iterator(); iter.hasNext();) { T element = (T) iter.next(); if (! s.add(element)) { iter.remove(); } } return list; } /** * Append an item to the end of an array and return the new array * * @param array an array of items * @param value the item to append to the end of the new array * @return a new array with value in the last spot */ public static String[] appendArray(String[] array, String value) { String[] newArray = new String[array.length + 1]; System.arraycopy( array, 0, newArray, 0, array.length ); newArray[newArray.length-1] = value; return newArray; } /** * Append an item to the end of an array and return the new array * * @param array an array of items * @param value the item to append to the end of the new array * @return a new array with value in the last spot */ @SuppressWarnings("unchecked") public static <T> T[] appendArray(T[] array, T value) { Class<?> type = array.getClass().getComponentType(); T[] newArray = (T[]) Array.newInstance(type, array.length + 1); System.arraycopy( array, 0, newArray, 0, array.length ); newArray[newArray.length-1] = value; return newArray; } /** * Append an item to the end of an array and return the new array * * @param array an array of items * @param value the item to append to the end of the new array * @return a new array with value in the last spot */ public static int[] appendArray(int[] array, int value) { int[] newArray = new int[array.length + 1]; System.arraycopy( array, 0, newArray, 0, array.length ); newArray[newArray.length-1] = value; return newArray; } /** * Prepend an item to the front of an array and return the new array * * @param array an array of items * @param value the item to prepend to the front of the new array * @return a new array with value in the first spot */ public static String[] prependArray(String[] array, String value) { String[] newArray = new String[array.length + 1]; System.arraycopy( array, 0, newArray, 1, array.length ); newArray[0] = value; return newArray; } /** * Prepend an item to the front of an array and return the new array * * @param array an array of items * @param value the item to prepend to the front of the new array * @return a new array with value in the first spot */ @SuppressWarnings("unchecked") public static <T> T[] prependArray(T[] array, T value) { Class<?> type = array.getClass().getComponentType(); T[] newArray = (T[]) Array.newInstance(type, array.length + 1); System.arraycopy( array, 0, newArray, 1, array.length ); newArray[0] = value; return newArray; } /** * Prepend an item to the front of an array and return the new array * * @param array an array of items * @param value the item to prepend to the front of the new array * @return a new array with value in the first spot */ public static int[] prependArray(int[] array, int value) { int[] newArray = new int[array.length + 1]; System.arraycopy( array, 0, newArray, 1, array.length ); newArray[0] = value; return newArray; } /** * Take an array of anything and turn it into a string * * @param array any array * @return a string representing that array */ public static String arrayToString(Object[] array) { StringBuilder result = new StringBuilder(); if (array != null && array.length > 0) { for (int i = 0; i < array.length; i++) { if (i > 0) { result.append(","); } if (array[i] != null) { result.append(array[i].toString()); } } } return result.toString(); } /** * Take a list of number objects and return an int[] array * @param list any list of {@link Number} * @return an array of int */ public static int[] listToIntArray(List<Number> list) { int[] newArray = new int[list.size()]; for (int i = 0; i < list.size(); i++) { newArray[i] = list.get(i).intValue(); } return newArray; } }
package fi.csc.antero.repository; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.vineey.rql.filter.parser.DefaultFilterParser; import com.github.vineey.rql.querydsl.filter.QueryDslFilterContext; import com.github.vineey.rql.querydsl.page.QuerydslPageParser; import com.github.vineey.rql.querydsl.sort.OrderSpecifierList; import com.github.vineey.rql.querydsl.sort.QuerydslSortContext; import com.github.vineey.rql.sort.parser.DefaultSortParser; import com.querydsl.core.QueryModifiers; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.Path; import com.querydsl.core.types.Predicate; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.NumberPath; import com.querydsl.core.types.dsl.StringTemplate; import com.querydsl.sql.SQLQuery; import com.querydsl.sql.SQLQueryFactory; import fi.csc.antero.config.ConfigService; import fi.csc.antero.controller.ApiQuery; import fi.csc.antero.dao.ApiDataDao; import fi.csc.antero.exception.FilterException; import fi.csc.antero.response.JsonRowHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @Service public class ApiDataService { private final Logger log = LoggerFactory.getLogger(getClass()); private final ApiDataDao dataDao; private final ObjectMapper om; private final SQLQueryFactory queryFactory; private final ConfigService configService; @Autowired public ApiDataService(ApiDataDao dataDao, ObjectMapper om, SQLQueryFactory queryFactory, ConfigService configService) { this.dataDao = dataDao; this.om = om; this.queryFactory = queryFactory; this.configService = configService; } public void streamToJsonArray(String table, OutputStream out, ApiQuery query) throws IOException, SQLException { final JsonGenerator jg = om.getFactory().createGenerator(out); jg.writeStartArray(); final StringTemplate path = getFromExpression(table); final SQLQuery<String> sql = queryFactory.select(Expressions.stringTemplate("*")) .from(path) .where(createFilterPredicate(table, query.getFilter())) .orderBy(createOrderSpecifiers(table, query.getSort())) .restrict(createLimitQueryModifier(query.getOffset(), query.getLimit())); sql.setUseLiterals(true); final String queryString = sql.getSQL().getSQL(); final JsonRowHandler rowHandler = new JsonRowHandler(jg, dataDao.queryTableColumns(table)); dataDao.queryForStream(queryString, rowHandler); jg.writeEndArray(); jg.flush(); } public Long getCount(String table, String filter) throws SQLException { final SQLQuery<Long> sqlQuery = queryFactory.select(Expressions.stringTemplate("*").count()) .from(getFromExpression(table)) .where(createFilterPredicate(table, filter)); sqlQuery.setUseLiterals(true); return dataDao.queryCount(sqlQuery.getSQL().getSQL()); } public Set<String> listResources() throws SQLException { return dataDao.queryTableNames(); } public List<ApiProperty> listResourceProperties(String resource) throws SQLException { return dataDao.queryTableColumns(resource).stream() .filter(p -> !p.isHidden()) .collect(Collectors.toList()); } private Predicate createFilterPredicate(String table, String filter) throws SQLException { if (StringUtils.isEmpty(filter)) { return null; } final Map<String, Path> pathMap = getPathMap(table); try { return new DefaultFilterParser().parse(filter, QueryDslFilterContext.withMapping(pathMap)); } catch (Throwable t) { final String msg = String.format("Filtering error! Table: '%s', Filter: '%s'", table, filter); log.error(msg, t); throw new FilterException("Bad filtering parameter! Cause: " + t.getMessage()); } } private QueryModifiers createLimitQueryModifier(Long offset, Long limit) { if (offset == null && limit == null) { return QueryModifiers.EMPTY; } String limitStr = "limit(%d,%d)"; if (offset == null || offset < 0) { limitStr = String.format(limitStr, 0, limit); } else if (limit == null || limit < 0) { limitStr = String.format(limitStr, offset, Long.MAX_VALUE); } else { limitStr = String.format(limitStr, offset, limit); } QuerydslPageParser querydslPageParser = new QuerydslPageParser(); try { return querydslPageParser.parse(limitStr); } catch (Throwable t) { final String msg = String.format("Limit error! Limit: '%s'", limitStr); log.error(msg, t); throw new FilterException("Bad limit parameter! Cause: " + t.getMessage()); } } private OrderSpecifier[] createOrderSpecifiers(String table, String sort) { final OrderSpecifier[] orderSpecifiers = {}; if (StringUtils.isEmpty(sort)) { sort = "(+" + configService.getDefaultOrderColumn() + ")"; } else if (!StringUtils.isEmpty(sort)) { sort = sort.substring(0, sort.length()-2) + ",+" + configService.getDefaultOrderColumn() + ")"; } DefaultSortParser sortParser = new DefaultSortParser(); try { OrderSpecifierList orderSpecifierList = sortParser.parse("sort" + sort, QuerydslSortContext.withMapping(getPathMap(table))); return orderSpecifierList.getOrders().toArray(orderSpecifiers); } catch (Throwable t) { final String msg = String.format("Sort error! Table: '%s', Sort: '%s'", table, sort); log.error(msg, t); throw new FilterException("Bad sorting parameter! Cause: " + t.getMessage()); } } private Map<String, Path> getPathMap(String table) throws SQLException { final Map<String, Path> pathMap = new HashMap<>(); for (ApiProperty column : dataDao.queryTableColumns(table)) { Path path; final PropType type = column.getType(); final String variable = column.getSqlName(); if (type.getPathType() == PathType.STRING) { path = Expressions.stringPath(variable); } else if (type.getPathType() == PathType.BOOLEAN) { path = Expressions.booleanPath(variable); } else if (type.getPathType() == PathType.NUMBER) { path = getNumberPath(type, variable); } else if (type.getPathType() == PathType.DATE) { path = Expressions.datePath(LocalDate.class, variable); } else if (type.getPathType() == PathType.TIME) { path = Expressions.timePath(LocalTime.class, variable); } else if (type.getPathType() == PathType.DATETIME) { path = Expressions.dateTimePath(LocalDateTime.class, variable); } else { continue; } pathMap.put(column.getApiName(), path); } return pathMap; } private NumberPath getNumberPath(PropType type, String variable) { switch (type) { case INTEGER: return Expressions.numberPath(Integer.class, variable); case BIG_DECIMAL: return Expressions.numberPath(BigDecimal.class, variable); case FLOAT: return Expressions.numberPath(Float.class, variable); case DOUBLE: return Expressions.numberPath(Double.class, variable); case LONG: return Expressions.numberPath(Long.class, variable); case SHORT: return Expressions.numberPath(Short.class, variable); case BYTE: return Expressions.numberPath(Byte.class, variable); default: return null; } } private StringTemplate getFromExpression(String table) { StringBuilder sb = new StringBuilder(); final String schema = configService.getSchema(); if (!schema.isEmpty()) { sb.append(schema).append("."); } sb.append(table); return Expressions.stringTemplate(sb.toString()); } }
package org.openmrs.module.sana.api; import com.google.gson.Gson; /** * A response returned from an entity of the Sana dispatch layer. * * @author Sana Development Team * */ public class MDSResponse { public static final String FAILURE = "FAIL"; public static final String SUCCESS = "OK"; public MDSResponse() {} /** A status string */ public String status; /** A status code string for providing more granular response */ public String code; /** A message body */ public String message; /** * Returns the JSON String representation of the object */ public String toJSON(){ Gson g = new Gson(); return g.toJson(this); } /** * Called when a transaction is successful. The response code is set to * unspecified. * @param message The message body of the response * @return */ public static MDSResponse succeed(String message){ return succeed(message, "unspecified"); } /** * Call when a transaction is successful to generate a response message. * * @param message The message body of the response * @param code A response code. * @return */ public static MDSResponse succeed(String message, String code){ MDSResponse mdsresponse = new MDSResponse(); mdsresponse.status = MDSResponse.SUCCESS; mdsresponse.code = code; mdsresponse.message = message; return mdsresponse; } /** * Called when a transaction fails. The response code is set to * unspecified. * @param message The message body of the response * @return */ public static MDSResponse fail(String message){ return fail(message, "unspecified"); } /** * Called when a transaction fails. * @param message The message body of the response * @param code * @return */ public static MDSResponse fail(String message, String code){ MDSResponse mdsresponse = new MDSResponse(); mdsresponse.status = MDSResponse.FAILURE; mdsresponse.code = "unspecified"; mdsresponse.message = message; return mdsresponse; } }
package edu.wustl.catissuecore.actionForm; import java.io.Serializable; import java.util.List; import org.apache.struts.action.ActionForm; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; /** * @author preeti_munot * */ public class AnnotationForm extends AbstractActionForm implements Serializable { private static final long serialVersionUID = 1L; private String annotationGroupsXML; private String annotationEntitiesXML; private List systemEntitiesList; private String selectedStaticEntityId; private List conditionalInstancesList; private String[] conditionVal; public String[] getConditionVal() { return conditionVal; } public void setConditionVal(String[] conditionVal) { this.conditionVal = conditionVal; } public String getSelectedStaticEntityId() { return this.selectedStaticEntityId; } public void setSelectedStaticEntityId(String selectedStaticEntityId) { this.selectedStaticEntityId = selectedStaticEntityId; } public List getSystemEntitiesList() { return this.systemEntitiesList; } public void setSystemEntitiesList(List systemEntitiesList) { this.systemEntitiesList = systemEntitiesList; } public String getAnnotationEntitiesXML() { return this.annotationEntitiesXML; } public void setAnnotationEntitiesXML(String annotationEntitiesXML) { this.annotationEntitiesXML = annotationEntitiesXML; } public String getAnnotationGroupsXML() { return this.annotationGroupsXML; } public void setAnnotationGroupsXML(String annotationGroupsXML) { this.annotationGroupsXML = annotationGroupsXML; } public int getFormId() { // TODO Auto-generated method stub return 0; } public void setAllValues(AbstractDomainObject abstractDomain) { // TODO Auto-generated method stub } protected void reset() { // TODO Auto-generated method stub } public List getConditionalInstancesList() { return conditionalInstancesList; } public void setConditionalInstancesList(List conditionalInstancesList) { this.conditionalInstancesList = conditionalInstancesList; } }
package edu.wustl.catissuecore.actionForm; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.PasswordManager; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.authorization.domainobjects.Role; /** * UserForm Class is used to encapsulate all the request parameters passed * from User Add/Edit webpage. * @author gautam_shetty * */ public class UserForm extends AbstractActionForm { /** * Last Name of the user. */ private String lastName; /** * First Name of the user. */ private String firstName; /** * Institution name of the user. */ private long institutionId; /** * EmailAddress Address of the user. */ private String emailAddress; /** * Old Password of the user. */ private String oldPassword; /** * New Password of the user. */ private String newPassword; /** * Confirmed new password of the user. */ private String confirmNewPassword; /** * Department name of the user. */ private long departmentId; /** * Street Address of the user. */ private String street; /** * The City where the user stays. */ private String city; /** * The State where the user stays. */ private String state; /** * The Country where the user stays. */ private String country; /** * The zip code of city where the user stays. * */ private String zipCode; /** * Phone number of the user. * */ private String phoneNumber; /** * Fax number of the user. * */ private String faxNumber; /** * Role of the user. * */ private String role; /** * Cancer Research Group of the user. */ private long cancerResearchGroupId; /** * Comments given by user. */ private String comments; /** * Status of user in the system. */ private String status; private Long csmUserId; /** * No argument constructor for UserForm class. */ public UserForm() { reset(); } /** * Returns the last name of the user * @return String representing the last name of the user. * @see #setFirstName(String) */ public String getLastName() { return (this.lastName); } /** * Sets the last name of the user. * @param lastName Last Name of the user * @see #getFirstName() */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Returns the first name of the user. * @return String representing the first name of the user. * @see #setFirstName(String) */ public String getFirstName() { return (this.firstName); } /** * Sets the first name of the user. * @param firstName String representing the first name of the user. * @see #getFirstName() */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Returns the institutionId name of the user. * @return String representing the institutionId of the user. * @see #setinstitution(String) */ public long getInstitutionId() { return (this.institutionId); } /** * Sets the institutionId name of the user. * @param institutionId String representing the institutionId of the user. * @see #getinstitution() */ public void setInstitutionId(long institution) { this.institutionId = institution; } /** * Returns the emailAddress Address of the user. * @return String representing the emailAddress address of the user. */ public String getEmailAddress() { return (this.emailAddress); } /** * Sets the emailAddress address of the user. * @param emailAddress String representing emailAddress address of the user * @see #getEmailAddress() */ public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } /** * @return Returns the confirmNewPassword. */ public String getConfirmNewPassword() { return confirmNewPassword; } /** * @return Returns the newPassword. */ public String getNewPassword() { return newPassword; } /** * @return Returns the oldPassword. */ public String getOldPassword() { return oldPassword; } /** * @param confirmNewPassword The confirmNewPassword to set. */ public void setConfirmNewPassword(String confirmNewPassword) { this.confirmNewPassword = confirmNewPassword; } /** * @param newPassword The newPassword to set. */ public void setNewPassword(String newPassword) { this.newPassword = newPassword; } /** * @param oldPassword The oldPassword to set. */ public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; } /** * Returns the Department Name of the user. * @return String representing departmentId of the user. * @see #getDepartmentId() */ public long getDepartmentId() { return (this.departmentId); } /** * Sets the Department Name of the user. * @param departmentId String representing departmentId of the user. * @see #getDepartmentId() */ public void setDepartmentId(long department) { this.departmentId = department; } /** * Returns the cancer research group the user belongs. * @return Returns the cancerResearchGroupId. * @see #setCancerResearchGroupId(String) */ public long getCancerResearchGroupId() { return cancerResearchGroupId; } /** * Sets the cancer research group the user belongs. * @param cancerResearchGroupId The cancerResearchGroupId to set. * @see #getCancerResearchGroupId() */ public void setCancerResearchGroupId(long cancerResearchGroup) { this.cancerResearchGroupId = cancerResearchGroup; } /** * Returns the Street Address of the user. * @return String representing mailing address of the user. * @see #setStreet(String) */ public String getStreet() { return (this.street); } /** * Sets the Street Address of the user. * @param address String representing mailing address of the user. * @see #getStreet() */ public void setStreet(String street) { this.street = street; } /** * Returns the City where the user stays. * @return String representing city of the user. * @see #setCity(String) */ public String getCity() { return (this.city); } /** * Sets the City where the user stays. * @param city String representing city of the user. * @see #getCity() */ public void setCity(String city) { this.city = city; } /** * Returns the State where the user stays. * @return String representing state of the user. * @see #setState(String) */ public String getState() { return (this.state); } /** * Sets the State where the user stays. * @param state String representing state of the user. * @see #getState() */ public void setState(String state) { this.state = state; } /** * Returns the Country where the user stays. * @return String representing country of the user. * @see #setCountry(String) */ public String getCountry() { return (this.country); } /** * Sets the Country where the user stays. * @param country String representing country of the user. * @see #getCountry() */ public void setCountry(String country) { this.country = country; } /** * Returns the zip code of the user's city. * @return Returns the zip. * @see #setZip(String) */ public String getZipCode() { return zipCode; } /** * Sets the zip code of the user's city. * @param zip The zip code to set. * @see #getZip() */ public void setZipCode(String zipCode) { this.zipCode = zipCode; } /** * Returns the phone number of the user. * @return Returns the phone number. * @see #setPhone(String) */ public String getPhoneNumber() { return phoneNumber; } /** * Sets the phone number of the user. * @param phone The phone number to set. * @see #getphoneNumber() */ public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } /** * Returns the fax number of the user. * @return Returns the fax. * @see #setFax(String) */ public String getFaxNumber() { return this.faxNumber; } /** * Sets the fax number of the user. * @param fax The fax to set. * @see #getFax() */ public void setFaxNumber(String faxNumber) { this.faxNumber = faxNumber; } /** * Returns the role of the user. * @return the role of the user. * @see #setRoleCollection(String) */ public String getRole() { return role; } /** * Sets the role of the user. * @param role the role of the user. * @see #getRole() */ public void setRole(String role) { this.role = role; } /** * @return Returns the comments. */ public String getComments() { return comments; } /** * @param comments The comments to set. */ public void setComments(String comments) { this.comments = comments; } /** * Returns the id assigned to form bean. */ public int getFormId() { int formId = Constants.APPROVE_USER_FORM_ID; if ((pageOf != null) && (Constants.PAGEOF_APPROVE_USER.equals(pageOf) == false)) { formId = Constants.USER_FORM_ID; } Logger.out.debug("................formId...................."+formId); return formId; } /** * @return Returns the status. */ public String getStatus() { return status; } /** * @param status The status to set. */ public void setStatus(String status) { this.status = status; } /** * @return Returns the csmUserId. */ public Long getCsmUserId() { return csmUserId; } /** * @param csmUserId The csmUserId to set. */ public void setCsmUserId(Long csmUserId) { this.csmUserId = csmUserId; } /** * Resets the values of all the fields. * Is called by the overridden reset method defined in ActionForm. * */ protected void reset() { this.lastName = null; this.firstName = null; this.institutionId = -1; this.emailAddress = null; this.departmentId = -1; this.street = null; this.city = null; this.state = null; this.country = null; this.zipCode = null; this.phoneNumber = null; this.faxNumber = null; this.role = null; this.cancerResearchGroupId = -1; this.status = Constants.ACTIVITY_STATUS_NEW; this.activityStatus = Constants.ACTIVITY_STATUS_NEW; } /** * Copies the data from an AbstractDomain object to a UserForm object. * @param user An AbstractDomain object. */ public void setAllValues(AbstractDomainObject abstractDomain) { if (Constants.PAGEOF_CHANGE_PASSWORD.equals(pageOf) == false) { User user = (User) abstractDomain; this.systemIdentifier = user.getSystemIdentifier().longValue(); this.lastName = user.getLastName(); this.firstName = user.getFirstName(); // Check for null entries (for admin) if(!edu.wustl.common.util.Utility.isNull(user.getInstitution()) ) this.institutionId = user.getInstitution().getSystemIdentifier().longValue(); this.emailAddress = user.getEmailAddress(); if(!edu.wustl.common.util.Utility.isNull(user.getDepartment()) ) this.departmentId = user.getDepartment().getSystemIdentifier().longValue(); if(!edu.wustl.common.util.Utility.isNull(user.getCancerResearchGroup()) ) this.cancerResearchGroupId = user.getCancerResearchGroup().getSystemIdentifier().longValue(); if(!edu.wustl.common.util.Utility.isNull(user.getAddress()) ) { this.street = user.getAddress().getStreet(); this.city = user.getAddress().getCity(); this.state = user.getAddress().getState(); this.country = user.getAddress().getCountry(); this.zipCode = user.getAddress().getZipCode(); this.phoneNumber = user.getAddress().getPhoneNumber(); this.faxNumber = user.getAddress().getFaxNumber(); } //Populate the activity status, comments and role for approve user and user edit. if ((getFormId() == Constants.APPROVE_USER_FORM_ID) || ((pageOf != null) && (Constants.PAGEOF_USER_ADMIN.equals(pageOf)))) { this.activityStatus = user.getActivityStatus(); if(!edu.wustl.common.util.Utility.isNull(user.getComments()) ) this.comments = user.getComments(); this.role = user.getRoleId(); if (getFormId() == Constants.APPROVE_USER_FORM_ID) { this.status = user.getActivityStatus(); if (activityStatus.equals(Constants.ACTIVITY_STATUS_ACTIVE)) { this.status = Constants.APPROVE_USER_APPROVE_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_CLOSED)) { this.status = Constants.APPROVE_USER_REJECT_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_NEW)) { this.status = Constants.APPROVE_USER_PENDING_STATUS; } } } if (Constants.PAGEOF_USER_ADMIN.equals(pageOf)) { this.setCsmUserId(user.getCsmUserId()); } } Logger.out.debug("this.activityStatus............."+this.activityStatus); Logger.out.debug("this.comments"+this.comments); Logger.out.debug("this.role"+this.role); Logger.out.debug("this.status"+this.status); Logger.out.debug("this.csmUserid"+this.csmUserId); } public void setAllVal(Object obj) { if(this.operation.equals(Constants.ADD)) this.pageOf = Constants.PAGEOF_SIGNUP; else if(this.operation.equals(Constants.EDIT)) this.pageOf = Constants.PAGEOF_USER_ADMIN; if (Constants.PAGEOF_CHANGE_PASSWORD.equals(pageOf) == false) { edu.wustl.catissuecore.domainobject.User user = (edu.wustl.catissuecore.domainobject.User) obj; this.systemIdentifier = user.getId().longValue(); this.lastName = user.getLastName(); this.firstName = user.getFirstName(); this.institutionId = user.getInstitution().getId() .longValue(); this.emailAddress = user.getEmailAddress(); this.departmentId = user.getDepartment().getId() .longValue(); this.cancerResearchGroupId = user.getCancerResearchGroup() .getId().longValue(); this.street = user.getAddress().getStreet(); this.city = user.getAddress().getCity(); this.state = user.getAddress().getState(); this.country = user.getAddress().getCountry(); this.zipCode = user.getAddress().getZipCode(); this.phoneNumber = user.getAddress().getPhoneNumber(); this.faxNumber = user.getAddress().getFaxNumber(); //Populate the activity status, comments and role for approve user and user edit. if ((getFormId() == Constants.APPROVE_USER_FORM_ID) || ((pageOf != null) && (Constants.PAGEOF_USER_ADMIN.equals(pageOf)))) { this.activityStatus = user.getActivityStatus(); this.comments = user.getComments(); try { SecurityManager securityManager=SecurityManager.getInstance(this.getClass()); Role role=securityManager.getUserRole(user.getCsmUserId().longValue()); this.role= Utility.toString(role.getId()); } catch(Exception e) { Logger.out.error(e.getMessage(), e); } if (getFormId() == Constants.APPROVE_USER_FORM_ID) { this.status = user.getActivityStatus(); if (activityStatus.equals(Constants.ACTIVITY_STATUS_ACTIVE)) { this.status = Constants.APPROVE_USER_APPROVE_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_CLOSED)) { this.status = Constants.APPROVE_USER_REJECT_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_NEW)) { this.status = Constants.APPROVE_USER_PENDING_STATUS; } } } if (Constants.PAGEOF_USER_ADMIN.equals(pageOf)) { this.setCsmUserId(user.getCsmUserId()); } } Logger.out.debug("this.activityStatus............."+this.activityStatus); Logger.out.debug("this.comments"+this.comments); Logger.out.debug("this.role"+this.role); Logger.out.debug("this.status"+this.status); Logger.out.debug("this.csmUserid"+this.csmUserId); } /** * Overrides the validate method of ActionForm. * */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); try { if (operation != null) { if (pageOf.equals(Constants.PAGEOF_CHANGE_PASSWORD)) { if (validator.isEmpty(oldPassword)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.oldPassword"))); } if (validator.isEmpty(newPassword)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.newPassword"))); } if (validator.isEmpty(confirmNewPassword)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.confirmNewPassword"))); } if (!validator.isEmpty(newPassword) && !validator.isEmpty(confirmNewPassword)) { if (!newPassword.equals(confirmNewPassword)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.confirmNewPassword.reType")); } } /* * begin: Added for Password validation */ Logger.out.debug("before if of Validate password " + newPassword + " " + oldPassword); if (!validator.isEmpty(newPassword) && !validator.isEmpty(oldPassword)) { int result=-1; // Call static method PasswordManager.validate() where params are // new password,old password,user name // returns int value. result=PasswordManager.validate(newPassword,oldPassword,request.getSession()); Logger.out.debug("return from Password validate " + result); // if validate method returns value greater than zero then validation fails if(result!=PasswordManager.SUCCESS) { // get error message of validation failure where param is result of validate() method String errorMessage=PasswordManager.getErrorMessage(result); Logger.out.debug("error from Password validate " + errorMessage); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item",errorMessage)); } } Logger.out.debug("after call to Validate password"); /* * end: Password validation */ } else { setRedirectValue(validator); Logger.out.debug("user form " ); if (operation.equals(Constants.ADD) || operation.equals(Constants.EDIT)) { if (validator.isEmpty(lastName)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.lastName"))); } if (validator.isEmpty(firstName)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.firstName"))); } if (validator.isEmpty(city)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.city"))); } if (state.trim().equals(Constants.SELECT_OPTION)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.state"))); } if (validator.isEmpty(zipCode)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.zipCode"))); } else { if(!validator.isValidZipCode(zipCode)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.zipCode.format", ApplicationProperties.getValue("user.zipCode"))); } } if(!validator.isValidOption(country)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.country"))); } if (validator.isEmpty(phoneNumber)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.phoneNumber"))); } // else // if(!validator.isValidPhoneNumber(phoneNumber)) // errors.add(ActionErrors.GLOBAL_ERROR, // new ActionError("errors.phoneNumber.format", // ApplicationProperties.getValue("user.phoneNumber"))); // if(!validator.isEmpty(faxNumber)&& !validator.isValidPhoneNumber(faxNumber)) // errors.add(ActionErrors.GLOBAL_ERROR, // new ActionError("errors.phoneNumber.format", // ApplicationProperties.getValue("user.faxNumber"))); if (validator.isEmpty(emailAddress)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.emailAddress"))); } else { if (!validator.isValidEmailAddress(emailAddress)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format", ApplicationProperties.getValue("user.emailAddress"))); } } if (validator.isValidOption(String.valueOf(institutionId)) == false) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.institution"))); } if (validator.isValidOption(String.valueOf(departmentId)) == false) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.department"))); } if (validator.isValidOption(String.valueOf(cancerResearchGroupId)) == false) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required", ApplicationProperties.getValue("user.cancerResearchGroup"))); } if(validator.isValidOption(activityStatus) == false) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required", ApplicationProperties.getValue("user.activityStatus"))); } } if (pageOf.equals(Constants.PAGEOF_USER_ADMIN) || pageOf.equals(Constants.PAGEOF_APPROVE_USER)) { if (role != null) { if (validator.isValidOption(role) == false) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.role"))); } } } if (pageOf.equals(Constants.PAGEOF_APPROVE_USER)) { if (validator.isValidOption(status) == false) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.approveOperation"))); } } } } } catch (Exception excp) { Logger.out.error(excp.getMessage(), excp); } return errors; } }
package edu.wustl.catissuecore.actionForm; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.domain.AbstractDomainObject; import edu.wustl.catissuecore.domain.SignUpUser; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.global.ApplicationProperties; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Validator; import edu.wustl.common.util.logger.Logger; /** * UserForm Class is used to encapsulate all the request parameters passed * from User Add/Edit webpage. * @author gautam_shetty * */ public class UserForm extends AbstractActionForm { /** * systemIdentifier is a unique id assigned to each User. * */ private long systemIdentifier; /** * Represents the operation(Add/Edit) to be performed. * */ private String operation; /** * Represents the page the user has submitted the form from. */ private String pageOf; /** * Last Name of the user. */ private String lastName; /** * First Name of the user. */ private String firstName; /** * Institution name of the user. */ private long institutionId; /** * EmailAddress Address of the user. */ private String emailAddress; /** * Password of the user. */ private String password; /** * Department name of the user. */ private long departmentId; /** * Street Address of the user. */ private String street; /** * The City where the user stays. */ private String city; /** * The State where the user stays. */ private String state; /** * The Country where the user stays. */ private String country; /** * The zip code of city where the user stays. * */ private String zipCode; /** * Phone number of the user. * */ private String phoneNumber; /** * Fax number of the user. * */ private String faxNumber; /** * Role of the user. * */ private String role; /** * Cancer Research Group of the user. */ private long cancerResearchGroupId; /** * Activity status of the user. */ private String activityStatus; /** * Comments given by user. */ private String comments; /** * Status of user in the system. */ private String status; /** * No argument constructor for UserForm class. */ public UserForm() { reset(); } /** * Returns the systemIdentifier assigned to User. * @return int representing the id assigned to User. * @see #setIdentifier(int) * */ public long getSystemIdentifier() { return (this.systemIdentifier); } /** * Sets an id for the User. * @param systemIdentifier id to be assigned to the User. * @see #getIdentifier() * */ public void setSystemIdentifier(long systemIdentifier) { this.systemIdentifier = systemIdentifier; } /** * Returns the operation(Add/Edit) to be performed. * @return Returns the operation. */ public String getOperation() { return operation; } /** * Sets the operation to be performed. * @param operation The operation to set. */ public void setOperation(String operation) { this.operation = operation; } /** * @return Returns the pageOf. */ public String getPageOf() { return pageOf; } /** * @param pageOf The pageOf to set. */ public void setPageOf(String pageOf) { this.pageOf = pageOf; } /** * Returns the last name of the user * @return String representing the last name of the user. * @see #setFirstName(String) */ public String getLastName() { return (this.lastName); } /** * Sets the last name of the user. * @param lastName Last Name of the user * @see #getFirstName() */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Returns the first name of the user. * @return String representing the first name of the user. * @see #setFirstName(String) */ public String getFirstName() { return (this.firstName); } /** * Sets the first name of the user. * @param firstName String representing the first name of the user. * @see #getFirstName() */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Returns the institutionId name of the user. * @return String representing the institutionId of the user. * @see #setinstitution(String) */ public long getInstitutionId() { return (this.institutionId); } /** * Sets the institutionId name of the user. * @param institutionId String representing the institutionId of the user. * @see #getinstitution() */ public void setInstitutionId(long institution) { this.institutionId = institution; } /** * Returns the emailAddress Address of the user. * @return String representing the emailAddress address of the user. */ public String getEmailAddress() { return (this.emailAddress); } /** * Sets the emailAddress address of the user. * @param emailAddress String representing emailAddress address of the user * @see #getEmailAddress() */ public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * Returns the Department Name of the user. * @return String representing departmentId of the user. * @see #getDepartmentId() */ public long getDepartmentId() { return (this.departmentId); } /** * Sets the Department Name of the user. * @param departmentId String representing departmentId of the user. * @see #getDepartmentId() */ public void setDepartmentId(long department) { this.departmentId = department; } /** * Returns the cancer research group the user belongs. * @return Returns the cancerResearchGroupId. * @see #setCancerResearchGroupId(String) */ public long getCancerResearchGroupId() { return cancerResearchGroupId; } /** * Sets the cancer research group the user belongs. * @param cancerResearchGroupId The cancerResearchGroupId to set. * @see #getCancerResearchGroupId() */ public void setCancerResearchGroupId(long cancerResearchGroup) { this.cancerResearchGroupId = cancerResearchGroup; } /** * Returns the Street Address of the user. * @return String representing mailing address of the user. * @see #setStreet(String) */ public String getStreet() { return (this.street); } /** * Sets the Street Address of the user. * @param address String representing mailing address of the user. * @see #getStreet() */ public void setStreet(String street) { this.street = street; } /** * Returns the City where the user stays. * @return String representing city of the user. * @see #setCity(String) */ public String getCity() { return (this.city); } /** * Sets the City where the user stays. * @param city String representing city of the user. * @see #getCity() */ public void setCity(String city) { this.city = city; } /** * Returns the State where the user stays. * @return String representing state of the user. * @see #setState(String) */ public String getState() { return (this.state); } /** * Sets the State where the user stays. * @param state String representing state of the user. * @see #getState() */ public void setState(String state) { this.state = state; } /** * Returns the Country where the user stays. * @return String representing country of the user. * @see #setCountry(String) */ public String getCountry() { return (this.country); } /** * Sets the Country where the user stays. * @param country String representing country of the user. * @see #getCountry() */ public void setCountry(String country) { this.country = country; } /** * Returns the zip code of the user's city. * @return Returns the zip. * @see #setZip(String) */ public String getZipCode() { return zipCode; } /** * Sets the zip code of the user's city. * @param zip The zip code to set. * @see #getZip() */ public void setZipCode(String zipCode) { this.zipCode = zipCode; } /** * Returns the phone number of the user. * @return Returns the phone number. * @see #setPhone(String) */ public String getPhoneNumber() { return phoneNumber; } /** * Sets the phone number of the user. * @param phone The phone number to set. * @see #getphoneNumber() */ public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } /** * Returns the fax number of the user. * @return Returns the fax. * @see #setFax(String) */ public String getFaxNumber() { return this.faxNumber; } /** * Sets the fax number of the user. * @param fax The fax to set. * @see #getFax() */ public void setFaxNumber(String faxNumber) { this.faxNumber = faxNumber; } /** * Returns the role of the user. * @return the role of the user. * @see #setRoleCollection(String) */ public String getRole() { return role; } /** * Sets the role of the user. * @param role the role of the user. * @see #getRole() */ public void setRole(String role) { this.role = role; } /** * @return Returns the activityStatus. */ public String getActivityStatus() { return activityStatus; } /** * @param activityStatus The activityStatus to set. */ public void setActivityStatus(String activityStatus) { this.activityStatus = activityStatus; } /** * @return Returns the comments. */ public String getComments() { return comments; } /** * @param comments The comments to set. */ public void setComments(String comments) { this.comments = comments; } /** * Checks the operation to be performed is add operation. * @return Returns true if operation is equal to "add", else it returns false. * */ public boolean isAddOperation() { return (getOperation().equals(Constants.ADD)); } /** * Returns the id assigned to form bean */ public int getFormId() { int formId = Constants.SIGNUP_FORM_ID; if (pageOf != null) { if (pageOf.equals(Constants.PAGEOF_APPROVE_USER)) { formId = Constants.APPROVE_USER_FORM_ID; if (this.status.equals(Constants.APPROVE_USER_PENDING_STATUS)) formId = Constants.SIGNUP_FORM_ID; } else if (pageOf.equals(Constants.PAGEOF_USER_ADMIN) || pageOf.equals(Constants.PAGEOF_USER_PROFILE)) formId = Constants.USER_FORM_ID; } return formId; } /** * @return Returns the status. */ public String getStatus() { return status; } /** * @param status The status to set. */ public void setStatus(String status) { this.status = status; } /** * Resets the values of all the fields. * Is called by the overridden reset method defined in ActionForm. * */ protected void reset() { this.systemIdentifier = -1; this.operation = null; this.lastName = null; this.firstName = null; this.institutionId = -1; this.emailAddress = null; this.departmentId = -1; this.street = null; this.city = null; this.state = null; this.country = null; this.zipCode = null; this.phoneNumber = null; this.faxNumber = null; this.role = null; this.cancerResearchGroupId = -1; this.status = Constants.ACTIVITY_STATUS_NEW; } /** * Copies the data from an AbstractDomain object to a UserForm object. * @param user An AbstractDomain object. */ public void setAllValues(AbstractDomainObject abstractDomain) { try { if (getFormId() == Constants.SIGNUP_FORM_ID) { SignUpUser signUpUser = (SignUpUser)abstractDomain; this.systemIdentifier = signUpUser .getSystemIdentifier().longValue(); this.lastName = signUpUser.getLastName(); this.firstName = signUpUser.getFirstName(); this.institutionId = signUpUser.getInstitution() .getSystemIdentifier().longValue(); this.emailAddress = signUpUser.getEmailAddress(); this.departmentId = signUpUser.getDepartment() .getSystemIdentifier().longValue(); this.cancerResearchGroupId = signUpUser.getCancerResearchGroup() .getSystemIdentifier().longValue(); this.street = signUpUser.getStreet(); this.city = signUpUser.getCity(); this.state = signUpUser.getState(); this.country = signUpUser.getCountry(); this.zipCode = signUpUser.getZipCode(); this.phoneNumber = signUpUser.getPhoneNumber(); this.faxNumber = signUpUser.getFaxNumber(); this.activityStatus = signUpUser.getActivityStatus(); if (activityStatus.equals(Constants.ACTIVITY_STATUS_ACTIVE)) { this.status = Constants.APPROVE_USER_APPROVE_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_CLOSED)) { this.status = Constants.APPROVE_USER_REJECT_STATUS; } else { this.status = Constants.APPROVE_USER_PENDING_STATUS; } this.role = signUpUser.getRoleId(); this.comments = signUpUser.getComments(); } else { User user = (User) abstractDomain; this.systemIdentifier = user.getSystemIdentifier().longValue(); this.lastName = user.getLastName(); this.firstName = user.getFirstName(); this.institutionId = user.getInstitution().getSystemIdentifier() .longValue(); this.emailAddress = user.getEmailAddress(); this.departmentId = user.getDepartment().getSystemIdentifier() .longValue(); this.cancerResearchGroupId = user.getCancerResearchGroup() .getSystemIdentifier().longValue(); this.street = user.getAddress().getStreet(); this.city = user.getAddress().getCity(); this.state = user.getAddress().getState(); this.country = user.getAddress().getCountry(); this.zipCode = user.getAddress().getZipCode(); this.phoneNumber = user.getAddress().getPhoneNumber(); this.faxNumber = user.getAddress().getFaxNumber(); if (pageOf.equals(Constants.PAGEOF_USER_PROFILE)) { this.password = user.getPassword(); } else { this.activityStatus = user.getActivityStatus(); this.comments = user.getComments(); if (activityStatus.equals(Constants.ACTIVITY_STATUS_ACTIVE)) { this.status = Constants.APPROVE_USER_APPROVE_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_NEW)) { this.status = Constants.APPROVE_USER_PENDING_STATUS; } else if (activityStatus.equals(Constants.ACTIVITY_STATUS_CLOSED)) { this.status = Constants.APPROVE_USER_REJECT_STATUS; } this.role = user.getRoleId(); } } } catch (Exception excp) { Logger.out.error(excp.getMessage()); } } /** * Overrides the validate method of ActionForm. * */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); Validator validator = new Validator(); try { if (operation != null) { if (operation.equals(Constants.ADD) || operation.equals(Constants.EDIT)) { if (validator.isEmpty(lastName)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.lastName"))); } if (validator.isEmpty(firstName)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.firstName"))); } if (validator.isEmpty(city)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.city"))); } if (state.trim().equals(Constants.SELECT_OPTION)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.state"))); } if (validator.isEmpty(zipCode)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.zipCode"))); } if (country.trim().equals(Constants.SELECT_OPTION)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.country"))); } if (validator.isEmpty(phoneNumber)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.phoneNumber"))); } if (validator.isEmpty(emailAddress)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.emailAddress"))); } else { if (!validator.isValidEmailAddress(emailAddress)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format", ApplicationProperties.getValue("user.emailAddress"))); } } if (institutionId == -1) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.institution"))); } if (departmentId == -1) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.department"))); } if (cancerResearchGroupId == -1) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required", ApplicationProperties.getValue("user.cancerResearchGroup"))); } } if (pageOf.equals(Constants.PAGEOF_USER_ADMIN) || pageOf.equals(Constants.PAGEOF_APPROVE_USER)) { if (role != null) { if (role.trim().equals("0")) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.role"))); } } } if (pageOf.equals(Constants.PAGEOF_APPROVE_USER)) { if (status.trim().equals(Constants.SELECT_OPTION)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.approveOperation"))); } } if (pageOf.equals(Constants.PAGEOF_USER_PROFILE)) { if (validator.isEmpty(password)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.item.required", ApplicationProperties .getValue("user.password"))); } } } } catch (Exception excp) { Logger.out.error(excp.getMessage(), excp); } return errors; } }
package edu.wustl.catissuecore.caties.util; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.log4j.PropertyConfigurator; import edu.wustl.catissuecore.bizlogic.BizLogicFactory; import edu.wustl.catissuecore.domain.CollectionProtocolRegistration; import edu.wustl.catissuecore.domain.Participant; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.util.XMLPropertyHandler; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Variables; import edu.wustl.common.util.logger.Logger; public class Utility { /** * Generic Initialization process for caTIES servers * @throws Exception */ public static void init()throws Exception { //Initialization methods Variables.applicationHome = System.getProperty("user.dir"); //Logger.out = org.apache.log4j.Logger.getLogger(""); //Configuring common logger Logger.configure(CaTIESConstants.LOGGER_GENERAL); //Configuring logger properties PropertyConfigurator.configure(Variables.applicationHome + File.separator+"logger.properties"); // Setting properties for UseImplManager System.setProperty("gov.nih.nci.security.configFile", "./catissuecore-properties"+File.separator+"ApplicationSecurityConfig.xml"); // initializing cache manager CDEManager.init(); //initializing XMLPropertyHandler to read properties from caTissueCore_Properties.xml file XMLPropertyHandler.init("./catissuecore-properties"+File.separator+"caTissueCore_Properties.xml"); ApplicationProperties.initBundle("ApplicationResources"); //initializing caties property configurator CaTIESProperties.initBundle("caTIES"); // initializing SiteInfoHandler to read site names from site configuration file SiteInfoHandler.init(CaTIESProperties.getValue(CaTIESConstants.SITE_INFO_FILENAME)); } /** * This method returns the list of all the SCGs associated with the given participant * @param participant Participant object * @return scgList SpecimenCollectionGroup list */ public static List<SpecimenCollectionGroup> getSCGList(Participant participant)throws DAOException { // FIRE ONLY ONE QUERY List<SpecimenCollectionGroup> scgList=new ArrayList<SpecimenCollectionGroup>(); DefaultBizLogic defaultBizLogic=new DefaultBizLogic(); // get all CollectionProtocolRegistration for participant String sourceObjectName=CollectionProtocolRegistration.class.getName(); String[] selectColumnName=new String[]{Constants.SYSTEM_IDENTIFIER}; String[] whereColumnName=new String[]{Constants.COLUMN_NAME_PARTICIPANT_ID}; String[] whereColumnValue=new String[]{participant.getId().toString()}; String[] whereColumnCondition=new String[]{"="}; String joinCondition=""; Collection cprCollection=(List)defaultBizLogic.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); Long cprID; Iterator cprIter=cprCollection.iterator(); // iterate on all colletionProtocolRegistration for participant while(cprIter.hasNext()) { cprID=(Long)cprIter.next(); Collection tempSCGCollection=(Collection)defaultBizLogic.retrieveAttribute(CollectionProtocolRegistration.class.getName(), cprID, Constants.COLUMN_NAME_SCG_COLL); Iterator scgIter=tempSCGCollection.iterator(); // add all the scg associated with cpr to scgList while(scgIter.hasNext()) { SpecimenCollectionGroup scg=(SpecimenCollectionGroup)scgIter.next(); scgList.add(scg); } } return scgList; } /** * Saves object tothe datastore * @param obj object * @throws Exception throws exception */ public static void saveObject(Object obj)throws Exception { BizLogicFactory bizLogicFactory = BizLogicFactory.getInstance(); IBizLogic bizLogic = bizLogicFactory.getBizLogic(obj.getClass().getName()); SessionDataBean sessionDataBean = new SessionDataBean(); sessionDataBean.setUserName(CaTIESProperties.getValue(CaTIESConstants.SESSION_DATA)); bizLogic.insert(obj,sessionDataBean,Constants.HIBERNATE_DAO); } /** * Delete object tothe datastore * @param obj object * @throws Exception throws exception */ public static void deleteObject(Object obj)throws Exception { BizLogicFactory bizLogicFactory = BizLogicFactory.getInstance(); IBizLogic bizLogic = bizLogicFactory.getBizLogic(obj.getClass().getName()); SessionDataBean sessionDataBean = new SessionDataBean(); sessionDataBean.setUserName(CaTIESProperties.getValue(CaTIESConstants.SESSION_DATA)); bizLogic.delete(obj,Constants.HIBERNATE_DAO); } /** * Gets object data grom datastore * @param objName object name * @param property property of the object * @param val value for the property * @return list of requested object from the datastore * @throws Exception throws exception */ public static List getObject(String objName,String property,String val) throws DAOException { List l=null; BizLogicFactory bizLogicFactory = BizLogicFactory.getInstance(); IBizLogic bizLogic = bizLogicFactory.getBizLogic(objName); SessionDataBean sessionDataBean = new SessionDataBean(); sessionDataBean.setUserName(CaTIESProperties.getValue(CaTIESConstants.SESSION_DATA)); l = bizLogic.retrieve(objName,property,val); return l; } /** * @param obj object * @throws Exception * updates the object in datastore */ public static void updateObject(Object obj)throws Exception { BizLogicFactory bizLogicFactory = BizLogicFactory.getInstance(); IBizLogic bizLogic = bizLogicFactory.getBizLogic(obj.getClass().getName()); SessionDataBean sessionDataBean = new SessionDataBean(); sessionDataBean.setUserName(CaTIESProperties.getValue(CaTIESConstants.SESSION_DATA)); if(obj instanceof Participant || obj instanceof SpecimenCollectionGroup) { bizLogic.update(obj,obj,Constants.HIBERNATE_DAO,sessionDataBean); } else { bizLogic.update(obj,null,Constants.HIBERNATE_DAO,sessionDataBean); } } }
package org.cbioportal.web.parameter; public enum ChartType { PIE_CHART, BAR_CHART, SURVIVAL, TABLE, SCATTER, MUTATED_GENES_TABLE, FUSION_GENES_TABLE, CNA_GENES_TABLE, NONE; }
package com.trovebox.android.app.service; import java.io.File; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.FileObserver; import android.support.v4.app.NotificationCompat; import android.webkit.MimeTypeMap; import com.trovebox.android.app.Preferences; import com.trovebox.android.app.R; import com.trovebox.android.app.TroveboxApplication; import com.trovebox.android.app.net.UploadMetaData; import com.trovebox.android.app.net.account.AccountLimitUtils; import com.trovebox.android.app.provider.UploadsProviderAccessor; import com.trovebox.android.app.util.CommonUtils; import com.trovebox.android.app.util.TrackerUtils; public class NewPhotoObserver extends FileObserver { private static final String TAG = NewPhotoObserver.class.getSimpleName(); private final String mPath; private final Context mContext; public NewPhotoObserver(Context context, String path) { super(path, FileObserver.CREATE); mPath = path; mContext = context; } @Override public void onEvent(int event, String fileName) { if (event == FileObserver.CREATE && !fileName.equals(".probe")) { File file = new File(mPath + "/" + fileName); CommonUtils.debug(TAG, "File created [" + file.getAbsolutePath() + "]"); // fix for the issue #309 String type = getMimeType(file); if (type != null && type.toLowerCase().startsWith("image/")) { TrackerUtils.trackBackgroundEvent("autoupload_observer", CommonUtils.format("Processed for Mime-Type: %1$s", type)); if (!Preferences.isAutoUploadActive(mContext) || !CommonUtils.checkLoggedIn(true)) { return; } if (checkLimits()) { TrackerUtils.trackLimitEvent("auto_upload_limit_check", "success"); CommonUtils.debug(TAG, "Adding new autoupload to queue for file: " + fileName); UploadsProviderAccessor uploads = new UploadsProviderAccessor(mContext); UploadMetaData metaData = new UploadMetaData(); metaData.setTags(Preferences.getAutoUploadTag(mContext)); uploads.addPendingAutoUpload(Uri.fromFile(file), metaData); mContext.startService(new Intent(mContext, UploaderService.class)); } else { TrackerUtils.trackLimitEvent("autoupload_observer", "fail"); showAutouploadIgnoredNotification(file); } } else { TrackerUtils.trackBackgroundEvent("autoupload_observer", CommonUtils.format("Skipped for Mime-Type: %1$s", type == null ? "null" : type)); } } } /** * Check upload limits to determine whether autoupload could be done * @return */ private boolean checkLimits() { AccountLimitUtils.updateLimitInformationCache(); if (Preferences.isProUser()) { return true; } else { int remaining = Preferences.getRemainingUploadingLimit(); UploadsProviderAccessor uploads = new UploadsProviderAccessor( TroveboxApplication.getContext()); int pending = uploads.getPendingUploadsCount(); boolean result = remaining - pending >= 1; return result; } } /** * Show the autoupload ignored notification * * @param file */ private void showAutouploadIgnoredNotification(File file) { NotificationManager notificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; long when = System.currentTimeMillis(); String contentMessageTitle; contentMessageTitle = CommonUtils .getStringResource(R.string.upload_limit_reached_message); NotificationCompat.Builder builder = new NotificationCompat.Builder( mContext); Notification notification = builder .setContentTitle(CommonUtils.getStringResource(R.string.autoupload_ignored)) .setContentText(contentMessageTitle) .setWhen(when) .setSmallIcon(icon) .setAutoCancel(true) .build(); notificationManager.notify(file.hashCode(), notification); } /** * Get the mime type for the file * * @param file * @return */ public static String getMimeType(File file) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).getPath()); if (extension != null) { MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extension); } CommonUtils.debug(TAG, "File: %1$s; extension %2$s; MimeType: %3$s", file.getAbsolutePath(), extension, type); return type; } }
package agersant.polaris.api.local; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaDataSource; import android.preference.PreferenceManager; 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.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import agersant.polaris.CollectionItem; import agersant.polaris.PlaybackQueue; import agersant.polaris.PolarisApplication; import agersant.polaris.R; public class OfflineCache { public static final String AUDIO_CACHED = "AUDIO_CACHED"; public static final String AUDIO_REMOVED_FROM_CACHE = "AUDIO_REMOVED_FROM_CACHE"; private static final String ITEM_FILENAME = "__polaris__item"; private static final String AUDIO_FILENAME = "__polaris__audio"; private static final String META_FILENAME = "__polaris__meta"; private static final int FIRST_VERSION = 1; private static final int VERSION = 2; private static final int BUFFER_SIZE = 1024 * 64; private static OfflineCache instance; private SharedPreferences preferences; private File root; private OfflineCache(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); for (int i = FIRST_VERSION; i <= VERSION; i++) { root = new File(context.getExternalCacheDir(), "collection"); root = new File(root, "v" + VERSION); if (i != VERSION) { deleteDirectory(root); } } } public static void init(Context context) { if (instance == null) { instance = new OfflineCache(context); } } public static OfflineCache getInstance() { return instance; } private void write(CollectionItem item, OutputStream storage) throws IOException { ObjectOutputStream objOut = new ObjectOutputStream(storage); objOut.writeObject(item); objOut.close(); } private void write(FileInputStream audio, OutputStream storage) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; int read; while ((read = audio.read(buffer)) > 0) { storage.write(buffer, 0, read); } } private void write(Bitmap image, OutputStream storage) throws IOException { image.compress(Bitmap.CompressFormat.PNG, 100, storage); } private void write(ItemCacheMetadata metadata, OutputStream storage) throws IOException { ObjectOutputStream objOut = new ObjectOutputStream(storage); objOut.writeObject(metadata); objOut.close(); } private void listDeletionCandidates(File path, ArrayList<DeletionCandidate> candidates) { assert (path.isDirectory()); File[] files = path.listFiles(); for (File child : files) { File audio = new File(child, AUDIO_FILENAME); if (audio.exists()) { ItemCacheMetadata metadata = new ItemCacheMetadata(); metadata.lastUse = new Date(0L); File meta = new File(child, META_FILENAME); if (meta.exists()) { try { metadata = readMetadata(meta); } catch (IOException e) { System.out.println("Error reading file metadata for " + child + " " + e); } } CollectionItem item = null; try { item = readItem(child); } catch (Exception e) { System.out.println("Error reading collection item for " + child + " " + e); } DeletionCandidate candidate = new DeletionCandidate(child, metadata, item); candidates.add(candidate); } else if (child.isDirectory()) { listDeletionCandidates(child, candidates); } } } private long getCacheSize(File file) { long size = 0; assert (file.isDirectory()); File[] files = file.listFiles(); for (File child : files) { size += child.length(); if (child.isDirectory()) { size += getCacheSize(child); } } return size; } private long getCacheCapacity() { PolarisApplication application = PolarisApplication.getInstance(); Resources resources = application.getResources(); String cacheSizeKey = resources.getString(R.string.pref_key_offline_cache_size); String cacheSizeString = preferences.getString(cacheSizeKey, "0"); return Long.parseLong(cacheSizeString) * 1024 * 1024; } private boolean removeOldAudio(File path, CollectionItem newItem, long bytesToSave) { final PlaybackQueue queue = PlaybackQueue.getInstance(); ArrayList<DeletionCandidate> candidates = new ArrayList<>(); listDeletionCandidates(path, candidates); Collections.sort(candidates, new Comparator<DeletionCandidate>() { @Override public int compare(DeletionCandidate a, DeletionCandidate b) { if (a.item == null && b.item != null) { return -1; } if (b.item == null && a.item != null) { return 1; } if (b.item != null && a.item != null) { return -queue.comparePriorities(a.item, b.item); } return (int) (a.metadata.lastUse.getTime() - b.metadata.lastUse.getTime()); } }); long cleared = 0; for (DeletionCandidate candidate : candidates) { try { if (candidate.item != null) { if (queue.comparePriorities(candidate.item, newItem) <= 0) { continue; } } } catch (Exception e) { } File audio = new File(candidate.cachePath, AUDIO_FILENAME); if (audio.exists()) { long size = audio.length(); if (audio.delete()) { System.out.println("Deleting " + audio); cleared += size; } if (cleared >= bytesToSave) { break; } } } if (cleared > 0) { broadcast(AUDIO_REMOVED_FROM_CACHE); } return cleared >= bytesToSave; } public synchronized boolean makeSpace(CollectionItem item) { long cacheSize = getCacheSize(root); long cacheCapacity = getCacheCapacity(); long overflow = cacheSize - cacheCapacity; boolean success = true; if (overflow > 0) { success = removeOldAudio(root, item, overflow); removeEmptyDirectories(root); } return success; } private void deleteDirectory(File path) { assert (path.isDirectory()); File[] files = path.listFiles(); if (files == null) { return; } for (File child : files) { if (child.isDirectory()) { deleteDirectory(child); } else { child.delete(); } } path.delete(); } private void removeEmptyDirectories(File path) { // TODO: Catastrophic complexity assert (path.isDirectory()); File[] files = path.listFiles(); for (File child : files) { if (child.isDirectory()) { if (!containsAudio(child)) { System.out.println("Deleting " + child); deleteDirectory(child); } else { removeEmptyDirectories(child); } } } } public synchronized void putAudio(CollectionItem item, FileInputStream audio) { makeSpace(item); String path = item.getPath(); try (FileOutputStream itemOut = new FileOutputStream(getCacheFile(path, CacheDataType.ITEM, true))) { write(item, itemOut); } catch (IOException e) { System.out.println("Error while caching item for local use: " + e); return; } if (audio != null) { try (FileOutputStream itemOut = new FileOutputStream(getCacheFile(path, CacheDataType.AUDIO, true))) { write(audio, itemOut); broadcast(AUDIO_CACHED); } catch (IOException e) { System.out.println("Error while caching audio for local use: " + e); return; } } if (!hasMetadata(path)) { saveMetadata(path, new ItemCacheMetadata()); } System.out.println("Saved audio to offline cache: " + path); } public synchronized void putImage(CollectionItem item, Bitmap image) { String path = item.getPath(); try (FileOutputStream itemOut = new FileOutputStream(getCacheFile(path, CacheDataType.ITEM, true))) { write(item, itemOut); } catch (IOException e) { System.out.println("Error while caching item for local use: " + e); } if (image != null) { String artworkPath = item.getArtwork(); assert (artworkPath != null); try (FileOutputStream itemOut = new FileOutputStream(getCacheFile(artworkPath, CacheDataType.ARTWORK, true))) { write(image, itemOut); } catch (IOException e) { System.out.println("Error while caching artwork for local use: " + e); } } System.out.println("Saved image to offline cache: " + path); } private File getCacheDir(String virtualPath) { String path = virtualPath.replace("\\", File.separator); return new File(root, path); } private File getCacheFile(String virtualPath, CacheDataType type, boolean create) throws IOException { File file = getCacheDir(virtualPath); switch (type) { case ITEM: file = new File(file, ITEM_FILENAME); break; case AUDIO: file = new File(file, AUDIO_FILENAME); break; case ARTWORK: break; case META: default: file = new File(file, META_FILENAME); break; } if (create) { if (!file.exists()) { File parent = file.getParentFile(); parent.mkdirs(); file.createNewFile(); } } return file; } public boolean hasAudio(String path) { try { File file = getCacheFile(path, CacheDataType.AUDIO, false); return file.exists(); } catch (IOException e) { return false; } } boolean hasImage(String virtualPath) { try { File file = getCacheFile(virtualPath, CacheDataType.ARTWORK, false); return file.exists(); } catch (IOException e) { return false; } } MediaDataSource getAudio(String virtualPath) throws IOException { if (!hasAudio(virtualPath)) { throw new FileNotFoundException(); } if (hasMetadata(virtualPath)) { ItemCacheMetadata metadata = getMetadata(virtualPath); metadata.lastUse = new Date(); saveMetadata(virtualPath, metadata); } File source = getCacheFile(virtualPath, CacheDataType.AUDIO, false); return new LocalMediaDataSource(source); } Bitmap getImage(String virtualPath) throws IOException { if (!hasImage(virtualPath)) { throw new FileNotFoundException(); } File file = getCacheFile(virtualPath, CacheDataType.ARTWORK, false); FileInputStream fileInputStream = new FileInputStream(file); return BitmapFactory.decodeFileDescriptor(fileInputStream.getFD()); } private void saveMetadata(String virtualPath, ItemCacheMetadata metadata) { try (FileOutputStream metaOut = new FileOutputStream(getCacheFile(virtualPath, CacheDataType.META, true))) { write(metadata, metaOut); } catch (IOException e) { System.out.println("Error while caching metadata for local use: " + e); } } private boolean hasMetadata(String virtualPath) { try { File file = getCacheFile(virtualPath, CacheDataType.META, false); return file.exists(); } catch (IOException e) { return false; } } private ItemCacheMetadata readMetadata(File file) throws IOException { try (FileInputStream fileInputStream = new FileInputStream(file); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); ) { return (ItemCacheMetadata) objectInputStream.readObject(); } catch (ClassNotFoundException e) { throw new FileNotFoundException(); } } private ItemCacheMetadata getMetadata(String virtualPath) throws IOException { if (!hasMetadata(virtualPath)) { throw new FileNotFoundException(); } File file = getCacheFile(virtualPath, CacheDataType.META, false); return readMetadata(file); } public ArrayList<CollectionItem> browse(String path) { ArrayList<CollectionItem> out = new ArrayList<>(); File dir = getCacheDir(path); File[] files = dir.listFiles(); if (files == null) { return out; } for (File file : files) { try { if (!file.isDirectory()) { continue; } if (isInternalFile(file)) { continue; } CollectionItem item = readItem(file); if (item.isDirectory()) { if (!containsAudio(file)) { continue; } } out.add(item); } catch (IOException | ClassNotFoundException e) { System.out.println("Error while reading offline cache: " + e); continue; } } return out; } ArrayList<CollectionItem> flatten(String path) { File dir = getCacheDir(path); return flattenDir(dir); } private boolean isInternalFile(File file) { String name = file.getName(); boolean isItem = name.equals(ITEM_FILENAME); boolean isAudio = name.equals(AUDIO_FILENAME); boolean isMeta = name.equals(META_FILENAME); return isItem || isAudio || isMeta; } private boolean containsAudio(File file) { if (!file.isDirectory()) { return file.getName().equals(AUDIO_FILENAME); } File[] files = file.listFiles(); for (File child : files) { if (containsAudio(child)) { return true; } } return false; } private ArrayList<CollectionItem> flattenDir(File source) { assert (source.isDirectory()); ArrayList<CollectionItem> out = new ArrayList<>(); File[] files = source.listFiles(); if (files == null) { return out; } for (File file : files) { try { if (isInternalFile(file)) { continue; } CollectionItem item = readItem(file); if (item.isDirectory()) { ArrayList<CollectionItem> content = flattenDir(file); if (content != null) { out.addAll(content); } } else if (hasAudio(item.getPath())) { out.add(item); } } catch (IOException | ClassNotFoundException e) { System.out.println("Error while reading offline cache: " + e); return null; } } return out; } private CollectionItem readItem(File dir) throws IOException, ClassNotFoundException { File itemFile = new File(dir, ITEM_FILENAME); if (!itemFile.exists()) { String path = root.toURI().relativize(dir.toURI()).getPath(); return CollectionItem.directory(path); } try (FileInputStream fileInputStream = new FileInputStream(itemFile); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); ) { return (CollectionItem) objectInputStream.readObject(); } } private void broadcast(String event) { PolarisApplication application = PolarisApplication.getInstance(); Intent intent = new Intent(); intent.setAction(event); application.sendBroadcast(intent); } private enum CacheDataType { ITEM, AUDIO, ARTWORK, META, } private class DeletionCandidate { File cachePath; ItemCacheMetadata metadata; CollectionItem item; DeletionCandidate(File cachePath, ItemCacheMetadata metadata, CollectionItem item) { this.cachePath = cachePath; this.metadata = metadata; this.item = item; } } }
package com.sun.star.wizards.web.export; import com.sun.star.beans.PropertyValue; import com.sun.star.frame.XComponentLoader; import com.sun.star.frame.XDesktop; import com.sun.star.frame.XStorable; import com.sun.star.io.IOException; import com.sun.star.lang.XComponent; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.util.XCloseable; import com.sun.star.wizards.common.Desktop; import com.sun.star.wizards.common.FileAccess; import com.sun.star.wizards.common.Properties; import com.sun.star.wizards.document.OfficeDocument; import com.sun.star.wizards.text.TextDocument; import com.sun.star.wizards.web.data.CGArgument; import com.sun.star.wizards.web.data.CGDocument; import com.sun.star.wizards.web.data.CGExporter; import com.sun.star.wizards.web.data.TypeDetection; /** * * @author rpiterman */ public abstract class AbstractExporter implements Exporter { protected CGExporter exporter; protected FileAccess fileAccess; protected void storeToURL(Object officeDocument, Properties props, String targetUrl, String filterName, PropertyValue[] filterData) throws IOException { props = new Properties(); props.put("FilterName", filterName); if (filterData.length>0) props.put("FilterData", filterData); XStorable xs = ((XStorable)UnoRuntime.queryInterface(XStorable.class,officeDocument)); PropertyValue[] o = props.getProperties(); xs.storeToURL(targetUrl, o); } protected void storeToURL(Object officeDocument, String targetUrl, String filterName, PropertyValue[] filterData) throws IOException { storeToURL(officeDocument, new Properties(), targetUrl, filterName, filterData); } protected void storeToURL(Object officeDocument, String targetUrl, String filterName ) throws IOException { storeToURL(officeDocument, new Properties(), targetUrl, filterName, new PropertyValue[0]); } protected String getArgument(String name, CGExporter p) { return ((CGArgument)p.cp_Arguments.getElement(name)).cp_Value; } protected Object openDocument(CGDocument doc, XMultiServiceFactory xmsf) throws com.sun.star.io.IOException { Object document = null; //open the document. try { XDesktop desktop = Desktop.getDesktop(xmsf); Properties props = new Properties(); props.put("Hidden", Boolean.TRUE); document = ( (XComponentLoader) UnoRuntime.queryInterface( XComponentLoader.class, desktop)).loadComponentFromURL( doc.cp_URL, "_blank", 0, props.getProperties()); } catch (com.sun.star.lang.IllegalArgumentException iaex) { } //try to get the number of pages in the document; try { pageCount(doc,document); } catch (Exception ex) { //Here i do nothing since pages is not *so* important. } return document; } protected void closeDocument(Object doc,XMultiServiceFactory xmsf) { /*OfficeDocument.dispose( xmsf, (XComponent) UnoRuntime.queryInterface(XComponent.class, doc));*/ try { XCloseable xc = (XCloseable)UnoRuntime.queryInterface(XCloseable.class, doc); xc.close(false); } catch (Exception ex) { ex.printStackTrace(); } } private void pageCount(CGDocument doc, Object document) { if (doc.appType.equals(TypeDetection.WRITER_DOC)) doc.pages = TextDocument.getPageCount(document); else if (doc.appType.equals(TypeDetection.IMPRESS_DOC)) doc.pages = OfficeDocument.getSlideCount(document); else if (doc.appType.equals(TypeDetection.DRAW_DOC)) doc.pages = OfficeDocument.getSlideCount(document); } public void init(CGExporter exporter_) { exporter = exporter_; } protected FileAccess getFileAccess(XMultiServiceFactory xmsf) { if ( fileAccess == null ) try { fileAccess = new FileAccess(xmsf); } catch (Exception ex) {} return fileAccess; } protected void calcFileSize(CGDocument doc, String url, XMultiServiceFactory xmsf) { /*if the exporter exports to a * binary format, get the size of the destination. */ if (exporter.cp_Binary) doc.sizeKB = getFileAccess(xmsf).getSize(url); } }
package com.example.coolweather; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.coolweather.gson.Forecast; import com.example.coolweather.gson.Weather; import com.example.coolweather.util.HttpUtil; import com.example.coolweather.util.Utility; import java.io.IOException; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class WeatherActivity extends AppCompatActivity { private TextView tv_title; private TextView tv_time; private TextView tv_tempeture; private TextView tv_weather; private TextView tv_aqi; private TextView tv_pm; private TextView tv_wear; private TextView tv_sport; private TextView tv_comfort; private LinearLayout layout; private LinearLayout layout_aqi; private ImageView iv; private SharedPreferences sharedPreferences; private Weather mWeather; public SwipeRefreshLayout swipeRefreshLayout; public DrawerLayout drawerLayout; private Button btn_dr_back; private Button btn_bg; private int NOW_PICTURE; private int INTER = 1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); intitView(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = sharedPreferences.getString("weather", null); // drawerlayoutbug // fragmentcityId String pic = sharedPreferences.getString("pic", null); if (pic != null) { Glide.with(this).load(pic).into(iv); } else { loadpic(); } if (weatherString != null) { Weather weather = Utility.handleWeatherRespone(weatherString); mWeather = weather; showInfo(weather); } else { String weatherId = getIntent().getStringExtra("weatherId"); requestWeather(weatherId); } } private void loadpic() { String picUrl = "http://guolin.tech/api/bing_pic"; HttpUtil.sendHttpRequest(picUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final String pic = response.body().string(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("pic", pic); editor.apply(); runOnUiThread(new Runnable() { @Override public void run() { Glide.with(WeatherActivity.this).load(pic).into(iv); } }); } }); } public void requestWeather(String weatherId) { String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=5ebc06a0e92b4b4e88ba0e40859d7a8b"; HttpUtil.sendHttpRequest(weatherUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final Weather weather = Utility.handleWeatherRespone(responseText); mWeather = weather; runOnUiThread(new Runnable() { @Override public void run() { if (weather != null && weather.getStatus().equals("ok")) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); showInfo(weather); } } }); } }); swipeRefreshLayout.setRefreshing(false); } private void showInfo(Weather weather) { tv_title.setText(weather.getBasic().getCity()); tv_time.setText(weather.getBasic().getUpdate().getLoc()); tv_tempeture.setText(weather.getNow().getTmp()); tv_weather.setText(weather.getNow().getCond().getTxt()); int j = weather.getDaily_forecast().size(); layout.removeAllViews(); for (int i = 0; i < j; i++) { View view = this.getLayoutInflater().inflate(R.layout.forecast_style, layout, false); TextView tv_date = view.findViewById(R.id.tv_date); TextView tv_foreweather = view.findViewById(R.id.tv_foreweather); TextView tv_max = view.findViewById(R.id.tv_max); TextView tv_min = view.findViewById(R.id.tv_min); Forecast ob = weather.getDaily_forecast().get(i); tv_date.setText(ob.getDate()); tv_foreweather.setText(ob.getCond().getTxt_d()); tv_max.setText(ob.getTmp().getMax()); tv_min.setText(ob.getTmp().getMin()); layout.addView(view); } //aqi!!!!!!! if (weather.getAqi() == null) { layout_aqi.setVisibility(View.GONE); } else { layout_aqi.setVisibility(View.VISIBLE); tv_aqi.setText(weather.getAqi().getCity().getAqi()); tv_pm.setText(weather.getAqi().getCity().getPm25()); } tv_comfort.setText(weather.getSuggestion().getComf().getBrf() + weather.getSuggestion().getComf().getTxt()); tv_wear.setText(weather.getSuggestion().getCw().getBrf() + weather.getSuggestion().getCw().getTxt()); tv_sport.setText(weather.getSuggestion().getSport().getBrf() + weather.getSuggestion().getSport().getTxt()); } private void intitView() { tv_title = (TextView) findViewById(R.id.tv_title); tv_time = (TextView) findViewById(R.id.tv_time); tv_tempeture = (TextView) findViewById(R.id.tv_tempeture); tv_weather = (TextView) findViewById(R.id.tv_weather); tv_aqi = (TextView) findViewById(R.id.tv_aqi); tv_pm = (TextView) findViewById(R.id.tv_pm); tv_wear = (TextView) findViewById(R.id.tv_wear); tv_sport = (TextView) findViewById(R.id.tv_sport); tv_comfort = (TextView) findViewById(R.id.tv_comfort); layout = (LinearLayout) findViewById(R.id.liner_forecast); layout_aqi = (LinearLayout) findViewById(R.id.layout_aqi); iv = (ImageView) findViewById(R.id.iv); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swip); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { requestWeather(mWeather.getBasic().getId()); } }); drawerLayout = (DrawerLayout) findViewById(R.id.drawer); btn_dr_back = (Button) findViewById(R.id.btn_dr_back); btn_dr_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.openDrawer(GravityCompat.START); } }); btn_bg = (Button) findViewById(R.id.bg); btn_bg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (NOW_PICTURE == INTER) { iv.setImageResource(R.drawable.timg); NOW_PICTURE = 0; }else { loadpic(); NOW_PICTURE = INTER; } } }); } }
package com.example.quotes.quotes; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.preference.PreferenceManager; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.quotes.R; import com.example.quotes.model.Quote; import java.util.List; class QuotesAdapter extends RecyclerView.Adapter<QuotesAdapter.MyViewHolder> { private List<Quote> quotes; private boolean showAuthor; QuotesAdapter(List<Quote> quotes, boolean showAuthor) { this.quotes = quotes; this.showAuthor = showAuthor; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.quote_card, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { final Quote quote = quotes.get(position); holder.content.setText(quote.getContent()); if(showAuthor) holder.author.setText(quote.getAuthor().getLastName() + " " + quote.getAuthor().getFirstName()); else holder.author.setVisibility(View.GONE); final Context ctx = holder.content.getContext(); if(PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(ctx.getString(R.string.pref_show_star), true)){ if(quote.isFavorite()) holder.favorite.setImageResource(R.drawable.full_star); else holder.favorite.setImageResource(R.drawable.empty_star); } else holder.favorite.setVisibility(View.GONE); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), EditQuoteActivity.class); intent.putExtra(EditQuoteActivity.AUTHOR_FIRST_NAME, quote.getAuthor().getFirstName()); intent.putExtra(EditQuoteActivity.AUTHOR_LAST_NAME, quote.getAuthor().getLastName()); intent.putExtra(EditQuoteActivity.IS_FAVORITE, quote.isFavorite()); intent.putExtra(EditQuoteActivity.QUOTE_CONTENT, quote.getContent()); v.getContext().startActivity(intent); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener(){ @Override public boolean onLongClick(View v){ AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setTitle(quote.getContent()) .setItems(R.array.share_copy, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch(which){ case 0: sharePlainText(ctx, prepareFullQuote(quote)); break; case 1: copyToClipboard(ctx, prepareFullQuote(quote)); break; } } }); builder.create().show(); return true; } }); } private void sharePlainText(Context ctx, String messageText){ Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, messageText); Intent chosenIntent = Intent.createChooser(intent, ctx.getString(R.string.share_quote)); ctx.startActivity(chosenIntent); } private void copyToClipboard(Context ctx, String messageText){ ClipboardManager clipboard = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(ctx.getString(R.string.clipboard_copied), messageText); clipboard.setPrimaryClip(clip); Toast.makeText(ctx, ctx.getString(R.string.clipboard_copied), Toast.LENGTH_SHORT).show(); } private String prepareFullQuote(Quote quote){ return new StringBuilder() .append("\"") .append(quote.getContent()) .append("\"") .append(" ") .append(quote.getAuthor().getLastName()) .append(" ") .append(quote.getAuthor().getFirstName()) .toString(); } @Override public int getItemCount() { return quotes.size(); } static class MyViewHolder extends RecyclerView.ViewHolder{ public TextView content; public TextView author; public ImageView favorite; MyViewHolder(View itemView) { super(itemView); content = (TextView) itemView.findViewById(R.id.quote_content); author = (TextView) itemView.findViewById(R.id.author_of_qoute); favorite = (ImageView) itemView.findViewById(R.id.is_favorite); } } }
package com.james.status.data.icon; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import com.james.status.R; import com.james.status.data.IconStyleData; import com.james.status.receivers.IconUpdateReceiver; import java.util.Arrays; import java.util.List; public class WifiIconData extends IconData<WifiIconData.WifiReceiver> { private WifiManager wifiManager; private ConnectivityManager connectivityManager; public WifiIconData(Context context) { super(context); wifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE); connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } @Override public WifiReceiver getReceiver() { return new WifiReceiver(this); } @Override public IntentFilter getIntentFilter() { return new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION); } @Override public void register() { super.register(); int level = WifiManager.calculateSignalLevel(wifiManager.getConnectionInfo().getRssi(), 5); if (level > 0) onDrawableUpdate(level); //temporary fix, cannot determine if wifi is enabled without BroadcastReceiver for some reason } @Override public String getTitle() { return getContext().getString(R.string.icon_wifi); } @Override public int getIconStyleSize() { return 5; } @Override public List<IconStyleData> getIconStyles() { List<IconStyleData> styles = super.getIconStyles(); styles.addAll( Arrays.asList( new IconStyleData( getContext().getString(R.string.icon_style_default), IconStyleData.TYPE_VECTOR, R.drawable.ic_wifi_0, R.drawable.ic_wifi_1, R.drawable.ic_wifi_2, R.drawable.ic_wifi_3, R.drawable.ic_wifi_4 ), new IconStyleData( getContext().getString(R.string.icon_style_radial), IconStyleData.TYPE_VECTOR, R.drawable.ic_wifi_radial_0, R.drawable.ic_wifi_radial_1, R.drawable.ic_wifi_radial_2, R.drawable.ic_wifi_radial_3, R.drawable.ic_wifi_radial_4 ), new IconStyleData( getContext().getString(R.string.icon_style_triangle), IconStyleData.TYPE_VECTOR, R.drawable.ic_wifi_triangle_0, R.drawable.ic_wifi_triangle_1, R.drawable.ic_wifi_triangle_2, R.drawable.ic_wifi_triangle_3, R.drawable.ic_wifi_triangle_4 ), new IconStyleData( getContext().getString(R.string.icon_style_retro), IconStyleData.TYPE_VECTOR, R.drawable.ic_wifi_retro_0, R.drawable.ic_wifi_retro_1, R.drawable.ic_wifi_retro_2, R.drawable.ic_wifi_retro_3, R.drawable.ic_wifi_retro_4 ), new IconStyleData( getContext().getString(R.string.icon_style_classic), IconStyleData.TYPE_VECTOR, R.drawable.ic_wifi_classic_0, R.drawable.ic_wifi_classic_1, R.drawable.ic_wifi_classic_2, R.drawable.ic_wifi_classic_3, R.drawable.ic_wifi_classic_4 ), new IconStyleData( getContext().getString(R.string.icon_style_clip), IconStyleData.TYPE_VECTOR, R.drawable.ic_number_clip_0, R.drawable.ic_number_clip_1, R.drawable.ic_number_clip_2, R.drawable.ic_number_clip_3, R.drawable.ic_number_clip_4 ) ) ); return styles; } static class WifiReceiver extends IconUpdateReceiver<WifiIconData> { private WifiReceiver(WifiIconData iconData) { super(iconData); } @Override public void onReceive(WifiIconData icon, Intent intent) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (networkInfo == null) networkInfo = icon.connectivityManager.getActiveNetworkInfo(); if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && networkInfo.isConnected()) icon.onDrawableUpdate(WifiManager.calculateSignalLevel(icon.wifiManager.getConnectionInfo().getRssi(), 5)); else icon.onDrawableUpdate(-1); } } }
package com.jamieadkins.gwent.main; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.customtabs.CustomTabsIntent; import android.support.design.widget.BottomNavigationView; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.preference.PreferenceManager; import android.view.MenuItem; import android.view.View; import com.jamieadkins.gwent.R; import com.jamieadkins.gwent.base.BaseActivity; import com.jamieadkins.gwent.card.list.CardDatabaseFragment; import com.jamieadkins.gwent.deck.list.NewDeckDialog; import com.jamieadkins.gwent.settings.PreferenceFragment; import com.jamieadkins.gwent.settings.SettingsActivity; import java.util.Locale; public class MainActivity extends BaseActivity { private static final String STATE_NEWS_SHOWN = "com.jamieadkins.gwent.news.shown"; private boolean newsItemShown = false; private BottomNavigationView navigationView; @Override public void initialiseContentView() { setContentView(R.layout.activity_main); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { newsItemShown = savedInstanceState.getBoolean(STATE_NEWS_SHOWN, false); } checkLanguage(); checkIntentForNews(); SettingsActivity.checkAndUpdatePatchTopic(PreferenceManager.getDefaultSharedPreferences(this), getResources()); if (savedInstanceState == null) { // Cold start, launch card db fragment. Fragment fragment = new CardDatabaseFragment(); launchFragment(fragment, fragment.getClass().getSimpleName()); } navigationView = findViewById(R.id.navigation); navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment fragment = getFragmentForMenuItem(item.getItemId()); launchFragment(fragment, fragment.getClass().getSimpleName()); return true; } }); } private void checkIntentForNews() { Intent intent = getIntent(); if (intent.getExtras() != null) { String url = intent.getExtras().getString("url"); if (url != null && !newsItemShown) { showChromeCustomTab(url); newsItemShown = true; } } } private void checkLanguage() { String language = Locale.getDefault().getLanguage(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (!preferences.contains(getString(R.string.shown_language))) { SharedPreferences.Editor editor = preferences.edit(); String[] locales = getResources().getStringArray(R.array.locales); for (String locale : locales) { if (locale.contains(language)) { editor.putString(getString(R.string.pref_locale_key), locale); } } editor.putBoolean(getString(R.string.shown_language), true); editor.apply(); } if (!preferences.contains(getString(R.string.shown_news))) { SharedPreferences.Editor editor = preferences.edit(); String[] locales = getResources().getStringArray(R.array.locales_news); for (String locale : locales) { if (locale.contains(language)) { editor.putString(getString(R.string.pref_news_notifications_key), locale); } } editor.putBoolean(getString(R.string.shown_news), true); editor.apply(); } } private Fragment getFragmentForMenuItem(int itemId) { switch (itemId) { case R.id.navigation_card_db: return new CardDatabaseFragment(); case R.id.navigation_collection: return new CardDatabaseFragment(); case R.id.navigation_decks: return new CardDatabaseFragment(); case R.id.navigation_gwent: return PreferenceFragment.newInstance(R.xml.gwent); default: return new CardDatabaseFragment(); } } private void launchFragment(final Fragment fragment, String tag) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace( R.id.contentContainer, fragment, tag); fragmentTransaction.commit(); // Our options menu will be different for different tabs. invalidateOptionsMenu(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(STATE_NEWS_SHOWN, newsItemShown); super.onSaveInstanceState(outState); } private void showChromeCustomTab(String url) { new CustomTabsIntent.Builder() .setToolbarColor(ContextCompat.getColor(this, R.color.gwentGreen)) .setShowTitle(true) .build() .launchUrl(this, Uri.parse(url)); } }
package com.kickstarter.services; import android.net.Uri; import java.util.regex.Pattern; public class KickstarterUri { public static boolean isKickstarterUri(final Uri uri, final String webEndpoint) { return uri.getHost().equals(Uri.parse(webEndpoint).getHost()); } public static boolean isProjectUri(final Uri uri, final String webEndpoint) { return isKickstarterUri(uri, webEndpoint) && PROJECT_PATTERN.matcher(uri.getPath()).matches(); } public static boolean isSignupUri(final Uri uri, final String webEndpoint) { return isKickstarterUri(uri, webEndpoint) && uri.getPath().equals("/signup"); } public static boolean isCheckoutThanksUri(final Uri uri, final String webEndpoint) { return isKickstarterUri(uri, webEndpoint) && CHECKOUT_THANKS_PATTERN.matcher(uri.getPath()).matches(); } protected boolean isProjectNewPledgeUri(final Uri uri, final String webEndpoint) { return isKickstarterUri(uri, webEndpoint) && NEW_PLEDGE_PATTERN.matcher(uri.getPath()).matches(); } // /projects/slug-1/slug-2 private static final Pattern PROJECT_PATTERN = Pattern.compile("\\A\\/projects/[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+\\/?\\z"); // /projects/slug-1/slug-2/checkouts/1/thanks private static final Pattern CHECKOUT_THANKS_PATTERN = Pattern.compile("\\A\\/projects/[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+\\/checkouts\\/\\d+\\/thanks\\z"); // /projects/slug-1/slug-2/pledge/new private static final Pattern NEW_PLEDGE_PATTERN = Pattern.compile("\\A\\/projects/[a-zA-Z0-9_-]+\\/[a-zA-Z0-9_-]+\\/pledge\\/new\\z"); }
package com.poepoemyintswe.popularmovies; public class Config { public static final String BASE_URL = "http://api.themoviedb.org/3"; public static final String DISCOVER_MOVIE = "/discover/movie"; public static final String PHOTO_URL = "http://image.tmdb.org/t/p/w185//"; public static final String SORT_BY = "sort_by"; public static final String API_KEY = "api_key"; }
package de.eightbitboy.hijacr.data; import android.content.Context; import android.graphics.Bitmap; import android.view.View; import android.widget.ImageView; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import de.eightbitboy.hijacr.data.comic.ComicData; import de.eightbitboy.hijacr.data.database.ComicDatabaseHelper; import de.eightbitboy.hijacr.events.ComicViewUpdateEvent; import de.greenrobot.event.EventBus; /** * Handles the comic viewing state and updates the comic view. */ public class ComicManager { private ComicDatabaseHelper database; private ImageView comicView; private ComicData comicData; private int currentComicCount = 0; private String currentComicUrl; private String previousComicUrl; private String nextComicUrl; private SimpleImageLoadingListener loadListener; private ImageLoadingProgressListener progressListener; /** * Creates a new ComicManager intended for starting a new comic. * * @param comicView * @param comicData */ public ComicManager(Context context, ImageView comicView, ComicData comicData) { database = new ComicDatabaseHelper(context); this.comicView = comicView; this.comicData = comicData; if (this.comicData.isSimple()) { this.currentComicCount = this.comicData.getFirstNumber(); } else { this.currentComicUrl = this.comicData.getFirstUrl(); } int savedComicCount = database.getProgressNumber(this.comicData.getId()); if (savedComicCount > -1) { this.currentComicCount = savedComicCount; } String savedComicUrl = database.getProgressUrl(this.comicData.getId()); if (savedComicUrl != null) { this.currentComicUrl = savedComicUrl; } setUpImageListeners(); } private void setUpImageListeners() { loadListener = new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { EventBus.getDefault().post(new ComicViewUpdateEvent()); } }; progressListener = new ImageLoadingProgressListener() { @Override public void onProgressUpdate(String imageUri, View view, int current, int total) { //TODO show progress somewhere } }; } public void clearComic() { comicView.setImageBitmap(null); } public void loadCurrentComic() { fetchComicUrl(currentComicUrl); } public void loadNextComic() { currentComicCount++; database.setProgressNumber(comicData.getId(), currentComicCount); fetchComicUrl(nextComicUrl); if (nextComicUrl != null) { currentComicUrl = nextComicUrl; database.setProgressUrl(comicData.getId(), currentComicUrl); } } public void loadPreviousComic() { currentComicCount database.setProgressNumber(comicData.getId(), currentComicCount); fetchComicUrl(previousComicUrl); if (previousComicUrl != null) { currentComicUrl = previousComicUrl; database.setProgressUrl(comicData.getId(), currentComicUrl); } } private void fetchComicUrl(String url) { if (comicData.isSimple()) { new SimpleComicFetchTask(comicData.getBaseUrl(), currentComicCount, comicData.getImageQuery(), this).execute(); } else { new ComicFetchTask(url, comicData.getImageQuery(), comicData .getPreviousQuery(), comicData.getNextQuery(), this).execute(); } } public void onGetImageSource(String source, String previousComicUrl, String nextComicUrl) { this.previousComicUrl = previousComicUrl; this.nextComicUrl = nextComicUrl; ImageLoader.getInstance().displayImage(source, comicView, null, loadListener, progressListener); } /** * This callback is executed when a SimpleComicFetchTask returns successfully. * It loads the image from the given url into the comic ImageView. * * @param source The image URL. */ public void onGetSimpleImageSource(String source) { ImageLoader.getInstance().displayImage(source, comicView, null, loadListener, progressListener); } }
package edu.rit.gis.doctoreducator; import android.content.Context; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class AssetManager { private static final String LOG_TAG = "AssetManager"; private static final String ASSETS_FILE = "assets.json"; private static final String ASSET_DIRECTORY = "assets/"; private static final String LIST_URL = "content/list/?latest=true"; private FileHelper mFileHelper; private File mAssetFile; private Map<String, JSONObject> mAssetMap; private Context mContext; /** * Convenience method which calls the other constructor with read=true. */ public AssetManager(Context context) throws IOException, JSONException { this(context, true); } /** * Create a new AssetManager. * * Generally {@code read} should only be false if you encountered an exception * when read was true. * * @param context - context necessary to create the FileHelper * @param read - read the current asset file or not * @throws IOException - if the file cannot be read * @throws JSONException - if the file is corrupted */ public AssetManager(Context context, boolean read) throws IOException, JSONException { mContext = context; mFileHelper = new FileHelper(context); mAssetFile = mFileHelper.getFile(ASSETS_FILE); if (read) { mAssetMap = readCurrentAssets(); } else { mAssetMap = new HashMap<>(); } } /** * Create an asset manager. If an IO or JSON exception is thrown fall * back to creating the asset manager without reading from the file. * This is how clients should usually get an instance of an asset manager. * Exceptions are logged. * * @param context - context (usually Activity instance) * @return a created AssetManager */ public static AssetManager createInstance(Context context) { try { return new AssetManager(context, true); } catch (IOException | JSONException e1) { Log.e(LOG_TAG, e1.getMessage(), e1); try { return new AssetManager(context, false); } catch (IOException | JSONException e2) { throw new RuntimeException(e2); } } } public Map<String, JSONObject> getCurrentAssets() { return mAssetMap; } /** * Determine which file the given asset is in. * * @param name - Name of asset object already stored in the asset manager */ public File determineFile(String name) throws JSONException { return determineFile(mAssetMap.get(name)); } /** * Determine which file the given asset is in. * * @param assetObj - ContentFile object from REST server */ public File determineFile(JSONObject assetObj) throws JSONException { String filename = assetObj.getString("name") + "." + assetObj.getString("type"); return mFileHelper.getFile(ASSET_DIRECTORY, filename); } /** * Read the current assets file. If it doesn't yet exist an empty map will be returned. * * @return a map of names to {@code JSONObject}s. * @throws IOException * @throws JSONException */ private Map<String, JSONObject> readCurrentAssets() throws IOException, JSONException { File assetFile = mFileHelper.getFile(ASSETS_FILE); if (!assetFile.exists()) { return new HashMap<>(); } else { Map<String, JSONObject> assetMap = new HashMap<>(); JSONObject currentAssets = new JSONObject(IOUtil.readString( new FileInputStream(assetFile))); Iterator<String> names = currentAssets.keys(); while(names.hasNext()) { String name = names.next(); assetMap.put(name, currentAssets.getJSONObject(name)); } return assetMap; } } /** * Check if the next version is greater than the current one. * * If there is no current version it will always return true. * * @param next - a JSONObject with a "version" field * @return if the next object's version is greater than the current object's version * @throws JSONException if there is a JSON exception */ public boolean isNewVersion(JSONObject next) throws JSONException { return isNewVersion(next, mAssetMap.get(next.getString("name"))); } /** * Check if the next version is greater than the current one. * * If {@code current} is null it will always be considered out of date * * @param next - a JSONObject with a "version" field * @param current - a JSONObject with a "version" field or null * @return if the next object's version is greater than the current object's version * @throws JSONException if there is a JSON exception */ public boolean isNewVersion(JSONObject next, JSONObject current) throws JSONException { return current == null || next.getInt("version") > current.getInt("version"); } /** * Update an asset. * * @param asset - the asset data * @throws JSONException */ public void updateAsset(JSONObject asset) throws JSONException { validateJSON(asset); mAssetMap.put(asset.getString("name"), asset); } /** * Save the asset data to the asset file. * * @throws IOException */ public void save() throws IOException, JSONException { JSONObject storageObject = new JSONObject(); for (JSONObject obj : mAssetMap.values()) { storageObject.put(obj.getString("name"), obj); } FileWriter writer = new FileWriter(mAssetFile); writer.write(storageObject.toString()); writer.close(); } private boolean validateJSON(JSONObject obj) throws JSONException { // if all of these succeed we're good obj.getString("name"); obj.getInt("version"); obj.getString("type"); obj.getString("file"); return true; } public void updateAllAssets() throws IOException, JSONException { try { RestHelper rest = new RestHelper(mContext.getString(R.string.url_base)); // first we grab the list of the latest content JSONArray newFilesArray = new JSONArray(rest.sendGET( rest.resolve(LIST_URL))); // now we try to download each of them for (int i = 0; i < newFilesArray.length(); i++) { JSONObject nextFile = newFilesArray.getJSONObject(i); if (isNewVersion(nextFile)) { // download the file File output = determineFile(nextFile); IOUtil.downloadFile(new URL(nextFile.getString("file")), output); // file is downloaded so update the data updateAsset(nextFile); } } } finally { try { save(); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); } } } }
package com.mybigday.rnmediaplayer; import android.content.Context; import android.view.View; import android.widget.LinearLayout; import com.facebook.react.bridge.ReactApplicationContext; public class Root { Context context; ReactApplicationContext reactContext; private LinearLayout containerLayout; private Container currentReadyContainer; private boolean upsideDownMode = false; public Root(Context context, ReactApplicationContext reactContext, LinearLayout layout) { this.context = context; this.reactContext = reactContext; containerLayout = layout; } public View getView() { return containerLayout; } public void setUpsideDownMode(final boolean enable) { upsideDownMode = enable; } private void finalRendIn(String type, String filePath) { Container container = type == "image" ? new ImageContainer(context, reactContext, upsideDownMode) : new VideoContainer(context, reactContext, upsideDownMode); containerLayout.removeAllViews(); containerLayout.refreshDrawableState(); containerLayout.addView(container.getView()); currentReadyContainer = container; currentReadyContainer.rendIn(filePath, new Container.Callback() { @Override public void call() { containerLayout.removeAllViews(); containerLayout.refreshDrawableState(); currentReadyContainer = null; } }); } public void rendIn(final String type, final String filePath) { if (currentReadyContainer != null) { rendOut(new Container.Callback() { @Override public void call() { finalRendIn(type, filePath); } }); } else { finalRendIn(type, filePath); } } public void rendOut(final Container.Callback cb) { if (currentReadyContainer == null) { if (cb != null) cb.call(); return; } currentReadyContainer.rendOut(new Container.Callback() { @Override public void call() { containerLayout.removeAllViews(); containerLayout.refreshDrawableState(); currentReadyContainer = null; if (cb != null) cb.call(); } }); } public void destroyContainer() { if (currentReadyContainer != null) { currentReadyContainer.destroy(); } } }
package jp.blanktar.ruumusic.service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.WorkerThread; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.media.MediaBrowserCompat.MediaItem; import android.support.v4.media.MediaBrowserServiceCompat; import android.widget.Toast; import jp.blanktar.ruumusic.R; import jp.blanktar.ruumusic.util.PlayingStatus; import jp.blanktar.ruumusic.util.Preference; import jp.blanktar.ruumusic.util.RepeatModeType; import jp.blanktar.ruumusic.util.RuuDirectory; import jp.blanktar.ruumusic.util.RuuFile; import jp.blanktar.ruumusic.util.RuuFileBase; @WorkerThread public class RuuService extends MediaBrowserServiceCompat implements SharedPreferences.OnSharedPreferenceChangeListener{ public final static String ACTION_PLAY = "jp.blanktar.ruumusic.PLAY"; public final static String ACTION_PLAY_RECURSIVE = "jp.blanktar.ruumusic.PLAY_RECURSIVE"; public final static String ACTION_PLAY_SEARCH = "jp.blanktar.ruumusic.PLAY_SEARCH"; public final static String ACTION_PAUSE = "jp.blanktar.ruumusic.PAUSE"; public final static String ACTION_PAUSE_TRANSIENT = "jp.blanktar.ruumusic.PAUSE_TRANSIENT"; public final static String ACTION_PLAY_PAUSE = "jp.blanktar.ruumusic.PLAY_PAUSE"; public final static String ACTION_NEXT = "jp.blanktar.ruumusic.NEXT"; public final static String ACTION_PREV = "jp.blanktar.ruumusic.PREV"; public final static String ACTION_SEEK = "jp.blanktar.ruumusic.SEEK"; public final static String ACTION_REPEAT = "jp.blanktar.ruumusic.REPEAT"; public final static String ACTION_SHUFFLE = "jp.blanktar.ruumusic.SHUFFLE"; public final static String ACTION_PING = "jp.blanktar.ruumusic.PING"; public final static String ACTION_REQUEST_EQUALIZER_INFO = "jp.blanktar.ruumusic.REQUEST_EQUALIZER_INFO"; public final static String ACTION_EQUALIZER_INFO = "jp.blanktar.ruumusic.EQUALIZER_INFO"; public final static String ACTION_STATUS = "jp.blanktar.ruumusic.STATUS"; public final static String ACTION_FAILED_PLAY = "jp.blanktar.ruumusic.FAILED_PLAY"; public final static String ACTION_NOT_FOUND = "jp.blanktar.ruumusic.NOT_FOUND"; public enum Status{ INITIAL, LOADING_FROM_LASTEST, LOADING, READY, ERRORED } @NonNull private final MediaPlayer player = new MediaPlayer(); private MediaPlayer endOfListSE; private MediaPlayer errorSE; @Nullable private Timer deathTimer; @Nullable private Preference preference; @Nullable private Playlist playlist; @NonNull private RepeatModeType repeatMode = RepeatModeType.OFF; private boolean shuffleMode = false; @NonNull private Status status = Status.INITIAL; @Nullable private EffectManager effectManager = null; private IntentEndpoint intentEndpoint; private MediaSessionEndpoint mediaSessionEndpoint; private EndpointManager endpoints = new EndpointManager(); @Override public void onCreate(){ super.onCreate(); endOfListSE = MediaPlayer.create(getApplicationContext(), R.raw.eol); errorSE = MediaPlayer.create(getApplicationContext(), R.raw.err); preference = new Preference(getApplicationContext()); repeatMode = preference.RepeatMode.get(); shuffleMode = preference.ShuffleMode.get(); String recursive = preference.RecursivePath.get(); if(recursive != null){ try{ playlist = Playlist.getRecursive(getApplicationContext(), recursive); }catch(RuuFileBase.NotFound | Playlist.EmptyDirectory e){ playlist = null; } }else{ String searchQuery = preference.SearchQuery.get(); String searchPath = preference.SearchPath.get(); if(searchQuery != null && searchPath != null){ try{ playlist = Playlist.getSearchResults(getApplicationContext(), RuuDirectory.getInstanceFromFullPath(getApplicationContext(), searchPath), searchQuery); }catch(RuuFileBase.NotFound | RuuFileBase.OutOfRootDirectory | Playlist.EmptyDirectory e){ playlist = null; } } } String last_play = preference.LastPlayMusic.get(); if(last_play != null && !last_play.equals("")){ try{ if(playlist != null){ playlist.goMusic(RuuFile.getInstance(getApplicationContext(), last_play)); }else{ playlist = Playlist.getByMusicPath(getApplicationContext(), last_play); } if(shuffleMode){ playlist.shuffle(true); } load(true); }catch(RuuFileBase.NotFound | Playlist.NotFound | Playlist.EmptyDirectory | SecurityException e){ playlist = null; } }else if(playlist != null && shuffleMode){ playlist.shuffle(false); load(true); } player.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){ @Override public void onCompletion(@Nullable MediaPlayer mp){ if(repeatMode.equals(RepeatModeType.SINGLE)){ player.pause(); play(); }else{ try{ playlist.goNext(); load(false); }catch(Playlist.EndOfList e){ if(repeatMode.equals(RepeatModeType.OFF)){ player.pause(); player.seekTo(0); pause(); }else{ if(shuffleMode){ playlist.shuffle(false); }else{ playlist.goFirst(); } load(false); } } } } }); player.setOnErrorListener(new MediaPlayer.OnErrorListener(){ @Override public boolean onError(@Nullable MediaPlayer mp, int what, int extra){ player.reset(); if(status != Status.ERRORED && playlist != null){ endpoints.onFailedPlay(getPlayingStatus()); if(!errorSE.isPlaying()){ errorSE.start(); } } status = Status.ERRORED; return true; } }); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){ @Override public void onPrepared(@NonNull MediaPlayer mp){ if(status == Status.LOADING_FROM_LASTEST){ status = Status.READY; player.seekTo(preference.LastPlayPosition.get()); sendStatus(); }else{ status = Status.READY; play(); } } }); effectManager = new EffectManager(player, getApplicationContext()); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).registerOnSharedPreferenceChangeListener(this); registerReceiver(broadcastReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)); intentEndpoint = new IntentEndpoint(getApplicationContext(), new Controller()); endpoints.add(intentEndpoint); mediaSessionEndpoint = new MediaSessionEndpoint(getApplicationContext(), new Controller(), getPlayingStatus(), playlist); setSessionToken(mediaSessionEndpoint.getSessionToken()); endpoints.add(mediaSessionEndpoint); endpoints.add(new NotificationEndpoint(this, mediaSessionEndpoint.getMediaSession())); endpoints.add(new WearEndpoint(getApplicationContext(), new Controller())); endpoints.add(new ShortcutsEndpoint(getApplicationContext())); String dataVersion = RuuFileBase.getDataVersion(getApplicationContext()); String currentVersion = preference.MediaStoreVersion.get(); if (currentVersion == null || dataVersion == null || !currentVersion.equals(dataVersion)) { endpoints.onMediaStoreUpdated(); preference.MediaStoreVersion.set(dataVersion); } startDeathTimer(); } @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId){ intentEndpoint.onIntent(intent); return START_NOT_STICKY; } @Override public void onDestroy(){ unregisterReceiver(broadcastReceiver); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).unregisterOnSharedPreferenceChangeListener(this); endpoints.close(); effectManager.release(); saveStatus(); } @Override public void onSharedPreferenceChanged(@NonNull SharedPreferences p, @NonNull String key){ if(key.equals("root_directory")){ updateRoot(); } } private PlayingStatus getPlayingStatus(){ return new PlayingStatus( status == Status.READY && player.isPlaying(), playlist != null ? playlist.getCurrent() : null, status == Status.READY ? (long)player.getDuration() : 0, status == Status.READY ? System.currentTimeMillis() - player.getCurrentPosition() : 0, status == Status.READY ? (long)player.getCurrentPosition() : 0, repeatMode, shuffleMode, (playlist != null && playlist.type == Playlist.Type.SEARCH) ? playlist.path : null, playlist != null ? playlist.query : null, (playlist != null && playlist.type == Playlist.Type.RECURSIVE) ? playlist.path : null ); } private void sendStatus(){ if (playlist != null) { mediaSessionEndpoint.updateQueue(playlist); } endpoints.onStatusUpdated(getPlayingStatus()); } private void sendEqualizerInfo(){ new Thread(new Runnable(){ @Override public void run(){ endpoints.onEqualizerInfo(effectManager.getEqualizerInfo()); } }).start(); } private void saveStatus(){ if(playlist != null){ preference.LastPlayMusic.set(playlist.getCurrent().getFullPath()); preference.LastPlayPosition.set(player.getCurrentPosition()); if(playlist.type == Playlist.Type.RECURSIVE){ preference.RecursivePath.set(playlist.path.getFullPath()); }else{ preference.RecursivePath.remove(); } if(playlist.type == Playlist.Type.SEARCH){ preference.SearchPath.set(playlist.path.getFullPath()); preference.SearchQuery.set(playlist.query); }else{ preference.SearchPath.remove(); preference.SearchQuery.remove(); } } } private void removeSavedStatus(){ preference.LastPlayMusic.remove(); preference.LastPlayPosition.remove(); preference.RecursivePath.remove(); preference.SearchPath.remove(); preference.SearchQuery.remove(); } private void updateRoot(){ RuuDirectory root; try{ root = RuuDirectory.rootDirectory(getApplicationContext()); }catch(RuuFileBase.NotFound e){ root = null; } if(playlist != null && (root == null || !root.contains(playlist.path))){ player.reset(); status = Status.INITIAL; playlist = null; removeSavedStatus(); } sendStatus(); } private void play(){ if(playlist != null){ if(status == Status.READY){ if(((AudioManager)getSystemService(Context.AUDIO_SERVICE)).requestAudioFocus(focusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){ player.start(); sendStatus(); saveStatus(); stopDeathTimer(); }else{ notifyError(getString(R.string.audiofocus_denied)); } }else if(status == Status.LOADING_FROM_LASTEST){ status = Status.LOADING; }else{ load(false); } } } private void playByPath(@NonNull String path){ try{ RuuFile file = RuuFile.getInstance(getApplicationContext(), path); if(playlist == null || playlist.type != Playlist.Type.SIMPLE || !playlist.path.equals(file.getParent())){ playlist = Playlist.getByMusicPath(getApplicationContext(), path); if(shuffleMode){ playlist.shuffle(true); } load(false); }else{ if(!playlist.getCurrent().equals(file)){ playlist.goMusic(file); load(false); }else if(status == Status.LOADING_FROM_LASTEST){ status = Status.LOADING; }else if(status == Status.READY){ if(player.isPlaying()){ player.pause(); } player.seekTo(0); play(); }else{ load(false); } } }catch(RuuFileBase.NotFound e){ notifyError(getString(R.string.cant_open_dir, e.path)); }catch(Playlist.EmptyDirectory e){ notifyError(getString(R.string.has_not_music, path)); }catch(Playlist.NotFound e){ notifyError(getString(R.string.music_not_found, path)); } } private void playRecursive(String path){ try{ playlist = Playlist.getRecursive(getApplicationContext(), path); }catch(RuuFileBase.NotFound e){ notifyError(getString(R.string.cant_open_dir, path)); return; }catch(Playlist.EmptyDirectory e){ notifyError(getString(R.string.has_not_music, path)); return; } if(shuffleMode){ playlist.shuffle(false); } load(false); } private void playBySearch(String path, String query){ try{ playlist = Playlist.getSearchResults(getApplicationContext(), RuuDirectory.getInstanceFromFullPath(getApplicationContext(), path), query); }catch(RuuFileBase.OutOfRootDirectory e){ notifyError(getString(R.string.out_of_root, path)); }catch(RuuFileBase.NotFound e){ notifyError(getString(R.string.cant_open_dir, path)); return; }catch(Playlist.EmptyDirectory e){ notifyError(getString(R.string.search_no_hits, query)); return; } if(shuffleMode){ playlist.shuffle(false); } load(false); } private void load(boolean fromLastest){ assert playlist != null; status = fromLastest ? Status.LOADING_FROM_LASTEST : Status.LOADING; player.reset(); String realName = playlist.getCurrent().getRealPath(); try{ player.setDataSource(realName); player.prepareAsync(); }catch(IOException e){ notifyError(getString(R.string.failed_open_music, realName)); } } private void pauseTransient(){ if(status == Status.READY){ if(player.isPlaying()){ player.pause(); } sendStatus(); startDeathTimer(); } } private void pause(){ pauseTransient(); ((AudioManager)getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(focusListener); sendStatus(); saveStatus(); } private void seek(@IntRange(from=0) int newtime){ if(0 <= newtime && newtime <= player.getDuration() && status == Status.READY){ player.seekTo(newtime); sendStatus(); } } private void setRepeatMode(@NonNull RepeatModeType mode){ repeatMode = mode; sendStatus(); preference.RepeatMode.set(repeatMode); } private void setShuffleMode(boolean mode){ if(playlist != null){ if(mode){ playlist.shuffle(true); }else{ playlist.sort(); } } shuffleMode = mode; sendStatus(); preference.ShuffleMode.set(shuffleMode); } private void next(){ if(playlist != null){ try{ playlist.goNext(); load(false); }catch(Playlist.EndOfList err){ if(repeatMode.equals(RepeatModeType.LOOP)){ if(shuffleMode){ playlist.shuffle(false); }else{ playlist.goFirst(); } load(false); }else{ showToast(getString(R.string.last_of_directory), false); if(!endOfListSE.isPlaying()){ endOfListSE.start(); } endpoints.onEndOfList(false, getPlayingStatus()); } } } } private void prev(){ if(playlist != null){ if(player.getCurrentPosition() >= 3000){ seek(0); }else{ try{ playlist.goPrev(); load(false); }catch(Playlist.EndOfList err){ if(repeatMode.equals(RepeatModeType.LOOP)){ if(shuffleMode){ playlist.shuffle(false); }else{ playlist.goLast(); } load(false); }else{ showToast(getString(R.string.first_of_directory), false); if(!endOfListSE.isPlaying()){ endOfListSE.start(); } endpoints.onEndOfList(true, getPlayingStatus()); } } } } } private void notifyError(@NonNull final String message){ endpoints.onError(message, getPlayingStatus()); showToast(message, true); } private void showToast(@NonNull final String message, final boolean show_long){ final Handler handler = new Handler(); (new Thread(new Runnable(){ @Override public void run(){ handler.post(new Runnable(){ @Override public void run(){ Toast.makeText(getApplicationContext(), message, show_long ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show(); } }); } })).start(); } private void startDeathTimer(){ stopDeathTimer(); final Handler handler = new Handler(); deathTimer = new Timer(true); deathTimer.schedule(new TimerTask(){ @Override public void run(){ handler.post(new Runnable(){ @Override public void run(){ if(!player.isPlaying()){ stopSelf(); } } }); } }, 60 * 1000); } private void stopDeathTimer(){ if(deathTimer != null){ deathTimer.cancel(); deathTimer = null; } } @Override public MediaBrowserServiceCompat.BrowserRoot onGetRoot(String clientPackageName, int cliendUid, Bundle rootHints) { String id = ""; try{ id = RuuDirectory.rootDirectory(getApplicationContext()).getFullPath(); }catch(RuuFileBase.NotFound e){ } return new MediaBrowserServiceCompat.BrowserRoot(id, null); } @Override public void onLoadChildren(String parentMediaId, final Result<List<MediaItem>> result){ if(parentMediaId == null || parentMediaId.equals("")){ result.sendResult(null); return; } try{ result.sendResult(RuuDirectory.getInstance(getApplicationContext(), parentMediaId).getMediaItemList()); }catch(RuuDirectory.NotFound e){ result.sendResult(null); } } @Override public void onSearch(String query, Bundle extras, Result<List<MediaItem>> result){ RuuDirectory dir = null; try{ dir = RuuDirectory.getInstance(getApplicationContext(), extras.getCharSequence("path").toString()); }catch(NullPointerException | RuuDirectory.NotFound e){ try{ dir = RuuDirectory.rootDirectory(getApplicationContext()); }catch(RuuDirectory.NotFound f){ result.sendResult(null); } } ArrayList<MediaItem> list = new ArrayList<>(); for(RuuFileBase file: dir.search(query)){ list.add(file.toMediaItem()); } result.sendResult(list); } private final AudioManager.OnAudioFocusChangeListener focusListener = new AudioManager.OnAudioFocusChangeListener(){ private float volume = 1.0f; @Override public void onAudioFocusChange(int focusChange){ switch(focusChange){ case AudioManager.AUDIOFOCUS_GAIN: if(volume < 1.0f){ final Handler handler = new Handler(); final Timer timer = new Timer(true); timer.schedule(new TimerTask(){ @Override public void run(){ handler.post(new Runnable(){ @Override public void run(){ volume += 0.1f; if(volume >= 1.0f){ timer.cancel(); volume = 1.0f; } player.setVolume(volume, volume); } }); } }, 0, 20); } play(); break; case AudioManager.AUDIOFOCUS_LOSS: pause(); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: volume = 0.0f; player.setVolume(volume, volume); pauseTransient(); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: volume = 0.3f; player.setVolume(volume, volume); break; } } }; private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver(){ @Override public void onReceive(@Nullable Context context, @NonNull Intent intent){ if(intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)){ pause(); } } }; public class Controller{ public void play(){ RuuService.this.play(); } public void play(String file){ RuuService.this.playByPath(file); } public void play(long index){ try{ playlist.goQueueIndex(index); }catch(IndexOutOfBoundsException e){ } load(false); play(); } public void playRecursive(String dir){ RuuService.this.playRecursive(dir); } public void playSearch(String dir, String query){ RuuService.this.playBySearch(dir, query); } public void pause(){ RuuService.this.pause(); } public void pauseTransient(){ RuuService.this.pauseTransient(); } public void playPause(){ if(player.isPlaying()){ pause(); }else{ play(); } } public void seek(long msec){ RuuService.this.seek((int)msec); } public void setRepeatMode(RepeatModeType type){ RuuService.this.setRepeatMode(type); } public void setShuffleMode(boolean enabled){ RuuService.this.setShuffleMode(enabled); } public void next(){ RuuService.this.next(); } public void prev(){ RuuService.this.prev(); } public void sendStatus(){ RuuService.this.sendStatus(); } public void sendEqualizerInfo(){ RuuService.this.sendEqualizerInfo(); } } }
package me.devsaki.hentoid.database; import android.content.Context; import android.util.SparseIntArray; import androidx.annotation.NonNull; import com.annimon.stream.Collectors; import com.annimon.stream.Stream; import org.apache.commons.lang3.tuple.ImmutablePair; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.annotation.Nullable; import io.objectbox.Box; import io.objectbox.BoxStore; import io.objectbox.Property; import io.objectbox.android.AndroidObjectBrowser; import io.objectbox.query.LazyList; import io.objectbox.query.Query; import io.objectbox.query.QueryBuilder; import me.devsaki.hentoid.BuildConfig; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.AttributeLocation; import me.devsaki.hentoid.database.domains.Attribute_; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.Content_; import me.devsaki.hentoid.database.domains.ErrorRecord; import me.devsaki.hentoid.database.domains.ErrorRecord_; import me.devsaki.hentoid.database.domains.Group; import me.devsaki.hentoid.database.domains.GroupItem; import me.devsaki.hentoid.database.domains.GroupItem_; import me.devsaki.hentoid.database.domains.Group_; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.database.domains.ImageFile_; import me.devsaki.hentoid.database.domains.MyObjectBox; import me.devsaki.hentoid.database.domains.QueueRecord; import me.devsaki.hentoid.database.domains.QueueRecord_; import me.devsaki.hentoid.database.domains.SiteHistory; import me.devsaki.hentoid.database.domains.SiteHistory_; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Grouping; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.enums.StatusContent; import me.devsaki.hentoid.util.AttributeMap; import me.devsaki.hentoid.util.ContentHelper; import me.devsaki.hentoid.util.Helper; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.util.RandomSeedSingleton; import timber.log.Timber; import static com.annimon.stream.Collectors.toList; public class ObjectBoxDB { // TODO - put indexes // Status displayed in the library view (all books of the library; both internal and external) private static final int[] libraryStatus = ContentHelper.getLibraryStatuses(); private static ObjectBoxDB instance; private final BoxStore store; private ObjectBoxDB(Context context) { store = MyObjectBox.builder().androidContext(context.getApplicationContext()).maxSizeInKByte(Preferences.getMaxDbSizeKb()).build(); if (BuildConfig.DEBUG && BuildConfig.INCLUDE_OBJECTBOX_BROWSER) { boolean started = new AndroidObjectBrowser(store).start(context.getApplicationContext()); Timber.i("ObjectBrowser started: %s", started); } } // For testing (store generated by the test framework) private ObjectBoxDB(BoxStore store) { this.store = store; } // Use this to get db instance public static synchronized ObjectBoxDB getInstance(Context context) { // Use application context only if (instance == null) { instance = new ObjectBoxDB(context); } return instance; } // Use this to get db instance for testing (store generated by the test framework) public static synchronized ObjectBoxDB getInstance(BoxStore store) { // Use application context only if (instance == null) { instance = new ObjectBoxDB(store); } return instance; } void closeThreadResources() { store.closeThreadResources(); } long getDbSizeBytes() { return store.sizeOnDisk(); } long insertContent(Content content) { List<Attribute> attributes = content.getAttributes(); Box<Attribute> attrBox = store.boxFor(Attribute.class); Query<Attribute> attrByUniqueKey = attrBox.query().equal(Attribute_.type, 0).equal(Attribute_.name, "").build(); return store.callInTxNoException(() -> { // Master data management managed manually // Ensure all known attributes are replaced by their ID before being inserted Attribute dbAttr; Attribute inputAttr; if (attributes != null) // This transaction may consume a lot of DB readers depending on the number of attributes involved for (int i = 0; i < attributes.size(); i++) { inputAttr = attributes.get(i); dbAttr = (Attribute) attrByUniqueKey.setParameter(Attribute_.name, inputAttr.getName()) .setParameter(Attribute_.type, inputAttr.getType().getCode()) .findFirst(); if (dbAttr != null) { attributes.set(i, dbAttr); // If existing -> set the existing attribute dbAttr.addLocationsFrom(inputAttr); attrBox.put(dbAttr); } else { inputAttr.setName(inputAttr.getName().toLowerCase().trim()); // If new -> normalize the attribute } } return store.boxFor(Content.class).put(content); }); } public void updateContentStatus(@NonNull final StatusContent updateFrom, @NonNull final StatusContent updateTo) { List<Content> content = selectContentByStatus(updateFrom); for (int i = 0; i < content.size(); i++) content.get(i).setStatus(updateTo); store.boxFor(Content.class).put(content); } List<Content> selectContentByStatus(StatusContent status) { return selectContentByStatusCodes(new int[]{status.getCode()}); } private List<Content> selectContentByStatusCodes(int[] statusCodes) { return store.boxFor(Content.class).query().in(Content_.status, statusCodes).build().find(); } Query<Content> selectAllInternalBooksQ(boolean favsOnly) { // All statuses except SAVED, DOWNLOADING, PAUSED and ERROR that imply the book is in the download queue // and EXTERNAL because we only want to manage internal books here int[] storedContentStatus = new int[]{ StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode(), StatusContent.IGNORED.getCode(), StatusContent.UNHANDLED_ERROR.getCode(), StatusContent.CANCELED.getCode(), StatusContent.ONLINE.getCode() }; QueryBuilder<Content> query = store.boxFor(Content.class).query().in(Content_.status, storedContentStatus); if (favsOnly) query.equal(Content_.favourite, true); return query.build(); } Query<Content> selectAllExternalBooksQ() { return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.EXTERNAL.getCode()).build(); } Query<Content> selectAllErrorJsonBooksQ() { return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.ERROR.getCode()).notNull(Content_.jsonUri).notEqual(Content_.jsonUri, "").build(); } Query<Content> selectAllQueueBooksQ() { int[] storedContentStatus = new int[]{ StatusContent.SAVED.getCode(), StatusContent.DOWNLOADING.getCode(), StatusContent.PAUSED.getCode(), StatusContent.ERROR.getCode() }; return store.boxFor(Content.class).query().in(Content_.status, storedContentStatus).build(); } Query<Content> selectAllFlaggedBooksQ() { return store.boxFor(Content.class).query().equal(Content_.isFlaggedForDeletion, true).build(); } Query<Content> selectAllMarkedBooksQ() { return store.boxFor(Content.class).query().equal(Content_.isBeingDeleted, true).build(); } void flagContentById(long[] contentId, boolean flag) { Box<Content> contentBox = store.boxFor(Content.class); for (long id : contentId) { Content c = contentBox.get(id); if (c != null) { c.setFlaggedForDeletion(flag); contentBox.put(c); } } } void markContentById(long[] contentId, boolean flag) { Box<Content> contentBox = store.boxFor(Content.class); List<Content> contents = contentBox.get(contentId); for (Content c : contents) { c.setIsBeingDeleted(flag); contentBox.put(c); } } void deleteContent(Content content) { deleteContentById(content.getId()); } private void deleteContentById(long contentId) { deleteContentById(new long[]{contentId}); } /** * Remove the given content and all related objects from the DB * NB : ObjectBox v2.3.1 does not support cascade delete, so everything has to be done manually * * @param contentId IDs of the contents to be removed from the DB */ void deleteContentById(long[] contentId) { Box<ErrorRecord> errorBox = store.boxFor(ErrorRecord.class); Box<ImageFile> imageFileBox = store.boxFor(ImageFile.class); Box<Attribute> attributeBox = store.boxFor(Attribute.class); Box<AttributeLocation> locationBox = store.boxFor(AttributeLocation.class); Box<Content> contentBox = store.boxFor(Content.class); Box<GroupItem> groupItemBox = store.boxFor(GroupItem.class); Box<Group> groupBox = store.boxFor(Group.class); for (long id : contentId) { Content c = contentBox.get(id); if (c != null) { store.runInTx(() -> { if (c.getImageFiles() != null) { for (ImageFile i : c.getImageFiles()) imageFileBox.remove(i); // Delete imageFiles c.getImageFiles().clear(); // Clear links to all imageFiles } if (c.getErrorLog() != null) { for (ErrorRecord e : c.getErrorLog()) errorBox.remove(e); // Delete error records c.getErrorLog().clear(); // Clear links to all errorRecords } // Delete attribute when current content is the only content left on the attribute for (Attribute a : c.getAttributes()) if (1 == a.contents.size()) { for (AttributeLocation l : a.getLocations()) locationBox.remove(l); // Delete all locations a.getLocations().clear(); // Clear location links attributeBox.remove(a); // Delete the attribute itself } c.getAttributes().clear(); // Clear links to all attributes // Delete corresponding groupItem List<GroupItem> groupItems = groupItemBox.query().equal(GroupItem_.contentId, id).build().find(); for (GroupItem groupItem : groupItems) { // If we're not in the Custom grouping and it's the only item of its group, delete the group Group g = groupItem.group.getTarget(); if (g != null && !g.grouping.equals(Grouping.CUSTOM) && g.items.size() < 2) groupBox.remove(g); // Delete the item groupItemBox.remove(groupItem); } contentBox.remove(c); // Remove the content itself }); } } } List<QueueRecord> selectQueue() { return store.boxFor(QueueRecord.class).query().order(QueueRecord_.rank).build().find(); } List<Content> selectQueueContents() { List<Content> result = new ArrayList<>(); List<QueueRecord> queueRecords = selectQueue(); for (QueueRecord q : queueRecords) result.add(q.content.getTarget()); return result; } Query<QueueRecord> selectQueueContentsQ() { return store.boxFor(QueueRecord.class).query().order(QueueRecord_.rank).build(); } long selectMaxQueueOrder() { return store.boxFor(QueueRecord.class).query().build().property(QueueRecord_.rank).max(); } void insertQueue(long id, int order) { store.boxFor(QueueRecord.class).put(new QueueRecord(id, order)); } void updateQueue(@NonNull final List<QueueRecord> queue) { Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class); queueRecordBox.put(queue); } void deleteQueue(@NonNull Content content) { deleteQueue(content.getId()); } void deleteQueue(int queueIndex) { store.boxFor(QueueRecord.class).remove(selectQueue().get(queueIndex).id); } void deleteQueue() { store.boxFor(QueueRecord.class).removeAll(); } private void deleteQueue(long contentId) { Box<QueueRecord> queueRecordBox = store.boxFor(QueueRecord.class); QueueRecord record = queueRecordBox.query().equal(QueueRecord_.contentId, contentId).build().findFirst(); if (record != null) queueRecordBox.remove(record); } Query<Content> selectVisibleContentQ() { return selectContentSearchContentQ("", -1, Collections.emptyList(), false, Preferences.Constant.ORDER_FIELD_NONE, false); } @Nullable Content selectContentById(long id) { return store.boxFor(Content.class).get(id); } @Nullable List<Content> selectContentById(List<Long> id) { return store.boxFor(Content.class).get(id); } @Nullable Content selectContentBySourceAndUrl(@NonNull Site site, @NonNull String url) { return store.boxFor(Content.class).query().notEqual(Content_.url, "").equal(Content_.url, url).equal(Content_.site, site.getCode()).build().findFirst(); } @Nullable Content selectContentByFolderUri(@NonNull final String folderUri, boolean onlyFlagged) { QueryBuilder<Content> queryBuilder = store.boxFor(Content.class).query().equal(Content_.storageUri, folderUri); if (onlyFlagged) queryBuilder.equal(Content_.isFlaggedForDeletion, true); return queryBuilder.build().findFirst(); } private static long[] getIdsFromAttributes(@NonNull List<Attribute> attrs) { long[] result = new long[attrs.size()]; if (!attrs.isEmpty()) { int index = 0; for (Attribute a : attrs) result[index++] = a.getId(); } return result; } private void applySortOrder( QueryBuilder<Content> query, long groupId, int orderField, boolean orderDesc) { // => Implemented post-query build if (orderField == Preferences.Constant.ORDER_FIELD_RANDOM) return; // Custom ordering depends on another "table" // => Implemented post-query build if (orderField == Preferences.Constant.ORDER_FIELD_CUSTOM) { //query.sort(new Content.GroupItemOrderComparator(groupId)); // doesn't work with PagedList because it uses Query.find(final long offset, final long limit) return; } Property<Content> field = getPropertyFromField(orderField); if (null == field) return; if (orderDesc) query.orderDesc(field); else query.order(field); // Specifics sub-sorting fields when ordering by reads if (orderField == Preferences.Constant.ORDER_FIELD_READS) { if (orderDesc) query.orderDesc(Content_.lastReadDate); else query.order(Content_.lastReadDate).orderDesc(Content_.downloadDate); } } @Nullable private Property<Content> getPropertyFromField(int prefsFieldCode) { switch (prefsFieldCode) { case Preferences.Constant.ORDER_FIELD_TITLE: return Content_.title; case Preferences.Constant.ORDER_FIELD_ARTIST: return Content_.author; // Might not be what users want when there are multiple authors case Preferences.Constant.ORDER_FIELD_NB_PAGES: return Content_.qtyPages; case Preferences.Constant.ORDER_FIELD_DOWNLOAD_DATE: return Content_.downloadDate; case Preferences.Constant.ORDER_FIELD_UPLOAD_DATE: return Content_.uploadDate; case Preferences.Constant.ORDER_FIELD_READ_DATE: return Content_.lastReadDate; case Preferences.Constant.ORDER_FIELD_READS: return Content_.reads; case Preferences.Constant.ORDER_FIELD_SIZE: return Content_.size; default: return null; } } Query<Content> selectContentSearchContentQ( String title, long groupId, List<Attribute> metadata, boolean filterFavourites, int orderField, boolean orderDesc) { if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField) return store.boxFor(Content.class).query().build(); AttributeMap metadataMap = new AttributeMap(); metadataMap.addAll(metadata); boolean hasTitleFilter = (title != null && title.length() > 0); boolean hasGroupFilter = (groupId > 0); List<Attribute> sources = metadataMap.get(AttributeType.SOURCE); boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE) && (sources != null) && !(sources.isEmpty()); boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0); QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (hasSiteFilter) query.in(Content_.site, getIdsFromAttributes(sources)); if (filterFavourites) query.equal(Content_.favourite, true); if (hasTitleFilter) query.contains(Content_.title, title); if (hasTagFilter) { for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) { AttributeType attrType = entry.getKey(); if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database List<Attribute> attrs = entry.getValue(); if (attrs != null && !attrs.isEmpty()) { query.in(Content_.id, selectFilteredContent(attrs, false)); } } } } if (hasGroupFilter) { query.in(Content_.id, selectFilteredContent(groupId)); } applySortOrder(query, groupId, orderField, orderDesc); return query.build(); } long[] selectContentSearchContentByGroupItem( String title, long groupId, List<Attribute> metadata, boolean filterFavourites, int orderField, boolean orderDesc) { if (orderField != Preferences.Constant.ORDER_FIELD_CUSTOM) return new long[]{}; AttributeMap metadataMap = new AttributeMap(); metadataMap.addAll(metadata); boolean hasTitleFilter = (title != null && title.length() > 0); boolean hasGroupFilter = (groupId > 0); List<Attribute> sources = metadataMap.get(AttributeType.SOURCE); boolean hasSiteFilter = metadataMap.containsKey(AttributeType.SOURCE) && (sources != null) && !(sources.isEmpty()); boolean hasTagFilter = metadataMap.keySet().size() > (hasSiteFilter ? 1 : 0); // Pre-filter and order on GroupItem QueryBuilder<GroupItem> query = store.boxFor(GroupItem.class).query(); if (hasGroupFilter) query.equal(GroupItem_.groupId, groupId); if (orderDesc) query.orderDesc(GroupItem_.order); else query.order(GroupItem_.order); // Get linked Content QueryBuilder<Content> contentQuery = query.link(GroupItem_.content); if (hasSiteFilter) contentQuery.in(Content_.site, getIdsFromAttributes(sources)); if (filterFavourites) contentQuery.equal(Content_.favourite, true); if (hasTitleFilter) contentQuery.contains(Content_.title, title); if (hasTagFilter) { for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) { AttributeType attrType = entry.getKey(); if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database List<Attribute> attrs = entry.getValue(); if (attrs != null && !attrs.isEmpty()) { contentQuery.in(Content_.id, selectFilteredContent(attrs, false)); } } } } return Helper.getPrimitiveLongArrayFromList(Stream.of(query.build().find()).map(gi -> gi.content.getTargetId()).toList()); } private Query<Content> selectContentUniversalAttributesQ(String queryStr, long groupId, boolean filterFavourites) { QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (filterFavourites) query.equal(Content_.favourite, true); query.link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); if (groupId > 0) query.in(Content_.id, selectFilteredContent(groupId)); return query.build(); } private Query<Content> selectContentUniversalContentQ( String queryStr, long groupId, boolean filterFavourites, long[] additionalIds, int orderField, boolean orderDesc) { if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField) return store.boxFor(Content.class).query().build(); QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (filterFavourites) query.equal(Content_.favourite, true); query.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); query.or().equal(Content_.uniqueSiteId, queryStr); // query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1 query.or().in(Content_.id, additionalIds); if (groupId > 0) query.in(Content_.id, selectFilteredContent(groupId)); applySortOrder(query, groupId, orderField, orderDesc); return query.build(); } private long[] selectContentUniversalContentByGroupItem( String queryStr, long groupId, boolean filterFavourites, long[] additionalIds, int orderField, boolean orderDesc) { if (orderField != Preferences.Constant.ORDER_FIELD_CUSTOM) return new long[]{}; // Pre-filter and order on GroupItem QueryBuilder<GroupItem> query = store.boxFor(GroupItem.class).query(); if (groupId > 0) query.equal(GroupItem_.groupId, groupId); if (orderDesc) query.orderDesc(GroupItem_.order); else query.order(GroupItem_.order); // Get linked content QueryBuilder<Content> contentQuery = query.link(GroupItem_.content); contentQuery.in(Content_.status, libraryStatus); if (filterFavourites) contentQuery.equal(Content_.favourite, true); contentQuery.contains(Content_.title, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); contentQuery.or().equal(Content_.uniqueSiteId, queryStr); // query.or().link(Content_.attributes).contains(Attribute_.name, queryStr, QueryBuilder.StringOrder.CASE_INSENSITIVE); // Use of or() here is not possible yet with ObjectBox v2.3.1 contentQuery.or().in(Content_.id, additionalIds); if (groupId > 0) contentQuery.in(Content_.id, selectFilteredContent(groupId)); return Helper.getPrimitiveLongArrayFromList(Stream.of(query.build().find()).map(gi -> gi.content.getTargetId()).toList()); } Query<Content> selectContentUniversalQ( String queryStr, long groupId, boolean filterFavourites, int orderField, boolean orderDesc) { // querying Content and attributes have to be done separately Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites); return selectContentUniversalContentQ(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc); } long[] selectContentUniversalByGroupItem( String queryStr, long groupId, boolean filterFavourites, int orderField, boolean orderDesc) { // querying Content and attributes have to be done separately Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites); return selectContentUniversalContentByGroupItem(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc); } private static long[] shuffleRandomSortId(Query<Content> query) { LazyList<Content> lazyList = query.findLazy(); List<Integer> order = new ArrayList<>(); for (int i = 0; i < lazyList.size(); i++) order.add(i); Collections.shuffle(order, new Random(RandomSeedSingleton.getInstance().getSeed())); List<Long> result = new ArrayList<>(); for (int i = 0; i < order.size(); i++) { result.add(lazyList.get(order.get(i)).getId()); } return Helper.getPrimitiveLongArrayFromList(result); } // TODO adapt long[] selectContentSearchId(String title, long groupId, List<Attribute> tags, boolean filterFavourites, int orderField, boolean orderDesc) { long[] result; Query<Content> query = selectContentSearchContentQ(title, groupId, tags, filterFavourites, orderField, orderDesc); if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) { result = query.findIds(); } else { result = shuffleRandomSortId(query); } return result; } // TODO adapt long[] selectContentUniversalId(String queryStr, long groupId, boolean filterFavourites, int orderField, boolean orderDesc) { long[] result; // querying Content and attributes have to be done separately Query<Content> contentAttrSubQuery = selectContentUniversalAttributesQ(queryStr, groupId, filterFavourites); Query<Content> query = selectContentUniversalContentQ(queryStr, groupId, filterFavourites, contentAttrSubQuery.findIds(), orderField, orderDesc); if (orderField != Preferences.Constant.ORDER_FIELD_RANDOM) { result = query.findIds(); } else { result = shuffleRandomSortId(query); } return result; } private long[] selectFilteredContent(long groupId) { if (groupId < 1) return new long[0]; return Helper.getPrimitiveLongArrayFromList(store.boxFor(Group.class).get(groupId).getContentIds()); } private long[] selectFilteredContent(List<Attribute> attrs, boolean filterFavourites) { if (null == attrs || attrs.isEmpty()) return new long[0]; // Pre-build queries to reuse them efficiently within the loops QueryBuilder<Content> contentFromSourceQueryBuilder = store.boxFor(Content.class).query(); contentFromSourceQueryBuilder.in(Content_.status, libraryStatus); contentFromSourceQueryBuilder.equal(Content_.site, 1); if (filterFavourites) contentFromSourceQueryBuilder.equal(Content_.favourite, true); Query<Content> contentFromSourceQuery = contentFromSourceQueryBuilder.build(); QueryBuilder<Content> contentFromAttributesQueryBuilder = store.boxFor(Content.class).query(); contentFromAttributesQueryBuilder.in(Content_.status, libraryStatus); if (filterFavourites) contentFromAttributesQueryBuilder.equal(Content_.favourite, true); contentFromAttributesQueryBuilder.link(Content_.attributes) .equal(Attribute_.type, 0) .equal(Attribute_.name, ""); Query<Content> contentFromAttributesQuery = contentFromAttributesQueryBuilder.build(); // Cumulative query loop // Each iteration restricts the results of the next because advanced search uses an AND logic List<Long> results = Collections.emptyList(); long[] ids; for (Attribute attr : attrs) { if (attr.getType().equals(AttributeType.SOURCE)) { ids = contentFromSourceQuery.setParameter(Content_.site, attr.getId()).findIds(); } else { ids = contentFromAttributesQuery.setParameter(Attribute_.type, attr.getType().getCode()) .setParameter(Attribute_.name, attr.getName()).findIds(); } if (results.isEmpty()) results = Helper.getListFromPrimitiveArray(ids); else { // Filter results with newly found IDs (only common IDs should stay) List<Long> idsAsList = Helper.getListFromPrimitiveArray(ids); results.retainAll(idsAsList); } } return Helper.getPrimitiveLongArrayFromList(results); } List<Attribute> selectAvailableSources() { return selectAvailableSources(null); } List<Attribute> selectAvailableSources(List<Attribute> filter) { List<Attribute> result = new ArrayList<>(); QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, libraryStatus); if (filter != null && !filter.isEmpty()) { AttributeMap metadataMap = new AttributeMap(); metadataMap.addAll(filter); List<Attribute> params = metadataMap.get(AttributeType.SOURCE); if (params != null && !params.isEmpty()) query.in(Content_.site, getIdsFromAttributes(params)); for (Map.Entry<AttributeType, List<Attribute>> entry : metadataMap.entrySet()) { AttributeType attrType = entry.getKey(); if (!attrType.equals(AttributeType.SOURCE)) { // Not a "real" attribute in database List<Attribute> attrs = entry.getValue(); if (attrs != null && !attrs.isEmpty()) query.in(Content_.id, selectFilteredContent(attrs, false)); } } } List<Content> content = query.build().find(); // SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1 // => Group by and count have to be done manually (thanks God Stream exists !) // Group and count by source Map<Site, List<Content>> map = Stream.of(content).collect(Collectors.groupingBy(Content::getSite)); for (Map.Entry<Site, List<Content>> entry : map.entrySet()) { Site site = entry.getKey(); int size = (null == entry.getValue()) ? 0 : entry.getValue().size(); result.add(new Attribute(AttributeType.SOURCE, site.getDescription()).setExternalId(site.getCode()).setCount(size)); } // Order by count desc result = Stream.of(result).sortBy(a -> -a.getCount()).collect(toList()); return result; } Query<Content> selectErrorContentQ() { return store.boxFor(Content.class).query().equal(Content_.status, StatusContent.ERROR.getCode()).orderDesc(Content_.downloadDate).build(); } private Query<Attribute> queryAvailableAttributes( @NonNull final AttributeType type, String filter, long[] filteredContent) { QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query(); query.equal(Attribute_.type, type.getCode()); if (filter != null && !filter.trim().isEmpty()) query.contains(Attribute_.name, filter.trim(), QueryBuilder.StringOrder.CASE_INSENSITIVE); if (filteredContent.length > 0) query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus); else query.link(Attribute_.contents).in(Content_.status, libraryStatus); return query.build(); } long countAvailableAttributes(AttributeType type, List<Attribute> attributeFilter, String filter, boolean filterFavourites) { return queryAvailableAttributes(type, filter, selectFilteredContent(attributeFilter, filterFavourites)).count(); } @SuppressWarnings("squid:S2184") // In our case, limit() argument has to be human-readable -> no issue concerning its type staying in the int range List<Attribute> selectAvailableAttributes( @NonNull AttributeType type, List<Attribute> attributeFilter, String filter, boolean filterFavourites, int sortOrder, int page, int itemsPerPage) { long[] filteredContent = selectFilteredContent(attributeFilter, filterFavourites); List<Long> filteredContentAsList = Helper.getListFromPrimitiveArray(filteredContent); List<Integer> libraryStatusAsList = Helper.getListFromPrimitiveArray(libraryStatus); List<Attribute> result = queryAvailableAttributes(type, filter, filteredContent).find(); // Compute attribute count for sorting long count; for (Attribute a : result) { count = Stream.of(a.contents) .filter(c -> libraryStatusAsList.contains(c.getStatus().getCode())) .filter(c -> filteredContentAsList.isEmpty() || filteredContentAsList.contains(c.getId())) .count(); a.setCount((int) count); } // Apply sort order Stream<Attribute> s = Stream.of(result); if (Preferences.Constant.ORDER_ATTRIBUTES_ALPHABETIC == sortOrder) { s = s.sortBy(a -> -a.getCount()).sortBy(Attribute::getName); } else { s = s.sortBy(Attribute::getName).sortBy(a -> -a.getCount()); } // Apply paging if (itemsPerPage > 0) { int start = (page - 1) * itemsPerPage; s = s.limit(page * itemsPerPage).skip(start); // squid:S2184 here because int * int -> int (not long) } return s.collect(toList()); } SparseIntArray countAvailableAttributesPerType() { return countAvailableAttributesPerType(null); } SparseIntArray countAvailableAttributesPerType(List<Attribute> attributeFilter) { // Get Content filtered by current selection long[] filteredContent = selectFilteredContent(attributeFilter, false); // Get available attributes of the resulting content list QueryBuilder<Attribute> query = store.boxFor(Attribute.class).query(); if (filteredContent.length > 0) query.link(Attribute_.contents).in(Content_.id, filteredContent).in(Content_.status, libraryStatus); else query.link(Attribute_.contents).in(Content_.status, libraryStatus); List<Attribute> attributes = query.build().find(); SparseIntArray result = new SparseIntArray(); // SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1 // => Group by and count have to be done manually (thanks God Stream exists !) // Group and count by type Map<AttributeType, List<Attribute>> map = Stream.of(attributes).collect(Collectors.groupingBy(Attribute::getType)); for (Map.Entry<AttributeType, List<Attribute>> entry : map.entrySet()) { AttributeType t = entry.getKey(); int size = (null == entry.getValue()) ? 0 : entry.getValue().size(); result.append(t.getCode(), size); } return result; } void updateImageFileStatusParamsMimeTypeUriSize(@NonNull ImageFile image) { Box<ImageFile> imgBox = store.boxFor(ImageFile.class); ImageFile img = imgBox.get(image.getId()); if (img != null) { img.setStatus(image.getStatus()); img.setDownloadParams(image.getDownloadParams()); img.setMimeType(image.getMimeType()); img.setFileUri(image.getFileUri()); img.setSize(image.getSize()); imgBox.put(img); } } void updateImageContentStatus( long contentId, @Nullable StatusContent updateFrom, @NonNull StatusContent updateTo) { QueryBuilder<ImageFile> query = store.boxFor(ImageFile.class).query(); if (updateFrom != null) query.equal(ImageFile_.status, updateFrom.getCode()); List<ImageFile> imgs = query.equal(ImageFile_.contentId, contentId).build().find(); if (imgs.isEmpty()) return; for (int i = 0; i < imgs.size(); i++) imgs.get(i).setStatus(updateTo); store.boxFor(ImageFile.class).put(imgs); } void updateImageFileUrl(@NonNull final ImageFile image) { Box<ImageFile> imgBox = store.boxFor(ImageFile.class); ImageFile img = imgBox.get(image.getId()); if (img != null) { img.setUrl(image.getUrl()); imgBox.put(img); } } // Returns a list of processed images grouped by status, with count and filesize Map<StatusContent, ImmutablePair<Integer, Long>> countProcessedImagesById(long contentId) { QueryBuilder<ImageFile> imgQuery = store.boxFor(ImageFile.class).query(); imgQuery.equal(ImageFile_.contentId, contentId); List<ImageFile> images = imgQuery.build().find(); Map<StatusContent, ImmutablePair<Integer, Long>> result = new EnumMap<>(StatusContent.class); // SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1 // => Group by and count have to be done manually (thanks God Stream exists !) // Group and count by type Map<StatusContent, List<ImageFile>> map = Stream.of(images).collect(Collectors.groupingBy(ImageFile::getStatus)); for (Map.Entry<StatusContent, List<ImageFile>> entry : map.entrySet()) { StatusContent t = entry.getKey(); int count = 0; long size = 0; if (entry.getValue() != null) { count = entry.getValue().size(); for (ImageFile img : entry.getValue()) size += img.getSize(); } result.put(t, new ImmutablePair<>(count, size)); } return result; } Map<Site, ImmutablePair<Integer, Long>> selectMemoryUsagePerSource() { // Get all downloaded images regardless of the book's status QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode()}); List<Content> books = query.build().find(); Map<Site, ImmutablePair<Integer, Long>> result = new EnumMap<>(Site.class); // SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1 // => Group by and count have to be done manually (thanks God Stream exists !) // Group and count by type Map<Site, List<Content>> map = Stream.of(books).collect(Collectors.groupingBy(Content::getSite)); for (Map.Entry<Site, List<Content>> entry : map.entrySet()) { Site s = entry.getKey(); int count = 0; long size = 0; if (entry.getValue() != null) { count = entry.getValue().size(); for (Content c : entry.getValue()) size += c.getSize(); } result.put(s, new ImmutablePair<>(count, size)); } return result; } void insertErrorRecord(@NonNull final ErrorRecord record) { store.boxFor(ErrorRecord.class).put(record); } List<ErrorRecord> selectErrorRecordByContentId(long contentId) { return store.boxFor(ErrorRecord.class).query().equal(ErrorRecord_.contentId, contentId).build().find(); } void deleteErrorRecords(long contentId) { List<ErrorRecord> records = selectErrorRecordByContentId(contentId); store.boxFor(ErrorRecord.class).remove(records); } void insertImageFile(@NonNull ImageFile img) { if (img.getId() > 0) store.boxFor(ImageFile.class).put(img); } void deleteImageFiles(long contentId) { store.boxFor(ImageFile.class).query().equal(ImageFile_.contentId, contentId).build().remove(); } void deleteImageFiles(List<ImageFile> images) { store.boxFor(ImageFile.class).remove(images); } void insertImageFiles(@NonNull List<ImageFile> imgs) { store.boxFor(ImageFile.class).put(imgs); } @Nullable ImageFile selectImageFile(long id) { if (id > 0) return store.boxFor(ImageFile.class).get(id); else return null; } Query<ImageFile> selectDownloadedImagesFromContent(long id) { QueryBuilder<ImageFile> builder = store.boxFor(ImageFile.class).query(); builder.equal(ImageFile_.contentId, id); builder.in(ImageFile_.status, new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.EXTERNAL.getCode()}); builder.order(ImageFile_.order); return builder.build(); } void insertSiteHistory(@NonNull Site site, @NonNull String url) { SiteHistory siteHistory = selectHistory(site); if (siteHistory != null) { siteHistory.setUrl(url); store.boxFor(SiteHistory.class).put(siteHistory); } else { store.boxFor(SiteHistory.class).put(new SiteHistory(site, url)); } } @Nullable SiteHistory selectHistory(@NonNull Site s) { return store.boxFor(SiteHistory.class).query().equal(SiteHistory_.site, s.getCode()).build().findFirst(); } long insertGroup(Group group) { return store.boxFor(Group.class).put(group); } long insertGroupItem(GroupItem item) { return store.boxFor(GroupItem.class).put(item); } List<GroupItem> selectGroupItems(long[] groupItemIds) { return store.boxFor(GroupItem.class).get(groupItemIds); } List<GroupItem> selectGroupItems(long contentId, int groupingId) { QueryBuilder<GroupItem> qb = store.boxFor(GroupItem.class).query().equal(GroupItem_.contentId, contentId); qb.link(GroupItem_.group).equal(Group_.grouping, groupingId); return qb.build().find(); } void deleteGroupItem(long groupItemId) { store.boxFor(GroupItem.class).remove(groupItemId); } void deleteGroupItems(long[] groupItemIds) { store.boxFor(GroupItem.class).remove(groupItemIds); } long countGroupsFor(@NonNull final Grouping grouping) { return store.boxFor(Group.class).query().equal(Group_.grouping, grouping.getId()).build().count(); } int getMaxGroupOrderFor(@NonNull final Grouping grouping) { return (int) store.boxFor(Group.class).query().equal(Group_.grouping, grouping.getId()).build().property(Group_.order).max(); } int getMaxGroupItemOrderFor(long groupid) { return (int) store.boxFor(GroupItem.class).query().equal(GroupItem_.groupId, groupid).build().property(GroupItem_.order).max(); } Query<Group> selectGroupsQ(int grouping, @Nullable String query, int orderField, boolean orderDesc) { QueryBuilder<Group> qb = store.boxFor(Group.class).query().equal(Group_.grouping, grouping); if (query != null) qb.contains(Group_.name, query); Property<Group> property = Group_.name; if (Preferences.Constant.ORDER_FIELD_CUSTOM == orderField) property = Group_.order; // Order by number of children is done by the DAO if (orderDesc) qb.orderDesc(property); else qb.order(property); return qb.build(); } @Nullable Group selectGroup(long groupId) { return store.boxFor(Group.class).get(groupId); } @Nullable Group selectGroupByName(int grouping, @NonNull final String name) { return store.boxFor(Group.class).query().equal(Group_.grouping, grouping).equal(Group_.name, name, QueryBuilder.StringOrder.CASE_INSENSITIVE).build().findFirst(); } void deleteGroup(long groupId) { store.boxFor(Group.class).remove(groupId); } Query<Group> selectGroupsByGroupingQ(int groupingId) { return store.boxFor(Group.class).query().equal(Group_.grouping, groupingId).build(); } Query<Group> selectFlaggedGroupsQ() { return store.boxFor(Group.class).query().equal(Group_.isFlaggedForDeletion, true).build(); } void flagGroupsById(long[] groupId, boolean flag) { Box<Group> groupBox = store.boxFor(Group.class); for (long id : groupId) { Group g = groupBox.get(id); if (g != null) { g.setFlaggedForDeletion(flag); groupBox.put(g); } } } void deleteGroupItemsByGrouping(int groupingId) { QueryBuilder<GroupItem> qb = store.boxFor(GroupItem.class).query(); qb.link(GroupItem_.group).equal(Group_.grouping, groupingId); qb.build().remove(); } void deleteGroupItemsByGroup(long groupId) { QueryBuilder<GroupItem> qb = store.boxFor(GroupItem.class).query(); qb.link(GroupItem_.group).equal(Group_.id, groupId); qb.build().remove(); } /** * ONE-SHOT USE QUERIES (MIGRATION & MAINTENANCE) */ List<Content> selectContentWithOldPururinHost() { return store.boxFor(Content.class).query().contains(Content_.coverImageUrl, "://api.pururin.io/images/").build().find(); } List<Content> selectContentWithOldTsuminoCovers() { return store.boxFor(Content.class).query().contains(Content_.coverImageUrl, ": } List<Content> selectDownloadedContentWithNoSize() { return store.boxFor(Content.class).query().in(Content_.status, libraryStatus).isNull(Content_.size).build().find(); } public Query<Content> selectOldStoredContentQ() { QueryBuilder<Content> query = store.boxFor(Content.class).query(); query.in(Content_.status, new int[]{ StatusContent.DOWNLOADING.getCode(), StatusContent.PAUSED.getCode(), StatusContent.DOWNLOADED.getCode(), StatusContent.ERROR.getCode(), StatusContent.MIGRATED.getCode()}); query.notNull(Content_.storageFolder); query.notEqual(Content_.storageFolder, ""); return query.build(); } long[] selectStoredContentIds(boolean nonFavouritesOnly, boolean includeQueued) { QueryBuilder<Content> query = store.boxFor(Content.class).query(); if (includeQueued) query.in(Content_.status, new int[]{ StatusContent.DOWNLOADING.getCode(), StatusContent.PAUSED.getCode(), StatusContent.DOWNLOADED.getCode(), StatusContent.ERROR.getCode(), StatusContent.MIGRATED.getCode()}); else query.in(Content_.status, new int[]{ StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode()}); query.notNull(Content_.storageUri); query.notEqual(Content_.storageUri, ""); if (nonFavouritesOnly) query.equal(Content_.favourite, false); return query.build().findIds(); } }
package org.wikipedia.feed.model; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.wikipedia.Site; import org.wikipedia.feed.UtcDate; import org.wikipedia.history.HistoryEntry; import org.wikipedia.page.PageTitle; import org.wikipedia.util.DateUtil; import org.wikipedia.util.StringUtil; public abstract class BigPictureCard extends Card { @NonNull private CardPageItem page; @NonNull private UtcDate age; @NonNull private Site site; public BigPictureCard(@NonNull CardPageItem page, @NonNull UtcDate age, @NonNull Site site) { this.page = page; this.age = age; this.site = site; } @Override @NonNull public String subtitle() { return DateUtil.getFeedCardDateString(age.baseCalendar()); } @NonNull public String articleTitle() { return page.title(); } @Nullable public String articleSubtitle() { return page.description() != null ? StringUtil.capitalizeFirstChar(page.description()) : null; } @Override @Nullable public Uri image() { return page.thumbnail(); } @Nullable @Override public String extract() { return page.extract(); } @NonNull public HistoryEntry historyEntry(int source) { PageTitle title = new PageTitle(articleTitle(), site); if (image() != null) { title.setThumbUrl(image().toString()); } title.setDescription(articleSubtitle()); return new HistoryEntry(title, source); } }
package pro.dbro.ble.transport.ble; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattServer; import android.bluetooth.le.ScanResult; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import java.util.ArrayDeque; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import pro.dbro.ble.data.model.DataUtil; import pro.dbro.ble.protocol.IdentityPacket; import pro.dbro.ble.protocol.MessagePacket; import pro.dbro.ble.protocol.Protocol; import pro.dbro.ble.transport.Transport; public class BLETransport extends Transport implements BLECentral.BLECentralConnectionGovernor, BLEPeripheral.BLEPeripheralConnectionGovernor, BLECentral.BLECentralConnectionListener { public static final String TAG = "BLETransport"; /** How many items to send for each request for this client's items */ private static final int MESSAGES_PER_RESPONSE = 10; private static final int IDENTITIES_PER_RESPONSE = 10; private Context mContext; private BLECentral mCentral; private BLEPeripheral mPeripheral; /** Identity public key -> outbox * use public key instead of Identity to avoid overriding Identity#equals, #hashcode 'for now' */ private HashMap<byte[], ArrayDeque<MessagePacket>> mMessageOutboxes = new HashMap<>(); private HashMap<byte[], ArrayDeque<IdentityPacket>> mIdentitiesOutboxes = new HashMap<>(); private HashMap<String, IdentityPacket> mAddressesToIdentity = new HashMap<>(); private ConcurrentHashMap<IdentityPacket, BluetoothGatt> mRemotePeripherals = new ConcurrentHashMap<>(); private ConcurrentHashMap<IdentityPacket, BluetoothDevice> mRemoteCentrals = new ConcurrentHashMap<>(); // <editor-fold desc="Public API"> public BLETransport(@NonNull Context context, @NonNull IdentityPacket identityPacket, @NonNull Protocol protocol, @NonNull TransportDataProvider dataProvider) { super(identityPacket, protocol, dataProvider); mContext = context.getApplicationContext(); init(); } @Override public void makeAvailable() { mCentral.start(); mPeripheral.start(); } @Override public void sendMessage(MessagePacket messagePacket) { // TODO If Message is instanceof DirectMessage etc, try to send directly to device // Note the message should already be stored and will be automatically delivered on next connection } @Override public void makeUnavailable() { mCentral.stop(); mPeripheral.stop(); } // </editor-fold desc="Public API"> // <editor-fold desc="Private API"> private void init() { mCentral = new BLECentral(mContext); mCentral.setConnectionGovernor(this); mCentral.setConnectionListener(this); // These Central requests are executed in order mCentral.addDefaultBLECentralRequest(mIdentityReadRequest); mCentral.addDefaultBLECentralRequest(mIdentityWriteRequest); mCentral.addDefaultBLECentralRequest(mMessageReadRequest); mCentral.addDefaultBLECentralRequest(mMessageWriteRequest); mPeripheral = new BLEPeripheral(mContext); mPeripheral.setConnectionGovernor(this); mPeripheral.addDefaultBLEPeripheralResponse(mMessageReadResponse); mPeripheral.addDefaultBLEPeripheralResponse(mIdentityReadResponse); mPeripheral.addDefaultBLEPeripheralResponse(mMessageWriteResponse); mPeripheral.addDefaultBLEPeripheralResponse(mIdentityWriteResponse); } /** BLECentralConnectionGovernor */ @Override public boolean shouldConnectToPeripheral(ScanResult potentialPeer) { // If the peripheral is connected to this device, don't duplicate the connection as central return !mPeripheral.getConnectedDeviceAddresses().contains(potentialPeer.getDevice().getAddress()); } /** BLEPeripheralConnectionGovernor */ @Override public boolean shouldConnectToCentral(BluetoothDevice potentialPeer) { return !mCentral.getConnectedDeviceAddresses().contains(potentialPeer.getAddress()); } /** BLECentralRequests */ BLECentralRequest mMessageReadRequest = new BLECentralRequest(GATT.MESSAGES_READ, BLECentralRequest.RequestType.READ) { @Override public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) { // Consume message from characteristic.getValue() // If status == GATT_SUCCESS, return false to re-issue this request // else if status == READ_NOT_PERMITTED, return true MessagePacket receivedMessagePacket = mProtocol.deserializeMessage(characteristic.getValue(), null); if (mCallback != null) mCallback.receivedMessage(receivedMessagePacket); return isCentralRequestComplete(status); } }; BLECentralRequest mIdentityReadRequest = new BLECentralRequest(GATT.IDENTITY_READ, BLECentralRequest.RequestType.READ) { @Override public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) { // Consume Identity from characteristic.getValue() // If status == GATT_SUCCESS, return false to re-issue this request // else if status == READ_NOT_PERMITTED, return true IdentityPacket receivedIdentityPacket = mProtocol.deserializeIdentity(characteristic.getValue()); mAddressesToIdentity.put(remotePeripheral.getDevice().getAddress(), receivedIdentityPacket); if (mCallback != null) { mCallback.receivedIdentity(receivedIdentityPacket); mCallback.becameAvailable(receivedIdentityPacket); } return isCentralRequestComplete(status); } }; BLECentralRequest mMessageWriteRequest = new BLECentralRequest(GATT.MESSAGES_WRITE, BLECentralRequest.RequestType.WRITE) { @Override public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) { MessagePacket justSent = getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), true); if (justSent == null) { // No data was available for this request. Mark request complete return true; } else { if (status == BluetoothGatt.GATT_SUCCESS && mCallback != null) { mCallback.sentMessage(getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), false)); } // If we have more messages to send, indicate request should be repeated return (getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), false) == null); } } @Override public byte[] getDataToWrite(BluetoothGatt remotePeripheral) { //return byte[] next_message MessagePacket forRecipient = getNextMessageForDeviceAddress(remotePeripheral.getDevice().getAddress(), true); return (forRecipient == null ) ? null : forRecipient.rawPacket; } }; BLECentralRequest mIdentityWriteRequest = new BLECentralRequest(GATT.IDENTITY_WRITE, BLECentralRequest.RequestType.WRITE) { @Override public boolean handleResponse(BluetoothGatt remotePeripheral, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS && mCallback != null) { mCallback.sentIdentity(getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false)); } // If we have more identities to send, issue write request with next identity return (getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), false) == null); } @Override public byte[] getDataToWrite(BluetoothGatt remotePeripheral) { //return byte[] next_identity IdentityPacket forRecipient = getNextIdentityForDeviceAddress(remotePeripheral.getDevice().getAddress(), true); return forRecipient.rawPacket; } }; /** BLEPeripheral Responses */ BLEPeripheralResponse mMessageReadResponse = new BLEPeripheralResponse(GATT.MESSAGES_READ, BLEPeripheralResponse.RequestType.READ) { @Override public void respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) { try { // Get messages to send and send first MessagePacket forRecipient = getNextMessageForDeviceAddress(remoteCentral.getAddress(), true); if (forRecipient != null) { boolean haveAnotherMessage = getNextMessageForDeviceAddress(remoteCentral.getAddress(), false) != null; byte[] payload = forRecipient.rawPacket; int gattStatus = haveAnotherMessage ? BluetoothGatt.GATT_SUCCESS : BluetoothGatt.GATT_READ_NOT_PERMITTED; boolean success = localPeripheral.sendResponse(remoteCentral, requestId, gattStatus, 0, payload); Log.i(TAG, "Sent message payload " + DataUtil.bytesToHex(payload)); if (success && mCallback != null) mCallback.sentMessage(forRecipient); } else { boolean success = localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_READ_NOT_PERMITTED, 0, null); Log.i(TAG, "Had no messages for peer. Sent READ_NOT_PERMITTED with success " + success); } } catch(Exception e) { Log.i(TAG, "Failed to respond to message read request"); e.printStackTrace(); } } }; BLEPeripheralResponse mIdentityReadResponse = new BLEPeripheralResponse(GATT.IDENTITY_READ, BLEPeripheralResponse.RequestType.READ) { @Override public void respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) { // Get identities to send and send first IdentityPacket forRecipient = getNextIdentityForDeviceAddress(remoteCentral.getAddress(), true); boolean haveAnotherIdentity = getNextIdentityForDeviceAddress(remoteCentral.getAddress(), false) != null; byte[] payload = forRecipient.rawPacket; int gattStatus = haveAnotherIdentity ? BluetoothGatt.GATT_SUCCESS : BluetoothGatt.GATT_READ_NOT_PERMITTED; boolean success = localPeripheral.sendResponse(remoteCentral, requestId, gattStatus, 0, payload); Log.i(TAG, String.format("Responded to read request success: %b data: %s", success, (payload == null || payload.length == 0) ? "null" : DataUtil.bytesToHex(payload))); if (success && mCallback != null) mCallback.sentIdentity(forRecipient); } }; BLEPeripheralResponse mMessageWriteResponse = new BLEPeripheralResponse(GATT.MESSAGES_WRITE, BLEPeripheralResponse.RequestType.WRITE) { @Override public void respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) { // Consume message and send GATT_SUCCESS If valid and response needed MessagePacket receivedMessagePacket = mProtocol.deserializeMessage(characteristic.getValue(), mAddressesToIdentity.get(remoteCentral.getAddress())); if (mCallback != null) mCallback.receivedMessage(receivedMessagePacket); if (responseNeeded) { // TODO: Response code based on message validation? localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_SUCCESS, 0, null); } } }; BLEPeripheralResponse mIdentityWriteResponse = new BLEPeripheralResponse(GATT.IDENTITY_WRITE, BLEPeripheralResponse.RequestType.WRITE) { @Override public void respondToRequest(BluetoothGattServer localPeripheral, BluetoothDevice remoteCentral, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) { // Consume Identity and send GATT_SUCCESS if valid and response needed if (value == null || value.length == 0) { Log.i(TAG, "got empty write data"); } else { Log.i(TAG, "got non-empty write data! length: " + value.length); IdentityPacket receivedIdentityPacket = mProtocol.deserializeIdentity(value); if (mCallback != null) { Log.i(TAG, "delivering identity to callback: "); mCallback.receivedIdentity(receivedIdentityPacket); } mAddressesToIdentity.put(remoteCentral.getAddress(), receivedIdentityPacket); } if (responseNeeded) { // TODO: Response code based on message validation? localPeripheral.sendResponse(remoteCentral, requestId, BluetoothGatt.GATT_SUCCESS, 0, null); } } }; /** BLECentralConnectionListener */ @Override public void connectedTo(String deviceAddress) { // do nothing. We shouldn't report peer available until we have an Identity for it } @Override public void disconnectedFrom(String deviceAddress) { IdentityPacket disconnectedIdentityPacket = mAddressesToIdentity.remove(deviceAddress); if (mCallback != null) { mCallback.becameUnavailable(disconnectedIdentityPacket); } } /** Utility */ @Nullable private IdentityPacket getNextIdentityForDeviceAddress(String address, boolean removeFromQueue) { byte[] publicKey = getPublicKeyForDeviceAddress(address); return getNextIdentityForPublicKey(publicKey, removeFromQueue); } @Nullable private MessagePacket getNextMessageForDeviceAddress(String address, boolean removeFromQueue) { // Do we have an Identity on file for this address? byte[] publicKey = getPublicKeyForDeviceAddress(address); return getNextMessageForPublicKey(publicKey, removeFromQueue); } @Nullable private MessagePacket getNextMessageForPublicKey(@Nullable byte[] publicKey, boolean removeFromQueue) { if (!mMessageOutboxes.containsKey(publicKey) || mMessageOutboxes.get(publicKey).size() == 0) { ArrayDeque<MessagePacket> messagesForRecipient = mDataProvider.getMessagesForIdentity(publicKey, MESSAGES_PER_RESPONSE); mMessageOutboxes.put(publicKey, messagesForRecipient); } return removeFromQueue ? mMessageOutboxes.get(publicKey).pop() : mMessageOutboxes.get(publicKey).peek(); } @Nullable private IdentityPacket getNextIdentityForPublicKey(@Nullable byte[] publicKey, boolean removeFromQueue) { if (!mIdentitiesOutboxes.containsKey(publicKey) || mIdentitiesOutboxes.get(publicKey).size() == 0) { ArrayDeque<IdentityPacket> identitiesForRecipient = mDataProvider.getIdentitiesForIdentity(publicKey, IDENTITIES_PER_RESPONSE); mIdentitiesOutboxes.put(publicKey, identitiesForRecipient); } return removeFromQueue ? mIdentitiesOutboxes.get(publicKey).pop() : mIdentitiesOutboxes.get(publicKey).peek(); } private byte[] getPublicKeyForDeviceAddress(String address) { byte[] publicKey = null; if (mAddressesToIdentity.containsKey(address)) publicKey = mAddressesToIdentity.get(address).publicKey; if (publicKey == null) { // No public key on file, perform naive message send for now Log.w(TAG, String.format("Don't have identity on file for device %s. Naively sending messages", address)); } return publicKey; } private boolean isCentralRequestComplete(int gattStatus) { switch(gattStatus) { case BluetoothGatt.GATT_READ_NOT_PERMITTED: case BluetoothGatt.GATT_FAILURE: return true; // request complete case BluetoothGatt.GATT_SUCCESS: return false; // peripheral reports more data available default: Log.w(TAG, String.format("Got unexpected GATT status %d", gattStatus)); return true; } } // </editor-fold desc="Private API"> }
package wraith.library.WindowUtil; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; import wraith.library.MiscUtil.FadeListener; import wraith.library.MiscUtil.FadeTimer; @SuppressWarnings("serial") public class ImageWindow extends JFrame{ protected BufferedImage img; private boolean fadeTimer; protected float fade; protected JPanel panel; public ImageWindow(BufferedImage image){ img=image; init(); setVisible(true); } private void init(){ setUndecorated(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(img.getWidth(), img.getHeight()); setLocationRelativeTo(null); setBackground(new Color(0, 0, 0, 0)); setAlwaysOnTop(true); add(panel=createPanel()); } public void addFadeTimer(int fadeIn, int fadeStay, int fadeOut, int pingDelay){ if(this.fadeTimer)return; this.fadeTimer=true; final FadeTimer fadeTimer = new FadeTimer(fadeIn, fadeStay, fadeOut, pingDelay); fadeTimer.addListener(new FadeListener(){ public void onComplete(){ dispose(); } public void onFadeOutTick(){ updateFadeLevel(fadeTimer.getFadeLevel()); } public void onFadeInTick(){ updateFadeLevel(fadeTimer.getFadeLevel()); } public void onFadeInComplete(){ updateFadeLevel(fadeTimer.getFadeLevel()); } public void onFadeOutComplete(){} public void onFadeStayTick(){} public void onFadeStayComplete(){} }); fadeTimer.start(); } public void updateFadeLevel(float fade){ this.fade=fade; repaint(); } protected JPanel createPanel(){ return new JPanel(){ @Override public void paintComponent(Graphics g){ g.setColor(getBackground()); g.clearRect(0, 0, getWidth(), getHeight()); ((Graphics2D)g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, fade)); g.drawImage(img, 0, 0, this); g.dispose(); } }; } }
package org.joda.example.time; import java.util.Locale; import org.joda.time.DateTime; import org.joda.time.Instant; /** * Example code demonstrating how to use Joda-Time. * * @author Stephen Colebourne */ public class Examples { public static void main(String[] args) throws Exception { try { new Examples().run(); } catch (Throwable ex) { ex.printStackTrace(); } } private void run() { runInstant(); System.out.println(); runDateTime(); System.out.println(); } private void runInstant() { System.out.println("Instant"); System.out.println("======="); System.out.println("Instant stores a point in the datetime continuum as millisecs from 1970-01-01T00:00:00Z"); System.out.println("Instant is immutable and thread-safe"); System.out.println(" in = new Instant()"); Instant in = new Instant(); System.out.println("Millisecond time: in.getMillis(): " + in.getMillis()); System.out.println("ISO string version: in.toString(): " + in.toString()); System.out.println("No chronology: in.getChronology(): " + in.getChronology()); System.out.println("No time zone: in.getDateTimeZone(): " + in.getZone()); System.out.println("Change millis: in.withMillis(0): " + in.withMillis(0L)); System.out.println(""); System.out.println("Convert to Instant: in.toInstant(): " + in.toInstant()); System.out.println("Convert to DateTime: in.toDateTime(): " + in.toDateTime()); System.out.println("Convert to trusted: in.toTrustedISODateTime():" + in.toTrustedISODateTime()); System.out.println("Convert to MutableDT: in.toMutableDateTime(): " + in.toMutableDateTime()); System.out.println("Convert to Date: in.toDate(): " + in.toDate()); System.out.println("Convert to Calendar: in.toCalendar(Locale.UK): " + in.toCalendar(Locale.UK).toString().substring(0, 46)); System.out.println("Convert to GregCal: in.toGregorianCalendar(): " + in.toGregorianCalendar().toString().substring(0, 46)); System.out.println(""); System.out.println(" in2 = new Instant(in.getMillis() + 10)"); Instant in2 = new Instant(in.getMillis() + 10); System.out.println("Equals ms and chrono: in.equals(in2): " + in.equals(in2)); System.out.println("Compare millisecond: in.compareTo(in2): " + in.compareTo(in2)); System.out.println("Compare millisecond: in.isEqual(in2): " + in.isEqual(in2)); System.out.println("Compare millisecond: in.isAfter(in2): " + in.isAfter(in2)); System.out.println("Compare millisecond: in.isBefore(in2): " + in.isBefore(in2)); } private void runDateTime() { System.out.println("DateTime"); System.out.println("======="); System.out.println("DateTime stores a the date and time using millisecs from 1970-01-01T00:00:00Z internally"); System.out.println("DateTime is immutable and thread-safe"); System.out.println(" in = new DateTime()"); DateTime in = new DateTime(); System.out.println("Millisecond time: in.getMillis(): " + in.getMillis()); System.out.println("ISO string version: in.toString(): " + in.toString()); System.out.println("ISO chronology: in.getChronology(): " + in.getChronology()); System.out.println("Your time zone: in.getDateTimeZone(): " + in.getZone()); System.out.println("Change millis: in.withMillis(0): " + in.withMillis(0L)); System.out.println(""); System.out.println("Get year: in.getYear(): " + in.getYear()); System.out.println("Get monthOfYear: in.getMonthOfYear(): " + in.getMonthOfYear()); System.out.println("Get dayOfMonth: in.getDayOfMonth(): " + in.getDayOfMonth()); System.out.println("..."); System.out.println("Property access: in.dayOfWeek().get(): " + in.dayOfWeek().get()); System.out.println("Day of week as text: in.dayOfWeek().getAsText(): " + in.dayOfWeek().getAsText()); System.out.println("Day as short text: in.dayOfWeek().getAsShortText(): " + in.dayOfWeek().getAsShortText()); System.out.println("Day in french: in.dayOfWeek().getAsText(Locale.FRENCH): " + in.dayOfWeek().getAsText(Locale.FRENCH)); System.out.println("Max allowed value: in.dayOfWeek().getMaximumValue(): " + in.dayOfWeek().getMaximumValue()); System.out.println("Min allowed value: in.dayOfWeek().getMinimumValue(): " + in.dayOfWeek().getMinimumValue()); System.out.println("Copy & set to Jan: in.monthOfYear().setCopy(1): " + in.monthOfYear().setCopy(1)); System.out.println("Copy & add 14 months: in.monthOfYear().addCopy(14): " + in.monthOfYear().addToCopy(14)); System.out.println("Add 14 mnths in field:in.monthOfYear().addInFieldCopy(14): " + in.monthOfYear().addWrappedToCopy(14)); System.out.println("..."); System.out.println("Convert to Instant: in.toInstant(): " + in.toInstant()); System.out.println("Convert to DateTime: in.toDateTime(): " + in.toDateTime()); System.out.println("Convert to trusted: in.toTrustedISODateTime():" + in.toTrustedISODateTime()); System.out.println("Convert to MutableDT: in.toMutableDateTime(): " + in.toMutableDateTime()); System.out.println("Convert to Date: in.toDate(): " + in.toDate()); System.out.println("Convert to Calendar: in.toCalendar(Locale.UK): " + in.toCalendar(Locale.UK).toString().substring(0, 46)); System.out.println("Convert to GregCal: in.toGregorianCalendar(): " + in.toGregorianCalendar().toString().substring(0, 46)); System.out.println(""); System.out.println(" in2 = new DateTime(in.getMillis() + 10)"); DateTime in2 = new DateTime(in.getMillis() + 10); System.out.println("Equals ms and chrono: in.equals(in2): " + in.equals(in2)); System.out.println("Compare millisecond: in.compareTo(in2): " + in.compareTo(in2)); System.out.println("Compare millisecond: in.isEqual(in2): " + in.isEqual(in2)); System.out.println("Compare millisecond: in.isAfter(in2): " + in.isAfter(in2)); System.out.println("Compare millisecond: in.isBefore(in2): " + in.isBefore(in2)); } }
package org.flightofstairs.adirstat; import com.google.common.base.Optional; import javax.annotation.Nonnull; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import static java.net.URLConnection.guessContentTypeFromName; import static java.net.URLConnection.guessContentTypeFromStream; public final class FileUtils { public static final String DIRECTORY_MIMETYPE = "inode/directory"; public static Optional<String> getMimeType(@Nonnull File file) { if (file.isDirectory()) return Optional.of(DIRECTORY_MIMETYPE); try { Optional<String> possibleMimeType = Optional.fromNullable(guessContentTypeFromName(file.getAbsolutePath())); if (!possibleMimeType.isPresent()) { try (FileInputStream inputStream = new FileInputStream(file)) { possibleMimeType = Optional.fromNullable(guessContentTypeFromStream(inputStream)); } catch (IOException e) { return Optional.absent(); } } return possibleMimeType; } catch (StringIndexOutOfBoundsException ignored) { return Optional.absent(); } } private FileUtils() { } }
package me.palazzetti.adktoolkit; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbAccessory; import android.hardware.usb.UsbManager; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import me.palazzetti.adktoolkit.response.AdkMessage; /** * Allows to manage your ADK Usb Interface. It exposes * methods to open/close connected accessories and to read/write * from/to it. */ public class AdkManager implements IAdkManager { private static final String LOG_TAG = "AdkManager"; private static final int BUFFER_SIZE = 255; private UsbManager mUsbManager; private UsbAccessory mUsbAccessory; private ParcelFileDescriptor mParcelFileDescriptor; private FileInputStream mFileInputStream; private FileOutputStream mFileOutputStream; private IntentFilter mDetachedFilter; private BroadcastReceiver mUsbReceiver; private int mByteRead = 0; public AdkManager(UsbManager mUsbManager) { // Store Android UsbManager reference this.mUsbManager = mUsbManager; attachFilters(); attachUsbReceiver(); } public AdkManager(Context ctx) { // Store Android UsbManager reference this.mUsbManager = (UsbManager) ctx.getSystemService(Context.USB_SERVICE); attachFilters(); attachUsbReceiver(); } private void attachFilters() { // Filter for detached events mDetachedFilter = new IntentFilter(); mDetachedFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED); } private void attachUsbReceiver() { // Broadcast Receiver mUsbReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(UsbManager.ACTION_USB_ACCESSORY_DETACHED)) { UsbAccessory usbAccessory = (UsbAccessory) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); if (usbAccessory != null && usbAccessory.equals(mUsbAccessory)) { closeAccessory(); } } } }; } protected void openAccessory(UsbAccessory usbAccessory) { mParcelFileDescriptor = mUsbManager.openAccessory(usbAccessory); if (mParcelFileDescriptor != null) { mUsbAccessory = usbAccessory; FileDescriptor fileDescriptor = mParcelFileDescriptor.getFileDescriptor(); if (fileDescriptor != null) { mFileInputStream = new FileInputStream(fileDescriptor); mFileOutputStream = new FileOutputStream(fileDescriptor); } } } protected void closeAccessory() { if (mParcelFileDescriptor != null) { try { mParcelFileDescriptor.close(); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); } } mParcelFileDescriptor = null; mUsbAccessory = null; } public boolean serialAvailable() { return mByteRead >= 0; } @Override public void write(byte[] values) { try { mFileOutputStream.write(values); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); } } @Override public void write(byte value) { write((int) value); } @Override public void write(int value) { try { mFileOutputStream.write(value); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); } } @Override public void write(float value) { String bufferOfString = String.valueOf(value); write(bufferOfString); } @Override public void write(String text) { byte[] buffer = text.getBytes(); try { mFileOutputStream.write(buffer); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); } } @Override public AdkMessage read() { byte[] buffer = new byte[BUFFER_SIZE]; byte[] response; AdkMessage message; try { // Read from ADK mByteRead = mFileInputStream.read(buffer, 0, buffer.length); if (mByteRead != -1) { // Create a new buffer that fits the exact number of read bytes response = Arrays.copyOfRange(buffer, 0, mByteRead); // Prepare a message instance message = new AdkMessage(response); } else { message = new AdkMessage(null); } } catch (IOException e) { Log.e(LOG_TAG, e.getMessage()); message = null; } return message; } @Override public void close() { closeAccessory(); } @Override public void open() { if (mFileInputStream == null || mFileOutputStream == null) { UsbAccessory[] usbAccessoryList = mUsbManager.getAccessoryList(); if (usbAccessoryList != null && usbAccessoryList.length > 0) { openAccessory(usbAccessoryList[0]); } } } public IntentFilter getDetachedFilter() { return mDetachedFilter; } public BroadcastReceiver getUsbReceiver() { return mUsbReceiver; } // Protected methods used by tests protected void setFileInputStream(FileInputStream fileInputStream) { this.mFileInputStream = fileInputStream; } protected void setFileOutputStream(FileOutputStream fileOutputStream) { this.mFileOutputStream = fileOutputStream; } protected UsbManager getUsbManager() { return mUsbManager; } }
package com.xpn.xwiki.doc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.lang.ref.SoftReference; import java.lang.reflect.Method; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ecs.filter.CharacterFilter; import org.apache.velocity.VelocityContext; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.suigeneris.jrcs.diff.Diff; import org.suigeneris.jrcs.diff.DifferentiationFailedException; import org.suigeneris.jrcs.diff.Revision; import org.suigeneris.jrcs.diff.delta.Delta; import org.suigeneris.jrcs.rcs.Version; import org.suigeneris.jrcs.util.ToString; import org.xwiki.bridge.DocumentModelBridge; import org.xwiki.rendering.block.LinkBlock; import org.xwiki.rendering.block.MacroBlock; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.listener.LinkType; import org.xwiki.rendering.parser.ParseException; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.parser.SyntaxFactory; import org.xwiki.rendering.renderer.PrintRendererFactory; import org.xwiki.rendering.renderer.printer.DefaultWikiPrinter; import org.xwiki.rendering.renderer.printer.WikiPrinter; import org.xwiki.rendering.transformation.TransformationManager; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiConstant; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.DocumentSection; import com.xpn.xwiki.content.Link; import com.xpn.xwiki.content.parsers.DocumentParser; import com.xpn.xwiki.content.parsers.LinkParser; import com.xpn.xwiki.content.parsers.RenamePageReplaceLinkHandler; import com.xpn.xwiki.content.parsers.ReplacementResultCollection; import com.xpn.xwiki.criteria.impl.RevisionCriteria; import com.xpn.xwiki.doc.rcs.XWikiRCSNodeInfo; import com.xpn.xwiki.notify.XWikiNotificationRule; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.ListProperty; import com.xpn.xwiki.objects.ObjectDiff; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.objects.classes.ListClass; import com.xpn.xwiki.objects.classes.PropertyClass; import com.xpn.xwiki.objects.classes.StaticListClass; import com.xpn.xwiki.plugin.query.XWikiCriteria; import com.xpn.xwiki.render.XWikiVelocityRenderer; import com.xpn.xwiki.store.XWikiAttachmentStoreInterface; import com.xpn.xwiki.store.XWikiStoreInterface; import com.xpn.xwiki.store.XWikiVersioningStoreInterface; import com.xpn.xwiki.util.Util; import com.xpn.xwiki.validation.XWikiValidationInterface; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.EditForm; import com.xpn.xwiki.web.ObjectAddForm; import com.xpn.xwiki.web.Utils; import com.xpn.xwiki.web.XWikiMessageTool; import com.xpn.xwiki.web.XWikiRequest; public class XWikiDocument implements DocumentModelBridge { private static final Log log = LogFactory.getLog(XWikiDocument.class); /** The default wiki name to use when one isn't specified. */ private static final String DEFAULT_WIKI_NAME = "xwiki"; /** * Regex Pattern to recognize if there's HTML code in a XWiki page. */ private static final Pattern HTML_TAG_PATTERN = Pattern.compile("</?(html|body|img|a|i|b|embed|script|form|input|textarea|object|" + "font|li|ul|ol|table|center|hr|br|p) ?([^>]*)>"); private static final String XWIKI10_SYNTAXID = "xwiki/1.0"; private String title; private String parent; private String space; private String name; private String content; private String meta; private String format; private String creator; private String author; private String contentAuthor; private String customClass; private Date contentUpdateDate; private Date updateDate; private Date creationDate; private Version version; private long id = 0; private boolean mostRecent = true; private boolean isNew = true; private String template; private String language; private String defaultLanguage; private int translation; private String database; private BaseObject tags; /** * Indicates whether the document is 'hidden', meaning that it should not be returned in public search results. * WARNING: this is a temporary hack until the new data model is designed and implemented. No code should rely on or * use this property, since it will be replaced with a generic metadata. */ private boolean hidden = false; /** * Comment on the latest modification. */ private String comment; /** * Wiki syntax supported by this document. This is used to support different syntaxes inside the same wiki. For * example a page can use the Confluence 2.0 syntax while another one uses the XWiki 1.0 syntax. In practice our * first need is to support the new rendering component. To use the old rendering implementation specify a * "xwiki/1.0" syntaxId and use a "xwiki/2.0" syntaxId for using the new rendering component. */ private String syntaxId; /** * Is latest modification a minor edit */ private boolean isMinorEdit = false; /** * Used to make sure the MetaData String is regenerated. */ private boolean isContentDirty = true; /** * Used to make sure the MetaData String is regenerated */ private boolean isMetaDataDirty = true; public static final int HAS_ATTACHMENTS = 1; public static final int HAS_OBJECTS = 2; public static final int HAS_CLASS = 4; private int elements = HAS_OBJECTS | HAS_ATTACHMENTS; /** * Separator string between database name and space name. */ public static final String DB_SPACE_SEP = ":"; /** * Separator string between space name and page name. */ public static final String SPACE_NAME_SEP = "."; // Meta Data private BaseClass xWikiClass; private String xWikiClassXML; /** * Map holding document objects grouped by classname (className -> Vector of objects). The map is not synchronized, * and uses a TreeMap implementation to preserve className ordering (consistent sorted order for output to XML, * rendering in velocity, etc.) */ private Map<String, Vector<BaseObject>> xWikiObjects = new TreeMap<String, Vector<BaseObject>>(); private List<XWikiAttachment> attachmentList; // Caching private boolean fromCache = false; private ArrayList<BaseObject> objectsToRemove = new ArrayList<BaseObject>(); // Template by default assign to a view private String defaultTemplate; private String validationScript; private Object wikiNode; // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) private SoftReference<XWikiDocumentArchive> archive; private XWikiStoreInterface store; /** * This is a copy of this XWikiDocument before any modification was made to it. It is reset to the actual values * when the document is saved in the database. This copy is used for finding out differences made to this document * (useful for example to send the correct notifications to document change listeners). */ private XWikiDocument originalDocument; private XDOM xdom; private XDOM clonedxdom; public XWikiStoreInterface getStore(XWikiContext context) { return context.getWiki().getStore(); } public XWikiAttachmentStoreInterface getAttachmentStore(XWikiContext context) { return context.getWiki().getAttachmentStore(); } public XWikiVersioningStoreInterface getVersioningStore(XWikiContext context) { return context.getWiki().getVersioningStore(); } public XWikiStoreInterface getStore() { return this.store; } public void setStore(XWikiStoreInterface store) { this.store = store; } public long getId() { if ((this.language == null) || this.language.trim().equals("")) { this.id = getFullName().hashCode(); } else { this.id = (getFullName() + ":" + this.language).hashCode(); } // if (log.isDebugEnabled()) // log.debug("ID: " + getFullName() + " " + language + ": " + id); return this.id; } public void setId(long id) { this.id = id; } /** * @return the name of the space of the document */ public String getSpace() { return this.space; } public void setSpace(String space) { this.space = space; } public String getVersion() { return getRCSVersion().toString(); } public void setVersion(String version) { if (version != null && !"".equals(version)) { this.version = new Version(version); } } public Version getRCSVersion() { if (this.version == null) { return new Version("1.1"); } return this.version; } public void setRCSVersion(Version version) { this.version = version; } public XWikiDocument() { this("Main", "WebHome"); } /** * Constructor that specifies the local document identifier: space name, document name. {@link #setDatabase(String)} * must be called afterwards to specify the wiki name. * * @param web The space this document belongs to. * @param name The name of the document. */ public XWikiDocument(String space, String name) { this(null, space, name); } /** * Constructor that specifies the full document identifier: wiki name, space name, document name. * * @param wiki The wiki this document belongs to. * @param web The space this document belongs to. * @param name The name of the document. */ public XWikiDocument(String wiki, String web, String name) { setDatabase(wiki); setSpace(web); int i1 = name.indexOf("."); if (i1 == -1) { setName(name); } else { setSpace(name.substring(0, i1)); setName(name.substring(i1 + 1)); } this.updateDate = new Date(); this.updateDate.setTime((this.updateDate.getTime() / 1000) * 1000); this.contentUpdateDate = new Date(); this.contentUpdateDate.setTime((this.contentUpdateDate.getTime() / 1000) * 1000); this.creationDate = new Date(); this.creationDate.setTime((this.creationDate.getTime() / 1000) * 1000); this.parent = ""; this.content = "\n"; this.format = ""; this.author = ""; this.language = ""; this.defaultLanguage = ""; this.attachmentList = new ArrayList<XWikiAttachment>(); this.customClass = ""; this.comment = ""; this.syntaxId = XWIKI10_SYNTAXID; // Note: As there's no notion of an Empty document we don't set the original document // field. Thus getOriginalDocument() may return null. } /** * @return the copy of this XWikiDocument instance before any modification was made to it. * @see #originalDocument */ public XWikiDocument getOriginalDocument() { return this.originalDocument; } /** * @param originalDocument the original document representing this document instance before any change was made to * it, prior to the last time it was saved * @see #originalDocument */ public void setOriginalDocument(XWikiDocument originalDocument) { this.originalDocument = originalDocument; } public XWikiDocument getParentDoc() { return new XWikiDocument(getSpace(), getParent()); } public String getParent() { return this.parent != null ? this.parent : ""; } public void setParent(String parent) { if (parent != null && !parent.equals(this.parent)) { setMetaDataDirty(true); } this.parent = parent; } public String getContent() { return this.content; } public void setContent(String content) { if (content == null) { content = ""; } if (!content.equals(this.content)) { setContentDirty(true); setWikiNode(null); } this.content = content; // invalidate parsed xdom this.xdom = null; this.clonedxdom = null; } public String getRenderedContent(XWikiContext context) throws XWikiException { String renderedContent; // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { renderedContent = context.getWiki().getRenderingEngine().renderDocument(this, context); } else { renderedContent = performSyntaxConversion(getContent(), getSyntaxId(), "xhtml/1.0"); } return renderedContent; } /** * @param text the text to render * @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0") * @param context the XWiki Context object * @return the given text rendered in the context of this document using the passed Syntax * @since 1.6M1 */ public String getRenderedContent(String text, String syntaxId, XWikiContext context) { String result; HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem. Otherwise use the new one. if (syntaxId.equalsIgnoreCase(XWIKI10_SYNTAXID)) { result = context.getWiki().getRenderingEngine().renderText(text, this, context); } else { result = performSyntaxConversion(text, getSyntaxId(), "xhtml/1.0"); } } catch (XWikiException e) { // Failed to render for some reason. This method should normally throw an exception but this // requires changing the signature of calling methods too. log.warn(e); result = ""; } finally { restoreContext(backup, context); } return result; } /** * @param text the text to render * @param context the XWiki Context object * @return the given text rendered in the context of this document * @deprecated since 1.6M1 use {@link #getRenderedContent(String, String, com.xpn.xwiki.XWikiContext)} */ @Deprecated public String getRenderedContent(String text, XWikiContext context) { return getRenderedContent(text, XWIKI10_SYNTAXID, context); } public String getEscapedContent(XWikiContext context) throws XWikiException { CharacterFilter filter = new CharacterFilter(); return filter.process(getTranslatedContent(context)); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getFullName() { StringBuffer buf = new StringBuffer(); buf.append(getSpace()); buf.append("."); buf.append(getName()); return buf.toString(); } public void setFullName(String name) { setFullName(name, null); } /** * {@inheritDoc} * * @see DocumentModelBridge#getWikiName() */ public String getWikiName() { return StringUtils.isEmpty(getDatabase()) ? DEFAULT_WIKI_NAME : getDatabase(); } public String getTitle() { return (this.title != null) ? this.title : ""; } /** * @param context the XWiki context used to get acces to the XWikiRenderingEngine object * @return the document title. If a title has not been provided, look for a section title in the document's content * and if not found return the page name. The returned title is also interpreted which means it's allowed to * use Velocity, Groovy, etc syntax within a title. */ public String getDisplayTitle(XWikiContext context) { // 1) Check if the user has provided a title String title = getTitle(); // 2) If not, then try to extract the title from the first document section title if (title.length() == 0) { title = extractTitle(); } // 3) Last if a title has been found renders it as it can contain macros, velocity code, // groovy, etc. if (title.length() > 0) { // This will not completely work for scriting code in title referencing variables // defined elsewhere. In that case it'll only work if those variables have been // parsed and put in the corresponding scripting context. This will not work for // breadcrumbs for example. title = context.getWiki().getRenderingEngine().interpretText(title, this, context); } else { // 4) No title has been found, return the page name as the title title = getName(); } return title; } /** * @return the first level 1 or level 1.1 title text in the document's content or "" if none are found * @todo this method has nothing to do in this class and should be moved elsewhere */ public String extractTitle() { try { String content = getContent(); int i1 = 0; int i2; while (true) { i2 = content.indexOf("\n", i1); String title = ""; if (i2 != -1) { title = content.substring(i1, i2).trim(); } else { title = content.substring(i1).trim(); } if ((!title.equals("")) && (title.matches("1(\\.1)?\\s+.+"))) { return title.substring(title.indexOf(" ")).trim(); } if (i2 == -1) { break; } i1 = i2 + 1; } } catch (Exception e) { } return ""; } public void setTitle(String title) { if (title != null && !title.equals(this.title)) { setContentDirty(true); } this.title = title; } public String getFormat() { return this.format != null ? this.format : ""; } public void setFormat(String format) { this.format = format; if (!format.equals(this.format)) { setMetaDataDirty(true); } } public String getAuthor() { return this.author != null ? this.author.trim() : ""; } public String getContentAuthor() { return this.contentAuthor != null ? this.contentAuthor.trim() : ""; } public void setAuthor(String author) { if (!getAuthor().equals(author)) { setMetaDataDirty(true); } this.author = author; } public void setContentAuthor(String contentAuthor) { if (!getContentAuthor().equals(contentAuthor)) { setMetaDataDirty(true); } this.contentAuthor = contentAuthor; } public String getCreator() { return this.creator != null ? this.creator.trim() : ""; } public void setCreator(String creator) { if (!getCreator().equals(creator)) { setMetaDataDirty(true); } this.creator = creator; } public Date getDate() { if (this.updateDate == null) { return new Date(); } else { return this.updateDate; } } public void setDate(Date date) { if ((date != null) && (!date.equals(this.updateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.updateDate = date; } public Date getCreationDate() { if (this.creationDate == null) { return new Date(); } else { return this.creationDate; } } public void setCreationDate(Date date) { if ((date != null) && (!date.equals(this.creationDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.creationDate = date; } public Date getContentUpdateDate() { if (this.contentUpdateDate == null) { return new Date(); } else { return this.contentUpdateDate; } } public void setContentUpdateDate(Date date) { if ((date != null) && (!date.equals(this.contentUpdateDate))) { setMetaDataDirty(true); } // Make sure we drop milliseconds for consistency with the database if (date != null) { date.setTime((date.getTime() / 1000) * 1000); } this.contentUpdateDate = date; } public String getMeta() { return this.meta; } public void setMeta(String meta) { if (meta == null) { if (this.meta != null) { setMetaDataDirty(true); } } else if (!meta.equals(this.meta)) { setMetaDataDirty(true); } this.meta = meta; } public void appendMeta(String meta) { StringBuffer buf = new StringBuffer(this.meta); buf.append(meta); buf.append("\n"); this.meta = buf.toString(); setMetaDataDirty(true); } public boolean isContentDirty() { return this.isContentDirty; } public void incrementVersion() { if (this.version == null) { this.version = new Version("1.1"); } else { if (isMinorEdit()) { this.version = this.version.next(); } else { this.version = this.version.getBranchPoint().next().newBranch(1); } } } public void setContentDirty(boolean contentDirty) { this.isContentDirty = contentDirty; } public boolean isMetaDataDirty() { return this.isMetaDataDirty; } public void setMetaDataDirty(boolean metaDataDirty) { this.isMetaDataDirty = metaDataDirty; } public String getAttachmentURL(String filename, XWikiContext context) { return getAttachmentURL(filename, "download", context); } public String getAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalAttachmentURL(String filename, String action, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, null, getDatabase(), context); return url.toString(); } public String getAttachmentURL(String filename, String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentURL(filename, getSpace(), getName(), action, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getAttachmentRevisionURL(String filename, String revision, String querystring, XWikiContext context) { URL url = context.getURLFactory().createAttachmentRevisionURL(filename, getSpace(), getName(), revision, querystring, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String params, boolean redirect, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, params, null, getDatabase(), context); if (redirect) { if (url == null) { return null; } else { return url.toString(); } } else { return context.getURLFactory().getURL(url, context); } } public String getURL(String action, boolean redirect, XWikiContext context) { return getURL(action, null, redirect, context); } public String getURL(String action, XWikiContext context) { return getURL(action, false, context); } public String getURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getURL(String action, String querystring, String anchor, XWikiContext context) { URL url = context.getURLFactory().createURL(getSpace(), getName(), action, querystring, anchor, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public String getExternalURL(String action, XWikiContext context) { URL url = context.getURLFactory() .createExternalURL(getSpace(), getName(), action, null, null, getDatabase(), context); return url.toString(); } public String getExternalURL(String action, String querystring, XWikiContext context) { URL url = context.getURLFactory().createExternalURL(getSpace(), getName(), action, querystring, null, getDatabase(), context); return url.toString(); } public String getParentURL(XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.setFullName(getParent(), context); URL url = context.getURLFactory() .createURL(doc.getSpace(), doc.getName(), "view", null, null, getDatabase(), context); return context.getURLFactory().getURL(url, context); } public XWikiDocumentArchive getDocumentArchive(XWikiContext context) throws XWikiException { loadArchive(context); return getDocumentArchive(); } /** * Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from * scripting. * * @param customClassName the name of the custom {@link com.xpn.xwiki.api.Document} class of the object to create. * @param context the XWiki context. * @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(String customClassName, XWikiContext context) { if (!((customClassName == null) || (customClassName.equals("")))) { try { return newDocument(Class.forName(customClassName), context); } catch (ClassNotFoundException e) { log.error("Failed to get java Class object from class name", e); } } return new com.xpn.xwiki.api.Document(this, context); } /** * Create a new protected {@link com.xpn.xwiki.api.Document} public API to access page information and actions from * scripting. * * @param customClass the custom {@link com.xpn.xwiki.api.Document} class the object to create. * @param context the XWiki context. * @return a wrapped version of an XWikiDocument. Prefer this function instead of new Document(XWikiDocument, * XWikiContext) */ public com.xpn.xwiki.api.Document newDocument(Class< ? > customClass, XWikiContext context) { if (customClass != null) { try { Class< ? >[] classes = new Class[] {XWikiDocument.class, XWikiContext.class}; Object[] args = new Object[] {this, context}; return (com.xpn.xwiki.api.Document) customClass.getConstructor(classes).newInstance(args); } catch (Exception e) { log.error("Failed to create a custom Document object", e); } } return new com.xpn.xwiki.api.Document(this, context); } public com.xpn.xwiki.api.Document newDocument(XWikiContext context) { String customClass = getCustomClass(); return newDocument(customClass, context); } public void loadArchive(XWikiContext context) throws XWikiException { if (this.archive == null || this.archive.get() == null) { XWikiDocumentArchive arch = getVersioningStore(context).getXWikiDocumentArchive(this, context); // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during // the request) this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public XWikiDocumentArchive getDocumentArchive() { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (this.archive == null) { return null; } else { return this.archive.get(); } } public void setDocumentArchive(XWikiDocumentArchive arch) { // We are using a SoftReference which will allow the archive to be // discarded by the Garbage collector as long as the context is closed (usually during the // request) if (arch != null) { this.archive = new SoftReference<XWikiDocumentArchive>(arch); } } public void setDocumentArchive(String sarch) throws XWikiException { XWikiDocumentArchive xda = new XWikiDocumentArchive(getId()); xda.setArchive(sarch); setDocumentArchive(xda); } public Version[] getRevisions(XWikiContext context) throws XWikiException { return getVersioningStore(context).getXWikiDocVersions(this, context); } public String[] getRecentRevisions(int nb, XWikiContext context) throws XWikiException { try { Version[] revisions = getVersioningStore(context).getXWikiDocVersions(this, context); int length = nb; // 0 means all revisions if (nb == 0) { length = revisions.length; } if (revisions.length < length) { length = revisions.length; } String[] recentrevs = new String[length]; for (int i = 1; i <= length; i++) { recentrevs[i - 1] = revisions[revisions.length - i].toString(); } return recentrevs; } catch (Exception e) { return new String[0]; } } /** * Get document versions matching criterias like author, minimum creation date, etc. * * @param criteria criteria used to match versions * @return a list of matching versions */ public List<String> getRevisions(RevisionCriteria criteria, XWikiContext context) throws XWikiException { List<String> results = new ArrayList<String>(); Version[] revisions = getRevisions(context); XWikiRCSNodeInfo nextNodeinfo = null; XWikiRCSNodeInfo nodeinfo = null; for (int i = 0; i < revisions.length; i++) { nodeinfo = nextNodeinfo; nextNodeinfo = getRevisionInfo(revisions[i].toString(), context); if (nodeinfo == null) { continue; } // Minor/Major version matching if (criteria.getIncludeMinorVersions() || !nextNodeinfo.isMinorEdit()) { // Author matching if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching Date versionDate = nodeinfo.getDate(); if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } } nodeinfo = nextNodeinfo; if (nodeinfo != null) { if (criteria.getAuthor().equals("") || criteria.getAuthor().equals(nodeinfo.getAuthor())) { // Date range matching Date versionDate = nodeinfo.getDate(); if (versionDate.after(criteria.getMinDate()) && versionDate.before(criteria.getMaxDate())) { results.add(nodeinfo.getVersion().toString()); } } } return criteria.getRange().subList(results); } public XWikiRCSNodeInfo getRevisionInfo(String version, XWikiContext context) throws XWikiException { return getDocumentArchive(context).getNode(new Version(version)); } /** * @return Is this version the most recent one. False if and only if there are newer versions of this document in * the database. */ public boolean isMostRecent() { return this.mostRecent; } /** * must not be used unless in store system. * * @param mostRecent - mark document as most recent. */ public void setMostRecent(boolean mostRecent) { this.mostRecent = mostRecent; } public BaseClass getxWikiClass() { if (this.xWikiClass == null) { this.xWikiClass = new BaseClass(); this.xWikiClass.setName(getFullName()); } return this.xWikiClass; } public void setxWikiClass(BaseClass xWikiClass) { this.xWikiClass = xWikiClass; } public Map<String, Vector<BaseObject>> getxWikiObjects() { return this.xWikiObjects; } public void setxWikiObjects(Map<String, Vector<BaseObject>> xWikiObjects) { this.xWikiObjects = xWikiObjects; } public BaseObject getxWikiObject() { return getObject(getFullName()); } public List<BaseClass> getxWikiClasses(XWikiContext context) { List<BaseClass> list = new ArrayList<BaseClass>(); // xWikiObjects is a TreeMap, with elements sorted by className for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = null; Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { bclass = obj.getxWikiClass(context); if (bclass != null) { break; } } } if (bclass != null) { list.add(bclass); } } return list; } public int createNewObject(String classname, XWikiContext context) throws XWikiException { BaseObject object = BaseClass.newCustomClassInstance(classname, context); object.setWiki(getDatabase()); object.setName(getFullName()); object.setClassName(classname); Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } objects.add(object); int nb = objects.size() - 1; object.setNumber(nb); setContentDirty(true); return nb; } public int getObjectNumbers(String classname) { try { return getxWikiObjects().get(classname).size(); } catch (Exception e) { return 0; } } public Vector<BaseObject> getObjects(String classname) { if (classname == null) { return new Vector<BaseObject>(); } if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname); } public void setObjects(String classname, Vector<BaseObject> objects) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } getxWikiObjects().put(classname, objects); } public BaseObject getObject(String classname) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } Vector<BaseObject> objects = getxWikiObjects().get(classname); if (objects == null) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { return obj; } } return null; } public BaseObject getObject(String classname, int nb) { try { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } return getxWikiObjects().get(classname).get(nb); } catch (Exception e) { return null; } } public BaseObject getObject(String classname, String key, String value) { return getObject(classname, key, value, false); } public BaseObject getObject(String classname, String key, String value, boolean failover) { if (classname.indexOf(".") == -1) { classname = "XWiki." + classname; } try { if (value == null) { if (failover) { return getObject(classname); } else { return null; } } Vector<BaseObject> objects = getxWikiObjects().get(classname); if ((objects == null) || (objects.size() == 0)) { return null; } for (int i = 0; i < objects.size(); i++) { BaseObject obj = objects.get(i); if (obj != null) { if (value.equals(obj.getStringValue(key))) { return obj; } } } if (failover) { return getObject(classname); } else { return null; } } catch (Exception e) { if (failover) { return getObject(classname); } e.printStackTrace(); return null; } } public void addObject(String classname, BaseObject object) { if (object != null) { object.setWiki(getDatabase()); object.setName(getFullName()); } Vector<BaseObject> vobj = getObjects(classname); if (vobj == null) { setObject(classname, 0, object); } else { setObject(classname, vobj.size(), object); } setContentDirty(true); } public void setObject(String classname, int nb, BaseObject object) { if (object != null) { object.setWiki(getDatabase()); object.setName(getFullName()); } Vector<BaseObject> objects = getObjects(classname); if (objects == null) { objects = new Vector<BaseObject>(); setObjects(classname, objects); } if (nb >= objects.size()) { objects.setSize(nb + 1); } objects.set(nb, object); object.setNumber(nb); setContentDirty(true); } /** * @return true if the document is a new one (ie it has never been saved) or false otherwise */ public boolean isNew() { return this.isNew; } public void setNew(boolean aNew) { this.isNew = aNew; } public void mergexWikiClass(XWikiDocument templatedoc) { BaseClass bclass = getxWikiClass(); BaseClass tbclass = templatedoc.getxWikiClass(); if (tbclass != null) { if (bclass == null) { setxWikiClass((BaseClass) tbclass.clone()); } else { getxWikiClass().merge((BaseClass) tbclass.clone()); } } setContentDirty(true); } public void mergexWikiObjects(XWikiDocument templatedoc) { // TODO: look for each object if it already exist and add it if it doesn't for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> myObjects = getxWikiObjects().get(name); if (myObjects == null) { myObjects = new Vector<BaseObject>(); } for (BaseObject otherObject : templatedoc.getxWikiObjects().get(name)) { if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); // BaseObject.clone copies the GUID, so randomize it for the copied object. myObject.setGuid(UUID.randomUUID().toString()); myObjects.add(myObject); myObject.setNumber(myObjects.size() - 1); } } getxWikiObjects().put(name, myObjects); } setContentDirty(true); } public void clonexWikiObjects(XWikiDocument templatedoc) { for (String name : templatedoc.getxWikiObjects().keySet()) { Vector<BaseObject> tobjects = templatedoc.getObjects(name); Vector<BaseObject> objects = new Vector<BaseObject>(); objects.setSize(tobjects.size()); for (int i = 0; i < tobjects.size(); i++) { BaseObject otherObject = tobjects.get(i); if (otherObject != null) { BaseObject myObject = (BaseObject) otherObject.clone(); objects.set(i, myObject); } } getxWikiObjects().put(name, objects); } } public String getTemplate() { return StringUtils.defaultString(this.template); } public void setTemplate(String template) { this.template = template; setMetaDataDirty(true); } public String displayPrettyName(String fieldname, XWikiContext context) { return displayPrettyName(fieldname, false, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayPrettyName(fieldname, showMandatory, before, object, context); } catch (Exception e) { return ""; } } public String displayPrettyName(String fieldname, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, false, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, BaseObject obj, XWikiContext context) { return displayPrettyName(fieldname, showMandatory, true, obj, context); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String dprettyName = ""; if (showMandatory) { dprettyName = context.getWiki().addMandatory(context); } if (before) { return dprettyName + pclass.getPrettyName(context); } else { return pclass.getPrettyName(context) + dprettyName; } } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return displayTooltip(fieldname, object, context); } catch (Exception e) { return ""; } } public String displayTooltip(String fieldname, BaseObject obj, XWikiContext context) { try { PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String tooltip = pclass.getTooltip(context); if ((tooltip != null) && (!tooltip.trim().equals(""))) { String img = "<img src=\"" + context.getWiki().getSkinFile("info.gif", context) + "\" class=\"tooltip_image\" align=\"middle\" />"; return context.getWiki().addTooltip(img, tooltip, context); } else { return ""; } } catch (Exception e) { return ""; } } public String display(String fieldname, String type, BaseObject obj, XWikiContext context) { return display(fieldname, type, "", obj, context); } public String display(String fieldname, String type, String pref, BaseObject obj, XWikiContext context) { HashMap<String, Object> backup = new HashMap<String, Object>(); try { backupContext(backup, context); setAsContextDoc(context); type = type.toLowerCase(); StringBuffer result = new StringBuffer(); PropertyClass pclass = (PropertyClass) obj.getxWikiClass(context).get(fieldname); String prefix = pref + obj.getxWikiClass(context).getName() + "_" + obj.getNumber() + "_"; if (pclass.isCustomDisplayed(context)) { pclass.displayCustom(result, fieldname, prefix, type, obj, context); } else if (type.equals("view")) { pclass.displayView(result, fieldname, prefix, obj, context); } else if (type.equals("rendered")) { String fcontent = pclass.displayView(fieldname, prefix, obj, context); // This mode is deprecated for the new rendering and should also be removed for the old rendering // since the way to implement this now is to choose the type of rendering to do in the class itself. // Thus for the new renderinfg we simply make this mode work like the "view" mode. if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append(getRenderedContent(fcontent, getSyntaxId(), context)); } else { result.append(fcontent); } } else if (type.equals("edit")) { context.addDisplayedField(fieldname); // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append("{pre}"); } pclass.displayEdit(result, fieldname, prefix, obj, context); if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append("{/pre}"); } } else if (type.equals("hidden")) { // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append("{pre}"); } pclass.displayHidden(result, fieldname, prefix, obj, context); if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append("{/pre}"); } } else if (type.equals("search")) { // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the // escaping. For example for a textarea check the TextAreaClass class. if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append("{pre}"); } prefix = obj.getxWikiClass(context).getName() + "_"; pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context); if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { result.append("{/pre}"); } } else { pclass.displayView(result, fieldname, prefix, obj, context); } return result.toString(); } catch (Exception ex) { // TODO: It would better to check if the field exists rather than catching an exception // raised by a NPE as this is currently the case here... log.warn("Failed to display field [" + fieldname + "] in [" + type + "] mode for Object [" + (obj == null ? "NULL" : obj.getName()) + "]"); return ""; } finally { restoreContext(backup, context); } } public String display(String fieldname, BaseObject obj, XWikiContext context) { String type = null; try { type = (String) context.get("display"); } catch (Exception e) { } if (type == null) { type = "view"; } return display(fieldname, type, obj, context); } public String display(String fieldname, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } return display(fieldname, object, context); } catch (Exception e) { return ""; } } public String display(String fieldname, String mode, XWikiContext context) { return display(fieldname, mode, "", context); } public String display(String fieldname, String mode, String prefix, XWikiContext context) { try { BaseObject object = getxWikiObject(); if (object == null) { object = getFirstObject(fieldname, context); } if (object == null) { return ""; } else { return display(fieldname, mode, prefix, object, context); } } catch (Exception e) { return ""; } } public String displayForm(String className, String header, String format, XWikiContext context) { return displayForm(className, header, format, true, context); } public String displayForm(String className, String header, String format, boolean linebreak, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (format.endsWith("\\n")) { linebreak = true; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); if (bclass.getPropertyList().size() == 0) { return ""; } StringBuffer result = new StringBuffer(); VelocityContext vcontext = new VelocityContext(); for (String propertyName : bclass.getPropertyList()) { PropertyClass pclass = (PropertyClass) bclass.getField(propertyName); vcontext.put(pclass.getName(), pclass.getPrettyName()); } result.append(XWikiVelocityRenderer.evaluate(header, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } // display each line for (int i = 0; i < objects.size(); i++) { vcontext.put("id", new Integer(i + 1)); BaseObject object = objects.get(i); if (object != null) { for (String name : bclass.getPropertyList()) { vcontext.put(name, display(name, object, context)); } result .append(XWikiVelocityRenderer.evaluate(format, context.getDoc().getFullName(), vcontext, context)); if (linebreak) { result.append("\n"); } } } return result.toString(); } public String displayForm(String className, XWikiContext context) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return ""; } BaseObject firstobject = null; Iterator<BaseObject> foit = objects.iterator(); while ((firstobject == null) && foit.hasNext()) { firstobject = foit.next(); } if (firstobject == null) { return ""; } BaseClass bclass = firstobject.getxWikiClass(context); if (bclass.getPropertyList().size() == 0) { return ""; } StringBuffer result = new StringBuffer(); result.append("{table}\n"); boolean first = true; for (String propertyName : bclass.getPropertyList()) { if (first == true) { first = false; } else { result.append("|"); } PropertyClass pclass = (PropertyClass) bclass.getField(propertyName); result.append(pclass.getPrettyName()); } result.append("\n"); for (int i = 0; i < objects.size(); i++) { BaseObject object = objects.get(i); if (object != null) { first = true; for (String propertyName : bclass.getPropertyList()) { if (first == true) { first = false; } else { result.append("|"); } String data = display(propertyName, object, context); data = data.trim(); data = data.replaceAll("\n", " "); if (data.length() == 0) { result.append("&nbsp;"); } else { result.append(data); } } result.append("\n"); } } result.append("{table}\n"); return result.toString(); } public boolean isFromCache() { return this.fromCache; } public void setFromCache(boolean fromCache) { this.fromCache = fromCache; } public void readDocMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String defaultLanguage = eform.getDefaultLanguage(); if (defaultLanguage != null) { setDefaultLanguage(defaultLanguage); } String defaultTemplate = eform.getDefaultTemplate(); if (defaultTemplate != null) { setDefaultTemplate(defaultTemplate); } String creator = eform.getCreator(); if ((creator != null) && (!creator.equals(getCreator()))) { if ((getCreator().equals(context.getUser())) || (context.getWiki().getRightService().hasAdminRights(context))) { setCreator(creator); } } String parent = eform.getParent(); if (parent != null) { setParent(parent); } // Read the comment from the form String comment = eform.getComment(); if (comment != null) { setComment(comment); } // Read the minor edit checkbox from the form setMinorEdit(eform.isMinorEdit()); String tags = eform.getTags(); if (tags != null) { setTags(tags, context); } // Set the Syntax id if defined String syntaxId = eform.getSyntaxId(); if (syntaxId != null) { setSyntaxId(syntaxId); } } /** * add tags to the document. */ public void setTags(String tags, XWikiContext context) throws XWikiException { loadTags(context); StaticListClass tagProp = (StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS); tagProp.fromString(tags); this.tags.safeput(XWikiConstant.TAG_CLASS_PROP_TAGS, tagProp.fromString(tags)); setMetaDataDirty(true); } public String getTags(XWikiContext context) { ListProperty prop = (ListProperty) getTagProperty(context); if (prop != null) { return prop.getTextValue(); } return null; } public List<String> getTagsList(XWikiContext context) { List<String> tagList = null; BaseProperty prop = getTagProperty(context); if (prop != null) { tagList = (List<String>) prop.getValue(); } return tagList; } private BaseProperty getTagProperty(XWikiContext context) { loadTags(context); return ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)); } private void loadTags(XWikiContext context) { if (this.tags == null) { this.tags = getObject(XWikiConstant.TAG_CLASS, true, context); } } public List getTagsPossibleValues(XWikiContext context) { loadTags(context); String possibleValues = ((StaticListClass) this.tags.getxWikiClass(context).getField(XWikiConstant.TAG_CLASS_PROP_TAGS)) .getValues(); return ListClass.getListFromString(possibleValues); // ((BaseProperty) this.tags.safeget(XWikiConstant.TAG_CLASS_PROP_TAGS)).toString(); } public void readTranslationMetaFromForm(EditForm eform, XWikiContext context) throws XWikiException { String content = eform.getContent(); if (content != null) { // Cleanup in case we use HTMLAREA // content = context.getUtil().substitute("s/<br class=\\\"htmlarea\\\"\\/>/\\r\\n/g", // content); content = context.getUtil().substitute("s/<br class=\"htmlarea\" \\/>/\r\n/g", content); setContent(content); } String title = eform.getTitle(); if (title != null) { setTitle(title); } } public void readObjectsFromForm(EditForm eform, XWikiContext context) throws XWikiException { for (String name : getxWikiObjects().keySet()) { Vector<BaseObject> oldObjects = getObjects(name); Vector<BaseObject> newObjects = new Vector<BaseObject>(); newObjects.setSize(oldObjects.size()); for (int i = 0; i < oldObjects.size(); i++) { BaseObject oldobject = oldObjects.get(i); if (oldobject != null) { BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(eform.getObject(baseclass.getName() + "_" + i), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setGuid(oldobject.getGuid()); newobject.setName(getFullName()); newObjects.set(newobject.getNumber(), newobject); } } getxWikiObjects().put(name, newObjects); } setContentDirty(true); } public void readFromForm(EditForm eform, XWikiContext context) throws XWikiException { readDocMetaFromForm(eform, context); readTranslationMetaFromForm(eform, context); readObjectsFromForm(eform, context); } public void readFromTemplate(EditForm eform, XWikiContext context) throws XWikiException { String template = eform.getTemplate(); readFromTemplate(template, context); } public void readFromTemplate(String template, XWikiContext context) throws XWikiException { if ((template != null) && (!template.equals(""))) { String content = getContent(); if ((!content.equals("\n")) && (!content.equals("")) && !isNew()) { Object[] args = {getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY, "Cannot add a template to document {0} because it already has content", null, args); } else { if (template.indexOf('.') == -1) { template = getSpace() + "." + template; } XWiki xwiki = context.getWiki(); XWikiDocument templatedoc = xwiki.getDocument(template, context); if (templatedoc.isNew()) { Object[] args = {template, getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_APP_TEMPLATE_DOES_NOT_EXIST, "Template document {0} does not exist when adding to document {1}", null, args); } else { setTemplate(template); setContent(templatedoc.getContent()); if ((getParent() == null) || (getParent().equals(""))) { String tparent = templatedoc.getParent(); if (tparent != null) { setParent(tparent); } } if (isNew()) { // We might have received the object from the cache // and the template objects might have been copied already // we need to remove them setxWikiObjects(new TreeMap<String, Vector<BaseObject>>()); } // Merge the external objects // Currently the choice is not to merge the base class and object because it is // not // the prefered way of using external classes and objects. mergexWikiObjects(templatedoc); } } } setContentDirty(true); } public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event, XWikiContext context) { // Do nothing for the moment.. // A usefull thing here would be to look at any instances of a Notification Object // with email addresses and send an email to warn that the document has been modified.. } /** * Use the document passsed as parameter as the new identity for the current document. * * @param document the document containing the new identity * @throws XWikiException in case of error */ private void clone(XWikiDocument document) throws XWikiException { setDatabase(document.getDatabase()); setRCSVersion(document.getRCSVersion()); setDocumentArchive(document.getDocumentArchive()); setAuthor(document.getAuthor()); setContentAuthor(document.getContentAuthor()); setContent(document.getContent()); setContentDirty(document.isContentDirty()); setCreationDate(document.getCreationDate()); setDate(document.getDate()); setCustomClass(document.getCustomClass()); setContentUpdateDate(document.getContentUpdateDate()); setTitle(document.getTitle()); setFormat(document.getFormat()); setFromCache(document.isFromCache()); setElements(document.getElements()); setId(document.getId()); setMeta(document.getMeta()); setMetaDataDirty(document.isMetaDataDirty()); setMostRecent(document.isMostRecent()); setName(document.getName()); setNew(document.isNew()); setStore(document.getStore()); setTemplate(document.getTemplate()); setSpace(document.getSpace()); setParent(document.getParent()); setCreator(document.getCreator()); setDefaultLanguage(document.getDefaultLanguage()); setDefaultTemplate(document.getDefaultTemplate()); setValidationScript(document.getValidationScript()); setLanguage(document.getLanguage()); setTranslation(document.getTranslation()); setxWikiClass((BaseClass) document.getxWikiClass().clone()); setxWikiClassXML(document.getxWikiClassXML()); setComment(document.getComment()); setMinorEdit(document.isMinorEdit()); setSyntaxId(document.getSyntaxId()); setHidden(document.isHidden()); clonexWikiObjects(document); copyAttachments(document); this.elements = document.elements; this.originalDocument = document.originalDocument; } @Override public Object clone() { XWikiDocument doc = null; try { doc = getClass().newInstance(); doc.setDatabase(getDatabase()); // use version field instead of getRCSVersion because it returns "1.1" if version==null. doc.version = this.version; doc.setDocumentArchive(getDocumentArchive()); doc.setAuthor(getAuthor()); doc.setContentAuthor(getContentAuthor()); doc.setContent(getContent()); doc.setContentDirty(isContentDirty()); doc.setCreationDate(getCreationDate()); doc.setDate(getDate()); doc.setCustomClass(getCustomClass()); doc.setContentUpdateDate(getContentUpdateDate()); doc.setTitle(getTitle()); doc.setFormat(getFormat()); doc.setFromCache(isFromCache()); doc.setElements(getElements()); doc.setId(getId()); doc.setMeta(getMeta()); doc.setMetaDataDirty(isMetaDataDirty()); doc.setMostRecent(isMostRecent()); doc.setName(getName()); doc.setNew(isNew()); doc.setStore(getStore()); doc.setTemplate(getTemplate()); doc.setSpace(getSpace()); doc.setParent(getParent()); doc.setCreator(getCreator()); doc.setDefaultLanguage(getDefaultLanguage()); doc.setDefaultTemplate(getDefaultTemplate()); doc.setValidationScript(getValidationScript()); doc.setLanguage(getLanguage()); doc.setTranslation(getTranslation()); doc.setxWikiClass((BaseClass) getxWikiClass().clone()); doc.setxWikiClassXML(getxWikiClassXML()); doc.setComment(getComment()); doc.setMinorEdit(isMinorEdit()); doc.setSyntaxId(getSyntaxId()); doc.setHidden(isHidden()); doc.clonexWikiObjects(this); doc.copyAttachments(this); doc.elements = this.elements; doc.originalDocument = this.originalDocument; } catch (Exception e) { // This should not happen log.error("Exception while doc.clone", e); } return doc; } public void copyAttachments(XWikiDocument xWikiSourceDocument) { getAttachmentList().clear(); Iterator<XWikiAttachment> attit = xWikiSourceDocument.getAttachmentList().iterator(); while (attit.hasNext()) { XWikiAttachment attachment = attit.next(); XWikiAttachment newattachment = (XWikiAttachment) attachment.clone(); newattachment.setDoc(this); if (newattachment.getAttachment_content() != null) { newattachment.getAttachment_content().setContentDirty(true); } getAttachmentList().add(newattachment); } setContentDirty(true); } public void loadAttachments(XWikiContext context) throws XWikiException { for (XWikiAttachment attachment : getAttachmentList()) { attachment.loadContent(context); attachment.loadArchive(context); } } @Override public boolean equals(Object object) { XWikiDocument doc = (XWikiDocument) object; if (!getName().equals(doc.getName())) { return false; } if (!getSpace().equals(doc.getSpace())) { return false; } if (!getAuthor().equals(doc.getAuthor())) { return false; } if (!getContentAuthor().equals(doc.getContentAuthor())) { return false; } if (!getParent().equals(doc.getParent())) { return false; } if (!getCreator().equals(doc.getCreator())) { return false; } if (!getDefaultLanguage().equals(doc.getDefaultLanguage())) { return false; } if (!getLanguage().equals(doc.getLanguage())) { return false; } if (getTranslation() != doc.getTranslation()) { return false; } if (getDate().getTime() != doc.getDate().getTime()) { return false; } if (getContentUpdateDate().getTime() != doc.getContentUpdateDate().getTime()) { return false; } if (getCreationDate().getTime() != doc.getCreationDate().getTime()) { return false; } if (!getFormat().equals(doc.getFormat())) { return false; } if (!getTitle().equals(doc.getTitle())) { return false; } if (!getContent().equals(doc.getContent())) { return false; } if (!getVersion().equals(doc.getVersion())) { return false; } if (!getTemplate().equals(doc.getTemplate())) { return false; } if (!getDefaultTemplate().equals(doc.getDefaultTemplate())) { return false; } if (!getValidationScript().equals(doc.getValidationScript())) { return false; } if (!getComment().equals(doc.getComment())) { return false; } if (isMinorEdit() != doc.isMinorEdit()) { return false; } if (!getSyntaxId().equals(doc.getSyntaxId())) { return false; } if (isHidden() != doc.isHidden()) { return false; } if (!getxWikiClass().equals(doc.getxWikiClass())) { return false; } Set<String> myObjectClassnames = getxWikiObjects().keySet(); Set<String> otherObjectClassnames = doc.getxWikiObjects().keySet(); if (!myObjectClassnames.equals(otherObjectClassnames)) { return false; } for (String name : myObjectClassnames) { Vector<BaseObject> myObjects = getObjects(name); Vector<BaseObject> otherObjects = doc.getObjects(name); if (myObjects.size() != otherObjects.size()) { return false; } for (int i = 0; i < myObjects.size(); i++) { if ((myObjects.get(i) == null) && (otherObjects.get(i) != null)) { return false; } if (!myObjects.get(i).equals(otherObjects.get(i))) { return false; } } } // We consider that 2 documents are still equal even when they have different original // documents (see getOriginalDocument() for more details as to what is an original // document). return true; } public String toXML(Document doc, XWikiContext context) { OutputFormat outputFormat = new OutputFormat("", true); if ((context == null) || (context.getWiki() == null)) { outputFormat.setEncoding("UTF-8"); } else { outputFormat.setEncoding(context.getWiki().getEncoding()); } StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String getXMLContent(XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(context); Document doc = tdoc.toXMLDocument(true, true, false, false, context); return toXML(doc, context); } public String toXML(XWikiContext context) throws XWikiException { Document doc = toXMLDocument(context); return toXML(doc, context); } public String toFullXML(XWikiContext context) throws XWikiException { return toXML(true, false, true, true, context); } public void addToZip(ZipOutputStream zos, boolean withVersions, XWikiContext context) throws IOException { try { String zipname = getSpace() + "/" + getName(); String language = getLanguage(); if ((language != null) && (!language.equals(""))) { zipname += "." + language; } ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); zos.write(toXML(true, false, true, withVersions, context).getBytes()); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } public void addToZip(ZipOutputStream zos, XWikiContext context) throws IOException { addToZip(zos, true, context); } public String toXML(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = toXMLDocument(bWithObjects, bWithRendering, bWithAttachmentContent, bWithVersions, context); return toXML(doc, context); } public Document toXMLDocument(XWikiContext context) throws XWikiException { return toXMLDocument(true, false, false, false, context); } public Document toXMLDocument(boolean bWithObjects, boolean bWithRendering, boolean bWithAttachmentContent, boolean bWithVersions, XWikiContext context) throws XWikiException { Document doc = new DOMDocument(); Element docel = new DOMElement("xwikidoc"); doc.setRootElement(docel); Element el = new DOMElement("web"); el.addText(getSpace()); docel.add(el); el = new DOMElement("name"); el.addText(getName()); docel.add(el); el = new DOMElement("language"); el.addText(getLanguage()); docel.add(el); el = new DOMElement("defaultLanguage"); el.addText(getDefaultLanguage()); docel.add(el); el = new DOMElement("translation"); el.addText("" + getTranslation()); docel.add(el); el = new DOMElement("parent"); el.addText(getParent()); docel.add(el); el = new DOMElement("creator"); el.addText(getCreator()); docel.add(el); el = new DOMElement("author"); el.addText(getAuthor()); docel.add(el); el = new DOMElement("customClass"); el.addText(getCustomClass()); docel.add(el); el = new DOMElement("contentAuthor"); el.addText(getContentAuthor()); docel.add(el); long d = getCreationDate().getTime(); el = new DOMElement("creationDate"); el.addText("" + d); docel.add(el); d = getDate().getTime(); el = new DOMElement("date"); el.addText("" + d); docel.add(el); d = getContentUpdateDate().getTime(); el = new DOMElement("contentUpdateDate"); el.addText("" + d); docel.add(el); el = new DOMElement("version"); el.addText(getVersion()); docel.add(el); el = new DOMElement("title"); el.addText(getTitle()); docel.add(el); el = new DOMElement("template"); el.addText(getTemplate()); docel.add(el); el = new DOMElement("defaultTemplate"); el.addText(getDefaultTemplate()); docel.add(el); el = new DOMElement("validationScript"); el.addText(getValidationScript()); docel.add(el); el = new DOMElement("comment"); el.addText(getComment()); docel.add(el); el = new DOMElement("minorEdit"); el.addText(String.valueOf(isMinorEdit())); docel.add(el); el = new DOMElement("syntaxId"); el.addText(getSyntaxId()); docel.add(el); el = new DOMElement("hidden"); el.addText(String.valueOf(isHidden())); docel.add(el); for (XWikiAttachment attach : getAttachmentList()) { docel.add(attach.toXML(bWithAttachmentContent, bWithVersions, context)); } if (bWithObjects) { // Add Class BaseClass bclass = getxWikiClass(); if (bclass.getFieldList().size() > 0) { // If the class has fields, add class definition and field information to XML docel.add(bclass.toXML(null)); } // Add Objects (THEIR ORDER IS MOLDED IN STONE!) for (Vector<BaseObject> objects : getxWikiObjects().values()) { for (BaseObject obj : objects) { if (obj != null) { BaseClass objclass = null; if (StringUtils.equals(getFullName(), obj.getClassName())) { objclass = bclass; } else { objclass = obj.getxWikiClass(context); } docel.add(obj.toXML(objclass)); } } } } // Add Content el = new DOMElement("content"); // Filter filter = new CharacterFilter(); // String newcontent = filter.process(getContent()); // String newcontent = encodedXMLStringAsUTF8(getContent()); String newcontent = this.content; el.addText(newcontent); docel.add(el); if (bWithRendering) { el = new DOMElement("renderedcontent"); try { el.addText(getRenderedContent(context)); } catch (XWikiException e) { el.addText("Exception with rendering content: " + e.getFullMessage()); } docel.add(el); } if (bWithVersions) { el = new DOMElement("versions"); try { el.addText(getDocumentArchive(context).getArchive(context)); docel.add(el); } catch (XWikiException e) { log.error("Document [" + this.getFullName() + "] has malformed history"); } } return doc; } protected String encodedXMLStringAsUTF8(String xmlString) { if (xmlString == null) { return ""; } int length = xmlString.length(); char character; StringBuffer result = new StringBuffer(); for (int i = 0; i < length; i++) { character = xmlString.charAt(i); switch (character) { case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '\n': result.append("\n"); break; case '\r': result.append("\r"); break; case '\t': result.append("\t"); break; default: if (character < 0x20) { } else if (character > 0x7F) { result.append("& result.append(Integer.toHexString(character).toUpperCase()); result.append(";"); } else { result.append(character); } break; } } return result.toString(); } protected String getElement(Element docel, String name) { Element el = docel.element(name); if (el == null) { return ""; } else { return el.getText(); } } public void fromXML(String xml) throws XWikiException { fromXML(xml, false); } public void fromXML(InputStream is) throws XWikiException { fromXML(is, false); } public void fromXML(String xml, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { StringReader in = new StringReader(xml); domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(InputStream in, boolean withArchive) throws XWikiException { SAXReader reader = new SAXReader(); Document domdoc; try { domdoc = reader.read(in); } catch (DocumentException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_DOC_XML_PARSING, "Error parsing xml", e, null); } fromXML(domdoc, withArchive); } public void fromXML(Document domdoc, boolean withArchive) throws XWikiException { Element docel = domdoc.getRootElement(); setName(getElement(docel, "name")); setSpace(getElement(docel, "web")); setParent(getElement(docel, "parent")); setCreator(getElement(docel, "creator")); setAuthor(getElement(docel, "author")); setCustomClass(getElement(docel, "customClass")); setContentAuthor(getElement(docel, "contentAuthor")); if (docel.element("version") != null) { setVersion(getElement(docel, "version")); } setContent(getElement(docel, "content")); setLanguage(getElement(docel, "language")); setDefaultLanguage(getElement(docel, "defaultLanguage")); setTitle(getElement(docel, "title")); setDefaultTemplate(getElement(docel, "defaultTemplate")); setValidationScript(getElement(docel, "validationScript")); setComment(getElement(docel, "comment")); String minorEdit = getElement(docel, "minorEdit"); setMinorEdit(Boolean.valueOf(minorEdit).booleanValue()); String hidden = getElement(docel, "hidden"); setHidden(Boolean.valueOf(hidden).booleanValue()); String strans = getElement(docel, "translation"); if ((strans == null) || strans.equals("")) { setTranslation(0); } else { setTranslation(Integer.parseInt(strans)); } String archive = getElement(docel, "versions"); if (withArchive && archive != null && archive.length() > 0) { setDocumentArchive(archive); } String sdate = getElement(docel, "date"); if (!sdate.equals("")) { Date date = new Date(Long.parseLong(sdate)); setDate(date); } String contentUpdateDateString = getElement(docel, "contentUpdateDate"); if (!StringUtils.isEmpty(contentUpdateDateString)) { Date contentUpdateDate = new Date(Long.parseLong(contentUpdateDateString)); setContentUpdateDate(contentUpdateDate); } String scdate = getElement(docel, "creationDate"); if (!scdate.equals("")) { Date cdate = new Date(Long.parseLong(scdate)); setCreationDate(cdate); } String syntaxId = getElement(docel, "syntaxId"); if ((syntaxId == null) || (syntaxId.length() == 0)) { setSyntaxId(XWIKI10_SYNTAXID); } else { setSyntaxId(syntaxId); } List atels = docel.elements("attachment"); for (int i = 0; i < atels.size(); i++) { Element atel = (Element) atels.get(i); XWikiAttachment attach = new XWikiAttachment(); attach.setDoc(this); attach.fromXML(atel); getAttachmentList().add(attach); } Element cel = docel.element("class"); BaseClass bclass = new BaseClass(); if (cel != null) { bclass.fromXML(cel); setxWikiClass(bclass); } List objels = docel.elements("object"); for (int i = 0; i < objels.size(); i++) { Element objel = (Element) objels.get(i); BaseObject bobject = new BaseObject(); bobject.fromXML(objel); setObject(bobject.getClassName(), bobject.getNumber(), bobject); } // We have been reading from XML so the document does not need a new version when saved setMetaDataDirty(false); setContentDirty(false); // Note: We don't set the original document as that is not stored in the XML, and it doesn't make much sense to // have an original document for a de-serialized object. } /** * Check if provided xml document is a wiki document. * * @param domdoc the xml document. * @return true if provided xml document is a wiki document. */ public static boolean containsXMLWikiDocument(Document domdoc) { return domdoc.getRootElement().getName().equals("xwikidoc"); } public void setAttachmentList(List<XWikiAttachment> list) { this.attachmentList = list; } public List<XWikiAttachment> getAttachmentList() { return this.attachmentList; } public void saveAllAttachments(XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), context); } } public void saveAllAttachments(boolean updateParent, boolean transaction, XWikiContext context) throws XWikiException { for (int i = 0; i < this.attachmentList.size(); i++) { saveAttachmentContent(this.attachmentList.get(i), updateParent, transaction, context); } } public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().saveAttachmentsContent(attachments, this, true, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void saveAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { saveAttachmentContent(attachment, true, true, context); } protected void saveAttachmentContent(XWikiAttachment attachment, boolean bParentUpdate, boolean bTransaction, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } // We need to make sure there is a version upgrade setMetaDataDirty(true); context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, bParentUpdate, context, bTransaction); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } finally { if (database != null) { context.setDatabase(database); } } } public void loadAttachmentContent(XWikiAttachment attachment, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } context.getWiki().getAttachmentStore().loadAttachmentContent(attachment, context, true); } finally { if (database != null) { context.setDatabase(database); } } } public void deleteAttachment(XWikiAttachment attachment, XWikiContext context) throws XWikiException { deleteAttachment(attachment, true, context); } public void deleteAttachment(XWikiAttachment attachment, boolean toRecycleBin, XWikiContext context) throws XWikiException { String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } try { // We need to make sure there is a version upgrade setMetaDataDirty(true); if (toRecycleBin && context.getWiki().hasAttachmentRecycleBin(context)) { context.getWiki().getAttachmentRecycleBinStore().saveToRecycleBin(attachment, context.getUser(), new Date(), context, true); } context.getWiki().getAttachmentStore().deleteXWikiAttachment(attachment, context, true); } catch (java.lang.OutOfMemoryError e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_JAVA_HEAP_SPACE, "Out Of Memory Exception"); } } finally { if (database != null) { context.setDatabase(database); } } } /** * @deprecated use {@link #getBackLinkedPages(XWikiContext)} instead */ @Deprecated public List<String> getBacklinks(XWikiContext context) throws XWikiException { return getBackLinkedPages(context); } /** * Get the wiki pages pointing to this page. * <p> * Theses links are stored to the database when documents are saved. You can use "backlinks" in XWikiPreferences or * "xwiki.backlinks" in xwiki.cfg file to enable links storage in the database. * * @param context the XWiki context. * @return the found wiki pages names. * @throws XWikiException error when getting pages names from database. */ public List<String> getBackLinkedPages(XWikiContext context) throws XWikiException { return getStore(context).loadBacklinks(getFullName(), context, true); } /** * @deprecated use {@link #getWikiLinkedPages(XWikiContext)} instead */ @Deprecated public List<XWikiLink> getLinks(XWikiContext context) throws XWikiException { return getWikiLinkedPages(context); } /** * <ul> * <li>1.0 content: get the links associated to document from database. This is stored when the document is saved. * You can use "backlinks" in XWikiPreferences or "xwiki.backlinks" in xwiki.cfg file to enable links storage in the * database.</li> * <li>Other content: call {@link #getLinkedPages(XWikiContext)} and generate the List</li>. * </ul> * * @param context the XWiki context * @return the found wiki links. * @throws XWikiException error when getting links from database when 1.0 content. */ public List<XWikiLink> getWikiLinkedPages(XWikiContext context) throws XWikiException { List<XWikiLink> links; if (getSyntaxId().equals(XWIKI10_SYNTAXID)) { links = getStore(context).loadLinks(getId(), context, true); } else { List<String> linkedPages = getLinkedPages(context); links = new ArrayList<XWikiLink>(linkedPages.size()); for (String linkedPage : linkedPages) { XWikiLink wikiLink = new XWikiLink(); wikiLink.setDocId(getId()); wikiLink.setFullName(getFullName()); wikiLink.setLink(linkedPage); links.add(wikiLink); } } return links; } private List<String> getLinkedPages10(XWikiContext context) { try { String pattern = "\\[(.*?)\\]"; List<String> newlist = new ArrayList<String>(); List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 1); for (String name : list) { try { int i1 = name.indexOf(">"); if (i1 != -1) { name = name.substring(i1 + 1); } i1 = name.indexOf("&gt;"); if (i1 != -1) { name = name.substring(i1 + 4); } i1 = name.indexOf(" if (i1 != -1) { name = name.substring(0, i1); } i1 = name.indexOf("?"); if (i1 != -1) { name = name.substring(0, i1); } // Let's get rid of anything that's not a real link if (name.trim().equals("") || (name.indexOf("$") != -1) || (name.indexOf(": || (name.indexOf("\"") != -1) || (name.indexOf("\'") != -1) || (name.indexOf("..") != -1) || (name.indexOf(":") != -1) || (name.indexOf("=") != -1)) { continue; } // generate the link String newname = StringUtils.replace(Util.noaccents(name), " ", ""); // If it is a local link let's add the space if (newname.indexOf(".") == -1) { newname = getSpace() + "." + name; } if (context.getWiki().exists(newname, context)) { name = newname; } else { // If it is a local link let's add the space if (name.indexOf(".") == -1) { name = getSpace() + "." + name; } } // Let's finally ignore the autolinks if (!name.equals(getFullName())) { newlist.add(name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return newlist; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } /** * Extract all the static wiki links (pointing to wiki page) from this document's content. * * @param context the XWiki context. * @return all the found wiki links. */ public List<String> getLinkedPages(XWikiContext context) { List<String> pageNames; if (getSyntaxId().equals(XWIKI10_SYNTAXID)) { pageNames = getLinkedPages10(context); } else { XDOM dom = getXDOM(); List<LinkBlock> linkBlocks = dom.getChildrenByType(LinkBlock.class, true); pageNames = new ArrayList<String>(linkBlocks.size()); for (LinkBlock linkBlock : linkBlocks) { org.xwiki.rendering.listener.Link link = linkBlock.getLink(); if (link.getType() == LinkType.DOCUMENT) { pageNames.add(link.getReference()); } } } return pageNames; } public List<String> getChildren(XWikiContext context) throws XWikiException { String hql = "select doc.fullName from XWikiDocument doc " + "where doc.parent='" + getFullName() + "' order by doc.fullName"; return context.getWiki().search(hql, context); } public void renameProperties(String className, Map fieldsToRename) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return; } for (BaseObject bobject : objects) { if (bobject == null) { continue; } for (Iterator renameit = fieldsToRename.keySet().iterator(); renameit.hasNext();) { String origname = (String) renameit.next(); String newname = (String) fieldsToRename.get(origname); BaseProperty origprop = (BaseProperty) bobject.safeget(origname); if (origprop != null) { BaseProperty prop = (BaseProperty) origprop.clone(); bobject.removeField(origname); prop.setName(newname); bobject.addField(newname, prop); } } } setContentDirty(true); } public void addObjectsToRemove(BaseObject object) { getObjectsToRemove().add(object); setContentDirty(true); } public ArrayList<BaseObject> getObjectsToRemove() { return this.objectsToRemove; } public void setObjectsToRemove(ArrayList<BaseObject> objectsToRemove) { this.objectsToRemove = objectsToRemove; setContentDirty(true); } public List<String> getIncludedPages(XWikiContext context) { if (getSyntaxId().equalsIgnoreCase(XWIKI10_SYNTAXID)) { return getIncludedPagesForXWiki10Syntax(context); } else { // Find all include macros listed on the page XDOM dom = getXDOM(); List<String> result = new ArrayList<String>(); for (MacroBlock macroBlock : dom.getChildrenByType(MacroBlock.class, true)) { if (macroBlock.getName().equalsIgnoreCase("include")) { String documentName = macroBlock.getParameters().get("document"); if (documentName.indexOf(".") == -1) { documentName = getSpace() + "." + documentName; } result.add(documentName); } } return result; } } private List<String> getIncludedPagesForXWiki10Syntax(XWikiContext context) { try { String pattern = "#include(Topic|InContext|Form|Macros|parseGroovyFromPage)\\([\"'](.*?)[\"']\\)"; List<String> list = context.getUtil().getUniqueMatches(getContent(), pattern, 2); for (int i = 0; i < list.size(); i++) { try { String name = list.get(i); if (name.indexOf(".") == -1) { list.set(i, getSpace() + "." + name); } } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } return list; } catch (Exception e) { // This should never happen e.printStackTrace(); return null; } } public List<String> getIncludedMacros(XWikiContext context) { return context.getWiki().getIncludedMacros(getSpace(), getContent(), context); } public String displayRendered(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) throws XWikiException { String result = pclass.displayView(pclass.getName(), prefix, object, context); return getRenderedContent(result, context); } public String displayView(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayView(pclass.getName(), prefix, object, context); } public String displayEdit(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayEdit(pclass.getName(), prefix, object, context); } public String displayHidden(PropertyClass pclass, String prefix, BaseCollection object, XWikiContext context) { return (pclass == null) ? "" : pclass.displayHidden(pclass.getName(), prefix, object, context); } public String displaySearch(PropertyClass pclass, String prefix, XWikiCriteria criteria, XWikiContext context) { return (pclass == null) ? "" : pclass.displaySearch(pclass.getName(), prefix, criteria, context); } public XWikiAttachment getAttachment(String filename) { for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().equals(filename)) { return attach; } } for (XWikiAttachment attach : getAttachmentList()) { if (attach.getFilename().startsWith(filename + ".")) { return attach; } } return null; } public XWikiAttachment addAttachment(String fileName, InputStream iStream, XWikiContext context) throws XWikiException, IOException { ByteArrayOutputStream bAOut = new ByteArrayOutputStream(); IOUtils.copy(iStream, bAOut); return addAttachment(fileName, bAOut.toByteArray(), context); } public XWikiAttachment addAttachment(String fileName, byte[] data, XWikiContext context) throws XWikiException { int i = fileName.indexOf("\\"); if (i == -1) { i = fileName.indexOf("/"); } String filename = fileName.substring(i + 1); // TODO : avoid name clearing when encoding problems will be solved filename = context.getWiki().clearName(filename, false, true, context); XWikiAttachment attachment = getAttachment(filename); if (attachment == null) { attachment = new XWikiAttachment(); // TODO: Review this code and understand why it's needed. // Add the attachment in the current doc getAttachmentList().add(attachment); } attachment.setContent(data); attachment.setFilename(filename); attachment.setAuthor(context.getUser()); // Add the attachment to the document attachment.setDoc(this); return attachment; } public BaseObject getFirstObject(String fieldname) { // Keeping this function with context null for compatibility reasons. // It should not be used, since it would miss properties which are only defined in the class // and not present in the object because the object was not updated return getFirstObject(fieldname, null); } public BaseObject getFirstObject(String fieldname, XWikiContext context) { Collection<Vector<BaseObject>> objectscoll = getxWikiObjects().values(); if (objectscoll == null) { return null; } for (Vector<BaseObject> objects : objectscoll) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); if (bclass != null) { Set<String> set = bclass.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } Set<String> set = obj.getPropertyList(); if ((set != null) && set.contains(fieldname)) { return obj; } } } } return null; } public void setProperty(String className, String fieldName, BaseProperty value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.safeput(fieldName, value); setContentDirty(true); } public int getIntValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getIntValue(fieldName); } public long getLongValue(String className, String fieldName) { BaseObject obj = getObject(className, 0); if (obj == null) { return 0; } return obj.getLongValue(fieldName); } public String getStringValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return ""; } String result = obj.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public int getIntValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getIntValue(fieldName); } } public long getLongValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return 0; } else { return object.getLongValue(fieldName); } } public String getStringValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return ""; } String result = object.getStringValue(fieldName); if (result.equals(" ")) { return ""; } else { return result; } } public void setStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringValue(fieldName, value); setContentDirty(true); } public List getListValue(String className, String fieldName) { BaseObject obj = getObject(className); if (obj == null) { return new ArrayList(); } return obj.getListValue(fieldName); } public List getListValue(String fieldName) { BaseObject object = getFirstObject(fieldName, null); if (object == null) { return new ArrayList(); } return object.getListValue(fieldName); } public void setStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setStringListValue(fieldName, value); setContentDirty(true); } public void setDBStringListValue(String className, String fieldName, List value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setDBStringListValue(fieldName, value); setContentDirty(true); } public void setLargeStringValue(String className, String fieldName, String value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setLargeStringValue(fieldName, value); setContentDirty(true); } public void setIntValue(String className, String fieldName, int value) { BaseObject bobject = getObject(className); if (bobject == null) { bobject = new BaseObject(); addObject(className, bobject); } bobject.setName(getFullName()); bobject.setClassName(className); bobject.setIntValue(fieldName, value); setContentDirty(true); } public String getDatabase() { return this.database; } public void setDatabase(String database) { this.database = database; } public void setFullName(String fullname, XWikiContext context) { if (fullname == null) { return; } int i0 = fullname.lastIndexOf(":"); int i1 = fullname.lastIndexOf("."); if (i0 != -1) { setDatabase(fullname.substring(0, i0)); setSpace(fullname.substring(i0 + 1, i1)); setName(fullname.substring(i1 + 1)); } else { if (context != null) { setDatabase(context.getDatabase()); } if (i1 == -1) { try { setSpace(context.getDoc().getSpace()); } catch (Exception e) { setSpace("XWiki"); } setName(fullname); } else { setSpace(fullname.substring(0, i1)); setName(fullname.substring(i1 + 1)); } } if (getName().equals("")) { setName("WebHome"); } setContentDirty(true); } public String getLanguage() { if (this.language == null) { return ""; } else { return this.language.trim(); } } public void setLanguage(String language) { this.language = language; } public String getDefaultLanguage() { if (this.defaultLanguage == null) { return ""; } else { return this.defaultLanguage.trim(); } } public void setDefaultLanguage(String defaultLanguage) { this.defaultLanguage = defaultLanguage; setMetaDataDirty(true); } public int getTranslation() { return this.translation; } public void setTranslation(int translation) { this.translation = translation; setMetaDataDirty(true); } public String getTranslatedContent(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedContent(language, context); } public String getTranslatedContent(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = getTranslatedDocument(language, context); String rev = (String) context.get("rev"); if ((rev == null) || (rev.length() == 0)) { return tdoc.getContent(); } XWikiDocument cdoc = context.getWiki().getDocument(tdoc, rev, context); return cdoc.getContent(); } public XWikiDocument getTranslatedDocument(XWikiContext context) throws XWikiException { String language = context.getWiki().getLanguagePreference(context); return getTranslatedDocument(language, context); } public XWikiDocument getTranslatedDocument(String language, XWikiContext context) throws XWikiException { XWikiDocument tdoc = this; if (!((language == null) || (language.equals("")) || language.equals(this.defaultLanguage))) { tdoc = new XWikiDocument(getSpace(), getName()); tdoc.setLanguage(language); String database = context.getDatabase(); try { // We might need to switch database to // get the translated content if (getDatabase() != null) { context.setDatabase(getDatabase()); } tdoc = getStore(context).loadXWikiDoc(tdoc, context); if (tdoc.isNew()) { tdoc = this; } } catch (Exception e) { tdoc = this; } finally { context.setDatabase(database); } } return tdoc; } public String getRealLanguage(XWikiContext context) throws XWikiException { return getRealLanguage(); } public String getRealLanguage() { String lang = getLanguage(); if ((lang.equals("") || lang.equals("default"))) { return getDefaultLanguage(); } else { return lang; } } public List<String> getTranslationList(XWikiContext context) throws XWikiException { return getStore().getTranslationList(this, context); } public List<Delta> getXMLDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.toXML(context)), ToString.stringToArray(toDoc .toXML(context)))); } public List<Delta> getContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { return getDeltas(Diff.diff(ToString.stringToArray(fromDoc.getContent()), ToString.stringToArray(toDoc .getContent()))); } public List<Delta> getContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getContentDiff(fromDoc, toDoc, context); } public List<Delta> getContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getContentDiff(revdoc, this, context); } public List<Delta> getLastChanges(XWikiContext context) throws XWikiException, DifferentiationFailedException { Version version = getRCSVersion(); try { String prev = getDocumentArchive(context).getPrevVersion(version).toString(); XWikiDocument prevDoc = context.getWiki().getDocument(this, prev, context); return getDeltas(Diff.diff(ToString.stringToArray(prevDoc.getContent()), ToString .stringToArray(getContent()))); } catch (Exception ex) { log.debug("Exception getting differences from previous version: " + ex.getMessage()); } return new ArrayList<Delta>(); } public List<Delta> getRenderedContentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException, DifferentiationFailedException { String originalContent, newContent; originalContent = context.getWiki().getRenderingEngine().renderText(fromDoc.getContent(), fromDoc, context); newContent = context.getWiki().getRenderingEngine().renderText(toDoc.getContent(), toDoc, context); return getDeltas(Diff.diff(ToString.stringToArray(originalContent), ToString.stringToArray(newContent))); } public List<Delta> getRenderedContentDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getRenderedContentDiff(fromDoc, toDoc, context); } public List<Delta> getRenderedContentDiff(String fromRev, XWikiContext context) throws XWikiException, DifferentiationFailedException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getRenderedContentDiff(revdoc, this, context); } protected List<Delta> getDeltas(Revision rev) { List<Delta> list = new ArrayList<Delta>(); for (int i = 0; i < rev.size(); i++) { list.add(rev.getDelta(i)); } return list; } public List<MetaDataDiff> getMetaDataDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getMetaDataDiff(fromDoc, toDoc, context); } public List<MetaDataDiff> getMetaDataDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getMetaDataDiff(revdoc, this, context); } public List<MetaDataDiff> getMetaDataDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<MetaDataDiff> list = new ArrayList<MetaDataDiff>(); if ((fromDoc == null) || (toDoc == null)) { return list; } if (!fromDoc.getParent().equals(toDoc.getParent())) { list.add(new MetaDataDiff("parent", fromDoc.getParent(), toDoc.getParent())); } if (!fromDoc.getAuthor().equals(toDoc.getAuthor())) { list.add(new MetaDataDiff("author", fromDoc.getAuthor(), toDoc.getAuthor())); } if (!fromDoc.getSpace().equals(toDoc.getSpace())) { list.add(new MetaDataDiff("web", fromDoc.getSpace(), toDoc.getSpace())); } if (!fromDoc.getName().equals(toDoc.getName())) { list.add(new MetaDataDiff("name", fromDoc.getName(), toDoc.getName())); } if (!fromDoc.getLanguage().equals(toDoc.getLanguage())) { list.add(new MetaDataDiff("language", fromDoc.getLanguage(), toDoc.getLanguage())); } if (!fromDoc.getDefaultLanguage().equals(toDoc.getDefaultLanguage())) { list.add(new MetaDataDiff("defaultLanguage", fromDoc.getDefaultLanguage(), toDoc.getDefaultLanguage())); } return list; } public List<List<ObjectDiff>> getObjectDiff(String fromRev, String toRev, XWikiContext context) throws XWikiException { XWikiDocument fromDoc = context.getWiki().getDocument(this, fromRev, context); XWikiDocument toDoc = context.getWiki().getDocument(this, toRev, context); return getObjectDiff(fromDoc, toDoc, context); } public List<List<ObjectDiff>> getObjectDiff(String fromRev, XWikiContext context) throws XWikiException { XWikiDocument revdoc = context.getWiki().getDocument(this, fromRev, context); return getObjectDiff(revdoc, this, context); } /** * Return the object differences between two document versions. There is no hard requirement on the order of the two * versions, but the results are semantically correct only if the two versions are given in the right order. * * @param fromDoc The old ('before') version of the document. * @param toDoc The new ('after') version of the document. * @param context The {@link com.xpn.xwiki.XWikiContext context}. * @return The object differences. The returned list's elements are other lists, one for each changed object. The * inner lists contain {@link ObjectDiff} elements, one object for each changed property of the object. * Additionally, if the object was added or removed, then the first entry in the list will be an * "object-added" or "object-removed" marker. * @throws XWikiException If there's an error computing the differences. */ public List<List<ObjectDiff>> getObjectDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); // Since objects could have been deleted or added, we iterate on both the old and the new // object collections. // First, iterate over the old objects. for (Vector<BaseObject> objects : fromDoc.getxWikiObjects().values()) { for (BaseObject originalObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (originalObj != null) { BaseObject newObj = toDoc.getObject(originalObj.getClassName(), originalObj.getNumber()); List<ObjectDiff> dlist; if (newObj == null) { // The object was deleted. dlist = new BaseObject().getDiff(originalObj, context); ObjectDiff deleteMarker = new ObjectDiff(originalObj.getClassName(), originalObj.getNumber(), originalObj.getGuid(), "object-removed", "", "", ""); dlist.add(0, deleteMarker); } else { // The object exists in both versions, but might have been changed. dlist = newObj.getDiff(originalObj, context); } if (dlist.size() > 0) { difflist.add(dlist); } } } } // Second, iterate over the objects which are only in the new version. for (Vector<BaseObject> objects : toDoc.getxWikiObjects().values()) { for (BaseObject newObj : objects) { // This happens when objects are deleted, and the document is still in the cache // storage. if (newObj != null) { BaseObject originalObj = fromDoc.getObject(newObj.getClassName(), newObj.getNumber()); if (originalObj == null) { // Only consider added objects, the other case was treated above. originalObj = new BaseObject(); originalObj.setClassName(newObj.getClassName()); originalObj.setNumber(newObj.getNumber()); originalObj.setGuid(newObj.getGuid()); List<ObjectDiff> dlist = newObj.getDiff(originalObj, context); ObjectDiff addMarker = new ObjectDiff(newObj.getClassName(), newObj.getNumber(), newObj.getGuid(), "object-added", "", "", ""); dlist.add(0, addMarker); if (dlist.size() > 0) { difflist.add(dlist); } } } } } return difflist; } public List<List<ObjectDiff>> getClassDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { ArrayList<List<ObjectDiff>> difflist = new ArrayList<List<ObjectDiff>>(); BaseClass oldClass = fromDoc.getxWikiClass(); BaseClass newClass = toDoc.getxWikiClass(); if ((newClass == null) && (oldClass == null)) { return difflist; } List<ObjectDiff> dlist = newClass.getDiff(oldClass, context); if (dlist.size() > 0) { difflist.add(dlist); } return difflist; } /** * @param fromDoc * @param toDoc * @param context * @return * @throws XWikiException */ public List<AttachmentDiff> getAttachmentDiff(XWikiDocument fromDoc, XWikiDocument toDoc, XWikiContext context) throws XWikiException { List<AttachmentDiff> difflist = new ArrayList<AttachmentDiff>(); for (XWikiAttachment origAttach : fromDoc.getAttachmentList()) { String fileName = origAttach.getFilename(); XWikiAttachment newAttach = toDoc.getAttachment(fileName); if (newAttach == null) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), null)); } else { if (!origAttach.getVersion().equals(newAttach.getVersion())) { difflist.add(new AttachmentDiff(fileName, origAttach.getVersion(), newAttach.getVersion())); } } } for (XWikiAttachment newAttach : toDoc.getAttachmentList()) { String fileName = newAttach.getFilename(); XWikiAttachment origAttach = fromDoc.getAttachment(fileName); if (origAttach == null) { difflist.add(new AttachmentDiff(fileName, null, newAttach.getVersion())); } } return difflist; } /** * Rename the current document and all the backlinks leading to it. See * {@link #rename(String, java.util.List, com.xpn.xwiki.XWikiContext)} for more details. * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, XWikiContext context) throws XWikiException { rename(newDocumentName, getBackLinkedPages(context), context); } /** * Rename the current document and all the links pointing to it in the list of passed backlink documents. The * renaming algorithm takes into account the fact that there are several ways to write a link to a given page and * all those forms need to be renamed. For example the following links all point to the same page: * <ul> * <li>[Page]</li> * <li>[Page?param=1]</li> * <li>[currentwiki:Page]</li> * <li>[CurrentSpace.Page]</li> * </ul> * <p> * Note: links without a space are renamed with the space added. * </p> * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the * new renamed document. * @param context the ubiquitous XWiki Context * @throws XWikiException in case of an error */ public void rename(String newDocumentName, List<String> backlinkDocumentNames, XWikiContext context) throws XWikiException { // TODO: Do all this in a single DB transaction as otherwise the state will be unknown if // something fails in the middle... if (isNew()) { return; } // This link handler recognizes that 2 links are the same when they point to the same // document (regardless of query string, target or alias). It keeps the query string, // target and alias from the link being replaced. RenamePageReplaceLinkHandler linkHandler = new RenamePageReplaceLinkHandler(); // Transform string representation of old and new links so that they can be manipulated. Link oldLink = new LinkParser().parse(getFullName()); Link newLink = new LinkParser().parse(newDocumentName); // Verify if the user is trying to rename to the same name... In that case, simply exits // for efficiency. if (linkHandler.compare(newLink, oldLink)) { return; } // Step 1: Copy the document and all its translations under a new name context.getWiki().copyDocument(getFullName(), newDocumentName, false, context); // Step 2: For each backlink to rename, parse the backlink document and replace the links // with the new name. // Note: we ignore invalid links here. Invalid links should be shown to the user so // that they fix them but the rename feature ignores them. DocumentParser documentParser = new DocumentParser(); for (String backlinkDocumentName : backlinkDocumentNames) { XWikiDocument backlinkDocument = context.getWiki().getDocument(backlinkDocumentName, context); // Note: Here we cannot do a simple search/replace as there are several ways to point // to the same document. For example [Page], [Page?param=1], [currentwiki:Page], // [CurrentSpace.Page] all point to the same document. Thus we have to parse the links // to recognize them and do the replace. ReplacementResultCollection result = documentParser.parseLinksAndReplace(backlinkDocument.getContent(), oldLink, newLink, linkHandler, getSpace()); backlinkDocument.setContent((String) result.getModifiedContent()); context.getWiki().saveDocument(backlinkDocument, context.getMessageTool().get("core.comment.renameLink", Arrays.asList(new String[] {newDocumentName})), true, context); } // Step 3: Delete the old document context.getWiki().deleteDocument(this, context); // Step 4: The current document needs to point to the renamed document as otherwise it's // pointing to an invalid XWikiDocument object as it's been deleted... clone(context.getWiki().getDocument(newDocumentName, context)); } public XWikiDocument copyDocument(String newDocumentName, XWikiContext context) throws XWikiException { String oldname = getFullName(); loadAttachments(context); loadArchive(context); /* * if (oldname.equals(docname)) return this; */ XWikiDocument newdoc = (XWikiDocument) clone(); newdoc.setFullName(newDocumentName, context); newdoc.setContentDirty(true); newdoc.getxWikiClass().setName(newDocumentName); Vector<BaseObject> objects = newdoc.getObjects(oldname); if (objects != null) { for (BaseObject object : objects) { object.setName(newDocumentName); // Since GUIDs are supposed to be Unique, although this object holds the same data, it is not exactly // the same object, so it should have a different identifier. object.setGuid(UUID.randomUUID().toString()); } } XWikiDocumentArchive archive = newdoc.getDocumentArchive(); if (archive != null) { newdoc.setDocumentArchive(archive.clone(newdoc.getId(), context)); } return newdoc; } public XWikiLock getLock(XWikiContext context) throws XWikiException { XWikiLock theLock = getStore(context).loadLock(getId(), context, true); if (theLock != null) { int timeout = context.getWiki().getXWikiPreferenceAsInt("lock_Timeout", 30 * 60, context); if (theLock.getDate().getTime() + timeout * 1000 < new Date().getTime()) { getStore(context).deleteLock(theLock, context, true); theLock = null; } } return theLock; } public void setLock(String userName, XWikiContext context) throws XWikiException { XWikiLock lock = new XWikiLock(getId(), userName); getStore(context).saveLock(lock, context, true); } public void removeLock(XWikiContext context) throws XWikiException { XWikiLock lock = getStore(context).loadLock(getId(), context, true); if (lock != null) { getStore(context).deleteLock(lock, context, true); } } public void insertText(String text, String marker, XWikiContext context) throws XWikiException { setContent(StringUtils.replaceOnce(getContent(), marker, text + marker)); context.getWiki().saveDocument(this, context); } public Object getWikiNode() { return this.wikiNode; } public void setWikiNode(Object wikiNode) { this.wikiNode = wikiNode; } public String getxWikiClassXML() { return this.xWikiClassXML; } public void setxWikiClassXML(String xWikiClassXML) { this.xWikiClassXML = xWikiClassXML; } public int getElements() { return this.elements; } public void setElements(int elements) { this.elements = elements; } public void setElement(int element, boolean toggle) { if (toggle) { this.elements = this.elements | element; } else { this.elements = this.elements & (~element); } } public boolean hasElement(int element) { return ((this.elements & element) == element); } public String getDefaultEditURL(XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); if (getContent().indexOf("includeForm(") != -1) { return getEditURL("inline", "", context); } else { String editor = xwiki.getEditorPreference(context); return getEditURL("edit", editor, context); } } public String getEditURL(String action, String mode, XWikiContext context) throws XWikiException { com.xpn.xwiki.XWiki xwiki = context.getWiki(); String language = ""; XWikiDocument tdoc = (XWikiDocument) context.get("tdoc"); String realLang = tdoc.getRealLanguage(context); if ((xwiki.isMultiLingual(context) == true) && (!realLang.equals(""))) { language = realLang; } return getEditURL(action, mode, language, context); } public String getEditURL(String action, String mode, String language, XWikiContext context) { StringBuffer editparams = new StringBuffer(); if (!mode.equals("")) { editparams.append("xpage="); editparams.append(mode); } if (!language.equals("")) { if (!mode.equals("")) { editparams.append("&"); } editparams.append("language="); editparams.append(language); } return getURL(action, editparams.toString(), context); } public String getDefaultTemplate() { if (this.defaultTemplate == null) { return ""; } else { return this.defaultTemplate; } } public void setDefaultTemplate(String defaultTemplate) { this.defaultTemplate = defaultTemplate; setMetaDataDirty(true); } public Vector<BaseObject> getComments() { return getComments(true); } /** * {@inheritDoc} * * @see org.xwiki.bridge.DocumentModelBridge#getSyntaxId() */ public String getSyntaxId() { String result; if ((this.syntaxId == null) || (this.syntaxId.length() == 0)) { result = XWIKI10_SYNTAXID; } else { result = this.syntaxId; } return result; } /** * @param syntaxId the new syntax id to set (eg "xwiki/1.0", "xwiki/2.0", etc) * @see #getSyntaxId() */ public void setSyntaxId(String syntaxId) { this.syntaxId = syntaxId; } public Vector<BaseObject> getComments(boolean asc) { if (asc) { return getObjects("XWiki.XWikiComments"); } else { Vector<BaseObject> list = getObjects("XWiki.XWikiComments"); if (list == null) { return list; } Vector<BaseObject> newlist = new Vector<BaseObject>(); for (int i = list.size() - 1; i >= 0; i newlist.add(list.get(i)); } return newlist; } } public boolean isCurrentUserCreator(XWikiContext context) { return isCreator(context.getUser()); } public boolean isCreator(String username) { if (username.equals("XWiki.XWikiGuest")) { return false; } return username.equals(getCreator()); } public boolean isCurrentUserPage(XWikiContext context) { String username = context.getUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public boolean isCurrentLocalUserPage(XWikiContext context) { String username = context.getLocalUser(); if (username.equals("XWiki.XWikiGuest")) { return false; } return context.getUser().equals(getFullName()); } public void resetArchive(XWikiContext context) throws XWikiException { boolean hasVersioning = context.getWiki().hasVersioning(getFullName(), context); if (hasVersioning) { getVersioningStore(context).resetRCSArchive(this, true, context); } } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(XWikiContext context) throws XWikiException { // Read info in object ObjectAddForm form = new ObjectAddForm(); form.setRequest((HttpServletRequest) context.getRequest()); form.readRequest(); String className = form.getClassName(); BaseObject object = newObject(className, context); BaseClass baseclass = object.getxWikiClass(context); baseclass.fromMap(form.getObject(className), object); return object; } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", 0, context); } // This functions adds an object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, prefix, 0, context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return addObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> addObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(addObjectFromRequest(className, pref, num, context)); } } } return objects; } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, int num, XWikiContext context) throws XWikiException { return addObjectFromRequest(className, "", num, context); } // This functions adds object from an new object creation form public BaseObject addObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { BaseObject object = newObject(className, context); BaseClass baseclass = object.getxWikiClass(context); baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + num), object); return object; } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, "", context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, XWikiContext context) throws XWikiException { return updateObjectFromRequest(className, prefix, 0, context); } // This functions adds an object from an new object creation form public BaseObject updateObjectFromRequest(String className, String prefix, int num, XWikiContext context) throws XWikiException { int nb; BaseObject oldobject = getObject(className, num); if (oldobject == null) { nb = createNewObject(className, context); oldobject = getObject(className, nb); } else { nb = oldobject.getNumber(); } BaseClass baseclass = oldobject.getxWikiClass(context); BaseObject newobject = (BaseObject) baseclass.fromMap(Util.getObject(context.getRequest(), prefix + className + "_" + nb), oldobject); newobject.setNumber(oldobject.getNumber()); newobject.setGuid(oldobject.getGuid()); newobject.setName(getFullName()); setObject(className, nb, newobject); return newobject; } // This functions adds an object from an new object creation form public List<BaseObject> updateObjectsFromRequest(String className, XWikiContext context) throws XWikiException { return updateObjectsFromRequest(className, "", context); } // This functions adds multiple objects from an new objects creation form public List<BaseObject> updateObjectsFromRequest(String className, String pref, XWikiContext context) throws XWikiException { Map map = context.getRequest().getParameterMap(); List<Integer> objectsNumberDone = new ArrayList<Integer>(); List<BaseObject> objects = new ArrayList<BaseObject>(); Iterator it = map.keySet().iterator(); String start = pref + className + "_"; while (it.hasNext()) { String name = (String) it.next(); if (name.startsWith(start)) { int pos = name.indexOf("_", start.length() + 1); String prefix = name.substring(0, pos); int num = Integer.decode(prefix.substring(prefix.lastIndexOf("_") + 1)).intValue(); if (!objectsNumberDone.contains(new Integer(num))) { objectsNumberDone.add(new Integer(num)); objects.add(updateObjectFromRequest(className, pref, num, context)); } } } return objects; } public boolean isAdvancedContent() { String[] matches = {"<%", "#set", "#include", "#if", "public class", "/* Advanced content */", "## Advanced content", "/* Programmatic content */", "## Programmatic content"}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } if (HTML_TAG_PATTERN.matcher(content2).find()) { return true; } return false; } public boolean isProgrammaticContent() { String[] matches = {"<%", "\\$xwiki.xWiki", "$context.context", "$doc.document", "$xwiki.getXWiki()", "$context.getContext()", "$doc.getDocument()", "WithProgrammingRights(", "/* Programmatic content */", "## Programmatic content", "$xwiki.search(", "$xwiki.createUser", "$xwiki.createNewWiki", "$xwiki.addToAllGroup", "$xwiki.sendMessage", "$xwiki.copyDocument", "$xwiki.copyWikiWeb", "$xwiki.parseGroovyFromString", "$doc.toXML()", "$doc.toXMLDocument()",}; String content2 = this.content.toLowerCase(); for (int i = 0; i < matches.length; i++) { if (content2.indexOf(matches[i].toLowerCase()) != -1) { return true; } } return false; } public boolean removeObject(BaseObject bobj) { Vector<BaseObject> objects = getObjects(bobj.getClassName()); if (objects == null) { return false; } if (objects.elementAt(bobj.getNumber()) == null) { return false; } objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); return true; } /** * Remove all the objects of a given type (XClass) from the document. * * @param className The class name of the objects to be removed. */ public boolean removeObjects(String className) { Vector<BaseObject> objects = getObjects(className); if (objects == null) { return false; } Iterator<BaseObject> it = objects.iterator(); while (it.hasNext()) { BaseObject bobj = it.next(); if (bobj != null) { objects.set(bobj.getNumber(), null); addObjectsToRemove(bobj); } } return true; } /** * @return the sections in the current document */ public List<DocumentSection> getSections() { return getSplitSectionsAccordingToTitle(); } /** * This method to split section according to title. * * @return the sections in the current document * @throws XWikiException * @deprecated use {@link #getSections()} instead, since 1.6M1 */ @Deprecated public List<DocumentSection> getSplitSectionsAccordingToTitle() { // Pattern to match the title. Matches only level 1 and level 2 headings. Pattern headingPattern = Pattern.compile("^[ \\t]*+(1(\\.1){0,1}+)[ \\t]++(.++)$", Pattern.MULTILINE); Matcher matcher = headingPattern.matcher(getContent()); List<DocumentSection> splitSections = new ArrayList<DocumentSection>(); int sectionNumber = 0; // find title to split while (matcher.find()) { ++sectionNumber; String sectionLevel = matcher.group(1); String sectionTitle = matcher.group(3); int sectionIndex = matcher.start(); // Initialize a documentSection object. DocumentSection docSection = new DocumentSection(sectionNumber, sectionIndex, sectionLevel, sectionTitle); // Add the document section to list. splitSections.add(docSection); } return splitSections; } // This function to return a Document section with parameter is sectionNumber public DocumentSection getDocumentSection(int sectionNumber) throws XWikiException { // return a document section according to section number return getSplitSectionsAccordingToTitle().get(sectionNumber - 1); } // This method to return the content of a section public String getContentOfSection(int sectionNumber) throws XWikiException { List<DocumentSection> splitSections = getSplitSectionsAccordingToTitle(); int indexEnd = 0; // get current section DocumentSection section = splitSections.get(sectionNumber - 1); int indexStart = section.getSectionIndex(); String sectionLevel = section.getSectionLevel(); // Determine where this section ends, which is at the start of the next section of the // same or a higher level. for (int i = sectionNumber; i < splitSections.size(); i++) { DocumentSection nextSection = splitSections.get(i); String nextLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextLevel) || sectionLevel.length() > nextLevel.length()) { indexEnd = nextSection.getSectionIndex(); break; } } String sectionContent = null; if (indexStart < 0) { indexStart = 0; } if (indexEnd == 0) { sectionContent = getContent().substring(indexStart); } else { sectionContent = getContent().substring(indexStart, indexEnd); } return sectionContent; } // This function to update a section content in document public String updateDocumentSection(int sectionNumber, String newSectionContent) throws XWikiException { StringBuffer newContent = new StringBuffer(); // get document section that will be edited DocumentSection docSection = getDocumentSection(sectionNumber); int numberOfSections = getSplitSectionsAccordingToTitle().size(); int indexSection = docSection.getSectionIndex(); if (numberOfSections == 1) { // there is only a sections in document String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else if (sectionNumber == numberOfSections) { // edit lastest section that doesn't contain subtitle String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent); return newContent.toString(); } else { String sectionLevel = docSection.getSectionLevel(); int nextSectionIndex = 0; // get index of next section for (int i = sectionNumber; i < numberOfSections; i++) { DocumentSection nextSection = getDocumentSection(i + 1); // get next section String nextSectionLevel = nextSection.getSectionLevel(); if (sectionLevel.equals(nextSectionLevel)) { nextSectionIndex = nextSection.getSectionIndex(); break; } else if (sectionLevel.length() > nextSectionLevel.length()) { nextSectionIndex = nextSection.getSectionIndex(); break; } } if (nextSectionIndex == 0) {// edit the last section newContent = newContent.append(getContent().substring(0, indexSection)).append(newSectionContent); return newContent.toString(); } else { String contentAfter = getContent().substring(nextSectionIndex); String contentBegin = getContent().substring(0, indexSection); newContent = newContent.append(contentBegin).append(newSectionContent).append(contentAfter); } return newContent.toString(); } } /** * Computes a document hash, taking into account all document data: content, objects, attachments, metadata... TODO: * cache the hash value, update only on modification. */ public String getVersionHashCode(XWikiContext context) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { log.error("Cannot create MD5 object", ex); return this.hashCode() + ""; } try { String valueBeforeMD5 = toXML(true, false, true, false, context); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } return sb.toString(); } catch (Exception ex) { log.error("Exception while computing document hash", ex); } return this.hashCode() + ""; } public static String getInternalPropertyName(String propname, XWikiContext context) { XWikiMessageTool msg = context.getMessageTool(); String cpropname = StringUtils.capitalize(propname); return (msg == null) ? cpropname : msg.get(cpropname); } public String getInternalProperty(String propname) { String methodName = "get" + StringUtils.capitalize(propname); try { Method method = getClass().getDeclaredMethod(methodName, (Class[]) null); return (String) method.invoke(this, (Object[]) null); } catch (Exception e) { return null; } } public String getCustomClass() { if (this.customClass == null) { return ""; } return this.customClass; } public void setCustomClass(String customClass) { this.customClass = customClass; setMetaDataDirty(true); } public void setValidationScript(String validationScript) { this.validationScript = validationScript; setMetaDataDirty(true); } public String getValidationScript() { if (this.validationScript == null) { return ""; } else { return this.validationScript; } } public String getComment() { if (this.comment == null) { return ""; } return this.comment; } public void setComment(String comment) { this.comment = comment; } public boolean isMinorEdit() { return this.isMinorEdit; } public void setMinorEdit(boolean isMinor) { this.isMinorEdit = isMinor; } // methods for easy table update. It is need only for hibernate. // when hibernate update old database without minorEdit field, hibernate will create field with // null in despite of notnull in hbm. // so minorEdit will be null for old documents. But hibernate can't convert null to boolean. // so we need convert Boolean to boolean protected Boolean getMinorEdit1() { return Boolean.valueOf(this.isMinorEdit); } protected void setMinorEdit1(Boolean isMinor) { this.isMinorEdit = (isMinor != null && isMinor.booleanValue()); } public BaseObject newObject(String classname, XWikiContext context) throws XWikiException { int nb = createNewObject(classname, context); return getObject(classname, nb); } public BaseObject getObject(String classname, boolean create, XWikiContext context) { try { BaseObject obj = getObject(classname); if ((obj == null) && create) { return newObject(classname, context); } if (obj == null) { return null; } else { return obj; } } catch (Exception e) { return null; } } public boolean validate(XWikiContext context) throws XWikiException { return validate(null, context); } public boolean validate(String[] classNames, XWikiContext context) throws XWikiException { boolean isValid = true; if ((classNames == null) || (classNames.length == 0)) { for (String classname : getxWikiObjects().keySet()) { BaseClass bclass = context.getWiki().getClass(classname, context); Vector<BaseObject> objects = getObjects(classname); for (BaseObject obj : objects) { if (obj != null) { isValid &= bclass.validateObject(obj, context); } } } } else { for (int i = 0; i < classNames.length; i++) { Vector<BaseObject> objects = getObjects(classNames[i]); if (objects != null) { for (BaseObject obj : objects) { if (obj != null) { BaseClass bclass = obj.getxWikiClass(context); isValid &= bclass.validateObject(obj, context); } } } } } String validationScript = ""; XWikiRequest req = context.getRequest(); if (req != null) { validationScript = req.get("xvalidation"); } if ((validationScript == null) || (validationScript.trim().equals(""))) { validationScript = getValidationScript(); } if ((validationScript != null) && (!validationScript.trim().equals(""))) { isValid &= executeValidationScript(context, validationScript); } return isValid; } private boolean executeValidationScript(XWikiContext context, String validationScript) throws XWikiException { try { XWikiValidationInterface validObject = (XWikiValidationInterface) context.getWiki().parseGroovyFromPage(validationScript, context); return validObject.validateDocument(this, context); } catch (Throwable e) { XWikiValidationStatus.addExceptionToContext(getFullName(), "", e, context); return false; } } public static void backupContext(HashMap<String, Object> backup, XWikiContext context) { backup.put("doc", context.getDoc()); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); if (vcontext != null) { backup.put("vdoc", vcontext.get("doc")); backup.put("vcdoc", vcontext.get("cdoc")); backup.put("vtdoc", vcontext.get("tdoc")); } Map gcontext = (Map) context.get("gcontext"); if (gcontext != null) { backup.put("gdoc", gcontext.get("doc")); backup.put("gcdoc", gcontext.get("cdoc")); backup.put("gtdoc", gcontext.get("tdoc")); } } public static void restoreContext(HashMap<String, Object> backup, XWikiContext context) { context.setDoc((XWikiDocument) backup.get("doc")); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { if (backup.get("vdoc") != null) { vcontext.put("doc", backup.get("vdoc")); } if (backup.get("vcdoc") != null) { vcontext.put("cdoc", backup.get("vcdoc")); } if (backup.get("vtdoc") != null) { vcontext.put("tdoc", backup.get("vtdoc")); } } if (gcontext != null) { if (backup.get("gdoc") != null) { gcontext.put("doc", backup.get("gdoc")); } if (backup.get("gcdoc") != null) { gcontext.put("cdoc", backup.get("gcdoc")); } if (backup.get("gtdoc") != null) { gcontext.put("tdoc", backup.get("gtdoc")); } } } public void setAsContextDoc(XWikiContext context) { try { context.setDoc(this); com.xpn.xwiki.api.Document apidoc = this.newDocument(context); com.xpn.xwiki.api.Document tdoc = apidoc.getTranslatedDocument(); VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map gcontext = (Map) context.get("gcontext"); if (vcontext != null) { vcontext.put("doc", apidoc); vcontext.put("tdoc", tdoc); } if (gcontext != null) { gcontext.put("doc", apidoc); gcontext.put("tdoc", tdoc); } } catch (XWikiException ex) { log.warn("Unhandled exception setting context", ex); } } public String getPreviousVersion() { return getDocumentArchive().getPrevVersion(this.version).toString(); } @Override public String toString() { return getFullName(); } /** * Indicates whether the document should be 'hidden' or not, meaning that it should not be returned in public search * results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should * rely on or use this property, since it will be replaced with a generic metadata. * * @param hidden The new value of the {@link #hidden} property. */ public void setHidden(Boolean hidden) { if (hidden == null) { this.hidden = false; } else { this.hidden = hidden; } } /** * Indicates whether the document is 'hidden' or not, meaning that it should not be returned in public search * results. WARNING: this is a temporary hack until the new data model is designed and implemented. No code should * rely on or use this property, since it will be replaced with a generic metadata. * * @return <code>true</code> if the document is hidden and does not appear among the results of * {@link com.xpn.xwiki.api.XWiki#searchDocuments(String)}, <code>false</code> otherwise. */ public Boolean isHidden() { return this.hidden; } /** * Convert the current document content from its current syntax to the new syntax passed as parameter. * * @param targetSyntaxId the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc) * @throws XWikiException if an exception occurred during the conversion process */ public void convertSyntax(String targetSyntaxId) throws XWikiException { setContent(performSyntaxConversion(getContent(), getSyntaxId(), targetSyntaxId)); } /** * @return the XDOM conrrexponding to the document's string content. */ public XDOM getXDOM() { if (this.xdom == null) { try { this.xdom = parseContent(getContent()); this.clonedxdom = this.xdom.clone(); } catch (ParseException e) { log.error("Failed to parse document content to XDOM", e); } } return this.clonedxdom; } /** * Convert the passed content from the passed syntax to the passed new syntax. * * @param content the content to convert * @param currentSyntaxId the syntax of the current content to convert * @param targetSyntaxId the new syntax after the conversion * @return the converted content in the new syntax * @throws XWikiException if an exception occurred during the conversion process */ private String performSyntaxConversion(String content, String currentSyntaxId, String targetSyntaxId) throws XWikiException { try { XDOM dom = parseContent(currentSyntaxId, content); return performSyntaxConversion(dom, currentSyntaxId, targetSyntaxId); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to convert document to syntax [" + targetSyntaxId + "]", e); } } /** * Convert the passed content from the passed syntax to the passed new syntax. * * @param content the XDOM content to convert, the XDOM can be modified suring the transformation * @param currentSyntaxId the syntax of the current content to convert * @param targetSyntaxId the new syntax after the conversion * @return the converted content in the new syntax * @throws XWikiException if an exception occurred during the conversion process */ private String performSyntaxConversion(XDOM content, String currentSyntaxId, String targetSyntaxId) throws XWikiException { WikiPrinter printer; try { // Transform XDOM TransformationManager transformations = (TransformationManager) Utils.getComponent(TransformationManager.ROLE); SyntaxFactory syntaxFactory = (SyntaxFactory) Utils.getComponent(SyntaxFactory.ROLE); transformations.performTransformations(content, syntaxFactory.createSyntaxFromIdString(currentSyntaxId)); // Render XDOM PrintRendererFactory factory = (PrintRendererFactory) Utils.getComponent(PrintRendererFactory.ROLE); printer = new DefaultWikiPrinter(); content.traverse(factory.createRenderer(syntaxFactory.createSyntaxFromIdString(targetSyntaxId), printer)); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_RENDERING, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to convert document to syntax [" + targetSyntaxId + "]", e); } return printer.toString(); } private XDOM parseContent(String content) throws ParseException { return parseContent(getSyntaxId(), content); } private XDOM parseContent(String syntaxId, String content) throws ParseException { Parser parser = (Parser) Utils.getComponent(Parser.ROLE, syntaxId); return parser.parse(new StringReader(content)); } }
package com.ilscipio.solr; import java.io.IOException; import java.net.ConnectException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion; import org.apache.solr.common.SolrInputDocument; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ServiceAuthException; import org.ofbiz.service.ServiceUtil; import org.ofbiz.service.ServiceValidationException; import javolution.util.FastList; import javolution.util.FastMap; /** * Base class for OFBiz Test Tools test case implementations. */ public abstract class SolrProductSearch { public static final String module = SolrProductSearch.class.getName(); /** * Adds product to solr, with product denoted by productId field in instance * attribute - intended for use with ECAs/SECAs. */ public static Map<String, Object> addToSolr(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { Map<String, Object> result; LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); GenericValue productInstance = (GenericValue) context.get("instance"); String productId = (String) productInstance.get("productId"); if (SolrUtil.isSolrEcaEnabled()) { if (SolrUtil.isSolrEcaWebappInitCheckPassed()) { Debug.logVerbose("Solr: addToSolr: Running indexing for productId '" + productId + "'", module); try { GenericValue product = delegator.findOne("Product", UtilMisc.toMap("productId", productId), false); Map<String, Object> dispatchContext = ProductUtil.getProductContent(product, dctx, context); dispatchContext.put("treatConnectErrorNonFatal", SolrUtil.isEcaTreatConnectErrorNonFatal()); Map<String, Object> runResult = dispatcher.runSync("addToSolrIndex", dispatchContext); String runMsg = ServiceUtil.getErrorMessage(runResult); if (UtilValidate.isEmpty(runMsg)) { runMsg = null; } if (ServiceUtil.isError(runResult)) { result = ServiceUtil.returnError(runMsg); } else if (ServiceUtil.isFailure(runResult)) { result = ServiceUtil.returnFailure(runMsg); } else { result = ServiceUtil.returnSuccess(); } } catch (Exception e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } } else { final String statusMsg = "Solr webapp not available; skipping indexing for productId '" + productId + "'"; Debug.logVerbose("Solr: addToSolr: " + statusMsg, module); result = ServiceUtil.returnSuccess(); } } else { final String statusMsg = "Solr ECA indexing disabled; skipping indexing for productId '" + productId + "'"; Debug.logVerbose("Solr: addToSolr: " + statusMsg, module); result = ServiceUtil.returnSuccess(); } return result; } /** * Adds product to solr index. */ public static Map<String, Object> addToSolrIndex(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { HttpSolrClient client = null; Map<String, Object> result; String productId = (String) context.get("productId"); // connectErrorNonFatal is a necessary option because in some cases it // may be considered normal that solr server is unavailable; // don't want to return error and abort transactions in these cases. Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal"); try { Debug.logInfo("Solr: Generating and indexing document for productId '" + productId + "'", module); if (UtilValidate.isNotEmpty(context.get("core"))) client = new HttpSolrClient(SolrUtil.solrUrl + "/" + context.get("core")); else client = new HttpSolrClient(SolrUtil.solrFullUrl); // Debug.log(server.ping().toString()); // Construct Documents SolrInputDocument doc1 = SolrUtil.generateSolrDocument(context); Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); if (Debug.verboseOn()) { Debug.logVerbose("Solr: Indexing document: " + doc1.toString(), module); } docs.add(doc1); // push Documents to server client.add(docs); client.commit(); final String statusStr = "Document for productId " + productId + " added to solr index"; Debug.logInfo("Solr: " + statusStr, module); result = ServiceUtil.returnSuccess(statusStr); } catch (MalformedURLException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "urlError"); } catch (SolrServerException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { final String statusStr = "Failure connecting to solr server to commit productId " + context.get("productId") + "; product not updated"; if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) { Debug.logWarning(e, "Solr: " + statusStr, module); result = ServiceUtil.returnFailure(statusStr); } else { Debug.logError(e, "Solr: " + statusStr, module); result = ServiceUtil.returnError(statusStr); } result.put("errorType", "connectError"); } else { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "solrServerError"); } } catch (IOException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "ioError"); } finally { try { if (UtilValidate.isNotEmpty(client)) client.close(); } catch (IOException e) { result = ServiceUtil.returnError(e.toString()); result.put("errorType", "ioError"); } } return result; } /** * Adds a List of products to the solr index. * <p> * This is faster than reflushing the index each time. */ public static Map<String, Object> addListToSolrIndex(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { HttpSolrClient client = null; Map<String, Object> result; Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal"); try { Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(); // Construct Documents List<Map<String, Object>> fieldList = UtilGenerics.<Map<String, Object>> checkList(context.get("fieldList")); Debug.logInfo("Solr: Generating and adding " + fieldList.size() + " documents to solr index", module); for (Iterator<Map<String, Object>> fieldListIterator = fieldList.iterator(); fieldListIterator.hasNext();) { SolrInputDocument doc1 = SolrUtil.generateSolrDocument(fieldListIterator.next()); if (Debug.verboseOn()) { Debug.logVerbose("Solr: Indexing document: " + doc1.toString(), module); } docs.add(doc1); } // push Documents to server if (UtilValidate.isNotEmpty(context.get("core"))) client = new HttpSolrClient(SolrUtil.solrUrl + "/" + context.get("core")); else client = new HttpSolrClient(SolrUtil.solrFullUrl); client.add(docs); client.commit(); final String statusStr = "Added " + fieldList.size() + " documents to solr index"; Debug.logInfo("Solr: " + statusStr, module); result = ServiceUtil.returnSuccess(statusStr); } catch (MalformedURLException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "urlError"); } catch (SolrServerException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { final String statusStr = "Failure connecting to solr server to commit product list; products not updated"; if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) { Debug.logWarning(e, "Solr: " + statusStr, module); result = ServiceUtil.returnFailure(statusStr); } else { Debug.logError(e, "Solr: " + statusStr, module); result = ServiceUtil.returnError(statusStr); } result.put("errorType", "connectError"); } else { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "solrServerError"); } } catch (IOException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); result.put("errorType", "ioError"); } finally { try { if (UtilValidate.isNotEmpty(client)) client.close(); } catch (IOException e) { result = ServiceUtil.returnError(e.toString()); result.put("errorType", "ioError"); } } return result; } /** * Runs a query on the Solr Search Engine and returns the results. * <p> * This function only returns an object of type QueryResponse, so it is * probably not a good idea to call it directly from within the groovy files * (As a decent example on how to use it, however, use keywordSearch * instead). */ public static Map<String, Object> runSolrQuery(DispatchContext dctx, Map<String, Object> context) { // get Connection HttpSolrClient client = null; Map<String, Object> result; try { if (UtilValidate.isNotEmpty(context.get("core"))) client = new HttpSolrClient(SolrUtil.solrUrl + "/" + context.get("core")); else client = new HttpSolrClient(SolrUtil.solrFullUrl); // create Query Object SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery((String) context.get("query")); // solrQuery.setQueryType("dismax"); boolean faceted = (Boolean) context.get("facet"); if (faceted) { solrQuery.setFacet(faceted); solrQuery.addFacetField("manu"); solrQuery.addFacetField("cat"); solrQuery.setFacetMinCount(1); solrQuery.setFacetLimit(8); solrQuery.addFacetQuery("listPrice:[0 TO 50]"); solrQuery.addFacetQuery("listPrice:[50 TO 100]"); solrQuery.addFacetQuery("listPrice:[100 TO 250]"); solrQuery.addFacetQuery("listPrice:[250 TO 500]"); solrQuery.addFacetQuery("listPrice:[500 TO 1000]"); solrQuery.addFacetQuery("listPrice:[1000 TO 2500]"); solrQuery.addFacetQuery("listPrice:[2500 TO 5000]"); solrQuery.addFacetQuery("listPrice:[5000 TO 10000]"); solrQuery.addFacetQuery("listPrice:[10000 TO 50000]"); solrQuery.addFacetQuery("listPrice:[50000 TO *]"); } boolean spellCheck = (Boolean) context.get("spellcheck"); if (spellCheck) { solrQuery.setParam("spellcheck", spellCheck); } boolean highLight = (Boolean) context.get("highlight"); if (highLight) { solrQuery.setHighlight(highLight); solrQuery.setHighlightSimplePre("<span class=\"highlight\">"); solrQuery.addHighlightField("description"); solrQuery.setHighlightSimplePost("</span>"); solrQuery.setHighlightSnippets(2); } // Set additional Parameter // SolrQuery.ORDER order = SolrQuery.ORDER.desc; if (context.get("viewIndex") != null && (Integer) context.get("viewIndex") > 0) { solrQuery.setStart((Integer) context.get("viewIndex")); } if (context.get("viewSize") != null && (Integer) context.get("viewSize") > 0) { solrQuery.setRows((Integer) context.get("viewSize")); } // if ((List) context.get("queryFilter") != null && // ((ArrayList<SolrDocument>) context.get("queryFilter")).size() > // List filter = (List) context.get("queryFilter"); // String[] tn = new String[filter.size()]; // Iterator it = filter.iterator(); // for (int i = 0; i < filter.size(); i++) { // tn[i] = (String) filter.get(i); // solrQuery.setFilterQueries(tn); String queryFilter = (String) context.get("queryFilter"); if (UtilValidate.isNotEmpty(queryFilter)) solrQuery.setFilterQueries(queryFilter.split(" ")); if ((String) context.get("returnFields") != null) { solrQuery.setFields((String) context.get("returnFields")); } // if((Boolean)context.get("sortByReverse"))order.reverse(); if ((String) context.get("sortBy") != null && ((String) context.get("sortBy")).length() > 0) { SolrQuery.ORDER order; if (!((Boolean) context.get("sortByReverse"))) order = SolrQuery.ORDER.asc; else order = SolrQuery.ORDER.desc; solrQuery.setSort(((String) context.get("sortBy")).replaceFirst("-", ""), order); } if ((String) context.get("facetQuery") != null) { solrQuery.addFacetQuery((String) context.get("facetQuery")); } QueryResponse rsp = client.query(solrQuery, METHOD.POST); result = ServiceUtil.returnSuccess(); result.put("queryResult", rsp); } catch (Exception e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } return result; } /** * Performs solr products search. */ public static Map<String, Object> productsSearch(DispatchContext dctx, Map<String, Object> context) { Map<String, Object> result; LocalDispatcher dispatcher = dctx.getDispatcher(); try { Map<String, Object> dispatchMap = FastMap.newInstance(); if (UtilValidate.isNotEmpty(context.get("productCategoryId"))) { String productCategoryId = (String) context.get("productCategoryId"); dispatchMap.put("query", "cat:*" + productCategoryId + "*"); } else return ServiceUtil.returnError("Missing product category id"); if (context.get("viewSize") != null) dispatchMap.put("viewSize", Integer.parseInt(((String) context.get("viewSize")))); if (context.get("viewIndex") != null) dispatchMap.put("viewIndex", Integer.parseInt((String) context.get("viewIndex"))); if (context.get("queryFilter") != null) dispatchMap.put("queryFilter", context.get("queryFilter")); dispatchMap.put("facet", false); dispatchMap.put("spellcheck", true); dispatchMap.put("highlight", true); Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap); QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult"); result = ServiceUtil.returnSuccess(); result.put("results", queryResult.getResults()); result.put("listSize", queryResult.getResults().getNumFound()); result.put("viewIndex", queryResult.getResults().getStart()); result.put("viewSize", queryResult.getResults().size()); } catch (Exception e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } return result; } /** * Performs keyword search. * <p> * The search form requires the result to be in a specific layout, so this * will generate the proper results. */ public static Map<String, Object> keywordSearch(DispatchContext dctx, Map<String, Object> context) { Map<String, Object> result; LocalDispatcher dispatcher = dctx.getDispatcher(); try { if (context.get("query") == null || context.get("query").equals("")) context.put("query", "*:*"); Map<String, Object> dispatchMap = FastMap.newInstance(); if (context.get("viewSize") != null) dispatchMap.put("viewSize", Integer.parseInt(((String) context.get("viewSize")))); if (context.get("viewIndex") != null) dispatchMap.put("viewIndex", Integer.parseInt((String) context.get("viewIndex"))); if (context.get("query") != null) dispatchMap.put("query", context.get("query")); if (context.get("queryFilter") != null) dispatchMap.put("queryFilter", context.get("queryFilter")); dispatchMap.put("spellcheck", true); Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap); QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult"); List<List<String>> suggestions = FastList.newInstance(); if (queryResult.getSpellCheckResponse() != null && queryResult.getSpellCheckResponse().getSuggestions() != null) { Iterator<Suggestion> iter = queryResult.getSpellCheckResponse().getSuggestions().iterator(); while (iter.hasNext()) { Suggestion resultDoc = iter.next(); Debug.logInfo("Suggestion " + resultDoc.getAlternatives(), module); suggestions.add(resultDoc.getAlternatives()); } } Boolean isCorrectlySpelled = true; if (queryResult.getSpellCheckResponse() != null) { isCorrectlySpelled = queryResult.getSpellCheckResponse().isCorrectlySpelled(); } result = ServiceUtil.returnSuccess(); result.put("isCorrectlySpelled", isCorrectlySpelled); Map<String, Integer> facetQuery = queryResult.getFacetQuery(); Map<String, String> facetQueries = FastMap.newInstance(); for (String fq : facetQuery.keySet()) { if (facetQuery.get(fq).intValue() > 0) facetQueries.put(fq, fq.replaceAll("^.*\\u005B(.*)\\u005D", "$1") + " (" + facetQuery.get(fq).intValue() + ")"); } Map<String, Map<String, Long>> facetFields = FastMap.newInstance(); List<FacetField> facets = queryResult.getFacetFields(); for (FacetField facet : facets) { Map<String, Long> facetEntry = FastMap.newInstance(); List<FacetField.Count> facetEntries = facet.getValues(); if (UtilValidate.isNotEmpty(facetEntries)) { for (FacetField.Count fcount : facetEntries) facetEntry.put(fcount.getName(), fcount.getCount()); facetFields.put(facet.getName(), facetEntry); } } result.put("results", queryResult.getResults()); result.put("facetFields", facetFields); result.put("facetQueries", facetQueries); result.put("queryTime", queryResult.getElapsedTime()); result.put("listSize", queryResult.getResults().getNumFound()); result.put("viewIndex", queryResult.getResults().getStart()); result.put("viewSize", queryResult.getResults().size()); result.put("suggestions", suggestions); } catch (Exception e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } return result; } /** * Returns a map of the categories currently available under the root * element. */ public static Map<String, Object> getAvailableCategories(DispatchContext dctx, Map<String, Object> context) { Map<String, Object> result; try { boolean displayProducts = false; if (UtilValidate.isNotEmpty(context.get("displayProducts"))) displayProducts = (Boolean) context.get("displayProducts"); int viewIndex = 0; int viewSize = 9; if (displayProducts) { viewIndex = (Integer) context.get("viewIndex"); viewSize = (Integer) context.get("viewSize"); } String catalogId = null; if (UtilValidate.isNotEmpty(context.get("catalogId"))) catalogId = (String) context.get("catalogId"); List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail")); // String productCategoryId = (String) // context.get("productCategoryId") != null ? // CategoryUtil.getCategoryNameWithTrail((String) // context.get("productCategoryId"), dctx, currentTrail): null; String productCategoryId = (String) context.get("productCategoryId") != null ? CategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"), dctx, currentTrail) : null; Debug.logInfo("productCategoryId " + productCategoryId, module); Map<String, Object> query = SolrUtil.categoriesAvailable(catalogId, productCategoryId, (String) context.get("productId"), displayProducts, viewIndex, viewSize); QueryResponse cat = (QueryResponse) query.get("rows"); result = ServiceUtil.returnSuccess(); result.put("numFound", (long) 0); Map<String, Object> categories = FastMap.newInstance(); List<FacetField> catList = (List<FacetField>) cat.getFacetFields(); for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) { FacetField field = (FacetField) catIterator.next(); List<Count> catL = (List<Count>) field.getValues(); if (catL != null) { // log.info("FacetFields = "+catL); for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) { FacetField.Count f = (FacetField.Count) catIter.next(); if (f.getCount() > 0) { categories.put(f.getName(), Long.toString(f.getCount())); } } result.put("categories", categories); result.put("numFound", cat.getResults().getNumFound()); // log.info("The returned map is this:"+result); } } } catch (Exception e) { result = ServiceUtil.returnError(e.toString()); result.put("numFound", (long) 0); } return result; } /** * Return a map of the side deep categories. */ public static Map<String, Object> getSideDeepCategories(DispatchContext dctx, Map<String, Object> context) { Map<String, Object> result; try { String catalogId = null; if (UtilValidate.isNotEmpty(context.get("catalogId"))) catalogId = (String) context.get("catalogId"); List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail")); String productCategoryId = (String) context.get("productCategoryId") != null ? CategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"), dctx, currentTrail) : null; result = ServiceUtil.returnSuccess(); Map<String, List<Map<String, Object>>> catLevel = FastMap.newInstance(); Debug.logInfo("productCategoryId: " + productCategoryId, module); // Add toplevel categories String[] trailElements = productCategoryId.split("/"); long numFound = 0; // iterate over actual results for (String elements : trailElements) { Debug.logInfo("elements: " + elements, module); String categoryPath = CategoryUtil.getCategoryNameWithTrail(elements, dctx, currentTrail); String[] categoryPathArray = categoryPath.split("/"); int level = Integer.parseInt(categoryPathArray[0]); String facetQuery = CategoryUtil.getFacetFilterForCategory(categoryPath, dctx); // Debug.logInfo("categoryPath: "+categoryPath + " // facetQuery: "+facetQuery,module); Map<String, Object> query = SolrUtil.categoriesAvailable(catalogId, categoryPath, null, facetQuery, false, 0, 0); QueryResponse cat = (QueryResponse) query.get("rows"); List<Map<String, Object>> categories = FastList.newInstance(); List<FacetField> catList = (List<FacetField>) cat.getFacetFields(); for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) { FacetField field = (FacetField) catIterator.next(); List<Count> catL = (List<Count>) field.getValues(); if (catL != null) { for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) { FacetField.Count f = (FacetField.Count) catIter.next(); if (f.getCount() > 0) { Map<String, Object> catMap = FastMap.newInstance(); FastList<String> iName = FastList.newInstance(); iName.addAll(Arrays.asList(f.getName().split("/"))); // Debug.logInfo("topLevel "+topLevel,""); // int l = Integer.parseInt((String) // iName.getFirst()); catMap.put("catId", iName.getLast()); iName.removeFirst(); String path = f.getName(); catMap.put("path", path); if (level > 0) { iName.removeLast(); catMap.put("parentCategory", StringUtils.join(iName, "/")); } else { catMap.put("parentCategory", null); } catMap.put("count", Long.toString(f.getCount())); numFound += f.getCount(); categories.add(catMap); } } } } catLevel.put("menu-" + level, categories); } result.put("categories", catLevel); result.put("numFound", numFound); } catch (Exception e) { result = ServiceUtil.returnError(e.toString()); result.put("numFound", (long) 0); } return result; } /** * Rebuilds the solr index. */ public static Map<String, Object> rebuildSolrIndex(DispatchContext dctx, Map<String, Object> context) throws GenericEntityException { HttpSolrClient client = null; Map<String, Object> result; GenericDelegator delegator = (GenericDelegator) dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = new Locale("de_DE"); Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal"); try { if (UtilValidate.isNotEmpty(context.get("core"))) client = new HttpSolrClient(SolrUtil.solrUrl + "/" + context.get("core")); else client = new HttpSolrClient(SolrUtil.solrFullUrl); // now lets fetch all products List<Map<String, Object>> solrDocs = FastList.newInstance(); List<GenericValue> products = delegator.findList("Product", null, null, null, null, true); int numDocs = 0; if (products != null) { numDocs = products.size(); } Debug.logInfo("Solr: Clearing solr index and rebuilding with " + numDocs + " found products", module); Iterator<GenericValue> productIterator = products.iterator(); while (productIterator.hasNext()) { GenericValue product = productIterator.next(); Map<String, Object> dispatchContext = ProductUtil.getProductContent(product, dctx, context); solrDocs.add(dispatchContext); } // this removes everything from the index client.deleteByQuery("*:*"); client.commit(); // THis adds all products to the Index (instantly) Map<String, Object> runResult = dispatcher.runSync("addListToSolrIndex", UtilMisc.toMap("fieldList", solrDocs, "userLogin", userLogin, "locale", locale, "treatConnectErrorNonFatal", treatConnectErrorNonFatal)); String runMsg = ServiceUtil.getErrorMessage(runResult); if (UtilValidate.isEmpty(runMsg)) { runMsg = null; } if (ServiceUtil.isError(runResult)) { result = ServiceUtil.returnError(runMsg); } else if (ServiceUtil.isFailure(runResult)) { result = ServiceUtil.returnFailure(runMsg); } else { final String statusMsg = "Cleared solr index and reindexed " + numDocs + " documents"; result = ServiceUtil.returnSuccess(statusMsg); } } catch (MalformedURLException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (SolrServerException e) { if (e.getCause() != null && e.getCause() instanceof ConnectException) { final String statusStr = "Failure connecting to solr server to rebuild index; index not updated"; if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) { Debug.logWarning(e, "Solr: " + statusStr, module); result = ServiceUtil.returnFailure(statusStr); } else { Debug.logError(e, "Solr: " + statusStr, module); result = ServiceUtil.returnError(statusStr); } } else { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } } catch (IOException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (ServiceAuthException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (ServiceValidationException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (GenericServiceException e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } catch (Exception e) { Debug.logError(e, e.getMessage(), module); result = ServiceUtil.returnError(e.toString()); } return result; } }
package ee.ioc.phon.android.speak; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.RemoteException; import android.preference.PreferenceManager; import android.speech.RecognitionService; import android.speech.SpeechRecognizer; import com.koushikdutta.async.callback.CompletedCallback; import com.koushikdutta.async.http.AsyncHttpClient; import com.koushikdutta.async.http.WebSocket; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeoutException; public class WebSocketRecognizer extends RecognitionService { private static final String PROTOCOL = ""; private static final String WS_ARGS = "?content-type=audio/x-raw,+layout=(string)interleaved,+rate=(int)16000,+format=(string)S16LE,+channels=(int)1"; private static final int MSG_RESULT = 1; private static final int MSG_ERROR = 2; private RawAudioRecorder mRecorder; private RecognitionService.Callback mListener; private MyHandler mMyHandler; private volatile Looper mSendLooper; private volatile Handler mSendHandler; private Handler mVolumeHandler = new Handler(); private Runnable mSendTask; private Runnable mShowVolumeTask; private WebSocket mWebSocket; public void onDestroy() { super.onDestroy(); onCancel0(); } /** * Opens the socket and starts recording and sending the recorded packages. */ @Override protected void onStartListening(final Intent recognizerIntent, RecognitionService.Callback listener) { Log.i("onStartListening"); mListener = listener; mMyHandler = new MyHandler(this, listener, recognizerIntent.getBooleanExtra(Extras.EXTRA_UNLIMITED_DURATION, false), recognizerIntent.getBooleanExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, false) ); try { onReadyForSpeech(new Bundle()); startRecord(); onBeginningOfSpeech(); startSocket(getWsServiceUrl(recognizerIntent) + "speech" + WS_ARGS + getQueryParams(recognizerIntent)); } catch (IOException e) { onError(SpeechRecognizer.ERROR_AUDIO); } } /** * Stops the recording and closes the socket. */ @Override protected void onCancel(RecognitionService.Callback listener) { onCancel0(); // Send empty results if recognition is cancelled // TEST: if it works with Google Translate and Slide IT onResults(new Bundle()); } /** * Stops the recording and informs the socket that no more packages are coming. */ @Override protected void onStopListening(RecognitionService.Callback listener) { stopRecording0(); onEndOfSpeech(); } private void stopRecording0() { if (mVolumeHandler != null) mVolumeHandler.removeCallbacks(mShowVolumeTask); if (mRecorder != null) { mRecorder.release(); } } private void onCancel0() { stopRecording0(); if (mSendHandler != null) mSendHandler.removeCallbacks(mSendTask); if (mSendLooper != null) { mSendLooper.quit(); mSendLooper = null; } if (mWebSocket != null && mWebSocket.isOpen()) { mWebSocket.end(); // TODO: or close? } } /** * Starts recording. * * @throws IOException if there was an error, e.g. another app is currently recording */ private void startRecord() throws IOException { mRecorder = new RawAudioRecorder(); if (mRecorder.getState() == RawAudioRecorder.State.ERROR) { throw new IOException(); } if (mRecorder.getState() != RawAudioRecorder.State.READY) { throw new IOException(); } mRecorder.start(); if (mRecorder.getState() != RawAudioRecorder.State.RECORDING) { throw new IOException(); } // Monitor the volume level mShowVolumeTask = new Runnable() { public void run() { if (mRecorder != null) { onRmsChanged(mRecorder.getRmsdb()); mVolumeHandler.postDelayed(this, Constants.TASK_INTERVAL_VOL); } } }; mVolumeHandler.postDelayed(mShowVolumeTask, Constants.TASK_DELAY_VOL); } /** * Opens the socket and starts recording/sending. * * @param url Webservice URL */ private void startSocket(String url) { Log.i(url); AsyncHttpClient.getDefaultInstance().websocket(url, PROTOCOL, new AsyncHttpClient.WebSocketConnectCallback() { @Override public void onCompleted(Exception ex, final WebSocket webSocket) { if (ex != null) { handleException(ex); return; } mWebSocket = webSocket; startSending(webSocket); webSocket.setStringCallback(new WebSocket.StringCallback() { public void onStringAvailable(String s) { Log.i(s); handleResult(s); } }); webSocket.setClosedCallback(new CompletedCallback() { @Override public void onCompleted(Exception ex) { Log.e("ClosedCallback: ", ex); if (ex == null) { handleFinish(); } else { handleException(ex); } } }); webSocket.setEndCallback(new CompletedCallback() { @Override public void onCompleted(Exception ex) { Log.e("EndCallback: ", ex); if (ex == null) { handleFinish(); } else { handleException(ex); } } }); } }); } private void startSending(final WebSocket webSocket) { HandlerThread thread = new HandlerThread("SendHandlerThread", android.os.Process.THREAD_PRIORITY_BACKGROUND); thread.start(); mSendLooper = thread.getLooper(); mSendHandler = new Handler(mSendLooper); // Send chunks to the server mSendTask = new Runnable() { public void run() { if (mRecorder != null) { if (webSocket != null && webSocket.isOpen()) { RawAudioRecorder.State recorderState = mRecorder.getState(); Log.i("Recorder state = " + recorderState); byte[] buffer = mRecorder.consumeRecordingAndTruncate(); // We assume that if only 0 bytes have been recorded then the recording // has finished and we can notify the server with "EOF". if (buffer.length > 0 && recorderState == RawAudioRecorder.State.RECORDING) { Log.i("Sending bytes: " + buffer.length); webSocket.send(buffer); boolean success = mSendHandler.postDelayed(this, Constants.TASK_INTERVAL_IME_SEND); if (!success) { Log.i("mSendHandler.postDelayed returned false"); } } else { Log.i("Sending: EOS"); webSocket.send("EOS"); } } } } }; mSendHandler.postDelayed(mSendTask, Constants.TASK_DELAY_IME_SEND); } private void handleResult(String text) { Message msg = new Message(); msg.what = MSG_RESULT; msg.obj = text; mMyHandler.sendMessage(msg); } private void handleException(Exception error) { Message msg = new Message(); msg.what = MSG_ERROR; msg.obj = error; mMyHandler.sendMessage(msg); } // TODO: call onError(SpeechRecognizer.ERROR_SPEECH_TIMEOUT); if server initiates close // without having received EOS private void handleFinish() { onCancel(mListener); } private void onReadyForSpeech(Bundle bundle) { try { mListener.readyForSpeech(bundle); } catch (RemoteException e) { } } private void onRmsChanged(float rms) { try { mListener.rmsChanged(rms); } catch (RemoteException e) { } } private void onError(int errorCode) { // As soon as there is an error we shut down the socket and the recorder onCancel0(); try { mListener.error(errorCode); } catch (RemoteException e) { } } private void onResults(Bundle bundle) { try { mListener.results(bundle); } catch (RemoteException e) { } } private void onPartialResults(Bundle bundle) { try { mListener.partialResults(bundle); } catch (RemoteException e) { } } private void onBeginningOfSpeech() { try { mListener.beginningOfSpeech(); } catch (RemoteException e) { } } private void onEndOfSpeech() { try { mListener.endOfSpeech(); } catch (RemoteException e) { } } private String getWsServiceUrl(Intent intent) { String url = intent.getStringExtra(Extras.EXTRA_SERVER_URL); if (url == null) { return Utils.getPrefString( PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()), getResources(), R.string.keyServerWs, R.string.defaultServerWs); } return url; } /** * Extracts the editor info, and uses * ChunkedWebRecSessionBuilder to extract some additional extras. * TODO: unify this better */ private String getQueryParams(Intent intent) { List<BasicNameValuePair> list = new ArrayList<>(); flattenBundle("editorInfo_", list, intent.getBundleExtra(Extras.EXTRA_EDITOR_INFO)); try { ChunkedWebRecSessionBuilder builder = new ChunkedWebRecSessionBuilder(this, intent.getExtras(), null); if (Log.DEBUG) Log.i(builder.toStringArrayList()); // TODO: review these parameter names listAdd(list, "lang", builder.getLang()); listAdd(list, "lm", toString(builder.getGrammarUrl())); listAdd(list, "output-lang", builder.getGrammarTargetLang()); listAdd(list, "user-agent", builder.getUserAgentComment()); listAdd(list, "calling-package", builder.getCaller()); listAdd(list, "user-id", builder.getDeviceId()); listAdd(list, "partial", "" + builder.isPartialResults()); } catch (MalformedURLException e) { } if (list.size() == 0) { return ""; } return "&" + URLEncodedUtils.format(list, "utf-8"); } private static boolean listAdd(List<BasicNameValuePair> list, String key, String value) { if (value == null || value.length() == 0) { return false; } return list.add(new BasicNameValuePair(key, value)); } private static void flattenBundle(String prefix, List<BasicNameValuePair> list, Bundle bundle) { if (bundle != null) { for (String key : bundle.keySet()) { Object value = bundle.get(key); if (value != null) { if (value instanceof Bundle) { flattenBundle(prefix + key + "_", list, (Bundle) value); } else { list.add(new BasicNameValuePair(prefix + key, toString(value))); } } } } } private static Bundle toBundle(ArrayList<String> hypotheses, boolean isFinal) { Bundle bundle = new Bundle(); bundle.putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, hypotheses); bundle.putBoolean(Extras.EXTRA_SEMI_FINAL, isFinal); return bundle; } // TODO: replace by a built-in private static String toString(Object obj) { if (obj == null) { return null; } return obj.toString(); } private static class MyHandler extends Handler { private final WeakReference<WebSocketRecognizer> mRef; private final RecognitionService.Callback mCallback; private final boolean mIsUnlimitedDuration; private final boolean mIsPartialResults; public MyHandler(WebSocketRecognizer c, RecognitionService.Callback callback, boolean isUnlimitedDuration, boolean isPartialResults) { mRef = new WeakReference<WebSocketRecognizer>(c); mCallback = callback; mIsUnlimitedDuration = isUnlimitedDuration; mIsPartialResults = isPartialResults; } @Override public void handleMessage(Message msg) { WebSocketRecognizer outerClass = mRef.get(); if (outerClass != null) { if (msg.what == MSG_ERROR) { Exception e = (Exception) msg.obj; if (e instanceof TimeoutException) { outerClass.onError(SpeechRecognizer.ERROR_NETWORK_TIMEOUT); } else { outerClass.onError(SpeechRecognizer.ERROR_NETWORK); } } else if (msg.what == MSG_RESULT) { try { WebSocketResponse response = new WebSocketResponse((String) msg.obj); int statusCode = response.getStatus(); if (statusCode == WebSocketResponse.STATUS_SUCCESS && response.isResult()) { WebSocketResponse.Result responseResult = response.parseResult(); if (responseResult.isFinal()) { ArrayList<String> hypotheses = responseResult.getHypothesesPp(); if (hypotheses == null || hypotheses.isEmpty()) { Log.i("Empty final result (" + hypotheses + "), stopping"); outerClass.onError(SpeechRecognizer.ERROR_SPEECH_TIMEOUT); } else { // We stop listening unless the caller explicitly asks us to carry on, // by setting EXTRA_UNLIMITED_DURATION=true if (mIsUnlimitedDuration) { outerClass.onPartialResults(toBundle(hypotheses, true)); } else { outerClass.onStopListening(mCallback); outerClass.onResults(toBundle(hypotheses, true)); } } } else { // We fire this only if the caller wanted partial results if (mIsPartialResults) { ArrayList<String> hypotheses = responseResult.getHypothesesPp(); if (hypotheses == null || hypotheses.isEmpty()) { Log.i("Empty non-final result (" + hypotheses + "), ignoring"); } else { outerClass.onPartialResults(toBundle(hypotheses, false)); } } } } else if (statusCode == WebSocketResponse.STATUS_SUCCESS) { // TODO: adaptation_state currently not handled } else if (statusCode == WebSocketResponse.STATUS_ABORTED) { outerClass.onError(SpeechRecognizer.ERROR_SERVER); } else if (statusCode == WebSocketResponse.STATUS_NOT_AVAILABLE) { outerClass.onError(SpeechRecognizer.ERROR_RECOGNIZER_BUSY); } else if (statusCode == WebSocketResponse.STATUS_NO_SPEECH) { outerClass.onError(SpeechRecognizer.ERROR_SPEECH_TIMEOUT); } else { // Server sent unsupported status code, client should be updated outerClass.onError(SpeechRecognizer.ERROR_CLIENT); } } catch (WebSocketResponse.WebSocketResponseException e) { // This results from a syntactically incorrect server response object Log.e((String) msg.obj, e); outerClass.onError(SpeechRecognizer.ERROR_SERVER); } } } } } }
package com.denizugur.ninegagsaver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class fetchGAG { private String Title = null; private String photoURL = null; private String url; private String ID; private String Likes; private String Comments; private int Height; public String getURL() { return url; } public void setURL(String string) { this.url = string; } public String getPhotoURL() { return photoURL; } public String getTitle() { return Title; } public int getHeightImage() { return Height; } public String getLikes() { return Likes; } public String getComments() { return Comments; } public String getID() { return ID; } public void fetch() { if (url != null) { fetchRunnable fr = new fetchRunnable(); Thread t = new Thread(fr); Log.d(t.getName(), "Fetch started"); try { t.start(); t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } private class fetchRunnable implements Runnable { public void run() { try { Document doc = Jsoup.connect(url).timeout(0).get(); Elements elementImage = doc.select("meta[property=og:image]"); Elements elementTitle = doc.select("meta[property=og:title]"); Elements elementComments = doc.select("span[class=badge-item-comment-count]"); Elements elementLikes = doc.select("span[class=badge-item-love-count]"); Elements elementGif = doc.select("div[data-mp4]"); if (!elementGif.isEmpty()) { Height = 0; return; } photoURL = elementImage.attr("content"); Title = elementTitle.attr("content"); URL urlID = new URL(url); String path = urlID.getPath(); ID = path.substring(path.lastIndexOf('/') + 1); Comments = elementComments.html(); Likes = elementLikes.html(); Log.d("GAG", ID + " " + Likes + " " + Comments); URL urlPhoto = new URL(photoURL); HttpURLConnection connection = (HttpURLConnection) urlPhoto.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); Height = myBitmap.getHeight(); } catch (Exception e) { e.printStackTrace(); } } } }
package com.androidsx.rateme; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Intent; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RatingBar; import com.androidsx.libraryrateme.R; public class DialogRateMe extends DialogFragment { private static final String TAG = DialogRateMe.class.getSimpleName(); private static final String EXTRA_PACKAGE_NAME = "package-name"; private static final String MARKET_CONSTANT = "market://details?id="; private static final String GOOGLE_PLAY_CONSTANT = "http://play.google.com/store/apps/details?id="; private String appPackageName; private View mView; private View tView; private Button close; private RatingBar ratingBar; private LayerDrawable stars; private Button rateMe; private Button noThanks; private Button share; public static DialogRateMe newInstance(String packageName) { DialogRateMe dialogo = new DialogRateMe(); Bundle args = new Bundle(); args.putString(EXTRA_PACKAGE_NAME, packageName); dialogo.setArguments(args); return dialogo; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { appPackageName = getArguments().getString(EXTRA_PACKAGE_NAME); initializeUiFields(); Log.d(TAG, "initialize correctly all the components"); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP); ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { if (rating >= 4.0) { rateMe.setVisibility(View.VISIBLE); noThanks.setVisibility(View.GONE); } else { noThanks.setVisibility(View.VISIBLE); rateMe.setVisibility(View.GONE); } } }); configureButtons(); close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); CustomShowDialog.clearSharedPreferences(getActivity()); Log.d(TAG, "clear preferences"); } }); share.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(shareApp(appPackageName)); Log.d(TAG, "share App"); } }); return builder.setView(mView).setCustomTitle(tView).setCancelable(false).create(); } private void initializeUiFields() { mView = getActivity().getLayoutInflater().inflate(R.layout.library, null); tView = getActivity().getLayoutInflater().inflate(R.layout.title, null); close = (Button) tView.findViewById(R.id.buttonClose); share = (Button) tView.findViewById(R.id.buttonShare); rateMe = (Button) mView.findViewById(R.id.buttonRateMe); noThanks = (Button) mView.findViewById(R.id.buttonThanks); ratingBar = (RatingBar) mView.findViewById(R.id.ratingBar); stars = (LayerDrawable) ratingBar.getProgressDrawable(); } private void configureButtons() { rateMe.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { rateApp(); Log.d(TAG, "go to Google Play Store for Rate-Me"); } }); noThanks.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { goToMail(); Log.d(TAG, "got to Mail for explain what is the problem"); } }); } private void rateApp() { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MARKET_CONSTANT + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_CONSTANT + appPackageName))); } } private void goToMail() { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("plain/text"); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "some@email.com" }); intent.putExtra(Intent.EXTRA_SUBJECT, "subject"); intent.putExtra(Intent.EXTRA_TEXT, "mail body"); try { startActivity(Intent.createChooser(intent, "")); } catch (android.content.ActivityNotFoundException ex) { rateApp(); } } private Intent shareApp(String appPackageName) { Intent shareApp = new Intent(); shareApp.setAction(Intent.ACTION_SEND); try { shareApp.putExtra(Intent.EXTRA_TEXT, MARKET_CONSTANT + appPackageName); } catch (android.content.ActivityNotFoundException anfe) { shareApp.putExtra(Intent.EXTRA_TEXT, GOOGLE_PLAY_CONSTANT + appPackageName); } shareApp.setType("text/plain"); return shareApp; } }
package com.soctec.soctec.core; import java.util.ArrayList; import java.util.Locale; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.net.wifi.WifiManager; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.soctec.soctec.R; import com.soctec.soctec.achievements.Achievement; import com.soctec.soctec.achievements.AchievementCreator; import com.soctec.soctec.achievements.AchievementUnlocker; import com.soctec.soctec.achievements.Stats; import com.soctec.soctec.network.ConnectionChecker; import com.soctec.soctec.network.NetworkHandler; import com.soctec.soctec.profile.Profile; import com.soctec.soctec.profile.ProfileActivity; import com.soctec.soctec.profile.ProfileMatchActivity; import com.soctec.soctec.utils.APIHandler; import com.soctec.soctec.utils.Encryptor; import com.soctec.soctec.utils.FileHandler; /** * MainActivity is a tabbed activity, and sets up most of the other objects for the App * @author Jesper, Joakim, David, Carl-Henrik, Robin * @version 1.3 */ public class MainActivity extends AppCompatActivity implements ActionBar.TabListener { SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager; ConnectionChecker connectionChecker = null; private Stats stats; private AchievementCreator creator; private AchievementUnlocker unlocker; private static int REQUEST_CODE = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String account = getPlayAcc(); if(account == null) account = "walla"; //TODO crash and burn (handle this some way...) //Initialize the FileHandler FileHandler.getInstance().setContext(this); //Initialize the Profile String userCode = new Encryptor().encrypt(account); Profile.setUserCode(userCode); Profile.initProfile(); //Initialize the Achievement engine stats = new Stats(); creator = new AchievementCreator(); unlocker = new AchievementUnlocker(stats, creator); creator.addObserver(unlocker); creator.createFromFile(); //Initialize networkHandler. Start server thread NetworkHandler.getInstance().setMyActivity(this); NetworkHandler.getInstance().startThread(); //Initialize the ActionBar setupActionBar(); mViewPager.addOnPageChangeListener(new PageChangeListener()); mViewPager.setCurrentItem(1); //Display help to user. Only on the very first startup SharedPreferences preferences = getSharedPreferences("com.soctec.soctec", MODE_PRIVATE); if (preferences.getBoolean("first_time", true)) { //Do this only the first startup Toast.makeText(getApplicationContext(), "First time ever!", Toast.LENGTH_SHORT).show(); preferences.edit().putBoolean("first_time", false).apply(); } } /** * Initiate the BroadcastReceiver and register it. */ public void startReceiver() { IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver( connectionChecker = new ConnectionChecker(MainActivity.this), intentFilter); Log.i("Main", "Receiver started!"); } /** * Tells ScanActivity to start scanning * @param v currently unused */ public void scanNow (View v) { startActivityForResult( new Intent(getApplicationContext(), ScanActivity.class), REQUEST_CODE); updateAchievementFragment(); } /** * Initiates refresh of AchievementFragment by retrieving the fragment from * mSectionsPagerAdapter and calling the method */ protected void updateAchievementFragment() { AchievementsFragment aF = (AchievementsFragment)mSectionsPagerAdapter.getFragment(2); aF.refreshAchievements(unlocker.getUnlockableAchievements(), stats.getAchievements()); aF.setPoints(stats.getPoints()); } public Stats getStats() { return stats; } /** * Called when an activity started with "startActivityForResult()" has finished. * @param requestCode Indicates which request this method call is a response to * @param resultCode The result of the request * @param data The data from the finished activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == RESULT_OK && requestCode == REQUEST_CODE) { String scannedCode = data.getExtras().getString("result"); NetworkHandler.getInstance().sendScanInfoToPeer(scannedCode); } } @Override protected void onStart() { super.onStart(); //mViewPager.setCurrentItem(1); } /** * Starts NetworkHandler and registers connectionChecker as receiver */ @Override protected void onResume() { super.onResume(); //Start thread that listens for peer connections NetworkHandler.getInstance().startThread(); //Register broadcast receiver that listens for wifi changes IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver(connectionChecker, intentFilter); //Fetch latest rating statistics from server NetworkHandler.getInstance().fetchRatingFromServer(); //Set current tab if (mViewPager.getCurrentItem()== 0) mViewPager.setCurrentItem(1); } /** * Stops NetworkHandler and unregisters connectionChecker as receiver */ @Override protected void onPause() { super.onPause(); NetworkHandler.getInstance().stopThread(); unregisterReceiver(connectionChecker); } /** * Makes sure the application only exits when in main fragment * and back button is pressed. Otherwise switches to main fragment. */ @Override public void onBackPressed() { if (mViewPager.getCurrentItem()==1) super.onBackPressed(); else mViewPager.setCurrentItem(1); } /** * Called by NetworkHandler when data has been received from a peer. * @param idFromPeer The unique ID of the peer * @param profileFromPeer The peer's profile data */ public void receiveDataFromPeer(String idFromPeer, ArrayList<ArrayList<String>> profileFromPeer) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(100); unlocker.receiveEvent(1, idFromPeer); for(Achievement achi : stats.getLastCompleted()) { Intent showerIntent = new Intent(this, AchievementShowerActivity.class); showerIntent.putExtra("AchievementObject", achi); startActivity(showerIntent); } //Match profile stuff Bundle b = new Bundle(); b.putSerializable("list1", Profile.getProfile()); b.putSerializable("list2", profileFromPeer); Intent matchIntent = new Intent(this, ProfileMatchActivity.class); matchIntent.putExtras(b); startActivity(matchIntent); updateAchievementFragment(); ((MainFragment)mSectionsPagerAdapter.getFragment(1)).enableRatingButtons(); } /** * Update the QR image * @param QR */ public void updateQR(Bitmap QR) { Log.i("MainFrag", "Update qr"); ImageView im = (ImageView) findViewById(R.id.qr_image); im.setImageBitmap(QR); } /** * Returns the device's google account name * @return the device's google account name */ private String getPlayAcc() { String accMail = null; AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE); Account[] list = manager.getAccounts(); for(Account account : list) { if(account.type.equalsIgnoreCase("com.google")) //TODO Felhatering vid avsaknad av gmail-konto { accMail = account.name; break; } } return accMail; } public class PageChangeListener implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == 0) { mViewPager.setCurrentItem(0); scanNow(null); //mViewPager.setCurrentItem(1); } } @Override public void onPageScrollStateChanged(int state) { } } /** * Sets up the ActionBar */ private void setupActionBar() { final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for(int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab( actionBar.newTab() .setCustomView(i == 0 ? R.layout.camera_tab_icon : i == 1 ? R.layout.main_tab_icon : R.layout.achievement_tab_icon) .setTabListener(this)); //Set tab icon's width DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int screenWidth = displaymetrics.widthPixels; actionBar.getTabAt(i).getCustomView().getLayoutParams().width = (screenWidth/3) - (2*Math.round(16 * (displaymetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT))); } } @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; } @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(); InfoFragment iFragment = new InfoFragment(); HelpFragment hFragment = new HelpFragment(); //noinspection SimplifiableIfStatement if(id == R.id.action_settings) { return true; } else if(id == R.id.action_profile) { Intent intent = new Intent(this, ProfileActivity.class); startActivity(intent); } else if(id == R.id.about) { iFragment.show(getFragmentManager(), "Om"); } else if (id == R.id.help) { hFragment.show(getFragmentManager(), "Hjälp"); } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { FragmentManager fragmentManager; public SectionsPagerAdapter(FragmentManager fm) { super(fm); fragmentManager = fm; } public Fragment getFragment(int position) { return fragmentManager.getFragments().get(position); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. switch(position) { case 0: return new ScanFragment(); case 1: return new MainFragment(); case 2: return new AchievementsFragment(); } return null; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch(position) { case 0: return getString(R.string.title_section3).toUpperCase(l); case 1: return getString(R.string.title_section1).toUpperCase(l); case 2: return getString(R.string.title_section2).toUpperCase(l); } return null; } public int getIcon(int position) { Locale l = Locale.getDefault(); FileHandler fileHandler = FileHandler.getInstance(); switch(position) { case 0: return fileHandler.getResourceID("camera6", "drawable"); case 1: return fileHandler.getResourceID("qricon", "drawable"); case 2: return fileHandler.getResourceID("trophy", "drawable"); } return 0; } } }
package com.mapswithme.maps.downloader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.os.AsyncTask; import android.util.Log; class DownloadChunkTask extends AsyncTask<Void, byte [], Boolean> { private static final String TAG = "DownloadChunkTask"; private long m_httpCallbackID; private String m_url; private long m_beg; private long m_end; private long m_expectedFileSize; private String m_postBody; private String m_userAgent; private final int NOT_SET = -1; private final int IO_ERROR = -2; private final int INVALID_URL = -3; private int m_httpErrorCode = NOT_SET; private long m_downloadedBytes = 0; native void onWrite(long httpCallbackID, long beg, byte [] data, long size); native void onFinish(long httpCallbackID, long httpCode, long beg, long end); public DownloadChunkTask(long httpCallbackID, String url, long beg, long end, long expectedFileSize, String postBody, String userAgent) { m_httpCallbackID = httpCallbackID; m_url = url; m_beg = beg; m_end = end; m_expectedFileSize = expectedFileSize; m_postBody = postBody; m_userAgent = userAgent; } @Override protected void onPreExecute() { } @Override protected void onPostExecute(Boolean success) { if (success) onFinish(m_httpCallbackID, 200, m_beg, m_end); } @Override protected void onCancelled() { // Report error in callback only if we're not forcibly canceled if (m_httpErrorCode != NOT_SET) onFinish(m_httpCallbackID, m_httpErrorCode, m_beg, m_end); } @Override protected void onProgressUpdate(byte []... data) { if (!isCancelled()) { // Use progress event to save downloaded bytes onWrite(m_httpCallbackID, m_beg + m_downloadedBytes, data[0], data[0].length); m_downloadedBytes += data[0].length; } } void start() { execute(); } @Override protected Boolean doInBackground(Void... p) { URL url; HttpURLConnection urlConnection = null; try { url = new URL(m_url); urlConnection = (HttpURLConnection) url.openConnection(); if (isCancelled()) return false; urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(15 * 1000); urlConnection.setReadTimeout(15 * 1000); // Set user agent with unique client id urlConnection.setRequestProperty("User-Agent", m_userAgent); // use Range header only if we don't download whole file from start if (!(m_beg == 0 && m_end < 0)) { if (m_end > 0) urlConnection.setRequestProperty("Range", String.format("bytes=%d-%d", m_beg, m_end)); else urlConnection.setRequestProperty("Range", String.format("bytes=%d-", m_beg)); } if (m_postBody.length() > 0) { urlConnection.setDoOutput(true); byte[] utf8 = m_postBody.getBytes("UTF-8"); urlConnection.setFixedLengthStreamingMode(utf8.length); final DataOutputStream os = new DataOutputStream(urlConnection.getOutputStream()); os.write(utf8); os.flush(); } if (isCancelled()) return false; final int err = urlConnection.getResponseCode(); if (err != HttpURLConnection.HTTP_OK && err != HttpURLConnection.HTTP_PARTIAL) { // we've set error code so client should be notified about the error m_httpErrorCode = err; cancel(false); return false; } final InputStream is = urlConnection.getInputStream(); byte [] tempBuf = new byte[1024 * 64]; long readBytes; while ((readBytes = is.read(tempBuf)) != -1) { if (isCancelled()) return false; byte [] chunk = new byte[(int)readBytes]; System.arraycopy(tempBuf, 0, chunk, 0, (int)readBytes); publishProgress(chunk); } } catch (MalformedURLException ex) { Log.d(TAG, "invalid url: " + m_url); // Notify the client about error m_httpErrorCode = INVALID_URL; cancel(false); } catch (IOException ex) { Log.d(TAG, "ioexception: " + ex.toString()); // Notify the client about error m_httpErrorCode = IO_ERROR; cancel(false); } finally { if (urlConnection != null) urlConnection.disconnect(); } return true; } }
package com.x1unix.avi; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.kinopoisk.Constants; import com.x1unix.avi.model.KPMovie; import com.x1unix.avi.model.KPMovieDetailViewResponse; import com.x1unix.avi.model.KPPeople; import com.x1unix.avi.rest.KPApiInterface; import com.x1unix.avi.rest.KPRestClient; import com.x1unix.avi.storage.MoviesRepository; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MovieDetailsActivity extends AppCompatActivity implements View.OnClickListener { private Intent args; private String movieId; private String movieTitle; private String movieGenre; private String movieDescription; private String movieRating; private ActionBar actionBar; private KPApiInterface client; private String currentLocale; private ImageButton btnAddToBookmarks; private ImageButton btnRmFromBookmarks; private Button btnWatchMovie; private Button btnRetry; private MoviesRepository moviesRepository; private String LOG_TAG = "MovieDetailsActivity"; private boolean isCached = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_details); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } moviesRepository = MoviesRepository.getInstance(this); extractIntentData(); setBasicMovieInfo(); currentLocale = getResources().getConfiguration().locale.getLanguage(); // Get movie info if (moviesRepository.movieExists(movieId)) { Log.d(LOG_TAG, "#" + movieId + " Cached!"); // Import data from cache KPMovie movie = moviesRepository.getMovieById(movieId); applyMovieData(movie, false); isCached = true; } else { Log.d(LOG_TAG, "#" + movieId +" No data in cache"); getFullMovieInfo(); } // Init UI elements initUIElements(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } private void initUIElements() { btnAddToBookmarks = (ImageButton) findViewById(R.id.amd_bookmark_add); btnRmFromBookmarks = (ImageButton) findViewById(R.id.amd_bookmark_remove); btnWatchMovie = (Button) findViewById(R.id.amd_btn_watch); btnRetry = (Button) findViewById(R.id.amd_retry); btnWatchMovie.setOnClickListener(this); btnAddToBookmarks.setOnClickListener(this); btnRmFromBookmarks.setOnClickListener(this); btnRetry.setOnClickListener(this); } @Override public void onStop() { moviesRepository.close(); moviesRepository = null; super.onStop(); } @Override public void onRestart() { moviesRepository = MoviesRepository.getInstance(this); super.onRestart(); } public void onClick(View v) { switch (v.getId()) { case R.id.amd_btn_watch: watchMovie(); break; case R.id.amd_retry: retry(); break; case R.id.amd_bookmark_add: btnAddToBookmarks.setVisibility(View.GONE); moviesRepository.addToFavorites(movieId); setBookmarkedVisibility(true); showSnackMessage(R.string.added_to_favs); break; case R.id.amd_bookmark_remove: btnRmFromBookmarks.setVisibility(View.GONE); moviesRepository.removeFromFavorites(movieId); setBookmarkedVisibility(false); showSnackMessage(R.string.removed_from_favs); break; default: Toast.makeText(getApplicationContext(), getResources().getString(R.string.feature_not_available), Toast.LENGTH_LONG).show(); break; } } private void watchMovie() { Intent wmIntent = new Intent(this, MoviePlayerActivity.class); // Put id and title wmIntent.putExtra("movieId", movieId); wmIntent.putExtra("movieTitle", movieTitle); // Kickstart player startActivity(wmIntent); } private void extractIntentData() { args = getIntent(); movieId = args.getStringExtra("movieId"); movieTitle = args.getStringExtra("movieTitle"); movieGenre = args.getStringExtra("movieGenre"); movieDescription = args.getStringExtra("movieDescription"); movieRating = args.getStringExtra("movieRating"); } private void setBasicMovieInfo() { ((TextView) findViewById(R.id.amd_movie_title)).setText(movieTitle); ((TextView) findViewById(R.id.amd_short_desc)).setText(movieDescription); ((TextView) findViewById(R.id.amd_rating)).setText(movieRating); setTitle(movieTitle); Glide.with(getApplicationContext()) .load(Constants.getPosterUrl(movieId)) .placeholder(R.drawable.no_poster) .into((ImageView) findViewById(R.id.amd_movie_poster)); } private void setProgressVisibility(boolean ifShow) { int visible = (ifShow) ? View.VISIBLE : View.GONE; ((ProgressBar) findViewById(R.id.amd_preloader)).setVisibility(visible); } private void setInfoVisibility(boolean ifShow) { int visible = (ifShow) ? View.VISIBLE : View.GONE; ((LinearLayout) findViewById(R.id.amd_movie_info)).setVisibility(visible); } private void setErrVisibility(boolean ifShow) { int visible = (ifShow) ? View.VISIBLE : View.GONE; ((LinearLayout) findViewById(R.id.amd_msg_fail)).setVisibility(visible); } private void setBookmarkedVisibility(boolean ifShow) { btnRmFromBookmarks.setVisibility((ifShow) ? View.VISIBLE : View.GONE); btnAddToBookmarks.setVisibility((!ifShow) ? View.VISIBLE : View.GONE); } private void getFullMovieInfo() { if (client == null) { client = KPRestClient.getClient().create(KPApiInterface.class); } Call<KPMovieDetailViewResponse> call = client.getMovieById(movieId); call.enqueue(new Callback<KPMovieDetailViewResponse>() { @Override public void onResponse(Call<KPMovieDetailViewResponse>call, Response<KPMovieDetailViewResponse> response) { int statusCode = response.code(); KPMovieDetailViewResponse result = response.body(); if (result != null) { KPMovie movie = result.getResult(); if (movie == null) { showNoMovieDataMsg(result.getMessage()); } else { applyMovieData(movie); } } } @Override public void onFailure(Call<KPMovieDetailViewResponse>call, Throwable t) { showNoMovieDataMsg(t.toString()); } }); } private void retry() { setErrVisibility(false); setProgressVisibility(true); getFullMovieInfo(); } private void showNoMovieDataMsg(String msg) { // Log error here since request failed setProgressVisibility(false); setErrVisibility(true); String prefix = getResources().getString(R.string.err_movie_info_fetch_fail); Toast.makeText(getApplicationContext(), prefix + " " + msg, Toast.LENGTH_LONG).show(); } private void applyMovieData(final KPMovie movie, boolean cacheItem) { setProgressVisibility(false); // Main Info ((TextView) findViewById(R.id.amd_description)).setText(movie.getDescription()); ((TextView) findViewById(R.id.amd_genre)).setText(movie.getGenre()); ((TextView) findViewById(R.id.amd_age_restrictions)).setText(movie.getRatingMPAA()); ((TextView) findViewById(R.id.amd_year)).setText(movie.getYear()); ((TextView) findViewById(R.id.amd_length)).setText(movie.getFilmLength()); // Artists, etc. setAuthorInfo(movie.getDirectors(), R.id.amd_directors); setAuthorInfo(movie.getActors(), R.id.amd_actors); setAuthorInfo(movie.getProducers(), R.id.amd_producers); // Save movie to the cache if (cacheItem) { moviesRepository.addMovie( movie.setShortDescription(movieDescription).setStars(movieRating) ); } setBookmarkedVisibility(moviesRepository.isInFavorites(movieId)); setInfoVisibility(true); } private void applyMovieData(final KPMovie movie) { applyMovieData(movie, true); } private void setAuthorInfo(KPPeople[] src, int targetId) { String val = "-"; if(src.length > 0) { val = ""; for(int c = 0; c < src.length; c++) { String name = src[c].getName(currentLocale); if (name != null) { val += src[c].getName(currentLocale); if (c < (src.length - 1)) { val += ", "; } } } } ((TextView) findViewById(targetId)).setText(val); } private void showSnackMessage(int stringId) { Snackbar.make(findViewById(android.R.id.content), getResources().getString(stringId), Snackbar.LENGTH_LONG).show(); } }
public class Event { private Random e_calc; private int choice; private AttackEngine encounter; private int event; // Type of event private Character player; public void EventCalc(int x, String charName){ encounter = new AttackEngine(charName); switch(x){ case 1: H.pln("You are stuck in quicksand!"); H.pln("You lost 30 health!"); player.setCHealth(player.getHealth-30); break; case 2: H.pln("You are in a Forest!"); e_calc = new Random(); event = e_calc.nextInt(99)+1; if(event>0 && event<60){ //Finiding an enemy (60% chance) encounter.Battle(); } if(event>=61 && event<=90){ //30% chance of nothing H.pln("Nothing here seems out of the ordinary."); } if(event>=91 && event<=95){ //5% chance of finding extra XP H.pln("You found a book"); H.pln("It looks old an is hard to read."); H.pln("However after figuring out the symbols"); H.pln("You have learned valuable skills"); H.pln("You gained 500 XP!"); player.addXP(500); } if(event>=96 && event<=100){ //Need to make changes to character class and //allow hasmap to be seen in //this class } break; case 3: H.pln("You have found a pond."); H.pln("All seems quiet ad nd peaceful."); H.pln("You have regained 30 Health!"); player.setCHealth(player.getCHealth+30); break; case 4: H.pln("You are on a field"); H.pln("There is a person on the Horizon."); H.pln("Would you like to : (1)Attack or (2)Ignore and Keep Moving?"); choice = H.input(); if(choice<= 1 || choice >2){ ecounter.Battle(); } else{ H.pln("You and the person pass by without"); H.pln("either of you intending to attack"); } break; } } }
package org.appcelerator.titanium.view; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.Log; import org.appcelerator.titanium.util.TiAnimationBuilder; import org.appcelerator.titanium.util.TiAnimationBuilder.TiMatrixAnimation; import org.appcelerator.titanium.util.TiConfig; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout.LayoutParams; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; public abstract class TiUIView implements KrollProxyListener, OnFocusChangeListener { private static final String LCAT = "TiUIView"; private static final boolean DBG = TiConfig.LOGD; private static AtomicInteger idGenerator; public static final int SOFT_KEYBOARD_DEFAULT_ON_FOCUS = 0; public static final int SOFT_KEYBOARD_HIDE_ON_FOCUS = 1; public static final int SOFT_KEYBOARD_SHOW_ON_FOCUS = 2; protected View nativeView; // Native View object protected TiViewProxy proxy; protected TiViewProxy parent; protected ArrayList<TiUIView> children = new ArrayList<TiUIView>(); protected LayoutParams layoutParams; protected int zIndex; protected TiAnimationBuilder animBuilder; protected TiBackgroundDrawable background; public TiUIView(TiViewProxy proxy) { if (idGenerator == null) { idGenerator = new AtomicInteger(0); } this.proxy = proxy; this.layoutParams = new TiCompositeLayout.LayoutParams(); } public void add(TiUIView child) { if (child != null) { View cv = child.getNativeView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { if (cv.getParent() == null) { ((ViewGroup) nv).addView(cv, child.getLayoutParams()); } children.add(child); } } } } public void remove(TiUIView child) { if (child != null) { View cv = child.getNativeView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { ((ViewGroup) nv).removeView(cv); children.remove(child); } } } } public List<TiUIView> getChildren() { return children; } public TiViewProxy getProxy() { return proxy; } public void setProxy(TiViewProxy proxy) { this.proxy = proxy; } public TiViewProxy getParent() { return parent; } public void setParent(TiViewProxy parent) { this.parent = parent; } public LayoutParams getLayoutParams() { return layoutParams; } public int getZIndex() { return zIndex; } public View getNativeView() { return nativeView; } protected void setNativeView(View view) { if (view.getId() == View.NO_ID) { view.setId(idGenerator.incrementAndGet()); } this.nativeView = view; boolean clickable = true; if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED)); } nativeView.setClickable(clickable); nativeView.setOnFocusChangeListener(this); } protected void setLayoutParams(LayoutParams layoutParams) { this.layoutParams = layoutParams; } protected void setZIndex(int index) { zIndex = index; } public void animate() { TiAnimationBuilder builder = proxy.getPendingAnimation(); if (builder != null && nativeView != null) { AnimationSet as = builder.render(proxy, nativeView); if (DBG) { Log.d(LCAT, "starting animation: "+as); } nativeView.startAnimation(as); // Clean up proxy proxy.clearAnimation(); } } public void listenerAdded(String type, int count, KrollProxy proxy) { } public void listenerRemoved(String type, int count, KrollProxy proxy){ } private boolean hasImage(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); } private boolean hasBorder(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); } private boolean hasColorState(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); } protected void applyTransform(Ti2DMatrix matrix) { layoutParams.optionTransform = matrix; if (animBuilder == null) { animBuilder = new TiAnimationBuilder(); } if (nativeView != null) { if (matrix != null) { TiMatrixAnimation matrixAnimation = animBuilder.createMatrixAnimation(matrix); matrixAnimation.interpolate = false; matrixAnimation.setDuration(1); matrixAnimation.setFillAfter(true); nativeView.startAnimation(matrixAnimation); } else { nativeView.clearAnimation(); } } } protected void layoutNativeView() { if (nativeView != null) { Animation a = nativeView.getAnimation(); if (a != null && a instanceof TiMatrixAnimation) { TiMatrixAnimation matrixAnimation = (TiMatrixAnimation) a; matrixAnimation.invalidateWithMatrix(nativeView); } nativeView.requestLayout(); } } public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_LEFT)) { if (newValue != null) { layoutParams.optionLeft = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_LEFT); } else { layoutParams.optionLeft = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_TOP)) { if (newValue != null) { layoutParams.optionTop = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_TOP); } else { layoutParams.optionTop = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_CENTER)) { TiConvert.updateLayoutCenter(newValue, layoutParams); layoutNativeView(); } else if (key.equals(TiC.PROPERTY_RIGHT)) { if (newValue != null) { layoutParams.optionRight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_RIGHT); } else { layoutParams.optionRight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_BOTTOM)) { if (newValue != null) { layoutParams.optionBottom = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_BOTTOM); } else { layoutParams.optionBottom = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_SIZE)) { if (newValue instanceof KrollDict) { KrollDict d = (KrollDict)newValue; propertyChanged(TiC.PROPERTY_WIDTH, oldValue, d.get(TiC.PROPERTY_WIDTH), proxy); propertyChanged(TiC.PROPERTY_HEIGHT, oldValue, d.get(TiC.PROPERTY_HEIGHT), proxy); }else if (newValue != null){ Log.w(LCAT, "Unsupported property type ("+(newValue.getClass().getSimpleName())+") for key: " + key+". Must be an object/dictionary"); } } else if (key.equals(TiC.PROPERTY_HEIGHT)) { if (newValue != null) { if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionHeight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_HEIGHT); layoutParams.autoHeight = false; } else { layoutParams.optionHeight = null; layoutParams.autoHeight = true; } } else { layoutParams.optionHeight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_WIDTH)) { if (newValue != null) { if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionWidth = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_WIDTH); layoutParams.autoWidth = false; } else { layoutParams.optionWidth = null; layoutParams.autoWidth = true; } } else { layoutParams.optionWidth = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_ZINDEX)) { if (newValue != null) { layoutParams.optionZIndex = TiConvert.toInt(TiConvert.toString(newValue)); } else { layoutParams.optionZIndex = 0; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_FOCUSABLE)) { boolean focusable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_FOCUSABLE)); nativeView.setFocusable(focusable); if (focusable) { registerForKeyClick(nativeView); } else { nativeView.setOnClickListener(null); } } else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) { nativeView.setClickable(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VISIBLE)) { nativeView.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE); } else if (key.equals(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.startsWith(TiC.PROPERTY_BACKGROUND_PADDING)) { Log.i(LCAT, key + " not yet implemented."); } else if (key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX) || key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { // Update first before querying. proxy.setProperty(key, newValue, false); KrollDict d = proxy.getProperties(); boolean hasImage = hasImage(d); boolean hasColorState = hasColorState(d); boolean hasBorder = hasBorder(d); boolean requiresCustomBackground = hasImage || hasColorState || hasBorder; if (!requiresCustomBackground) { if (background != null) { background.releaseDelegate(); background.setCallback(null); background = null; } if (d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_COLOR)) { Integer bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (nativeView != null){ nativeView.setBackgroundColor(bgColor); nativeView.postInvalidate(); } } else { if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue)); } if (nativeView != null) { nativeView.setBackgroundDrawable(null); nativeView.postInvalidate(); } } } else { boolean newBackground = background == null; if (newBackground) { background = new TiBackgroundDrawable(); } Integer bgColor = null; if (!hasColorState) { if (d.get(TiC.PROPERTY_BACKGROUND_COLOR) != null) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (newBackground || (key.equals(TiC.PROPERTY_OPACITY) || key.equals(TiC.PROPERTY_BACKGROUND_COLOR))) { background.setBackgroundColor(bgColor); } } } if (hasImage || hasColorState) { if (newBackground || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)) { handleBackgroundImage(d); } } if (hasBorder) { if (newBackground) { initializeBorder(d, bgColor); } else if (key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { handleBorderProperty(key, newValue); } } applyCustomBackground(); } if (nativeView != null) { nativeView.postInvalidate(); } } else if (key.equals(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) { Log.w(LCAT, "Focus state changed to " + TiConvert.toString(newValue) + " not honored until next focus event."); } else if (key.equals(TiC.PROPERTY_TRANSFORM)) { if (nativeView != null) { applyTransform((Ti2DMatrix)newValue); } } else { if (DBG) { Log.d(LCAT, "Unhandled property key: " + key); } } } public void processProperties(KrollDict d) { if (d.containsKey(TiC.PROPERTY_LAYOUT)) { String layout = TiConvert.toString(d, TiC.PROPERTY_LAYOUT); if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout)nativeView).setLayoutArrangement(layout); } } if (TiConvert.fillLayout(d, layoutParams)) { if (nativeView != null) { nativeView.requestLayout(); } } Integer bgColor = null; // Default background processing. // Prefer image to color. if (hasImage(d) || hasColorState(d) || hasBorder(d)) { handleBackgroundImage(d); } else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR)) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); nativeView.setBackgroundColor(bgColor); } if (d.containsKey(TiC.PROPERTY_OPACITY)) { if (nativeView != null) { setOpacity(TiConvert.toFloat(d, TiC.PROPERTY_OPACITY)); } } if (d.containsKey(TiC.PROPERTY_VISIBLE)) { nativeView.setVisibility(TiConvert.toBoolean(d, TiC.PROPERTY_VISIBLE) ? View.VISIBLE : View.INVISIBLE); } if (d.containsKey(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED)); } if (d.containsKey(TiC.PROPERTY_FOCUSABLE)) { boolean focusable = TiConvert.toBoolean(d, TiC.PROPERTY_FOCUSABLE); nativeView.setFocusable(focusable); if (focusable) { registerForKeyClick(nativeView); } else { nativeView.setOnClickListener(null); } } initializeBorder(d, bgColor); if (d.containsKey(TiC.PROPERTY_TRANSFORM)) { Ti2DMatrix matrix = (Ti2DMatrix) d.get(TiC.PROPERTY_TRANSFORM); if (matrix != null) { applyTransform(matrix); } } } @Override public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy) { for (KrollPropertyChange change : changes) { propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy); } } private void applyCustomBackground() { applyCustomBackground(true); } private void applyCustomBackground(boolean reuseCurrentDrawable) { if (nativeView != null) { if (background == null) { background = new TiBackgroundDrawable(); Drawable currentDrawable = nativeView.getBackground(); if (currentDrawable != null) { if (reuseCurrentDrawable) { background.setBackgroundDrawable(currentDrawable); } else { nativeView.setBackgroundDrawable(null); currentDrawable.setCallback(null); if (currentDrawable instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable) currentDrawable).releaseDelegate(); } } } } nativeView.setBackgroundDrawable(background); } } public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { TiUIHelper.requestSoftInputChange(proxy, v); proxy.fireEvent(TiC.EVENT_FOCUS, getFocusEventObject(hasFocus)); } else { proxy.fireEvent(TiC.EVENT_BLUR, getFocusEventObject(hasFocus)); } } protected KrollDict getFocusEventObject(boolean hasFocus) { return null; } protected InputMethodManager getIMM() { InputMethodManager imm = null; imm = (InputMethodManager) proxy.getTiContext().getTiApp().getSystemService(Context.INPUT_METHOD_SERVICE); return imm; } public void focus() { if (nativeView != null) { nativeView.requestFocus(); } } public void blur() { if (nativeView != null) { InputMethodManager imm = getIMM(); if (imm != null) { imm.hideSoftInputFromWindow(nativeView.getWindowToken(), 0); } nativeView.clearFocus(); } } public void release() { if (DBG) { Log.d(LCAT, "Releasing: " + this); } View nv = getNativeView(); if (nv != null) { if (nv instanceof ViewGroup) { ViewGroup vg = (ViewGroup) nv; if (DBG) { Log.d(LCAT, "Group has: " + vg.getChildCount()); } if (!(vg instanceof AdapterView<?>)) { vg.removeAllViews(); } } Drawable d = nv.getBackground(); if (d != null) { nv.setBackgroundDrawable(null); d.setCallback(null); if (d instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable)d).releaseDelegate(); } d = null; } nativeView = null; if (proxy != null) { proxy.setModelListener(null); } } } public void show() { if (nativeView != null) { nativeView.setVisibility(View.VISIBLE); } else { if (DBG) { Log.w(LCAT, "Attempt to show null native control"); } } } public void hide() { if (nativeView != null) { nativeView.setVisibility(View.INVISIBLE); } else { if (DBG) { Log.w(LCAT, "Attempt to hide null native control"); } } } private void handleBackgroundImage(KrollDict d) { String bg = d.getString(TiC.PROPERTY_BACKGROUND_IMAGE); String bgSelected = d.getString(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE); String bgFocused = d.getString(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE); String bgDisabled = d.getString(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); String bgColor = d.getString(TiC.PROPERTY_BACKGROUND_COLOR); String bgSelectedColor = d.getString(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); String bgFocusedColor = d.getString(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); String bgDisabledColor = d.getString(TiC.PROPERTY_BACKGROUND_DISABLED_COLOR); TiContext tiContext = getProxy().getTiContext(); if (bg != null) { bg = tiContext.resolveUrl(null, bg); } if (bgSelected != null) { bgSelected = tiContext.resolveUrl(null, bgSelected); } if (bgFocused != null) { bgFocused = tiContext.resolveUrl(null, bgFocused); } if (bgDisabled != null) { bgDisabled = tiContext.resolveUrl(null, bgDisabled); } if (bg != null || bgSelected != null || bgFocused != null || bgDisabled != null || bgColor != null || bgSelectedColor != null || bgFocusedColor != null || bgDisabledColor != null) { if (background == null) { applyCustomBackground(false); } Drawable bgDrawable = TiUIHelper.buildBackgroundDrawable(tiContext, bg, bgColor, bgSelected, bgSelectedColor, bgDisabled, bgDisabledColor, bgFocused, bgFocusedColor); background.setBackgroundDrawable(bgDrawable); } } private void initializeBorder(KrollDict d, Integer bgColor) { if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS) || d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (background == null) { applyCustomBackground(); } if (background.getBorder() == null) { background.setBorder(new TiBackgroundDrawable.Border()); } TiBackgroundDrawable.Border border = background.getBorder(); if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS)) { border.setRadius(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_RADIUS)); } if (d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (d.containsKey(TiC.PROPERTY_BORDER_COLOR)) { border.setColor(TiConvert.toColor(d, TiC.PROPERTY_BORDER_COLOR)); } else { if (bgColor != null) { border.setColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { border.setWidth(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_WIDTH)); } } //applyCustomBackground(); } } private void handleBorderProperty(String property, Object value) { if (background.getBorder() == null) { background.setBorder(new TiBackgroundDrawable.Border()); } TiBackgroundDrawable.Border border = background.getBorder(); if (property.equals(TiC.PROPERTY_BORDER_COLOR)) { border.setColor(TiConvert.toColor(value.toString())); } else if (property.equals(TiC.PROPERTY_BORDER_RADIUS)) { border.setRadius(TiConvert.toFloat(value)); } else if (property.equals(TiC.PROPERTY_BORDER_WIDTH)) { border.setWidth(TiConvert.toFloat(value)); } applyCustomBackground(); } private static HashMap<Integer, String> motionEvents = new HashMap<Integer,String>(); static { motionEvents.put(MotionEvent.ACTION_DOWN, TiC.EVENT_TOUCH_START); motionEvents.put(MotionEvent.ACTION_UP, TiC.EVENT_TOUCH_END); motionEvents.put(MotionEvent.ACTION_MOVE, TiC.EVENT_TOUCH_MOVE); motionEvents.put(MotionEvent.ACTION_CANCEL, TiC.EVENT_TOUCH_CANCEL); } private KrollDict dictFromEvent(MotionEvent e) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_X, (double)e.getX()); data.put(TiC.EVENT_PROPERTY_Y, (double)e.getY()); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected boolean allowRegisterForTouch() { return true; } public void registerForTouch() { if (allowRegisterForTouch()) { registerForTouch(getNativeView()); } } protected void registerForTouch(final View touchable) { if (touchable == null) { return; } final GestureDetector detector = new GestureDetector(proxy.getTiContext().getActivity(), new SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { boolean handledTap = proxy.fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e)); boolean handledClick = proxy.fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e)); return handledTap || handledClick; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { Log.e(LCAT, "TAP, TAP, TAP on " + proxy); boolean handledTap = proxy.fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e)); boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(e)); return handledTap || handledClick; } }); touchable.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { boolean handled = detector.onTouchEvent(event); if (!handled && motionEvents.containsKey(event.getAction())) { if (event.getAction() == MotionEvent.ACTION_UP) { Rect r = new Rect(0, 0, view.getWidth(), view.getHeight()); int actualAction = r.contains((int)event.getX(), (int)event.getY()) ? MotionEvent.ACTION_UP : MotionEvent.ACTION_CANCEL; handled = proxy.fireEvent(motionEvents.get(actualAction), dictFromEvent(event)); } else { handled = proxy.fireEvent(motionEvents.get(event.getAction()), dictFromEvent(event)); } } return handled; } }); } public void setOpacity(float opacity) { setOpacity(nativeView, opacity); } protected void setOpacity(View view, float opacity) { if (view != null) { TiUIHelper.setDrawableOpacity(view.getBackground(), opacity); if (opacity == 1) { clearOpacity(view); } view.invalidate(); } } public void clearOpacity(View view) { view.getBackground().clearColorFilter(); } protected void registerForKeyClick(View clickable) { clickable.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { switch(keyCode) { case KeyEvent.KEYCODE_ENTER : case KeyEvent.KEYCODE_DPAD_CENTER : if (proxy.hasListeners(TiC.EVENT_CLICK)) { proxy.fireEvent(TiC.EVENT_CLICK, null); return true; } } } return false; } }); } public KrollDict toImage() { return TiUIHelper.viewToImage(proxy.getTiContext(), proxy.getProperties(), getNativeView()); } }
package com.x1unix.avi; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.graphics.drawable.VectorDrawableCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.kinopoisk.Constants; import com.x1unix.avi.model.KPMovie; import com.x1unix.avi.model.KPMovieDetailViewResponse; import com.x1unix.avi.model.KPPeople; import com.x1unix.avi.rest.KPApiInterface; import com.x1unix.avi.rest.KPRestClient; import com.x1unix.avi.storage.MoviesRepository; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MovieDetailsActivity extends AppCompatActivity implements View.OnClickListener { private Intent args; private String movieId; private String movieTitle; private String movieGenre; private String movieDescription; private String movieRating; private ActionBar actionBar; private KPApiInterface client; private String currentLocale; private View btnAddToBookmarks; private View btnRmFromBookmarks; private Button btnWatchMovie; private Button btnRetry; private MoviesRepository moviesRepository; private String LOG_TAG = "MovieDetailsActivity"; private boolean isCached = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_details); actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } // Init UI elements initUIElements(); moviesRepository = MoviesRepository.getInstance(this); extractIntentData(); setBasicMovieInfo(); currentLocale = getResources().getConfiguration().locale.getLanguage(); // Get movie info if (moviesRepository.movieExists(movieId)) { Log.d(LOG_TAG, "#" + movieId + " Cached!"); isCached = true; // Import data from cache KPMovie movie = moviesRepository.getMovieById(movieId); applyMovieData(movie, false); } else { Log.d(LOG_TAG, "#" + movieId +" No data in cache"); getFullMovieInfo(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } private void initUIElements() { btnAddToBookmarks = findViewById(R.id.amd_bookmark_add); btnRmFromBookmarks = findViewById(R.id.amd_bookmark_remove); btnWatchMovie = (Button) findViewById(R.id.amd_btn_watch); btnRetry = (Button) findViewById(R.id.amd_retry); btnWatchMovie.setOnClickListener(this); btnAddToBookmarks.setOnClickListener(this); btnRmFromBookmarks.setOnClickListener(this); btnRetry.setOnClickListener(this); } @Override public void onStop() { moviesRepository.close(); moviesRepository = null; super.onStop(); } @Override public void onRestart() { moviesRepository = MoviesRepository.getInstance(this); super.onRestart(); } public void onClick(View v) { switch (v.getId()) { case R.id.amd_btn_watch: watchMovie(); break; case R.id.amd_retry: retry(); break; case R.id.amd_bookmark_add: btnAddToBookmarks.setVisibility(View.GONE); moviesRepository.addToFavorites(movieId); setBookmarkedVisibility(true); showSnackMessage(R.string.added_to_favs); break; case R.id.amd_bookmark_remove: btnRmFromBookmarks.setVisibility(View.GONE); moviesRepository.removeFromFavorites(movieId); setBookmarkedVisibility(false); showSnackMessage(R.string.removed_from_favs); break; default: Toast.makeText(getApplicationContext(), getResources().getString(R.string.feature_not_available), Toast.LENGTH_LONG).show(); break; } } private void watchMovie() { Intent wmIntent = new Intent(this, MoviePlayerActivity.class); // Put id and title wmIntent.putExtra("movieId", movieId); wmIntent.putExtra("movieTitle", movieTitle); // Kickstart player startActivity(wmIntent); } private void extractIntentData() { args = getIntent(); movieId = args.getStringExtra("movieId"); movieTitle = args.getStringExtra("movieTitle"); movieGenre = args.getStringExtra("movieGenre"); movieDescription = args.getStringExtra("movieDescription"); movieRating = args.getStringExtra("movieRating"); } private void setBasicMovieInfo() { ((TextView) findViewById(R.id.amd_movie_title)).setText(movieTitle); ((TextView) findViewById(R.id.amd_short_desc)).setText(movieDescription); ((TextView) findViewById(R.id.amd_rating)).setText(movieRating); setTitle(movieTitle); Glide.with(getApplicationContext()) .load(Constants.getPosterUrl(movieId)) .placeholder(R.drawable.no_poster) .into((ImageView) findViewById(R.id.amd_movie_poster)); } private void setProgressVisibility(boolean ifShow) { int visible = (ifShow) ? View.VISIBLE : View.GONE; findViewById(R.id.amd_preloader).setVisibility(visible); } private void setInfoVisibility(boolean ifShow) { int visible = (ifShow) ? View.VISIBLE : View.GONE; findViewById(R.id.amd_movie_info).setVisibility(visible); } private void setErrVisibility(boolean ifShow) { int visible = (ifShow) ? View.VISIBLE : View.GONE; findViewById(R.id.amd_msg_fail).setVisibility(visible); } private void setBookmarkedVisibility(boolean ifShow) { btnRmFromBookmarks.setVisibility((ifShow) ? View.VISIBLE : View.GONE); btnAddToBookmarks.setVisibility((!ifShow) ? View.VISIBLE : View.GONE); } private void getFullMovieInfo() { if (client == null) { client = KPRestClient.getClient().create(KPApiInterface.class); } Call<KPMovieDetailViewResponse> call = client.getMovieById(movieId); call.enqueue(new Callback<KPMovieDetailViewResponse>() { @Override public void onResponse(Call<KPMovieDetailViewResponse>call, Response<KPMovieDetailViewResponse> response) { int statusCode = response.code(); KPMovieDetailViewResponse result = response.body(); if (result != null) { KPMovie movie = result.getResult(); if (movie == null) { showNoMovieDataMsg(result.getMessage()); } else { applyMovieData(movie); } } } @Override public void onFailure(Call<KPMovieDetailViewResponse>call, Throwable t) { showNoMovieDataMsg(t.toString()); } }); } private void retry() { setErrVisibility(false); setProgressVisibility(true); getFullMovieInfo(); } private void showNoMovieDataMsg(String msg) { // Log error here since request failed setProgressVisibility(false); setErrVisibility(true); String prefix = getResources().getString(R.string.err_movie_info_fetch_fail); Toast.makeText(getApplicationContext(), prefix + " " + msg, Toast.LENGTH_LONG).show(); } private void applyMovieData(final KPMovie movie, boolean cacheItem) { setProgressVisibility(false); // Main Info ((TextView) findViewById(R.id.amd_description)).setText(movie.getDescription()); ((TextView) findViewById(R.id.amd_genre)).setText(movie.getGenre()); ((TextView) findViewById(R.id.amd_age_restrictions)).setText(movie.getRatingMPAA()); ((TextView) findViewById(R.id.amd_year)).setText(movie.getYear()); ((TextView) findViewById(R.id.amd_length)).setText(movie.getFilmLength()); // Artists, etc. setAuthorInfo(movie.getDirectors(), R.id.amd_directors); setAuthorInfo(movie.getActors(), R.id.amd_actors); setAuthorInfo(movie.getProducers(), R.id.amd_producers); // Save movie to the cache if (cacheItem) { if (movie != null) { try { moviesRepository.addMovie( movie.setShortDescription(movieDescription).setStars(movieRating) ); isCached = true; } catch (Exception ex) { Log.e(LOG_TAG, "Failed to cache movie info (KPID: " + movieId + "):\n\n" + ex.getMessage()); isCached = false; } } } if (isCached) setBookmarkedVisibility(moviesRepository.isInFavorites(movieId)); setInfoVisibility(true); } private void applyMovieData(final KPMovie movie) { applyMovieData(movie, true); } private void setAuthorInfo(KPPeople[] src, int targetId) { String val = "-"; if(src.length > 0) { val = ""; for(int c = 0; c < src.length; c++) { String name = src[c].getName(currentLocale); if (name != null) { val += src[c].getName(currentLocale); if (c < (src.length - 1)) { val += ", "; } } } } ((TextView) findViewById(targetId)).setText(val); } private void showSnackMessage(int stringId) { Snackbar.make(findViewById(android.R.id.content), getResources().getString(stringId), Snackbar.LENGTH_LONG).show(); } }
package edu.purdue.voltag.data; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; import com.parse.FindCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseRelation; import com.parse.SaveCallback; import java.util.ArrayList; import java.util.List; import edu.purdue.voltag.MainActivity; import edu.purdue.voltag.interfaces.OnDBRefreshListener; import edu.purdue.voltag.interfaces.OnGameCreatedListener; import edu.purdue.voltag.interfaces.OnUserCreatedListener; public class VoltagDB extends SQLiteOpenHelper{ /** Database information */ public static final String DB_NAME = "voltag_db"; public static final int DB_VERSION = 1; private Context c; /** Tables */ public static final String TABLE_PLAYERS = "t_players"; /** Table - Players */ public static final String PLAYERS_PARSE_ID = "player_parse_id"; public static final String PLAYERS_HARDWARE_ID = "player_hardware_id"; public static final String PLAYERS_NAME = "player_name"; public static final String PLAYERS_EMAIL = "player_email"; public static final String PLAYERS_ISIT = "player_isit"; public VoltagDB(Context c) { super(c, DB_NAME, null, DB_VERSION); this.c = c; } @Override public void onCreate(SQLiteDatabase db) { String createTablePlayers = "CREATE " + TABLE_PLAYERS + " (" + PLAYERS_HARDWARE_ID + " TEXT, " + PLAYERS_PARSE_ID + " TEXT, " + PLAYERS_NAME + " TEXT, " + PLAYERS_EMAIL + " TEXT, " + PLAYERS_ISIT + " INTEGER);"; if (db != null) { db.execSQL(createTablePlayers); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // On database upgrade } /** Destroys the entire database */ public void destroy() { SQLiteDatabase db = getWritableDatabase(); if (db != null) { db.execSQL("DROP TABLE " + TABLE_PLAYERS); onCreate(db); } } /** Destroys the players table */ public void dropTablePlayers() { SQLiteDatabase db = getWritableDatabase(); if (db != null) { db.execSQL("DROP TABLE " + TABLE_PLAYERS); String createTablePlayers = "CREATE " + TABLE_PLAYERS + " (" + PLAYERS_HARDWARE_ID + " TEXT, " + PLAYERS_PARSE_ID + " TEXT, " + PLAYERS_NAME + " TEXT, " + PLAYERS_EMAIL + " TEXT, " + PLAYERS_ISIT + " INTEGER);"; db.execSQL(createTablePlayers); } } /** Creates a new player on parse. * The ParseID field in the player object should be null. This call will fail if it isn't. */ public void createPlayerOnParse(final Player p, final OnUserCreatedListener listener) { if (p.getParseID() != null) { Log.d(MainActivity.LOG_TAG, "Error in createPlayer(): ParseID field SHOULD be null."); return; } new Thread(new Runnable() { public void run() { // Check to see if the user has already logged in ParseQuery<ParseObject> userQuery = ParseQuery.getQuery(ParseConstants.PARSE_CLASS_PLAYER); userQuery.whereEqualTo(ParseConstants.PLAYER_EMAIL, p.getEmail()); List<ParseObject> users = null; try { users = userQuery.find(); } catch (ParseException e) { e.printStackTrace(); } if (users.size() >= 1) { // Don't add the user // TODO: Add the ID if they are logged in already Toast.makeText(c, "You're already logged in.", Toast.LENGTH_SHORT).show(); return; } // Create the player ParseObject player = new ParseObject(ParseConstants.PARSE_CLASS_PLAYER); player.put(ParseConstants.PLAYER_HARDWARE_ID, p.getHardwareID()); player.put(ParseConstants.PLAYER_NAME, p.getUserName()); player.put(ParseConstants.PLAYER_EMAIL, p.getEmail()); // Save to parse try { player.save(); } catch (ParseException e) { e.printStackTrace(); } // When complete, query to get the new ID ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstants.PARSE_CLASS_PLAYER); query.whereEqualTo(ParseConstants.PLAYER_HARDWARE_ID, p.getHardwareID()); ParseObject user = null; try { user = query.find().get(0); } catch (ParseException e) { e.printStackTrace(); } // Update their ID in shared preferences SharedPreferences prefs = c.getSharedPreferences(MainActivity.PREFS_NAME, 0); prefs.edit().putString(MainActivity.PREF_USER_ID, user.getObjectId()).commit(); prefs.edit().putBoolean(MainActivity.PREF_ISREGISTERED, true).commit(); // Alert listeners if (listener != null) { listener.onUserCreated(user.getObjectId()); } } }).start(); } /** Creates a new game on parse. * When complete, the game ID is stored in the shared preferences. */ public void createGameOnParse(final String gameName, final OnGameCreatedListener listener) { // Get the user's userID final SharedPreferences prefs = c.getSharedPreferences(MainActivity.PREFS_NAME, 0); final String userID = prefs.getString(MainActivity.PREF_USER_ID, ""); if (userID.equals("")) { Log.d(MainActivity.LOG_TAG, "Cannot create map. User is not logged in."); return; } // Get the user from parse new Thread(new Runnable() { public void run() { ParseQuery<ParseObject> queryUser = ParseQuery.getQuery(ParseConstants.PARSE_CLASS_PLAYER); queryUser.whereEqualTo(ParseConstants.CLASS_ID, userID); ParseObject currentUser = null; try { currentUser = queryUser.find().get(0); } catch (ParseException e) { e.printStackTrace(); } // Create the game ParseObject game = new ParseObject(ParseConstants.PARSE_CLASS_GAME); game.put(ParseConstants.GAME_NAME, gameName); game.getRelation(ParseConstants.GAME_PLAYERS).add(currentUser); game.getRelation(ParseConstants.GAME_TAGGED).add(currentUser); // Send the game to the server try { game.save(); } catch (ParseException e) { e.printStackTrace(); } // Save the ID in the shared preferences String id = game.getObjectId(); prefs.edit().putString(MainActivity.PREF_CURRENT_GAME_ID, id).commit(); // Call the listener if (listener != null) { listener.onGameCreated(id); } } }).start(); } /** Adds a player to a given game on parse */ public void addPlayerToGameOnParse(final String gameID) { // Get user ID SharedPreferences prefs = c.getSharedPreferences(MainActivity.PREFS_NAME, 0); final String userID = prefs.getString(MainActivity.PREF_USER_ID, ""); if (userID.equals("")) { Toast.makeText(c, "User is not signed in.", Toast.LENGTH_SHORT).show(); return; } // Spawn off a thread new Thread(new Runnable() { public void run() { // Query parse for the game ParseQuery<ParseObject> gamequery = ParseQuery.getQuery(ParseConstants.PARSE_CLASS_GAME); gamequery.whereEqualTo(ParseConstants.CLASS_ID, gameID); ParseObject game = null; try { game = gamequery.find().get(0); } catch (ParseException e) { e.printStackTrace(); } // Query parse for the player ParseQuery<ParseObject> userquery = ParseQuery.getQuery(ParseConstants.PARSE_CLASS_PLAYER); userquery.whereEqualTo(ParseConstants.CLASS_ID, userID); ParseObject user = null; try { user = userquery.find().get(0); } catch (ParseException e) { e.printStackTrace(); } // Update game's relational reference to its player objects game.getRelation(ParseConstants.GAME_PLAYERS).add(user); // Save the game to parse try { game.save(); } catch (ParseException e) { e.printStackTrace(); } } }).start(); } /** Adds a player to the local database */ private void addPlayerToDB(Player p) { ContentValues values = new ContentValues(); values.put(PLAYERS_PARSE_ID, p.getParseID()); values.put(PLAYERS_HARDWARE_ID, p.getHardwareID()); values.put(PLAYERS_EMAIL, p.getEmail()); values.put(PLAYERS_NAME, p.getUserName()); SQLiteDatabase db = getWritableDatabase(); if (db != null) { db.insert(TABLE_PLAYERS, null, values); } } /** Refreshes the database from parse */ public void refreshPlayersTable(final OnDBRefreshListener listener) { Log.d(MainActivity.LOG_TAG, "Starting database refresh."); // Get current game ID SharedPreferences prefs = c.getSharedPreferences(MainActivity.PREFS_NAME, 0); String gameID = prefs.getString(MainActivity.PREF_CURRENT_GAME_ID, ""); // If there's no game, exit if (gameID.equals("")) { Toast.makeText(c, "No current game.", Toast.LENGTH_SHORT).show(); return; } // Query parse ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstants.PARSE_CLASS_GAME); query.whereEqualTo(ParseConstants.CLASS_ID, gameID); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> parseObjects, ParseException e) { // Parse should return a list of a single Game which is the game we are currently in if (parseObjects.size() > 1) { Toast.makeText(c, "Error in parse query. There should only be 1 game returned.", Toast.LENGTH_SHORT).show(); return; } ParseObject game = parseObjects.get(0); Log.d(MainActivity.LOG_TAG, "Found game " + game.getString(ParseConstants.GAME_NAME)); // Get relation to current users ParseRelation<ParseObject> relation = game.getRelation(ParseConstants.GAME_TAGGED); relation.getQuery().findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> parseObjects, ParseException e) { // Clear out the database dropTablePlayers(); // Re-fill it with new players for (ParseObject p : parseObjects) { String playerID = p.getString(ParseConstants.CLASS_ID); String hardwareID = p.getString(ParseConstants.PLAYER_HARDWARE_ID); String playerName = p.getString(ParseConstants.PLAYER_NAME); String playerEmail = p.getString(ParseConstants.PLAYER_EMAIL); Player player = new Player(playerID, hardwareID, playerName, playerEmail); addPlayerToDB(player); } // Alert listeners if (listener != null) { listener.onDBRefresh(); } } }); } }); } public List<Player> getPlayersInCurrentGame() { SQLiteDatabase db = getReadableDatabase(); if (db != null) { Cursor c = db.rawQuery("SELECT * FROM " + TABLE_PLAYERS + ";", null); List<Player> players = new ArrayList<Player>(); if (c.moveToFirst()) { do { String parseID = c.getString(c.getColumnIndex(PLAYERS_PARSE_ID)); String hwID = c.getString(c.getColumnIndex(PLAYERS_HARDWARE_ID)); String name = c.getString(c.getColumnIndex(PLAYERS_NAME)); String email = c.getString(c.getColumnIndex(PLAYERS_EMAIL)); Player p = new Player(parseID, hwID, name, email); players.add(p); } while (c.moveToNext()); } return players; } return null; } }
package me.devsaki.hentoid.json; import androidx.annotation.Nullable; import com.annimon.stream.Optional; import com.annimon.stream.Stream; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.Chapter; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.ErrorRecord; import me.devsaki.hentoid.database.domains.Group; import me.devsaki.hentoid.database.domains.GroupItem; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Grouping; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.enums.StatusContent; import me.devsaki.hentoid.util.ImportHelper; import me.devsaki.hentoid.util.StringHelper; public class JsonContent { private String url; private String title; private String coverImageUrl; private Integer qtyPages; private long uploadDate; private long downloadDate; private StatusContent status; private Site site; private boolean favourite; private boolean completed; private long reads; private long lastReadDate; private int lastReadPageIndex; private int downloadMode; private boolean manuallyMerged; private Map<String, String> bookPreferences = new HashMap<>(); private Map<AttributeType, List<JsonAttribute>> attributes; private final List<JsonImageFile> imageFiles = new ArrayList<>(); private final List<JsonChapter> chapters = new ArrayList<>(); private final List<JsonErrorRecord> errorRecords = new ArrayList<>(); private final List<JsonGroupItem> groups = new ArrayList<>(); private JsonContent() { } private void addAttribute(JsonAttribute attributeItem) { if (null == attributeItem) return; List<JsonAttribute> list; AttributeType type = attributeItem.getType(); if (attributes.containsKey(type)) { list = attributes.get(type); } else { list = new ArrayList<>(); attributes.put(type, list); } if (list != null) list.add(attributeItem); } public static JsonContent fromEntity(Content c) { return fromEntity(c, true); } public static JsonContent fromEntity(Content c, boolean keepImages) { JsonContent result = new JsonContent(); result.url = c.getUrl(); result.title = StringHelper.removeNonPrintableChars(c.getTitle()); result.coverImageUrl = c.getCoverImageUrl(); result.qtyPages = c.getQtyPages(); result.uploadDate = c.getUploadDate(); result.downloadDate = c.getDownloadDate(); result.status = c.getStatus(); result.site = c.getSite(); result.favourite = c.isFavourite(); result.completed = c.isCompleted(); result.reads = c.getReads(); result.lastReadDate = c.getLastReadDate(); result.lastReadPageIndex = c.getLastReadPageIndex(); result.bookPreferences = c.getBookPreferences(); result.downloadMode = c.getDownloadMode(); result.manuallyMerged = c.isManuallyMerged(); result.attributes = new EnumMap<>(AttributeType.class); for (Attribute a : c.getAttributes()) { JsonAttribute attr = JsonAttribute.fromEntity(a, c.getSite()); result.addAttribute(attr); } if (c.getChapters() != null) for (Chapter chp : c.getChapters()) result.chapters.add(JsonChapter.fromEntity(chp)); if (keepImages && c.getImageFiles() != null) for (ImageFile img : c.getImageFiles()) result.imageFiles.add(JsonImageFile.fromEntity(img)); if (c.getErrorLog() != null) for (ErrorRecord err : c.getErrorLog()) result.errorRecords.add(JsonErrorRecord.fromEntity(err)); if (c.groupItems != null && !c.groupItems.isEmpty()) for (GroupItem gi : c.groupItems) { Group g = gi.group.getTarget(); if (g != null && (g.grouping.equals(Grouping.CUSTOM) || g.hasCustomBookOrder)) // Don't persist group info that can be auto-generated result.groups.add(JsonGroupItem.fromEntity(gi)); } return result; } public Content toEntity(@Nullable final CollectionDAO dao) { Content result = new Content(); if (null == site) site = Site.NONE; result.setSite(site); result.setUrl(url); result.setTitle(StringHelper.removeNonPrintableChars(title)); result.setCoverImageUrl(coverImageUrl); result.setQtyPages(qtyPages); result.setUploadDate(uploadDate); result.setDownloadDate(downloadDate); result.setStatus(status); result.setFavourite(favourite); result.setCompleted(completed); result.setReads(reads); result.setLastReadDate(lastReadDate); result.setLastReadPageIndex(lastReadPageIndex); result.setBookPreferences(bookPreferences); result.setDownloadMode(downloadMode); result.setManuallyMerged(manuallyMerged); // ATTRIBUTES if (attributes != null) { result.clearAttributes(); for (List<JsonAttribute> jsonAttrList : attributes.values()) { // Remove duplicates that may exist in old JSONs (cause weird single tags to appear in the DB) jsonAttrList = Stream.of(jsonAttrList).distinct().toList(); List<Attribute> attrList = new ArrayList<>(); for (JsonAttribute attr : jsonAttrList) attrList.add(attr.toEntity(site)); result.addAttributes(attrList); } } // CHAPTERS List<Chapter> chps = new ArrayList<>(); for (JsonChapter chp : chapters) chps.add(chp.toEntity()); result.setChapters(chps); // IMAGES List<ImageFile> imgs = Stream.of(imageFiles).map(i -> i.toEntity(imageFiles.size(), chps)).toList(); // Fix empty covers Optional<ImageFile> cover = Stream.of(imgs).filter(ImageFile::isCover).findFirst(); if (cover.isEmpty() || cover.get().getUrl().isEmpty()) ImportHelper.createCover(imgs); result.setImageFiles(imgs); // Fix books with incorrect QtyPages that may exist in old JSONs if (qtyPages <= 0) result.setQtyPages(imageFiles.size()); // ERROR RECORDS List<ErrorRecord> errs = new ArrayList<>(); for (JsonErrorRecord err : errorRecords) errs.add(err.toEntity()); result.setErrorLog(errs); // GROUPS if (dao != null) { for (JsonGroupItem gi : groups) { Group group = dao.selectGroupByName(gi.getGroupingId(), gi.getGroupName()); if (group != null) // Group already exists result.groupItems.add(gi.toEntity(result, group)); else if (gi.getGroupingId() == Grouping.CUSTOM.getId()) { // Create group from scratch Group newGroup = new Group(Grouping.CUSTOM, gi.getGroupName(), -1); newGroup.id = dao.insertGroup(newGroup); result.groupItems.add(gi.toEntity(result, newGroup)); } } } result.populateUniqueSiteId(); result.computeSize(); result.computeReadProgress(); return result; } }
package me.devsaki.hentoid.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.drawable.Drawable; import androidx.core.content.ContextCompat; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import static android.graphics.Bitmap.Config.ARGB_8888; public final class ImageHelper { private ImageHelper() { throw new IllegalStateException("Utility class"); } private static FileHelper.NameFilter imageNamesFilter; private static final Charset CHARSET_LATIN_1 = StandardCharsets.ISO_8859_1; public static boolean isImageExtensionSupported(String extension) { return extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("jfif") || extension.equalsIgnoreCase("gif") || extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("webp"); } public static FileHelper.NameFilter getImageNamesFilter() { if (null == imageNamesFilter) imageNamesFilter = displayName -> ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName)); return imageNamesFilter; } public static String getMimeTypeFromPictureBinary(byte[] binary) { if (binary.length < 12) return ""; // In Java, byte type is signed ! // => Converting all raw values to byte to be sure they are evaluated as expected if ((byte) 0xFF == binary[0] && (byte) 0xD8 == binary[1] && (byte) 0xFF == binary[2]) return "image/jpeg"; else if ((byte) 0x89 == binary[0] && (byte) 0x50 == binary[1] && (byte) 0x4E == binary[2]) { // Detect animated PNG : To be recognized as APNG an 'acTL' chunk must appear in the stream before any 'IDAT' chunks int acTlPos = FileHelper.findSequencePosition(binary, 0, "acTL".getBytes(CHARSET_LATIN_1), (int) (binary.length * 0.2)); if (acTlPos > -1) { long idatPos = FileHelper.findSequencePosition(binary, acTlPos, "IDAT".getBytes(CHARSET_LATIN_1), (int) (binary.length * 0.1)); if (idatPos > -1) return "image/apng"; } return "image/png"; } else if ((byte) 0x47 == binary[0] && (byte) 0x49 == binary[1] && (byte) 0x46 == binary[2]) return "image/gif"; else if ((byte) 0x52 == binary[0] && (byte) 0x49 == binary[1] && (byte) 0x46 == binary[2] && (byte) 0x46 == binary[3] && (byte) 0x57 == binary[8] && (byte) 0x45 == binary[9] && (byte) 0x42 == binary[10] && (byte) 0x50 == binary[11]) return "image/webp"; else if ((byte) 0x42 == binary[0] && (byte) 0x4D == binary[1]) return "image/bmp";
package me.devsaki.hentoid.util; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.text.TextUtils; import androidx.preference.PreferenceManager; import com.annimon.stream.Stream; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import me.devsaki.hentoid.BuildConfig; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.enums.Theme; import timber.log.Timber; public final class Preferences { private Preferences() { throw new IllegalStateException("Utility class"); } private static final int VERSION = 4; private static SharedPreferences sharedPreferences; public static void init(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); int savedVersion = sharedPreferences.getInt(Key.PREFS_VERSION_KEY, VERSION); if (savedVersion != VERSION) { Timber.d("Shared Prefs Key Mismatch! Clearing Prefs!"); sharedPreferences.edit() .clear() .apply(); } } @SuppressWarnings({"deprecation", "squid:CallToDeprecatedMethod"}) public static void performHousekeeping() { // Fling factor -> Swipe to fling (v1.9.0) if (sharedPreferences.contains(Key.PREF_VIEWER_FLING_FACTOR)) { int flingFactor = Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_FLING_FACTOR, "0") + ""); sharedPreferences.edit().putBoolean(Key.PREF_VIEWER_SWIPE_TO_FLING, flingFactor > 0).apply(); sharedPreferences.edit().remove(Key.PREF_VIEWER_FLING_FACTOR).apply(); } if (sharedPreferences.contains(Key.PREF_ANALYTICS_TRACKING)) { boolean analyticsTracking = sharedPreferences.getBoolean(Key.PREF_ANALYTICS_TRACKING, false); sharedPreferences.edit().putBoolean(Key.PREF_ANALYTICS_PREFERENCE, !analyticsTracking).apply(); sharedPreferences.edit().remove(Key.PREF_ANALYTICS_TRACKING).apply(); } if (sharedPreferences.contains(Key.PREF_HIDE_RECENT)) { boolean hideRecent = sharedPreferences.getBoolean(Key.PREF_HIDE_RECENT, !BuildConfig.DEBUG); sharedPreferences.edit().putBoolean(Key.PREF_APP_PREVIEW, !hideRecent).apply(); sharedPreferences.edit().remove(Key.PREF_HIDE_RECENT).apply(); } if (sharedPreferences.contains(Key.PREF_CHECK_UPDATES_LISTS)) { boolean checkUpdates = sharedPreferences.getBoolean(Key.PREF_CHECK_UPDATES_LISTS, Default.PREF_CHECK_UPDATES); sharedPreferences.edit().putBoolean(Key.PREF_CHECK_UPDATES, checkUpdates).apply(); sharedPreferences.edit().remove(Key.PREF_CHECK_UPDATES_LISTS).apply(); } if (sharedPreferences.contains(Key.DARK_MODE)) { int darkMode = Integer.parseInt(sharedPreferences.getString(Key.DARK_MODE, "0") + ""); int colorTheme = (0 == darkMode) ? Constant.COLOR_THEME_LIGHT : Constant.COLOR_THEME_DARK; sharedPreferences.edit().putString(Key.PREF_COLOR_THEME, colorTheme + "").apply(); sharedPreferences.edit().remove(Key.DARK_MODE).apply(); } if (sharedPreferences.contains(Key.PREF_ORDER_CONTENT_LISTS)) { int field = 0; boolean isDesc = false; switch (sharedPreferences.getInt(Key.PREF_ORDER_CONTENT_LISTS, Constant.ORDER_CONTENT_TITLE_ALPHA)) { case (Constant.ORDER_CONTENT_TITLE_ALPHA): field = Constant.ORDER_FIELD_TITLE; break; case (Constant.ORDER_CONTENT_TITLE_ALPHA_INVERTED): field = Constant.ORDER_FIELD_TITLE; isDesc = true; break; case (Constant.ORDER_CONTENT_LAST_DL_DATE_FIRST): field = Constant.ORDER_FIELD_DOWNLOAD_DATE; isDesc = true; break; case (Constant.ORDER_CONTENT_LAST_DL_DATE_LAST): field = Constant.ORDER_FIELD_DOWNLOAD_DATE; break; case (Constant.ORDER_CONTENT_RANDOM): field = Constant.ORDER_FIELD_RANDOM; break; case (Constant.ORDER_CONTENT_LAST_UL_DATE_FIRST): field = Constant.ORDER_FIELD_UPLOAD_DATE; isDesc = true; break; case (Constant.ORDER_CONTENT_LEAST_READ): field = Constant.ORDER_FIELD_READS; break; case (Constant.ORDER_CONTENT_MOST_READ): field = Constant.ORDER_FIELD_READS; isDesc = true; break; case (Constant.ORDER_CONTENT_LAST_READ): field = Constant.ORDER_FIELD_READ_DATE; isDesc = true; break; case (Constant.ORDER_CONTENT_PAGES_DESC): field = Constant.ORDER_FIELD_NB_PAGES; isDesc = true; break; case (Constant.ORDER_CONTENT_PAGES_ASC): field = Constant.ORDER_FIELD_NB_PAGES; break; default: // Nothing there } sharedPreferences.edit().putInt(Key.PREF_ORDER_CONTENT_FIELD, field).apply(); sharedPreferences.edit().putBoolean(Key.PREF_ORDER_CONTENT_DESC, isDesc).apply(); sharedPreferences.edit().remove(Key.PREF_ORDER_CONTENT_LISTS).apply(); } } public static void registerPrefsChangedListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } public static void unregisterPrefsChangedListener(SharedPreferences.OnSharedPreferenceChangeListener listener) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } public static boolean isFirstRunProcessComplete() { return sharedPreferences.getBoolean(Key.PREF_WELCOME_DONE, false); } public static void setIsFirstRunProcessComplete(boolean isFirstRunProcessComplete) { sharedPreferences.edit() .putBoolean(Key.PREF_WELCOME_DONE, isFirstRunProcessComplete) .apply(); } public static boolean isAnalyticsEnabled() { return sharedPreferences.getBoolean(Key.PREF_ANALYTICS_PREFERENCE, true); } public static boolean isAutomaticUpdateEnabled() { return sharedPreferences.getBoolean(Key.PREF_CHECK_UPDATES, Default.PREF_CHECK_UPDATES); } public static boolean isFirstRun() { return sharedPreferences.getBoolean(Key.PREF_FIRST_RUN, Default.PREF_FIRST_RUN_DEFAULT); } public static void setIsFirstRun(boolean isFirstRun) { sharedPreferences.edit() .putBoolean(Key.PREF_FIRST_RUN, isFirstRun) .apply(); } public static String getSettingsFolder() { return sharedPreferences.getString(Key.PREF_SETTINGS_FOLDER, ""); } public static int getContentSortField() { return sharedPreferences.getInt(Key.PREF_ORDER_CONTENT_FIELD, Default.PREF_ORDER_CONTENT_FIELD); } public static void setContentSortField(int sortField) { sharedPreferences.edit() .putInt(Key.PREF_ORDER_CONTENT_FIELD, sortField) .apply(); } public static boolean isContentSortDesc() { return sharedPreferences.getBoolean(Key.PREF_ORDER_CONTENT_DESC, Default.PREF_ORDER_CONTENT_DESC); } public static void setContentSortDesc(boolean isDesc) { sharedPreferences.edit() .putBoolean(Key.PREF_ORDER_CONTENT_DESC, isDesc) .apply(); } public static int getAttributesSortOrder() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_ORDER_ATTRIBUTE_LISTS, Default.PREF_ORDER_ATTRIBUTES_DEFAULT + "") + ""); } public static int getContentPageQuantity() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_QUANTITY_PER_PAGE_LISTS, Default.PREF_QUANTITY_PER_PAGE_DEFAULT + "") + ""); } public static String getAppLockPin() { return sharedPreferences.getString(Key.PREF_APP_LOCK, ""); } public static void setAppLockPin(String pin) { sharedPreferences.edit() .putString(Key.PREF_APP_LOCK, pin) .apply(); } public static boolean getEndlessScroll() { return sharedPreferences.getBoolean(Key.PREF_ENDLESS_SCROLL, Default.PREF_ENDLESS_SCROLL_DEFAULT); } public static boolean getRecentVisibility() { return sharedPreferences.getBoolean(Key.PREF_APP_PREVIEW, BuildConfig.DEBUG); } public static String getStorageUri() { return sharedPreferences.getString(Key.PREF_SD_STORAGE_URI, ""); } public static void setStorageUri(String uri) { sharedPreferences.edit() .putString(Key.PREF_SD_STORAGE_URI, uri) .apply(); } public static int getMemoryAlertThreshold() { return Integer.parseInt(sharedPreferences.getString(Key.MEMORY_ALERT, Integer.toString(Default.PREF_MEMORY_ALERT_DEFAULT)) + ""); } public static String getExternalLibraryUri() { return sharedPreferences.getString(Key.EXTERNAL_LIBRARY_URI, ""); } public static void setExternalLibraryUri(String uri) { sharedPreferences.edit() .putString(Key.EXTERNAL_LIBRARY_URI, uri) .apply(); } public static boolean isDeleteExternalLibrary() { return sharedPreferences.getBoolean(Key.EXTERNAL_LIBRARY_DELETE, Default.EXTERNAL_LIBRARY_DELETE); } static int getFolderNameFormat() { return Integer.parseInt( sharedPreferences.getString(Key.PREF_FOLDER_NAMING_CONTENT_LISTS, Default.PREF_FOLDER_NAMING_CONTENT_DEFAULT + "") + ""); } public static int getWebViewInitialZoom() { return Integer.parseInt( sharedPreferences.getString( Key.PREF_WEBVIEW_INITIAL_ZOOM_LISTS, Default.PREF_WEBVIEW_INITIAL_ZOOM_DEFAULT + "") + ""); } public static boolean getWebViewOverview() { return sharedPreferences.getBoolean( Key.PREF_WEBVIEW_OVERRIDE_OVERVIEW_LISTS, Default.PREF_WEBVIEW_OVERRIDE_OVERVIEW_DEFAULT); } public static boolean isBrowserResumeLast() { return sharedPreferences.getBoolean(Key.PREF_BROWSER_RESUME_LAST, Default.PREF_BROWSER_RESUME_LAST_DEFAULT); } public static boolean isBrowserAugmented() { return sharedPreferences.getBoolean(Key.PREF_BROWSER_AUGMENTED, Default.PREF_BROWSER_AUGMENTED_DEFAULT); } public static boolean isBrowserQuickDl() { return sharedPreferences.getBoolean(Key.PREF_BROWSER_QUICK_DL, Default.PREF_BROWSER_QUICK_DL); } public static int getDownloadThreadCount() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_DL_THREADS_QUANTITY_LISTS, Default.PREF_DL_THREADS_QUANTITY_DEFAULT + "") + ""); } static int getFolderTruncationNbChars() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_FOLDER_TRUNCATION_LISTS, Default.PREF_FOLDER_TRUNCATION_DEFAULT + "") + ""); } public static boolean isViewerResumeLastLeft() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_RESUME_LAST_LEFT, Default.PREF_VIEWER_RESUME_LAST_LEFT); } public static boolean isViewerKeepScreenOn() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_KEEP_SCREEN_ON, Default.PREF_VIEWER_KEEP_SCREEN_ON); } public static int getViewerDisplayMode() { if (Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL == getViewerOrientation()) return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_IMAGE_DISPLAY, Integer.toString(Default.PREF_VIEWER_IMAGE_DISPLAY)) + ""); else return Constant.PREF_VIEWER_DISPLAY_FIT; // The only relevant mode for vertical (aka. webtoon) display } public static int getViewerBrowseMode() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_BROWSE_MODE, Integer.toString(Default.PREF_VIEWER_BROWSE_MODE)) + ""); } public static int getViewerDirection() { return (getViewerBrowseMode() == Constant.PREF_VIEWER_BROWSE_RTL) ? Constant.PREF_VIEWER_DIRECTION_RTL : Constant.PREF_VIEWER_DIRECTION_LTR; } public static int getViewerOrientation() { return (getViewerBrowseMode() == Constant.PREF_VIEWER_BROWSE_TTB) ? Constant.PREF_VIEWER_ORIENTATION_VERTICAL : Constant.PREF_VIEWER_ORIENTATION_HORIZONTAL; } public static void setViewerBrowseMode(int browseMode) { sharedPreferences.edit() .putString(Key.PREF_VIEWER_BROWSE_MODE, Integer.toString(browseMode)) .apply(); } public static boolean isContentSmoothRendering(Map<String, String> bookPrefs) { if (bookPrefs.containsKey(Key.PREF_VIEWER_RENDERING)) { String value = bookPrefs.get(Key.PREF_VIEWER_RENDERING); if (value != null) return isSmoothRendering(Integer.parseInt(value)); } return isViewerSmoothRendering(); } private static boolean isViewerSmoothRendering() { return isSmoothRendering(getViewerRenderingMode()); } private static boolean isSmoothRendering(int mode) { return (mode == Constant.PREF_VIEWER_RENDERING_SMOOTH && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M); } private static int getViewerRenderingMode() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_RENDERING, Integer.toString(Default.PREF_VIEWER_RENDERING)) + ""); } public static boolean isViewerDisplayPageNum() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_DISPLAY_PAGENUM, Default.PREF_VIEWER_DISPLAY_PAGENUM); } public static boolean isViewerTapTransitions() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_TAP_TRANSITIONS, Default.PREF_VIEWER_TAP_TRANSITIONS); } public static boolean isViewerZoomTransitions() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_ZOOM_TRANSITIONS, Default.PREF_VIEWER_ZOOM_TRANSITIONS); } public static boolean isViewerSwipeToFling() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_SWIPE_TO_FLING, Default.PREF_VIEWER_SWIPE_TO_FLING); } public static boolean isViewerInvertVolumeRocker() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_INVERT_VOLUME_ROCKER, Default.PREF_VIEWER_INVERT_VOLUME_ROCKER); } public static boolean isViewerTapToTurn() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_PAGE_TURN_TAP, Default.PREF_VIEWER_PAGE_TURN_TAP); } public static boolean isViewerSwipeToTurn() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_PAGE_TURN_SWIPE, Default.PREF_VIEWER_PAGE_TURN_SWIPE); } public static boolean isViewerVolumeToTurn() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_PAGE_TURN_VOLUME, Default.PREF_VIEWER_PAGE_TURN_VOLUME); } public static boolean isViewerOpenBookInGalleryMode() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_OPEN_GALLERY, Default.PREF_VIEWER_OPEN_GALLERY); } public static boolean isViewerContinuous() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_CONTINUOUS, Default.PREF_VIEWER_CONTINUOUS); } public static int getViewerReadThreshold() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_READ_THRESHOLD, Integer.toString(Default.PREF_VIEWER_READ_THRESHOLD)) + ""); } public static int getViewerSlideshowDelay() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_SLIDESHOW_DELAY, Integer.toString(Default.PREF_VIEWER_SLIDESHOW_DELAY)) + ""); } public static int getViewerSeparatingBars() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_VIEWER_SEPARATING_BARS, Integer.toString(Default.PREF_VIEWER_SEPARATING_BARS)) + ""); } public static boolean isViewerHoldToZoom() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_HOLD_TO_ZOOM, Default.PREF_VIEWER_HOLD_TO_ZOOM); } public static boolean isViewerAutoRotate() { return sharedPreferences.getBoolean(Key.PREF_VIEWER_AUTO_ROTATE, Default.PREF_VIEWER_AUTO_ROTATE); } public static int getLastKnownAppVersionCode() { return Integer.parseInt(sharedPreferences.getString(Key.LAST_KNOWN_APP_VERSION_CODE, "0") + ""); } public static void setLastKnownAppVersionCode(int versionCode) { sharedPreferences.edit() .putString(Key.LAST_KNOWN_APP_VERSION_CODE, Integer.toString(versionCode)) .apply(); } public static boolean isQueueAutostart() { return sharedPreferences.getBoolean(Key.PREF_QUEUE_AUTOSTART, Default.PREF_QUEUE_AUTOSTART); } public static boolean isQueueWifiOnly() { return sharedPreferences.getBoolean(Key.PREF_QUEUE_WIFI_ONLY, Default.PREF_QUEUE_WIFI_ONLY); } public static boolean isDownloadLargeOnlyWifi() { return sharedPreferences.getBoolean(Key.PREF_DL_SIZE_WIFI, Default.PREF_DL_SIZE_WIFI); } public static int getDownloadLargeOnlyWifiThreshold() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_DL_SIZE_WIFI_THRESHOLD, Integer.toString(Default.PREF_DL_SIZE_WIFI_THRESHOLD)) + ""); } public static boolean isDlRetriesActive() { return sharedPreferences.getBoolean(Key.PREF_DL_RETRIES_ACTIVE, Default.PREF_DL_RETRIES_ACTIVE); } public static int getDlRetriesNumber() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_DL_RETRIES_NUMBER, Integer.toString(Default.PREF_DL_RETRIES_NUMBER)) + ""); } public static int getDlRetriesMemLimit() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_DL_RETRIES_MEM_LIMIT, Integer.toString(Default.PREF_DL_RETRIES_MEM_LIMIT)) + ""); } public static boolean isDlHitomiWebp() { return sharedPreferences.getBoolean(Key.PREF_DL_HITOMI_WEBP, Default.PREF_DL_HITOMI_WEBP); } public static List<Site> getActiveSites() { String siteCodesStr = sharedPreferences.getString(Key.ACTIVE_SITES, Default.ACTIVE_SITES) + ""; if (siteCodesStr.isEmpty()) return Collections.emptyList(); List<String> siteCodes = Arrays.asList(siteCodesStr.split(",")); return Stream.of(siteCodes).map(s -> Site.searchByCode(Long.valueOf(s))).toList(); } public static void setActiveSites(List<Site> activeSites) { List<Integer> siteCodes = Stream.of(activeSites).map(Site::getCode).toList(); sharedPreferences.edit() .putString(Key.ACTIVE_SITES, android.text.TextUtils.join(",", siteCodes)) .apply(); } public static int getColorTheme() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_COLOR_THEME, Integer.toString(Default.PREF_COLOR_THEME)) + ""); } public static void setColorTheme(int colorTheme) { sharedPreferences.edit() .putString(Key.PREF_COLOR_THEME, Integer.toString(colorTheme)) .apply(); } public static boolean isLockOnAppRestore() { return sharedPreferences.getBoolean(Key.PREF_LOCK_ON_APP_RESTORE, Default.PREF_LOCK_ON_APP_RESTORE); } public static void setLockOnAppRestore(boolean lockOnAppRestore) { sharedPreferences.edit() .putBoolean(Key.PREF_LOCK_ON_APP_RESTORE, lockOnAppRestore) .apply(); } public static int getLockTimer() { return Integer.parseInt(sharedPreferences.getString(Key.PREF_LOCK_TIMER, Integer.toString(Default.PREF_LOCK_TIMER)) + ""); } public static void setLockTimer(int lockTimer) { sharedPreferences.edit() .putString(Key.PREF_LOCK_TIMER, Integer.toString(lockTimer)) .apply(); } public static final class Key { private Key() { throw new IllegalStateException("Utility class"); } public static final String PREF_ANALYTICS_PREFERENCE = "pref_analytics_preference"; public static final String PREF_APP_LOCK = "pref_app_lock"; public static final String PREF_APP_PREVIEW = "pref_app_preview"; static final String PREF_CHECK_UPDATES = "pref_check_updates"; public static final String PREF_CHECK_UPDATE_MANUAL = "pref_check_updates_manual"; public static final String PREF_REFRESH_LIBRARY = "pref_refresh_bookshelf"; public static final String DELETE_ALL_EXCEPT_FAVS = "pref_delete_all_except_favs"; public static final String EXPORT_LIBRARY = "pref_export_library"; public static final String IMPORT_LIBRARY = "pref_import_library"; static final String PREF_WELCOME_DONE = "pref_welcome_done"; static final String PREFS_VERSION_KEY = "prefs_version"; static final String PREF_QUANTITY_PER_PAGE_LISTS = "pref_quantity_per_page_lists"; static final String PREF_ORDER_CONTENT_FIELD = "pref_order_content_field"; static final String PREF_ORDER_CONTENT_DESC = "pref_order_content_desc"; static final String PREF_ORDER_ATTRIBUTE_LISTS = "pref_order_attribute_lists"; static final String PREF_FIRST_RUN = "pref_first_run"; public static final String PREF_ENDLESS_SCROLL = "pref_endless_scroll"; public static final String PREF_SD_STORAGE_URI = "pref_sd_storage_uri"; public static final String EXTERNAL_LIBRARY = "pref_external_library"; public static final String EXTERNAL_LIBRARY_URI = "pref_external_library_uri"; public static final String EXTERNAL_LIBRARY_DELETE = "pref_external_library_delete"; static final String PREF_FOLDER_NAMING_CONTENT_LISTS = "pref_folder_naming_content_lists"; public static final String PREF_SETTINGS_FOLDER = "folder"; public static final String MEMORY_USAGE = "pref_memory_usage"; public static final String MEMORY_ALERT = "pref_memory_alert"; static final String PREF_WEBVIEW_OVERRIDE_OVERVIEW_LISTS = "pref_webview_override_overview_lists"; static final String PREF_WEBVIEW_INITIAL_ZOOM_LISTS = "pref_webview_initial_zoom_lists"; static final String PREF_BROWSER_RESUME_LAST = "pref_browser_resume_last"; static final String PREF_BROWSER_AUGMENTED = "pref_browser_augmented"; static final String PREF_BROWSER_QUICK_DL = "pref_browser_quick_dl"; static final String PREF_FOLDER_TRUNCATION_LISTS = "pref_folder_trunc_lists"; static final String PREF_VIEWER_RESUME_LAST_LEFT = "pref_viewer_resume_last_left"; public static final String PREF_VIEWER_KEEP_SCREEN_ON = "pref_viewer_keep_screen_on"; public static final String PREF_VIEWER_IMAGE_DISPLAY = "pref_viewer_image_display"; public static final String PREF_VIEWER_RENDERING = "pref_viewer_rendering"; public static final String PREF_VIEWER_BROWSE_MODE = "pref_viewer_browse_mode"; public static final String PREF_VIEWER_DISPLAY_PAGENUM = "pref_viewer_display_pagenum"; public static final String PREF_VIEWER_SWIPE_TO_FLING = "pref_viewer_swipe_to_fling"; static final String PREF_VIEWER_TAP_TRANSITIONS = "pref_viewer_tap_transitions"; public static final String PREF_VIEWER_ZOOM_TRANSITIONS = "pref_viewer_zoom_transitions"; static final String PREF_VIEWER_OPEN_GALLERY = "pref_viewer_open_gallery"; public static final String PREF_VIEWER_CONTINUOUS = "pref_viewer_continuous"; static final String PREF_VIEWER_INVERT_VOLUME_ROCKER = "pref_viewer_invert_volume_rocker"; static final String PREF_VIEWER_PAGE_TURN_SWIPE = "pref_viewer_page_turn_swipe"; static final String PREF_VIEWER_PAGE_TURN_TAP = "pref_viewer_page_turn_tap"; static final String PREF_VIEWER_PAGE_TURN_VOLUME = "pref_viewer_page_turn_volume"; public static final String PREF_VIEWER_SEPARATING_BARS = "pref_viewer_separating_bars"; static final String PREF_VIEWER_READ_THRESHOLD = "pref_viewer_read_threshold"; static final String PREF_VIEWER_SLIDESHOW_DELAY = "pref_viewer_slideshow_delay"; public static final String PREF_VIEWER_HOLD_TO_ZOOM = "pref_viewer_zoom_holding"; public static final String PREF_VIEWER_AUTO_ROTATE = "pref_viewer_auto_rotate"; static final String LAST_KNOWN_APP_VERSION_CODE = "last_known_app_version_code"; public static final String PREF_COLOR_THEME = "pref_color_theme"; static final String PREF_QUEUE_AUTOSTART = "pref_queue_autostart"; static final String PREF_QUEUE_WIFI_ONLY = "pref_queue_wifi_only"; static final String PREF_DL_SIZE_WIFI = "pref_dl_size_wifi"; static final String PREF_DL_SIZE_WIFI_THRESHOLD = "pref_dl_size_wifi_threshold"; static final String PREF_DL_RETRIES_ACTIVE = "pref_dl_retries_active"; static final String PREF_DL_RETRIES_NUMBER = "pref_dl_retries_number"; static final String PREF_DL_RETRIES_MEM_LIMIT = "pref_dl_retries_mem_limit"; static final String PREF_DL_HITOMI_WEBP = "pref_dl_hitomi_webp"; public static final String PREF_DL_THREADS_QUANTITY_LISTS = "pref_dl_threads_quantity_lists"; public static final String ACTIVE_SITES = "active_sites"; static final String PREF_LOCK_ON_APP_RESTORE = "pref_lock_on_app_restore"; static final String PREF_LOCK_TIMER = "pref_lock_timer"; // Deprecated values kept for housekeeping/migration static final String PREF_ANALYTICS_TRACKING = "pref_analytics_tracking"; static final String PREF_HIDE_RECENT = "pref_hide_recent"; static final String PREF_VIEWER_FLING_FACTOR = "pref_viewer_fling_factor"; static final String PREF_CHECK_UPDATES_LISTS = "pref_check_updates_lists"; static final String DARK_MODE = "pref_dark_mode"; static final String PREF_ORDER_CONTENT_LISTS = "pref_order_content_lists"; } // IMPORTANT : Any default value change must be mirrored in res/values/strings_settings.xml public static final class Default { private Default() { throw new IllegalStateException("Utility class"); } static final int PREF_QUANTITY_PER_PAGE_DEFAULT = 20; static final int PREF_ORDER_CONTENT_FIELD = Constant.ORDER_FIELD_TITLE; static final boolean PREF_ORDER_CONTENT_DESC = false; static final int PREF_ORDER_ATTRIBUTES_DEFAULT = Constant.ORDER_ATTRIBUTES_COUNT; static final boolean PREF_FIRST_RUN_DEFAULT = true; static final boolean PREF_ENDLESS_SCROLL_DEFAULT = true; static final int PREF_MEMORY_ALERT_DEFAULT = 110; static final boolean EXTERNAL_LIBRARY_DELETE = false; static final int PREF_FOLDER_NAMING_CONTENT_DEFAULT = Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID; static final boolean PREF_WEBVIEW_OVERRIDE_OVERVIEW_DEFAULT = false; public static final int PREF_WEBVIEW_INITIAL_ZOOM_DEFAULT = 20; static final boolean PREF_BROWSER_RESUME_LAST_DEFAULT = false; static final boolean PREF_BROWSER_AUGMENTED_DEFAULT = true; static final boolean PREF_BROWSER_QUICK_DL = true; static final int PREF_DL_THREADS_QUANTITY_DEFAULT = Constant.DOWNLOAD_THREAD_COUNT_AUTO; static final int PREF_FOLDER_TRUNCATION_DEFAULT = Constant.TRUNCATE_FOLDER_NONE; static final boolean PREF_VIEWER_RESUME_LAST_LEFT = true; static final boolean PREF_VIEWER_KEEP_SCREEN_ON = true; static final int PREF_VIEWER_IMAGE_DISPLAY = Constant.PREF_VIEWER_DISPLAY_FIT; static final int PREF_VIEWER_RENDERING = Constant.PREF_VIEWER_RENDERING_SHARP; static final int PREF_VIEWER_BROWSE_MODE = Constant.PREF_VIEWER_BROWSE_NONE; static final boolean PREF_VIEWER_DISPLAY_PAGENUM = false; static final boolean PREF_VIEWER_TAP_TRANSITIONS = true; static final boolean PREF_VIEWER_ZOOM_TRANSITIONS = true; static final boolean PREF_VIEWER_OPEN_GALLERY = false; static final boolean PREF_VIEWER_CONTINUOUS = false; static final boolean PREF_VIEWER_PAGE_TURN_SWIPE = true; static final boolean PREF_VIEWER_PAGE_TURN_TAP = true; static final boolean PREF_VIEWER_PAGE_TURN_VOLUME = true; static final boolean PREF_VIEWER_SWIPE_TO_FLING = false; static final boolean PREF_VIEWER_INVERT_VOLUME_ROCKER = false; static final int PREF_VIEWER_SEPARATING_BARS = Constant.PREF_VIEWER_SEPARATING_BARS_OFF; static final int PREF_VIEWER_READ_THRESHOLD = Constant.PREF_VIEWER_READ_THRESHOLD_1; static final int PREF_VIEWER_SLIDESHOW_DELAY = Constant.PREF_VIEWER_SLIDESHOW_DELAY_2; static final boolean PREF_VIEWER_HOLD_TO_ZOOM = false; static final boolean PREF_VIEWER_AUTO_ROTATE = false; static final int PREF_COLOR_THEME = Constant.COLOR_THEME_LIGHT; static final boolean PREF_QUEUE_AUTOSTART = true; static final boolean PREF_QUEUE_WIFI_ONLY = false; static final boolean PREF_DL_SIZE_WIFI = false; static final int PREF_DL_SIZE_WIFI_THRESHOLD = 40; static final boolean PREF_DL_RETRIES_ACTIVE = false; static final int PREF_DL_RETRIES_NUMBER = 3; static final int PREF_DL_RETRIES_MEM_LIMIT = 100; static final boolean PREF_DL_HITOMI_WEBP = true; static final boolean PREF_CHECK_UPDATES = true; // Default menu in v1.9.x static final Site[] DEFAULT_SITES = new Site[]{Site.NHENTAI, Site.HENTAICAFE, Site.HITOMI, Site.ASMHENTAI, Site.TSUMINO, Site.PURURIN, Site.EHENTAI, Site.FAKKU2, Site.NEXUS, Site.MUSES, Site.DOUJINS}; static final String ACTIVE_SITES = TextUtils.join(",", Stream.of(DEFAULT_SITES).map(Site::getCode).toList()); static final boolean PREF_LOCK_ON_APP_RESTORE = false; static final int PREF_LOCK_TIMER = Constant.PREF_LOCK_TIMER_30S; } // IMPORTANT : Any value change must be mirrored in res/values/array_preferences.xml public static final class Constant { private Constant() { throw new IllegalStateException("Utility class"); } public static final int DOWNLOAD_THREAD_COUNT_AUTO = 0; public static final int ORDER_CONTENT_FAVOURITE = -2; // Artificial order created for clarity purposes public static final int ORDER_FIELD_NONE = -1; public static final int ORDER_FIELD_TITLE = 0; public static final int ORDER_FIELD_ARTIST = 1; public static final int ORDER_FIELD_NB_PAGES = 2; public static final int ORDER_FIELD_DOWNLOAD_DATE = 3; public static final int ORDER_FIELD_UPLOAD_DATE = 4; public static final int ORDER_FIELD_READ_DATE = 5; public static final int ORDER_FIELD_READS = 6; public static final int ORDER_FIELD_SIZE = 7; public static final int ORDER_FIELD_RANDOM = 99; public static final int ORDER_ATTRIBUTES_ALPHABETIC = 0; static final int ORDER_ATTRIBUTES_COUNT = 1; static final int PREF_FOLDER_NAMING_CONTENT_ID = 0; static final int PREF_FOLDER_NAMING_CONTENT_TITLE_ID = 1; static final int PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID = 2; static final int PREF_FOLDER_NAMING_CONTENT_TITLE_AUTH_ID = 3; static final int TRUNCATE_FOLDER_NONE = 0; public static final int PREF_VIEWER_DISPLAY_FIT = 0; public static final int PREF_VIEWER_DISPLAY_FILL = 1; public static final int PREF_VIEWER_DISPLAY_STRETCH = 2; public static final int PREF_VIEWER_RENDERING_SHARP = 0; public static final int PREF_VIEWER_RENDERING_SMOOTH = 1; public static final int PREF_VIEWER_BROWSE_NONE = -1; public static final int PREF_VIEWER_BROWSE_LTR = 0; public static final int PREF_VIEWER_BROWSE_RTL = 1; public static final int PREF_VIEWER_BROWSE_TTB = 2; public static final int PREF_VIEWER_DIRECTION_LTR = 0; public static final int PREF_VIEWER_DIRECTION_RTL = 1; public static final int PREF_VIEWER_ORIENTATION_HORIZONTAL = 0; public static final int PREF_VIEWER_ORIENTATION_VERTICAL = 1; public static final int PREF_VIEWER_SEPARATING_BARS_OFF = 0; public static final int PREF_VIEWER_SEPARATING_BARS_SMALL = 1; public static final int PREF_VIEWER_SEPARATING_BARS_MEDIUM = 2; public static final int PREF_VIEWER_SEPARATING_BARS_LARGE = 3; public static final int PREF_VIEWER_READ_THRESHOLD_1 = 0; public static final int PREF_VIEWER_READ_THRESHOLD_2 = 1; public static final int PREF_VIEWER_READ_THRESHOLD_5 = 2; public static final int PREF_VIEWER_READ_THRESHOLD_ALL = 3; public static final int PREF_VIEWER_SLIDESHOW_DELAY_2 = 0; public static final int PREF_VIEWER_SLIDESHOW_DELAY_4 = 1; public static final int PREF_VIEWER_SLIDESHOW_DELAY_8 = 2; public static final int PREF_VIEWER_SLIDESHOW_DELAY_16 = 3; public static final int COLOR_THEME_LIGHT = Theme.LIGHT.getId(); public static final int COLOR_THEME_DARK = Theme.DARK.getId(); public static final int COLOR_THEME_BLACK = Theme.BLACK.getId(); public static final int PREF_LOCK_TIMER_OFF = 0; public static final int PREF_LOCK_TIMER_10S = 1; public static final int PREF_LOCK_TIMER_30S = 2; public static final int PREF_LOCK_TIMER_1M = 3; public static final int PREF_LOCK_TIMER_2M = 4; // Deprecated values kept for housekeeping/migration @Deprecated public static final int ORDER_CONTENT_TITLE_ALPHA = 0; @Deprecated public static final int ORDER_CONTENT_LAST_DL_DATE_FIRST = 1; @Deprecated public static final int ORDER_CONTENT_TITLE_ALPHA_INVERTED = 2; @Deprecated public static final int ORDER_CONTENT_LAST_DL_DATE_LAST = 3; @Deprecated public static final int ORDER_CONTENT_RANDOM = 4; @Deprecated public static final int ORDER_CONTENT_LAST_UL_DATE_FIRST = 5; @Deprecated public static final int ORDER_CONTENT_LEAST_READ = 6; @Deprecated public static final int ORDER_CONTENT_MOST_READ = 7; @Deprecated public static final int ORDER_CONTENT_LAST_READ = 8; @Deprecated public static final int ORDER_CONTENT_PAGES_DESC = 9; @Deprecated public static final int ORDER_CONTENT_PAGES_ASC = 10; } }
package nfiniteloop.net.loqale; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import net.nfiniteloop.loqale.backend.checkins.Checkins; import net.nfiniteloop.loqale.backend.checkins.model.User; import net.nfiniteloop.loqale.backend.places.Places; import net.nfiniteloop.loqale.backend.places.model.Place; import net.nfiniteloop.loqale.backend.recommendations.Recommendations; import net.nfiniteloop.loqale.backend.registration.Registration; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class MainActivity extends FragmentActivity{ // Logging for debugging private Logger log = Logger.getLogger(MainActivity.class.getName()); LoqalePageAdapter pageAdapter; ViewPager pager; // asynchronous support classes // TODO: Move all to respective fragments private static checkInHelper checkInsTask; // endpoint client services private static Checkins checkInService; private static Places placesService; private static Recommendations recommendationService; //container class for places fragment private ArrayList<MessageItem> messages; private ArrayList<PlaceItem> places; Registration registrationService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); List<Fragment> fragments = getFragments(); messages = new ArrayList<MessageItem>(); places = new ArrayList<PlaceItem>(); pager = (ViewPager)findViewById(R.id.viewpager); pageAdapter = new LoqalePageAdapter(getApplicationContext(),getSupportFragmentManager(), fragments); pager.setAdapter(pageAdapter); SharedPreferences prefs = getSharedPreferences(LoqaleConstants.PREFS_NAME, Context.MODE_PRIVATE); Boolean newbie = prefs.getBoolean("newUser", true); String userDevice = prefs.getString("deviceId", ""); String userName = prefs.getString("username", "Anon Loqal"); int proximity = prefs.getInt("proximity", 1000); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater= getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } public void onSectionAttached(int number) { } @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_settings) { showSettingsActivity(); } log.severe("804"); return super.onOptionsItemSelected(item); } private void showSettingsActivity() { Intent intent; intent = new Intent(this, SettingsActivity.class); startActivity(intent); } private List<Fragment> getFragments() { List<Fragment> listFragments = new ArrayList<Fragment>(); listFragments.add((MessageFragment.newInstance(messages))); //listFragments.add(PlaceFragment.newInstance(places)); return listFragments; } public class checkInHelper extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { if (checkInService == null) { // Only do this once Checkins.Builder builder = new Checkins.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null) // options for running against local devappserver // - 10.0.2.2 is localhost's IP address in Android emulator // - turn off compression when running against local devappserver .setRootUrl("http://10.0.2.2:8080/_ah/api/") .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() { @Override public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException { abstractGoogleClientRequest.setDisableGZipContent(true); } }); checkInService = builder.build(); } return true; } @Override protected void onPostExecute(final Boolean success) { } @Override protected void onCancelled() { } } }
package org.sil.bloom.reader; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sil.bloom.reader.models.Book; public class ReaderActivity extends BaseActivity { private static final Pattern sLayoutPattern = Pattern.compile("\\S+([P|p]ortrait|[L|l]andscape)\\b"); // Matches a div with class bloom-page, that is, the start of the main content of one page. // (We're looking for the start of a div tag, then before finding the end wedge, we find // class<maybe space>=<maybe space><some sort of quote> and then bloom-page before we find // another quote. // Bizarre mismatches are possible...like finding the other sort of quote inside the class // value, or finding class='bloom-page' inside the value of some other attribute. But I think // it's good enough.) private static final Pattern sPagePattern = Pattern.compile("<div\\s+[^>]*class\\s*=\\s*['\"][^'\"]*bloom-page"); private static final Pattern sClassAttrPattern = Pattern.compile("class\\s*=\\s*(['\"])(.*?)\\1"); private ViewPager mPager; private BookPagerAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); setContentView(R.layout.activity_reader); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); Intent intent = getIntent(); String path = intent.getData().getPath(); if (path.toLowerCase().endsWith(Book.BOOK_FILE_EXTENSION)) { //.bloomd files are zip files try { String bookStagingPath = unzipBook(path); String filenameWithExtension = new File(path).getName(); // strip off the extension (which we already know exactly) String bookName = filenameWithExtension.substring(0, filenameWithExtension.length() - Book.BOOK_FILE_EXTENSION.length()); new Loader().execute(bookStagingPath, bookName); } catch (IOException err) { Toast.makeText(this.getApplicationContext(), "There was an error showing that book: " + err, Toast.LENGTH_LONG); } } else { new Loader().execute(path, new File(path).getName()); // during stylesheet development, it's nice to be able to work with a folder rather than a zip } } // class to run loadBook in the background (so the UI thread is available to animate the progress bar) private class Loader extends AsyncTask<String, Integer, Long> { @Override protected Long doInBackground(String... args) { loadBook(args[0], args[1]); return 0L; } } @Override protected void onNewOrUpdatedBook(String fullPath) { ((BloomReaderApplication)this.getApplication()).setBookToHighlight(fullPath); Intent intent = new Intent(this, MainActivity.class); // Clears the history so now the back button doesn't take from the main activity back to here. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } private String unzipBook(String zipPath) throws IOException { File bookStagingDir = this.getApplicationContext().getDir("currentbook", Context.MODE_PRIVATE); IOUtilities.emptyDirectory(bookStagingDir); IOUtilities.unzip(new File(zipPath), bookStagingDir); return bookStagingDir.getAbsolutePath(); } private void loadBook(String path, String bookName) { File bookFolder = new File(path); File bookHtmlPath = new File(path + File.separator + bookName + ".htm"); try { long start = System.currentTimeMillis(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(bookHtmlPath),"UTF-8")); // an infuriatingly inefficient way to read the file into a string. StringBuilder sb = new StringBuilder((int)bookHtmlPath.length()); try { String line = reader.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = reader.readLine(); } } catch (IOException e) { throw new RuntimeException(e); } String html = sb.toString(); long endTime = System.currentTimeMillis(); long timeToReadFile = endTime - start; // Break the html into everything before the first page, a sequence of pages, // and the bit after the last. Note: assumes there is nothing but the </body> after // the last page, that is, that pages are the direct children of <body> and // nothing follows the last page. final Matcher matcher = sPagePattern.matcher(html); String startFrame = ""; String endFrame = ""; ArrayList<String> pages = new ArrayList<String>(); // if we don't find even one start of page, we have no pages, and don't need startFrame, endFrame, etc. if (matcher.find()) { int firstPageIndex = matcher.start(); startFrame = html.substring(0, firstPageIndex); int startPage = firstPageIndex; while (matcher.find()) { pages.add(html.substring(startPage, matcher.start())); startPage = matcher.start(); } int endBody = html.indexOf("</body>", startPage); pages.add(html.substring(startPage, endBody)); endFrame = html.substring(endBody, html.length()); } long endTime2 = System.currentTimeMillis(); long timeToParse = endTime2 - endTime; mAdapter = new BookPagerAdapter(pages, this, bookHtmlPath, startFrame, endFrame, path); } catch (IOException ex) { Log.e("Reader", "IO Error loading " + path + " " + ex); return; } catch (Exception ex) { Log.e("Reader", "Error loading " + path + " " + ex); return; } runOnUiThread(new Runnable() { @Override public void run() { mPager = (ViewPager) findViewById(R.id.book_pager); mPager.setAdapter(mAdapter); // Now we're ready to display the book, so hide the 'progress bar' (spinning circle) findViewById(R.id.loadingPanel).setVisibility(View.GONE); } }); } // Forces the layout we want into the class, and inserts the specified style. // assumes some layout is already present in classes attribute, and no style already exists. private String modifyPage(String page, String newLayout, String style) { // Get the content of the class attribute and its position Matcher matcher = sClassAttrPattern.matcher(page); if (!matcher.find()) return page; // don't think this can happen, we create pages by finding class attr. int start = matcher.start(2); int end = matcher.end(2); String classNames = matcher.group(2); String newClassNames = sLayoutPattern.matcher(classNames).replaceFirst(newLayout); return page.substring(0,start) // everything up to the opening quote in class=" + newClassNames + matcher.group(1) // proper matching closing quote ends class attr + " style=" + matcher.group(1) // we need to use the same quote for style... + style + page.substring(end, page.length()); // because this includes the original closing quote from class attr } private int getPageScale(int viewWidth, int viewHeight){ //we'll probably want to read or calculate these at some point... //but for now, they are the width and height of the Device16x9Portrait layout int bookPageWidth = 378; int bookPageHeight = 674; Double widthScale = new Double(viewWidth)/new Double(bookPageWidth); Double heightScale = new Double(viewHeight)/new Double(bookPageHeight); Double scale = Math.min(widthScale, heightScale); scale = scale * 100d; return scale.intValue(); } // Copy in files like bloomPlayer.js private void updateSupportFiles(String bookFolderPath) { IOUtilities.copyAssetFolder(this.getApplicationContext().getAssets(), "book support files", bookFolderPath); } // Wraps access to what would otherwise be two variables of BookPagerAdapter and ensures // all access to them is synchronized. This is necessary because we access them both in the // UI thread and in a background thread used to create the next page view while // displaying the current one. private class NextPageWrapper { WebView mNextPageContentControl; int mNextPageIndex = -1; // flag value indicating we don't have a next page. // IF the known next page is the one wanted, return it. Otherwise null. WebView getBrowserIfForPage(int position) { synchronized (this) { if (position == mNextPageIndex) { return mNextPageContentControl; } } return null; } void setNextPage(WebView nextPageControl, int nextPageIndex) { synchronized (this) { if (mNextPageIndex == nextPageIndex) return; // already have page for this index, no need to replace it. mNextPageContentControl = nextPageControl; mNextPageIndex = nextPageIndex; } } // It's reasonable to get this without synchronization as long as there's no // independent access to the page control that assumes another thread hasn't changed // it meanwhile. For example, to decide whether to kick off creation of a next page control. // Please do NOT add a similar method that gives unsynchronized access to the control, // it's asking for trouble to access that without synchronizing access to the page index. int getNextPageIndex() { return mNextPageIndex; } } // Class that provides individual page views as needed. // possible enhancement: can we reuse the same browser, just change which page is visible? private class BookPagerAdapter extends PagerAdapter { // Each item is the full HTML text of one page div (div with class bloom-page). // the concatenation of mHtmlBeforeFirstPageDiv, mHtmlPageDivs, and mHtmlAfterLastPageDiv // is the whole book HTML file. (The code here assumes there is nothing in the body // of the document except page divs.) // The concatenation of mHtmlBeforeFirstPageDiv, one item from mHtmlPageDivs, and // mHtmlAfterLastPageDiv is the content we put in a browser representing a single page. private List<String> mHtmlPageDivs; private String mHtmlBeforeFirstPageDiv; private String mHtmlAfterLastPageDiv; ReaderActivity mParent; File mBookHtmlPath; String mFolderPath; NextPageWrapper mNextPageWrapper = new NextPageWrapper(); WebView mLastPageContentControl; int mLastPageIndex; int mThisPageIndex; WebView mThisPageContentControl; BookPagerAdapter(List<String> htmlPageDivs, ReaderActivity parent, File bookHtmlPath, String htmlBeforeFirstPageDiv, String htmlAfterLastPageDiv, String folderPath) { mHtmlPageDivs = htmlPageDivs; mParent = parent; mBookHtmlPath = bookHtmlPath; mHtmlBeforeFirstPageDiv = htmlBeforeFirstPageDiv; mHtmlAfterLastPageDiv = htmlAfterLastPageDiv; mFolderPath = folderPath; mLastPageIndex = -1; mThisPageIndex = -1; } @Override public void destroyItem(ViewGroup collection, int position, Object view) { Log.d("Reader", "destroyItem"); collection.removeView((View) view); } @Override public int getCount() { //Log.d("Reader", "getCount = "+ mHtmlPageDivs.size()); return mHtmlPageDivs.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { Log.d("Reader", "instantiateItem"); WebView browser = mNextPageWrapper.getBrowserIfForPage(position); // leaves null if not already created if (browser == null && position == mLastPageIndex) { browser = mLastPageContentControl; } else if (position == mThisPageIndex) { browser = mThisPageContentControl; } else { browser = MakeBrowserForPage(position); } if (mThisPageIndex == position - 1) { // we just advanced; current 'this' page becomes last page mLastPageIndex = mThisPageIndex; mLastPageContentControl = mThisPageContentControl; } else { // We just went back a page. Keep the current page as 'next'. if (mThisPageIndex == position + 1) { mNextPageWrapper.setNextPage(mThisPageContentControl, mThisPageIndex); } } mThisPageContentControl = browser; mThisPageIndex = position; // If relevant start a process to get the next page the user is likely to want. if ( mNextPageWrapper.getNextPageIndex() != position + 1 && position < mHtmlPageDivs.size() - 1) { new PageMaker().execute(position + 1); } container.addView(browser); return browser; } // class to manage async execution of work to get new page. // unfortunately it isn't very async since most of the work has to be done on the UI thread. // So at this point we might be better served by just posting the task. // But at some point we may figure out parts of this that can really be done in the // background. Then again, now that we're making pages that don't contain the // whole book with all but one page hidden we might not need to. private class PageMaker extends AsyncTask<Integer, Integer, Long> { @Override protected Long doInBackground(Integer[] positions) { final int position = positions[0]; // expect to be passed exactly one runOnUiThread(new Runnable() { @Override public void run() { WebView browser = MakeBrowserForPage(position); BookPagerAdapter.this.mNextPageWrapper.setNextPage(browser, position); } }); return 0L; } } private WebView MakeBrowserForPage(int position) { WebView browser = null; try { browser = new ScaledWebView(mParent); String page = mHtmlPageDivs.get(position); // Inserts the layout class we want and forces no border. page = modifyPage(page, "Device16x9Portrait", "border:0 !important"); String doc = mHtmlBeforeFirstPageDiv + page + mHtmlAfterLastPageDiv; browser.loadDataWithBaseURL("file:///" + mBookHtmlPath.getAbsolutePath(), doc, "text/html", "utf-8", null); }catch (Exception ex) { Log.e("Reader", "Error loading " + mFolderPath + " " + ex); } return browser; } @Override public boolean isViewFromObject(View view, Object object) { Log.d("Reader", "isViewFromObject = " + (view == object)); return view == object; } } private class ScaledWebView extends WebView { public ScaledWebView(Context context) { super(context); } @Override protected void onSizeChanged(int w, int h, int ow, int oh) { // if width is zero, this method will be called again if (w != 0) { setInitialScale(getPageScale(w, h)); } super.onSizeChanged(w, h, ow, oh); } } }
package org.sil.bloom.reader; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.webkit.WebView; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.segment.analytics.Analytics; import com.segment.analytics.Properties; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sil.bloom.reader.models.BookOrShelf; public class ReaderActivity extends BaseActivity { private static final String TAG = "ReaderActivity"; private static final String sAssetsStylesheetLink = "<link rel=\"stylesheet\" href=\"file:///android_asset/book support files/assets.css\" type=\"text/css\"></link>"; private static final String sAssetsBloomPlayerScript = "<script type=\"text/javascript\" src=\"file:///android_asset/book support files/bloomPagePlayer.js\"></script>"; private static final Pattern sLayoutPattern = Pattern.compile("\\S+([P|p]ortrait|[L|l]andscape)\\b"); private static final Pattern sHeadElementEndPattern = Pattern.compile("</head"); private static final Pattern sMainLangauge = Pattern.compile("<div data-book=\"contentLanguage1\"[^>]*>\\s*(\\S*)"); // Matches a div with class bloom-page, that is, the start of the main content of one page. // (We're looking for the start of a div tag, then before finding the end wedge, we find // class<maybe space>=<maybe space><some sort of quote> and then bloom-page before we find // another quote. // Bizarre mismatches are possible...like finding the other sort of quote inside the class // value, or finding class='bloom-page' inside the value of some other attribute. But I think // it's good enough.) private static final Pattern sPagePattern = Pattern.compile("<div\\s+[^>]*class\\s*=\\s*['\"][^'\"]*bloom-page"); // For searching in a page string to see whether it's a back-matter page. Looks for bloom-backmatter // in a class attribute in the first opening tag. private static final Pattern sBackPagePattern = Pattern.compile("[^>]*class\\s*=\\s*['\"][^'\"]*bloom-backMatter"); // Matches a page div with the class numberedPage...that string must occur in a class attribute before the // close of the div element. private static final Pattern sNumberedPagePattern = Pattern.compile("[^>]*?class\\s*=\\s*['\"][^'\"]*numberedPage"); private static final Pattern sBackgroundAudio = Pattern.compile("[^>]*?data-backgroundaudio\\s*=\\s*['\"]([^'\"]*)?['\"]"); private static final Pattern sBackgroundVolume = Pattern.compile("[^>]*?data-backgroundaudiovolume\\s*=\\s*['\"]([^'\"]*)?['\"]"); private static final Pattern sClassAttrPattern = Pattern.compile("class\\s*=\\s*(['\"])(.*?)\\1"); private static final Pattern sContentLangDiv = Pattern.compile("<div [^>]*?data-book=\"contentLanguage1\"[^>]*?>\\s*(\\S+)"); private ViewPager mPager; private BookPagerAdapter mAdapter; private String mBookName ="?"; private BloomFileReader mFileReader; private int mAudioPagesPlayed = 0; private int mNonAudioPagesShown = 0; private int mLastNumberedPageIndex = -1; private int mNumberedPageCount = 0; private boolean mLastNumberedPageRead = false; private String mContentLang1 = "unknown"; int mFirstQuestionPage; int mCountQuestionPages; WebView mCurrentView; String[] mBackgroundAudioFiles; float[] mBackgroundAudioVolumes; // Keeps track of whether we switched pages while audio paused. If so, we don't resume // the audio of the previously visible page, but start this page from the beginning. boolean mSwitchedPagesWhilePaused = false; // These variables support a minimum time on each page before we automatically switch to // the next (if the audio on this page is short or non-existent). private long mTimeLastPageSwitch; private Timer mNextPageTimer; private boolean mIsMultiMediaBook; private boolean mRTLBook; private String mBrandingProjectName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); setContentView(R.layout.activity_reader); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); mBrandingProjectName = getIntent().getStringExtra("brandingProjectName"); new Loader().execute(); } @Override protected void onPause() { if (isFinishing()) { ReportPagesRead(); } super.onPause(); WebAppInterface.stopAllAudio(); } private void ReportPagesRead() { try { // let's differentiate between pages read and audio book pages read: (BL-5082) Properties p = new Properties(); p.putValue("title", mBookName); p.putValue("audioPages", mAudioPagesPlayed); p.putValue("nonAudioPages", mNonAudioPagesShown); p.putValue("totalNumberedPages", mNumberedPageCount); p.putValue("lastNumberedPageRead", mLastNumberedPageRead); p.putValue("questionCount", mAdapter.mQuestions.size()); p.putValue("contentLang", mContentLang1); if (mBrandingProjectName != null) { p.putValue("brandingProjectName", mBrandingProjectName); } Analytics.with(BloomReaderApplication.getBloomApplicationContext()).track("Pages Read", p); } catch (Exception e) { Log.e(TAG, "Pages Read", e); BloomReaderApplication.VerboseToast("Error reporting Pages Read"); } } // class to run loadBook in the background (so the UI thread is available to animate the progress bar) private class Loader extends AsyncTask<Void, Integer, Long> { @Override protected Long doInBackground(Void... v) { loadBook(); return 0L; } } // Minimum time a page must be visible before we automatically switch to the next // (if playing audio...usually this only affects pages with no audio) final int MIN_PAGE_SWITCH_MILLIS = 3000; // This is the routine that is invoked as a result of a call-back from javascript indicating // that the current page is complete (which in turn typically follows a notification from // Java that a sound finished playing...but it is the JS that knows it is the last audio // on the page). Basically it is responsible for flipping to the next page (see goToNextPageNow). // But, we get the notification instantly if there is NO audio on the page. // So we do complicated things with a timer to make sure we don't flip the page too soon... // the minimum delay is specified in MIN_PAGE_SWITCH_MILLIS. public void pageAudioCompleted() { // For now, we have decided we want to force the user to initiate page turning always (BL-5067). if (true) return; clearNextPageTimer(); long millisSinceLastSwitch = System.currentTimeMillis() - mTimeLastPageSwitch; if (millisSinceLastSwitch >= MIN_PAGE_SWITCH_MILLIS) { goToNextPageNow(); return; } // If nothing else happens, we will go to next page when the minimum time has elapsed. // Unfortunately, the only way to stop scheduled events in a Java timer is to destroy it. // So that's what clearNextPageTimer() does (e.g., if the user manually changes pages). // Consequently, we have to make a new one each time. synchronized (this) { mNextPageTimer = new Timer(); mNextPageTimer.schedule(new TimerTask() { @Override public void run() { goToNextPageNow(); } }, MIN_PAGE_SWITCH_MILLIS - millisSinceLastSwitch); } } void clearNextPageTimer() { synchronized (this) { if (mNextPageTimer == null) return; mNextPageTimer.cancel(); mNextPageTimer = null; } } private void goToNextPageNow() { if (!mIsMultiMediaBook) return; clearNextPageTimer(); runOnUiThread(new Runnable() { @Override public void run() { // In case some race condition has this getting called while we are paused, // don't let it happen. if (WebAppInterface.isNarrationPaused()) { return; } int current = mPager.getCurrentItem(); if (current < mAdapter.getCount() - 1) { mPager.setCurrentItem(current + 1); } } } ); } public int indexOfCurrentPage() { return mPager.getCurrentItem(); } public void narrationPausedChanged() { if (!mIsMultiMediaBook) return; // no media visual effects. final ImageView view = (ImageView)findViewById(R.id.playPause); if (WebAppInterface.isNarrationPaused()) { clearNextPageTimer(); // any pending automatic page flip should be prevented. view.setImageResource(R.drawable.pause_on_circle); // black circle around android.R.drawable.ic_media_pause); } else { view.setImageResource(R.drawable.play_on_circle); if(mSwitchedPagesWhilePaused) { final int position = mPager.getCurrentItem(); mAdapter.startNarrationForPage(position); // also starts animation if any } } mSwitchedPagesWhilePaused = false; final Animation anim = AnimationUtils.loadAnimation(this, R.anim.grow_and_fade); // Make the view hidden when the animation finishes. Otherwise it returns to full visibility. anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { // required method for abstract class } @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { // required method for abstract class } }); view.setVisibility(View.VISIBLE); view.startAnimation(anim); } @Override protected void onNewOrUpdatedBook(String fullPath) { ((BloomReaderApplication)this.getApplication()).setBookToHighlight(fullPath); Intent intent = new Intent(this, MainActivity.class); // Clears the history so now the back button doesn't take from the main activity back to here. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } private void reportLoadBook(String path) { try { String filenameWithExtension = new File(path).getName(); // this mBookName is used by subsequent analytics reports mBookName = filenameWithExtension.substring(0, filenameWithExtension.length() - BookOrShelf.BOOK_FILE_EXTENSION.length()); Properties p = new Properties(); p.putValue("title", mBookName); p.putValue("totalNumberedPages", mNumberedPageCount); p.putValue("contentLang", mContentLang1); p.putValue("questionCount", mAdapter.mQuestions.size()); if (mBrandingProjectName != null) { p.putValue("brandingProjectName", mBrandingProjectName); } Analytics.with(BloomReaderApplication.getBloomApplicationContext()).track("BookOrShelf opened", p); } catch (Exception error) { Log.e("Reader", "Error reporting load of " + path + ". "+ error); BloomReaderApplication.VerboseToast("Error reporting load of "+path); } } private void loadBook() { final String path = getIntent().getData().getPath(); mFileReader = new BloomFileReader(getApplicationContext(), path); String bookDirectory; try { final File bookHtmlFile = mFileReader.getHtmlFile(); bookDirectory = bookHtmlFile.getParent(); String html = IOUtilities.FileToString(bookHtmlFile); // Enhance: eventually also look for images with animation data. // This is a fairly crude search, we really want the doc to have spans with class // audio-sentence; but I think it's a sufficiently unlikely string to find elsewhere // that this is good enough. mIsMultiMediaBook = html.indexOf("audio-sentence") >= 0; // Break the html into everything before the first page, a sequence of pages, // and the bit after the last. Note: assumes there is nothing but the </body> after // the last page, that is, that pages are the direct children of <body> and // nothing follows the last page. final Matcher matcher = sPagePattern.matcher(html); String startFrame = ""; String endFrame = ""; ArrayList<String> pages = new ArrayList<String>(); // if we don't find even one start of page, we have no pages, and don't need startFrame, endFrame, etc. if (matcher.find()) { int firstPageIndex = matcher.start(); startFrame = html.substring(0, firstPageIndex); Matcher match = sContentLangDiv.matcher(startFrame); if (match.find()) { mContentLang1 = match.group(1); } startFrame = addAssetsStylesheetLink(startFrame); int startPage = firstPageIndex; while (matcher.find()) { final String pageContent = html.substring(startPage, matcher.start()); AddPage(pages, pageContent); startPage = matcher.start(); } mFirstQuestionPage = pages.size(); for (; mFirstQuestionPage > 0; mFirstQuestionPage String pageContent = pages.get(mFirstQuestionPage-1); if (!sBackPagePattern.matcher(pageContent).find()) { break; } } int endBody = html.indexOf("</body>", startPage); AddPage(pages, html.substring(startPage, endBody)); // We can leave out the bloom player JS altogether if not needed. endFrame = (mIsMultiMediaBook ? sAssetsBloomPlayerScript : "") + html.substring(endBody, html.length()); } boolean hasEnterpriseBranding = mBrandingProjectName != null && !mBrandingProjectName.toLowerCase().equals("default"); ArrayList<JSONObject> questions = new ArrayList<JSONObject>(); if (hasEnterpriseBranding) { String primaryLanguage = getPrimaryLanguage(html); String questionSource = mFileReader.getFileContent("questions.json"); if (questionSource != null) { JSONArray groups = new JSONArray(questionSource); for(int i = 0; i < groups.length(); i++) { JSONObject group = groups.getJSONObject(i); if (!group.getString("lang").equals(primaryLanguage)) continue; JSONArray groupQuestions = group.getJSONArray("questions"); for (int j = 0; j < groupQuestions.length(); j++) { questions.add(groupQuestions.getJSONObject(j)); } } } mCountQuestionPages = questions.size(); for (int i = 0; i < mCountQuestionPages; i++) { // insert all these pages just before the final 'end' page. pages.add(mFirstQuestionPage, "Q"); } } mBackgroundAudioFiles = new String[pages.size()]; mBackgroundAudioVolumes = new float[pages.size()]; String currentBackgroundAudio = ""; float currentVolume = 1.0f; for (int i = 0; i < pages.size(); i++) { if (pages.get(i) == "Q") { mBackgroundAudioFiles[i] = ""; currentBackgroundAudio = ""; continue; } Matcher bgMatcher =sBackgroundAudio.matcher(pages.get(i)); if (bgMatcher.find()) { currentBackgroundAudio = bgMatcher.group(1); if (currentBackgroundAudio == null) // may never happen? currentBackgroundAudio = ""; // Getting a new background file implies full volume unless specified. currentVolume = 1.0f; } Matcher bgvMatcher =sBackgroundVolume.matcher(pages.get(i)); if (bgvMatcher.find()) { try { currentVolume = Float.parseFloat(bgvMatcher.group(1)); } catch (NumberFormatException e) { e.printStackTrace(); } } mBackgroundAudioFiles[i] = currentBackgroundAudio; mBackgroundAudioVolumes[i] = currentVolume; } mRTLBook = mFileReader.getBooleanMetaProperty("isRtl", false); mAdapter = new BookPagerAdapter(pages, questions, this, bookHtmlFile, startFrame, endFrame); reportLoadBook(path); } catch (Exception ex) { Log.e("Reader", "Error loading " + path + " " + ex); return; } final String audioDirectoryPath = bookDirectory + "/audio/"; runOnUiThread(new Runnable() { @Override public void run() { mPager = (ViewPager) findViewById(R.id.book_pager); if(mRTLBook) mPager.setRotationY(180); mPager.setAdapter(mAdapter); final ViewPager.SimpleOnPageChangeListener listener = new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { super.onPageSelected(position); clearNextPageTimer(); // in case user manually moved to a new page while waiting WebView oldView = mCurrentView; mCurrentView = mAdapter.getActiveView(position); mTimeLastPageSwitch = System.currentTimeMillis(); stopAndStartVideos(oldView, mCurrentView); if (mIsMultiMediaBook) { mSwitchedPagesWhilePaused = WebAppInterface.isNarrationPaused(); WebAppInterface.stopNarration(); // don't want to hear rest of anything on another page String backgroundAudioPath = ""; if (mBackgroundAudioFiles[position].length() > 0) { backgroundAudioPath = audioDirectoryPath + mBackgroundAudioFiles[position]; } WebAppInterface.SetBackgroundAudio(backgroundAudioPath, mBackgroundAudioVolumes[position]); // This new page may not be in the correct paused state. // (a) maybe we paused this page, moved to another, started narration, moved // back to this (adapter decided to reuse it), this one needs to not be paused. // (b) maybe we moved to another page while not paused, paused there, moved // back to this one (again, reused) and old animation is still running if (mCurrentView != null && mCurrentView.getTag() instanceof WebAppInterface) { WebAppInterface appInterface = (WebAppInterface) mCurrentView.getTag(); appInterface.setPaused(WebAppInterface.isNarrationPaused()); if (!WebAppInterface.isNarrationPaused() && mIsMultiMediaBook) { mAdapter.startNarrationForPage(position); // Note: this isn't super-reliable. We tried to narrate this page, but it may not // have any audio. All we know is that it's part of a book which has // audio (or animation) somewhere, and we tried to play any audio it has. mAudioPagesPlayed++; } else { mNonAudioPagesShown++; } } } else { mNonAudioPagesShown++; } if (position == mLastNumberedPageIndex) mLastNumberedPageRead = true; } }; mPager.addOnPageChangeListener(listener); // Now we're ready to display the book, so hide the 'progress bar' (spinning circle) findViewById(R.id.loadingPanel).setVisibility(View.GONE); // A design flaw in the ViewPager is that its onPageSelected method does not // get called for the page that is initially displayed. But we want to do all the // same things to the first page as the others. So we will call it // manually. Using post delays this until everything is initialized and the view // starts to process events. I'm not entirely sure why this should be done; // I copied this from something on StackOverflow. Probably it means that the // first-page call happens in a more similar situation to the change-page calls. // It might work to just call it immediately. mPager.post(new Runnable() { @Override public void run() { listener.onPageSelected(mPager.getCurrentItem()); } }); } }); } private void stopAndStartVideos(WebView oldView, WebView currentView){ // Selects the first (and presumably only) video on the page if any exists String videoSelector = "document.getElementsByTagName('video')[0]"; if(oldView != null) oldView.evaluateJavascript(videoSelector + ".pause();", null); if(currentView != null) currentView.evaluateJavascript(videoSelector + ".play();", null); } private void AddPage(ArrayList<String> pages, String pageContent) { pages.add(pageContent); if (sNumberedPagePattern.matcher(pageContent).find()) { mLastNumberedPageIndex = pages.size() - 1; mNumberedPageCount++; } } private String getPrimaryLanguage(String html) { Matcher matcher = sMainLangauge.matcher(html); if (!matcher.find()) return "en"; return matcher.group(1); } private String addAssetsStylesheetLink(String htmlSnippet) { final Matcher matcher = sHeadElementEndPattern.matcher(htmlSnippet); if (matcher.find()) { return htmlSnippet.substring(0, matcher.start()) + sAssetsStylesheetLink + htmlSnippet.substring(matcher.start()); } return htmlSnippet; } private int getPageOrientationAndRotateScreen(String page){ int orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; Matcher matcher = sClassAttrPattern.matcher(page); if (matcher.find()) { String classNames = matcher.group(2); if (classNames.contains("Landscape")) orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; } setRequestedOrientation(orientation); return orientation; } // Transforms [x]Portrait or [x]Landscape class to Device16x9Portrait / Device16x9Landscape private String pageUsingDeviceLayout(String page) { // Get the content of the class attribute and its position Matcher matcher = sClassAttrPattern.matcher(page); if (!matcher.find()) return page; // don't think this can happen, we create pages by finding class attr. int start = matcher.start(2); int end = matcher.end(2); String classNames = matcher.group(2); String newClassNames = sLayoutPattern.matcher(classNames).replaceFirst("Device16x9$1"); return page.substring(0,start) // everything up to the opening quote in class=" + newClassNames + page.substring(end, page.length()); // because this includes the original closing quote from class attr } private int getPageScale(int viewWidth, int viewHeight, int bookOrientation){ // 378 x 674 are the dimensions of the Device16x9 layouts in pixels int bookPageWidth = (bookOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) ? 378 : 674; int bookPageHeight = (bookOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) ? 674 : 378; Double widthScale = new Double(viewWidth)/new Double(bookPageWidth); Double heightScale = new Double(viewHeight)/new Double(bookPageHeight); Double scale = Math.min(widthScale, heightScale); scale = scale * 100d; return scale.intValue(); } // Copy in files like bloomPlayer.js private void updateSupportFiles(String bookFolderPath) { IOUtilities.copyAssetFolder(this.getApplicationContext().getAssets(), "book support files", bookFolderPath); } enum pageAnswerState { unanswered, firstTimeCorrect, secondTimeCorrect, wrongOnce, wrong } // Class that provides individual page views as needed. // possible enhancement: can we reuse the same browser, just change which page is visible? private class BookPagerAdapter extends PagerAdapter { // Each item is the full HTML text of one page div (div with class bloom-page). // the concatenation of mHtmlBeforeFirstPageDiv, mHtmlPageDivs, and mHtmlAfterLastPageDiv // is the whole book HTML file. (The code here assumes there is nothing in the body // of the document except page divs.) // The concatenation of mHtmlBeforeFirstPageDiv, one item from mHtmlPageDivs, and // mHtmlAfterLastPageDiv is the content we put in a browser representing a single page. private List<String> mHtmlPageDivs; List<JSONObject> mQuestions; pageAnswerState[] mAnswerStates; boolean mQuestionAnalyticsSent; private String mHtmlBeforeFirstPageDiv; private String mHtmlAfterLastPageDiv; ReaderActivity mParent; File mBookHtmlPath; int mLastPageIndex; int mThisPageIndex; // This map allows us to convert from the page index we get from the ViewPager to // the actual child WebView on that page. There ought to be a way to get the actual // current child control from the ViewPager, but I haven't found it yet. // Note that it only tracks WebViews for items that have been instantiated and not // yet destroyed; this is important to allow others to be garbage-collected. private HashMap<Integer, ScaledWebView> mActiveViews = new HashMap<Integer, ScaledWebView>(); BookPagerAdapter(List<String> htmlPageDivs, List<JSONObject> questions, ReaderActivity parent, File bookHtmlPath, String htmlBeforeFirstPageDiv, String htmlAfterLastPageDiv) { mHtmlPageDivs = htmlPageDivs; mQuestions = questions; mAnswerStates = new pageAnswerState[mQuestions.size()]; for (int i = 0; i < mAnswerStates.length; i++) { mAnswerStates[i] = pageAnswerState.unanswered; } mParent = parent; mBookHtmlPath = bookHtmlPath; mHtmlBeforeFirstPageDiv = htmlBeforeFirstPageDiv; mHtmlAfterLastPageDiv = htmlAfterLastPageDiv; } @Override public void destroyItem(ViewGroup collection, int position, Object view) { Log.d("Reader", "destroyItem " + position); collection.removeView((View) view); mActiveViews.remove(position); } @Override public int getCount() { //Log.d("Reader", "getCount = "+ mHtmlPageDivs.size()); return mHtmlPageDivs.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { Log.d("Reader", "instantiateItem " + position); assert(container.getChildCount() == 0); String page = mHtmlPageDivs.get(position); if (page.startsWith("<")) { // normal content page WebView browser = MakeBrowserForPage(position); container.addView(browser); return browser; } // question page LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); final LinearLayout questionPageView = (LinearLayout) inflater.inflate(R.layout.question_page, null); final int questionIndex = position - mFirstQuestionPage; JSONObject question = mQuestions.get(questionIndex); final TextView questionView = (TextView)questionPageView.findViewById(R.id.question); try { questionView.setText(question.getString("question")); JSONArray answers = question.getJSONArray("answers"); for (int i = 0; i < answers.length(); i++) { // Passing the intended parent view allows the button's margins to work properly. final LinearLayout answerLayout = (LinearLayout) inflater.inflate(R.layout.question_answer_item, questionPageView, false); JSONObject answerObj = answers.getJSONObject(i); Button answer = (Button) answerLayout.findViewById(R.id.answerButton); final ImageView imageView = (ImageView) answerLayout.findViewById(R.id.checkImage); if (answerObj.getBoolean("correct")) { answer.setTag("correct"); } answer.setText(answerObj.getString("text")); answer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean correct = view.getTag() == "correct"; if (correct) { // Clear any previous answers. for (int i = 0; i < questionPageView.getChildCount(); i++) { View item = questionPageView.getChildAt(i); ImageView imgItem = (ImageView) item.findViewById(R.id.checkImage); if (imgItem != null) { // will be for initial text views. imgItem.setImageResource(0); } } imageView.setImageResource(R.drawable.check_green); } else { imageView.setImageResource(R.drawable.cancel); // A strong red x: android.R.drawable.ic_delete); } pageAnswerState oldAnswerState = mAnswerStates[questionIndex]; if (correct) { if (oldAnswerState == pageAnswerState.wrongOnce) mAnswerStates[questionIndex] = pageAnswerState.secondTimeCorrect; else if (oldAnswerState == pageAnswerState.unanswered) mAnswerStates[questionIndex] = pageAnswerState.firstTimeCorrect; // if they already got it wrong twice they get no credit. // if they already got it right no credit for clicking again. // both sounds from // cc0 playSoundFile(R.raw.right_answer); } else { if (oldAnswerState == pageAnswerState.unanswered) mAnswerStates[questionIndex] = pageAnswerState.wrongOnce; else if (oldAnswerState == pageAnswerState.wrongOnce) mAnswerStates[questionIndex] = pageAnswerState.wrong; // if they previously got it right we won't hold it against them // that they now get it wrong. playSoundFile(R.raw.wrong_answer); } if (!mQuestionAnalyticsSent) { boolean allAnswered = true; int rightFirstTime = 0; for (int i = 0; i < mAnswerStates.length; i++) { if (mAnswerStates[i] == pageAnswerState.unanswered) { allAnswered = false; break; } else if (mAnswerStates[i] == pageAnswerState.firstTimeCorrect) { rightFirstTime++; } } if (allAnswered) { Properties p = new Properties(); p.putValue("title", mBookName); p.putValue("questionCount", mAnswerStates.length); p.putValue("rightFirstTime", rightFirstTime); p.putValue("percentRight", rightFirstTime * 100 / mAnswerStates.length); if (mBrandingProjectName != null) { p.putValue("brandingProjectName", mBrandingProjectName); } Analytics.with(BloomReaderApplication.getBloomApplicationContext()).track("Questions correct", p); // Don't send again unless they re-open the book and start over. mQuestionAnalyticsSent = true; } } } }); questionPageView.addView(answerLayout); } } catch (JSONException e) { e.printStackTrace(); } TextView progressView = (TextView) questionPageView.findViewById(R.id.question_progress); progressView.setText(String.format(progressView.getText().toString(), questionIndex + 1, mCountQuestionPages)); container.addView(questionPageView); return questionPageView; } // position should in fact be the position of the pager. public ScaledWebView getActiveView(int position) { return mActiveViews.get(position); } public void prepareForAnimation(int position) { final WebView pageView = mActiveViews.get(position); if (pageView == null) { Log.d("prepareForAnimation", "can't find page for " + position); return; } if (pageView.getTag() instanceof WebAppInterface) { WebAppInterface appInterface = (WebAppInterface) pageView.getTag(); appInterface.prepareDocumentWhenDocLoaded(); } } public void startNarrationForPage(int position) { WebView pageView = mActiveViews.get(position); if (pageView == null) { Log.d("startNarration", "can't find page for " + position); return; } if (pageView.getTag() instanceof WebAppInterface) { WebAppInterface appInterface = (WebAppInterface) pageView.getTag(); appInterface.startNarrationWhenDocLoaded(); } } private WebView MakeBrowserForPage(int position) { ScaledWebView browser = null; try { String page = mHtmlPageDivs.get(position); browser = new ScaledWebView(mParent, getPageOrientationAndRotateScreen(page)); mActiveViews.put(position, browser); if (mIsMultiMediaBook) { WebAppInterface appInterface = new WebAppInterface(this.mParent, mBookHtmlPath.getParent(), browser, position); browser.addJavascriptInterface(appInterface, "Android"); // Save the WebAppInterface in the browser's tag because there's no simple // way to get from the browser to the object we set as the JS interface. browser.setTag(appInterface); } // Styles to force 0 border and to vertically center books String moreStyles = "<style>html{ height: 100%; } body{ min-height:100%; display:flex; align-items:center; } div.bloom-page { border:0 !important; }</style>\n"; String doc = mHtmlBeforeFirstPageDiv + moreStyles + pageUsingDeviceLayout(page) + mHtmlAfterLastPageDiv; browser.loadDataWithBaseURL("file:///" + mBookHtmlPath.getAbsolutePath(), doc, "text/html", "utf-8", null); prepareForAnimation(position); }catch (Exception ex) { Log.e("Reader", "Error loading " + mBookHtmlPath.getAbsolutePath() + " " + ex); } return browser; } @Override public boolean isViewFromObject(View view, Object object) { Log.d("Reader", "isViewFromObject = " + (view == object)); return view == object; } } private class ScaledWebView extends WebView { private int bookOrientation; public ScaledWebView(Context context, int bookOrientation) { super(context); this.bookOrientation = bookOrientation; if(mRTLBook) setRotationY(180); getSettings().setJavaScriptEnabled(true); getSettings().setMediaPlaybackRequiresUserGesture(false); } @Override protected void onSizeChanged(int w, int h, int ow, int oh) { // if width is zero, this method will be called again if (w != 0) { setInitialScale(getPageScale(w, h, bookOrientation)); } super.onSizeChanged(w, h, ow, oh); } private float mXLocationForActionDown; private float mYLocationForActionDown; // After trying many things this is the only approach that worked so far for detecting // a tap on the window. Things I tried: // - setOnClickListener on the ViewPager. This is known not to work, e.g., // - the ClickableViewPager described as an answer there (captures move events, but for // no obvious reason does not capture down and up or detect clicks) // - setOnClickListener on the WebView. This is also known not to work. @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mXLocationForActionDown = event.getX(); mYLocationForActionDown = event.getY(); } else if (event.getAction() == MotionEvent.ACTION_UP) { ViewConfiguration viewConfiguration = ViewConfiguration.get(getContext()); if (Math.abs(event.getX() - mXLocationForActionDown) > viewConfiguration.getScaledTouchSlop() || Math.abs(event.getY() - mYLocationForActionDown) > viewConfiguration.getScaledTouchSlop()) { // We don't want to register a touch if the user is swiping. // Without this, we had some bizarre behavior wherein the user could swipe slightly more // vertical distance than horizontal and cause a play/pause event. } else if (event.getEventTime() - event.getDownTime() < viewConfiguration.getJumpTapTimeout()) { if (mCurrentView != null && mCurrentView.getTag() instanceof WebAppInterface) { WebAppInterface appInterface = (WebAppInterface) mCurrentView.getTag(); if (appInterface != null) { // may be null if this can happen in non-multimedia book appInterface.setPaused(!WebAppInterface.isNarrationPaused()); narrationPausedChanged(); } } } } return super.onTouchEvent(event); } } }
import java.io.IOException; import com.leapmotion.leap.*; import com.leapmotion.leap.Gesture.State; class LeapListener extends Listener { //Controller initialized public void onInit(Controller controller) { System.out.println("Initialized"); } //Controller connected public void onConnect(Controller controller) { System.out.println("Connected to motion Sensor"); //Declare Gestures controller.enableGesture(Gesture.Type.TYPE_SWIPE); controller.enableGesture(Gesture.Type.TYPE_CIRCLE); controller.enableGesture(Gesture.Type.TYPE_SCREEN_TAP); controller.enableGesture(Gesture.Type.TYPE_KEY_TAP); } //Controller disconnect public void onDisconnect(Controller controller) { System.out.println("Motion sensor disconnected"); } //Controller exit public void onExit(Controller controller) { System.out.println("Exited"); } //Frame method public void onFrame(Controller controller) { Frame frame = controller.frame(); //Frame Data /*System.out.println("Frame id: " + frame.id() + ", Timestamp: " + frame.timestamp() + ", Hands: " + frame.hands().count() + ", Fingers: " + frame.fingers().count() + ", Tools: " + frame.tools().count() + ", Gestures: " + frame.gestures().count()); for (Hand hand : frame.hands()) { String handType = hand.isLeft() ? "Left Hand" : "Right Hand"; System.out.println(handType + " " + ", id: " + hand.id() + ", Palm Position: " + hand.palmPosition()); Vector normal = hand.palmNormal(); Vector direction = hand.direction(); System.out.println("Pitch: " + Math.toDegrees(direction.pitch()) + "Roll: " + Math.toDegrees(normal.roll()) + " Yaw: " + Math.toDegrees(direction.yaw())); } for (Finger finger : frame.fingers()) { System.out.println("//Finger Type: " + finger.type() + " ID: " + finger.id() + " Finger length (mm): " + finger.length() + " Finger width (mm): " + finger.width()); for (Bone.Type boneType : Bone.Type.values()) { Bone bone = finger.bone(boneType); System.out.println("Bone Type: " + bone.type() + " Start: " + bone.prevJoint() + " End: " + bone.nextJoint() + " Direction: " + bone.direction()); } } for (Tool tool : frame.tools()) { System.out.println("Tool ID: " + tool.id() + " Tip position: " + tool.tipPosition() + " Direction: " + tool.direction() + " Width: " + tool.width() + " Touch Distance (mm) " + tool.touchDistance()); }*/ GestureList gestures = frame.gestures(); for (int i = 0; i < gestures.count(); i++) { Gesture gesture = gestures.get(i); switch (gesture.type()) { case TYPE_CIRCLE: CircleGesture circle = new CircleGesture(gesture); String clockwise; if (circle.pointable().direction().angleTo(circle.normal()) <= Math.PI/4) { clockwise = "clockwise"; } else { clockwise = " counter-clockwise"; } double sweptAngle = 0; if (circle.state() != State.STATE_START) { CircleGesture previous = new CircleGesture(controller.frame(1).gesture(circle.id())); sweptAngle = (circle.progress() - previous.progress()) * 2 * Math.PI; } System.out.println("Circle ID: " + circle.id() + " State: " + circle.state() + " Progress: " + circle.progress() + " Radius: " + circle.radius() + " Angle: " + Math.toDegrees(sweptAngle) + " " + clockwise); break; case TYPE_SWIPE: SwipeGesture swipe = new SwipeGesture(gesture); System.out.println("Swipe ID: " + swipe.id() + " State: " + swipe.state() + " Swipe position: " + swipe.position() + " Direction: " + swipe.direction() + " Speed: " + swipe.speed()); break; case TYPE_SCREEN_TAP: ScreenTapGesture screenTap = new ScreenTapGesture(gesture); System.out.println("ScreenTap ID: " + screenTap.id() + " State: " + screenTap.state() + " Position: " + screenTap.position() + " Direction: " + screenTap.direction()); break; case TYPE_KEY_TAP: KeyTapGesture keyTap = new KeyTapGesture(gesture); System.out.println("KeyTap ID: " + keyTap.id() + " State: " + keyTap.state() + " Position: " + keyTap.position() + " Direction: " + keyTap.direction()); break; default: System.out.println("Unknown gesture"); break; } } } } public class LeapController { public static void main(String[] args) { LeapListener listener = new LeapListener(); Controller controller = new Controller(); controller.addListener(listener); System.out.println("Press enter to quit"); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } controller.removeListener(listener); } }
package org.commcare.android.net; import android.content.SharedPreferences; import android.net.Uri; import android.net.http.AndroidHttpClient; import android.util.Log; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.params.HttpClientParams; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.commcare.android.database.SqlStorage; import org.commcare.android.database.user.models.ACase; import org.commcare.android.database.user.models.User; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.logic.GlobalConstants; import org.commcare.cases.util.CaseDBUtils; import org.commcare.dalvik.application.CommCareApplication; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.services.Logger; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.util.Date; import java.util.Vector; /** * @author ctsims */ public class HttpRequestGenerator { private static final String TAG = HttpRequestGenerator.class.getSimpleName(); /** * A possible domain that further qualifies the username of any account in use */ public static final String USER_DOMAIN_SUFFIX = "cc_user_domain"; public static final String LOG_COMMCARE_NETWORK = "commcare-network"; /** * The type of authentication that we're capable of providing to the server (digest if this isn't present) */ public static final String AUTH_REQUEST_TYPE = "authtype"; /** * No Authentication will be possible, there isn't a user account to authenticate this request */ public static final String AUTH_REQUEST_TYPE_NO_AUTH = "noauth"; private Credentials credentials; PasswordAuthentication passwordAuthentication; private String username; public HttpRequestGenerator(User user) { this(user.getUsername(), user.getCachedPwd()); } public HttpRequestGenerator(String username, String password) { String domainedUsername = username; SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); //TODO: We do this in a lot of places, we should wrap it somewhere if (prefs.contains(USER_DOMAIN_SUFFIX)) { domainedUsername += "@" + prefs.getString(USER_DOMAIN_SUFFIX, null); } this.credentials = new UsernamePasswordCredentials(domainedUsername, password); passwordAuthentication = new PasswordAuthentication(domainedUsername, password.toCharArray()); this.username = username; } public HttpRequestGenerator() { //No authentication possible } public HttpResponse get(String uri) throws ClientProtocolException, IOException { HttpClient client = client(); Log.d(TAG, "Fetching from: " + uri); HttpGet request = new HttpGet(uri); addHeaders(request, ""); HttpResponse response = execute(client, request); //May need to manually process a valid redirect if (response.getStatusLine().getStatusCode() == 301) { String newGetUri = request.getURI().toString(); Log.d(LOG_COMMCARE_NETWORK, "Following valid redirect from " + uri.toString() + " to " + newGetUri); request.abort(); //Make a new response to the redirect request = new HttpGet(newGetUri); addHeaders(request, ""); response = execute(client, request); } return response; } public HttpResponse makeCaseFetchRequest(String baseUri, boolean includeStateFlags) throws ClientProtocolException, IOException { HttpClient client = client(); Uri serverUri = Uri.parse(baseUri); String vparam = serverUri.getQueryParameter("version"); if (vparam == null) { serverUri = serverUri.buildUpon().appendQueryParameter("version", "2.0").build(); } String syncToken = null; if (includeStateFlags) { syncToken = getSyncToken(username); String digest = getDigest(); if (syncToken != null) { serverUri = serverUri.buildUpon().appendQueryParameter("since", syncToken).build(); } if (digest != null) { serverUri = serverUri.buildUpon().appendQueryParameter("state", "ccsh:" + digest).build(); } } //Add items count to fetch request serverUri = serverUri.buildUpon().appendQueryParameter("items", "true").build(); String uri = serverUri.toString(); Log.d(TAG, "Fetching from: " + uri); HttpGet request = new HttpGet(uri); AndroidHttpClient.modifyRequestToAcceptGzipResponse(request); addHeaders(request, syncToken); return execute(client, request); } public HttpResponse makeKeyFetchRequest(String baseUri, Date lastRequest) throws ClientProtocolException, IOException { HttpClient client = client(); Uri url = Uri.parse(baseUri); if (lastRequest != null) { url = url.buildUpon().appendQueryParameter("last_issued", DateUtils.formatTime(lastRequest, DateUtils.FORMAT_ISO8601)).build(); } HttpGet get = new HttpGet(url.toString()); return execute(client, get); } private void addHeaders(HttpRequestBase base, String lastToken) { //base.addHeader("Accept-Language", lang) base.addHeader("X-OpenRosa-Version", "1.0"); if (lastToken != null) { base.addHeader("X-CommCareHQ-LastSyncToken", lastToken); } base.addHeader("x-openrosa-deviceid", CommCareApplication._().getPhoneId()); } public String getSyncToken(String username) { if (username == null) { return null; } SqlStorage<User> storage = CommCareApplication._().getUserStorage(User.class); Vector<Integer> users = storage.getIDsForValue(User.META_USERNAME, username); //should be exactly one user if (users.size() != 1) { return null; } return storage.getMetaDataFieldForRecord(users.firstElement(), User.META_SYNC_TOKEN); } private String getDigest() { return CaseDBUtils.computeHash(CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class)); } public HttpResponse postData(String url, MultipartEntity entity) throws ClientProtocolException, IOException { // setup client HttpClient httpclient = client(); //If we're going to try to post with no credentials, we need to be explicit about the fact that we're //not ready if (credentials == null) { url = Uri.parse(url).buildUpon().appendQueryParameter(AUTH_REQUEST_TYPE, AUTH_REQUEST_TYPE_NO_AUTH).build().toString(); } HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); addHeaders(httppost, this.getSyncToken(username)); return execute(httpclient, httppost); } private HttpClient client() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, GlobalConstants.CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, GlobalConstants.CONNECTION_SO_TIMEOUT); HttpClientParams.setRedirecting(params, true); DefaultHttpClient client = new DefaultHttpClient(params); client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); System.setProperty("http.keepAlive", "false"); return client; } /** * Http requests are not so simple as "opening a request". Occasionally we may have to deal * with redirects. We don't want to just accept any redirect, though, since we may be directed * away from a secure connection. For now we'll only accept redirects from HTTP -> * servers, * or HTTPS -> HTTPS severs on the same domain */ private HttpResponse execute(HttpClient client, HttpUriRequest request) throws IOException { HttpContext context = new BasicHttpContext(); HttpResponse response = client.execute(request, context); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); //Don't allow redirects _from_ https _to_ https unless they are redirecting to the same server. URL originalRequest = request.getURI().toURL(); URL finalRedirect = new URL(currentUrl); if (!isValidRedirect(originalRequest, finalRedirect)) { Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Invalid redirect from " + originalRequest.toString() + " to " + finalRedirect.toString()); throw new IOException("Invalid redirect from secure server to insecure server"); } return response; } public static boolean isValidRedirect(URL url, URL newUrl) { //unless it's https, don't worry about it if (!url.getProtocol().equals("https")) { return true; } //if it is, verify that we're on the same server. if (url.getHost().equals(newUrl.getHost())) { return true; } else { //otherwise we got redirected from a secure link to a different //link, which isn't acceptable for now. return false; } } /** * TODO: At some point in the future this kind of division will be more central * but this generates an input stream for a URL using the best package for your * application * * @return a Stream to that URL */ public InputStream simpleGet(URL url) throws IOException { // only for versions past gingerbread use the HttpURLConnection if (android.os.Build.VERSION.SDK_INT > 11) { if (passwordAuthentication != null) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return passwordAuthentication; } }); } int responseCode = -1; HttpURLConnection con = (HttpURLConnection) url.openConnection(); setup(con); // Start the query con.connect(); try { responseCode = con.getResponseCode(); //It's possible we're getting redirected from http to https //if so, we need to handle it explicitly if (responseCode == 301) { //only allow one level of redirection here for now. Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Attempting 1 stage redirect from " + url.toString() + " to " + con.getURL().toString()); URL newUrl = new URL(con.getHeaderField("Location")); con.disconnect(); con = (HttpURLConnection) newUrl.openConnection(); setup(con); con.connect(); } //Don't allow redirects _from_ https _to_ https unless they are redirecting to the same server. if (!HttpRequestGenerator.isValidRedirect(url, con.getURL())) { Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Invalid redirect from " + url.toString() + " to " + con.getURL().toString()); throw new IOException("Invalid redirect from secure server to insecure server"); } return con.getInputStream(); } catch (IOException e) { if (e.getMessage().toLowerCase().contains("authentication") || responseCode == 401) { //Android http libraries _suuuuuck_, let's try apache. } else { throw e; } } } //On earlier versions of android use the apache libraries, they work much much better. Log.i(LOG_COMMCARE_NETWORK, "Falling back to Apache libs for network request"); HttpResponse get = get(url.toString()); if (get.getStatusLine().getStatusCode() == 404) { throw new FileNotFoundException("No Data available at URL " + url.toString()); } //TODO: Double check response code return get.getEntity().getContent(); } private void setup(HttpURLConnection con) throws IOException { con.setConnectTimeout(GlobalConstants.CONNECTION_TIMEOUT); con.setReadTimeout(GlobalConstants.CONNECTION_SO_TIMEOUT); con.setRequestMethod("GET"); con.setDoInput(true); con.setInstanceFollowRedirects(true); } }
public class Lab06 { public static int task9180(int A) throws Exception { if (A < -100 || A > 500) { throw new Exception("Значение A должно быть в интервале [-100, 500]"); } int sum = 0; while (-100 <= A && A <= 500) { sum = sum + A; A = A + 1; } return (sum); } public static double task2802(int n) throws Exception { if(n <= 0) { throw new Exception("Значение N должно быть положительным"); } double a = 1; double number = 0; while(a <= n) { number = number + (1 / a); a++; } return number; } }
package org.odk.collect.android.widgets; import android.content.Context; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.R; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.form.api.FormEntryPrompt; /** * Implements xform trigger tags, which are used to display messages on button * presses. This implementation is incomplete, acting like an output tag due to * a lack of message tag handling. * * @author wspride */ public class TriggerWidget extends QuestionWidget { private CheckBox mTriggerButton; /** * Stores the answer value of this question. Trigger elements shouldn't * have values, so this is contrary to the spec. */ private TextView mStringAnswer; /** * Shows a checkbox when set. */ private boolean mInteractive = true; /** * Value that this question is set to when in interactive mode and the * checkbox is clicked. */ private static String mOK = "OK"; /** * @param context Used to get font settings * @param prompt Contains question data * @param appearance Hint from form builder, when set to: * - 'minimal' show text label * - 'selectable' show a selectable text label useful for * copy/pasting output * - otherwise display interactively, showing a checkbox * with text */ public TriggerWidget(Context context, FormEntryPrompt prompt, String appearance) { super(context, prompt); // enable interactive mode if 'appearance' is an unrecognized string mInteractive = !("minimal".equals(appearance) || "selectable".equals(appearance)); if ("selectable".equals(appearance)) { if (android.os.Build.VERSION.SDK_INT >= 11) { // Let users to copy form display outputs. mQuestionText.setTextIsSelectable(true); } } if (mPrompt.getAppearanceHint() != null && mPrompt.getAppearanceHint().startsWith("floating-")) { this.setVisibility(View.GONE); } this.setOrientation(LinearLayout.VERTICAL); mTriggerButton = new CheckBox(getContext()); WidgetUtils.setupButton(mTriggerButton, StringUtils.getStringSpannableRobust(getContext(), R.string.trigger), mAnswerFontsize, !mPrompt.isReadOnly()); mTriggerButton.setOnClickListener(new View.OnClickListener() { /* * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { if (mTriggerButton.isChecked()) { mStringAnswer.setText(mOK); } else { mStringAnswer.setText(null); } TriggerWidget.this.widgetEntryChanged(); } }); // TODO PLM: This is never shown, but rather used to store the value of // this question, which shouldn't be needed since trigger shouldn't // have values. Figure out if anyone actually uses interactive mode, // and if not, remove. mStringAnswer = new TextView(getContext()); mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mStringAnswer.setGravity(Gravity.CENTER); String s = mPrompt.getAnswerText(); if (s != null) { mTriggerButton.setChecked(s.equals(mOK)); mStringAnswer.setText(s); } if (mInteractive) { this.addView(mTriggerButton); // this.addView(mStringAnswer); } } /* * (non-Javadoc) * @see org.odk.collect.android.widgets.QuestionWidget#clearAnswer() */ @Override public void clearAnswer() { mStringAnswer.setText(null); mTriggerButton.setChecked(false); } /* * (non-Javadoc) * @see org.odk.collect.android.widgets.QuestionWidget#getAnswer() */ @Override public IAnswerData getAnswer() { if (!mInteractive) { return new StringData(mOK); } String s = mStringAnswer.getText().toString(); if (s == null || s.equals("")) { return null; } else { return new StringData(s); } } /* * (non-Javadoc) * @see org.odk.collect.android.widgets.QuestionWidget#setFocus(android.content.Context) */ @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } /* * (non-Javadoc) * @see org.odk.collect.android.widgets.QuestionWidget#setOnLongClickListener(android.view.View.OnLongClickListener) */ @Override public void setOnLongClickListener(OnLongClickListener l) { mTriggerButton.setOnLongClickListener(l); mStringAnswer.setOnLongClickListener(l); } /* * (non-Javadoc) * @see org.odk.collect.android.widgets.QuestionWidget#cancelLongPress() */ @Override public void cancelLongPress() { super.cancelLongPress(); mTriggerButton.cancelLongPress(); mStringAnswer.cancelLongPress(); } }
package processing.app.syntax; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RecordableTextAction; import javax.swing.*; import javax.swing.text.*; import java.awt.event.ActionEvent; public class SketchTextAreaEditorKit extends RSyntaxTextAreaEditorKit { public static final String rtaDeleteNextWordAction = "RTA.DeleteNextWordAction"; public static final String rtaDeleteLineToCursorAction = "RTA.DeleteLineToCursorAction"; private static final Action[] defaultActions = { new DeleteNextWordAction(), new DeleteLineToCursorAction(), new SelectWholeLineAction(), new ToggleCommentAction() }; @Override public Action[] getActions() { return TextAction.augmentList(super.getActions(), SketchTextAreaEditorKit.defaultActions); } public static class DeleteNextWordAction extends RecordableTextAction { public DeleteNextWordAction() { super(rtaDeleteNextWordAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } try { int start = textArea.getSelectionStart(); int end = getNextWordStart(textArea, start); if (end > start) { textArea.getDocument().remove(start, end - start); } } catch (BadLocationException ex) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); } } @Override public String getMacroID() { return rtaDeleteNextWordAction; } /** * Returns the starting offset to delete. Exists so subclasses can * override. */ protected int getNextWordStart(RTextArea textArea, int end) throws BadLocationException { return Utilities.getNextWord(textArea, end); } } public static class DeleteLineToCursorAction extends RecordableTextAction { public DeleteLineToCursorAction() { super(rtaDeleteLineToCursorAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } try { // We use the elements instead of calling getLineOfOffset(), // etc. to speed things up just a tad (i.e. micro-optimize). Document document = textArea.getDocument(); int caretPosition = textArea.getCaretPosition(); Element map = document.getDefaultRootElement(); int currentLineNum = map.getElementIndex(caretPosition); Element currentLineElement = map.getElement(currentLineNum); int currentLineStart = currentLineElement.getStartOffset(); if (caretPosition > currentLineStart) { document.remove(currentLineStart, caretPosition - currentLineStart); } } catch (BadLocationException ble) { ble.printStackTrace(); } } @Override public String getMacroID() { return rtaDeleteLineToCursorAction; } } /** * Selects the line around the caret. */ public static class SelectWholeLineAction extends RecordableTextAction { public SelectWholeLineAction() { super(selectLineAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { Document document = textArea.getDocument(); Element map = document.getDefaultRootElement(); int currentLineNum = map.getElementIndex(textArea.getCaretPosition()); Element currentLineElement = map.getElement(currentLineNum); textArea.select(currentLineElement.getStartOffset(), currentLineElement.getEndOffset()); } @Override public final String getMacroID() { return DefaultEditorKit.selectLineAction; } } public static class ToggleCommentAction extends RecordableTextAction { public ToggleCommentAction() { super(rstaToggleCommentAction); } @Override public void actionPerformedImpl(ActionEvent e, RTextArea textArea) { if (!textArea.isEditable() || !textArea.isEnabled()) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } RSyntaxDocument doc = (RSyntaxDocument) textArea.getDocument(); Element map = doc.getDefaultRootElement(); Caret c = textArea.getCaret(); int dot = c.getDot(); int mark = c.getMark(); int line1 = map.getElementIndex(dot); int line2 = map.getElementIndex(mark); int start = Math.min(line1, line2); int end = Math.max(line1, line2); org.fife.ui.rsyntaxtextarea.Token t = doc.getTokenListForLine(start); int languageIndex = t != null ? t.getLanguageIndex() : 0; String[] startEnd = doc.getLineCommentStartAndEnd(languageIndex); if (startEnd == null) { UIManager.getLookAndFeel().provideErrorFeedback(textArea); return; } // Don't toggle comment on last line if there is no // text selected on it. if (start != end) { Element elem = map.getElement(end); if (Math.max(dot, mark) == elem.getStartOffset()) { end } } textArea.beginAtomicEdit(); try { boolean add = getDoAdd(doc, map, start, end, startEnd); for (line1 = start; line1 <= end; line1++) { Element elem = map.getElement(line1); handleToggleComment(elem, doc, startEnd, add); } } catch (BadLocationException ble) { ble.printStackTrace(); UIManager.getLookAndFeel().provideErrorFeedback(textArea); } finally { textArea.endAtomicEdit(); } } private boolean getDoAdd(Document doc, Element map, int startLine, int endLine, String[] startEnd) throws BadLocationException { boolean doAdd = false; for (int i = startLine; i <= endLine; i++) { Element elem = map.getElement(i); int start = elem.getStartOffset(); String t = doc.getText(start, elem.getEndOffset() - start - 1).trim(); if (!t.startsWith(startEnd[0]) || (startEnd[1] != null && !t.endsWith(startEnd[1]))) { doAdd = true; break; } } return doAdd; } private void handleToggleComment(Element elem, Document doc, String[] startEnd, boolean add) throws BadLocationException { int start = elem.getStartOffset(); int end = elem.getEndOffset() - 1; if (add) { doc.insertString(start, startEnd[0], null); if (startEnd[1] != null) { doc.insertString(end + startEnd[0].length(), startEnd[1], null); } } else { String text = doc.getText(start, elem.getEndOffset() - start - 1); start += text.indexOf(startEnd[0]); doc.remove(start, startEnd[0].length()); if (startEnd[1] != null) { int temp = startEnd[1].length(); doc.remove(end - startEnd[0].length() - temp, temp); } } } @Override public final String getMacroID() { return rstaToggleCommentAction; } } }
package acr.browser.lightning.activity; import android.app.Activity; import android.app.Application; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; import android.webkit.WebView; import com.squareup.otto.Bus; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import acr.browser.lightning.R; import acr.browser.lightning.app.BrowserApp; import acr.browser.lightning.constant.BookmarkPage; import acr.browser.lightning.constant.Constants; import acr.browser.lightning.constant.HistoryPage; import acr.browser.lightning.constant.StartPage; import acr.browser.lightning.database.BookmarkManager; import acr.browser.lightning.database.HistoryDatabase; import acr.browser.lightning.dialog.BrowserDialog; import acr.browser.lightning.preference.PreferenceManager; import com.anthonycr.bonsai.Action; import com.anthonycr.bonsai.Observable; import com.anthonycr.bonsai.OnSubscribe; import com.anthonycr.bonsai.Schedulers; import com.anthonycr.bonsai.Subscriber; import acr.browser.lightning.utils.FileUtils; import acr.browser.lightning.utils.UrlUtils; import acr.browser.lightning.view.LightningView; /** * A manager singleton that holds all the {@link LightningView} * and tracks the current tab. It handles creation, deletion, * restoration, state saving, and switching of tabs. */ public class TabsManager { private static final String TAG = TabsManager.class.getSimpleName(); private static final String BUNDLE_KEY = "WEBVIEW_"; private static final String URL_KEY = "URL_KEY"; private static final String BUNDLE_STORAGE = "SAVED_TABS.parcel"; private final List<LightningView> mTabList = new ArrayList<>(1); @Nullable private LightningView mCurrentTab; @Nullable private TabNumberChangedListener mTabNumberListener; private boolean mIsInitialized = false; private final List<Runnable> mPostInitializationWorkList = new ArrayList<>(); @Inject PreferenceManager mPreferenceManager; @Inject BookmarkManager mBookmarkManager; @Inject HistoryDatabase mHistoryManager; @Inject Bus mEventBus; @Inject Application mApp; public TabsManager() { BrowserApp.getAppComponent().inject(this); } // TODO remove and make presenter call new tab methods so it always knows @Deprecated public interface TabNumberChangedListener { void tabNumberChanged(int newNumber); } public void setTabNumberChangedListener(@Nullable TabNumberChangedListener listener) { mTabNumberListener = listener; } public void cancelPendingWork() { mPostInitializationWorkList.clear(); } public synchronized void doAfterInitialization(@NonNull Runnable runnable) { if (mIsInitialized) { runnable.run(); } else { mPostInitializationWorkList.add(runnable); } } private synchronized void finishInitialization() { mIsInitialized = true; for (Runnable runnable : mPostInitializationWorkList) { runnable.run(); } } /** * Restores old tabs that were open before the browser * was closed. Handles the intent used to open the browser. * * @param activity the activity needed to create tabs. * @param intent the intent that started the browser activity. * @param incognito whether or not we are in incognito mode. */ public synchronized Observable<Void> initializeTabs(@NonNull final Activity activity, @Nullable final Intent intent, final boolean incognito) { return Observable.create(new Action<Void>() { @Override public void onSubscribe(@NonNull final Subscriber<Void> subscriber) { // Make sure we start with a clean tab list shutdown(); String url = null; if (intent != null) { url = intent.getDataString(); } // If incognito, only create one tab if (incognito) { newTab(activity, url, true); subscriber.onComplete(); return; } Log.d(TAG, "URL from intent: " + url); mCurrentTab = null; if (mPreferenceManager.getRestoreLostTabsEnabled()) { restoreLostTabs(url, activity, subscriber); } else { if (!TextUtils.isEmpty(url)) { newTab(activity, url, false); } else { newTab(activity, null, false); } finishInitialization(); subscriber.onComplete(); } } }); } private void restoreLostTabs(@Nullable final String url, @NonNull final Activity activity, @NonNull final Subscriber subscriber) { restoreState().subscribeOn(Schedulers.io()) .observeOn(Schedulers.main()).subscribe(new OnSubscribe<Bundle>() { @Override public void onNext(Bundle item) { LightningView tab = newTab(activity, "", false); String url = item.getString(URL_KEY); if (url != null && tab.getWebView() != null) { if (UrlUtils.isBookmarkUrl(url)) { new BookmarkPage(tab, activity, mBookmarkManager).load(); } else if (UrlUtils.isStartPageUrl(url)) { new StartPage(tab, mApp).load(); } else if (UrlUtils.isHistoryUrl(url)) { new HistoryPage(tab, mApp, mHistoryManager).load(); } } else if (tab.getWebView() != null) { tab.getWebView().restoreState(item); } } @Override public void onComplete() { if (url != null) { if (url.startsWith(Constants.FILE)) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); Dialog dialog = builder.setCancelable(true) .setTitle(R.string.title_warning) .setMessage(R.string.message_blocked_local) .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (mTabList.isEmpty()) { newTab(activity, null, false); } finishInitialization(); subscriber.onComplete(); } }) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.action_open, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { newTab(activity, url, false); } }).show(); BrowserDialog.setDialogSize(activity, dialog); } else { newTab(activity, url, false); if (mTabList.isEmpty()) { newTab(activity, null, false); } finishInitialization(); subscriber.onComplete(); } } else { if (mTabList.isEmpty()) { newTab(activity, null, false); } finishInitialization(); subscriber.onComplete(); } } }); } /** * Method used to resume all the tabs in the browser. * This is necessary because we cannot pause the * WebView when the app is open currently due to a * bug in the WebView, where calling onResume doesn't * consistently resume it. * * @param context the context needed to initialize * the LightningView preferences. */ public void resumeAll(@NonNull Context context) { LightningView current = getCurrentTab(); if (current != null) { current.resumeTimers(); } for (LightningView tab : mTabList) { if (tab != null) { tab.onResume(); tab.initializePreferences(context); } } } /** * Method used to pause all the tabs in the browser. * This is necessary because we cannot pause the * WebView when the app is open currently due to a * bug in the WebView, where calling onResume doesn't * consistently resume it. */ public void pauseAll() { LightningView current = getCurrentTab(); if (current != null) { current.pauseTimers(); } for (LightningView tab : mTabList) { if (tab != null) { tab.onPause(); } } } /** * Return the tab at the given position in tabs list, or * null if position is not in tabs list range. * * @param position the index in tabs list * @return the corespondent {@link LightningView}, * or null if the index is invalid */ @Nullable public synchronized LightningView getTabAtPosition(final int position) { if (position < 0 || position >= mTabList.size()) { return null; } return mTabList.get(position); } /** * Frees memory for each tab in the * manager. Note: this will only work * on API < KITKAT as on KITKAT onward * the WebViews manage their own * memory correctly. */ public synchronized void freeMemory() { for (LightningView tab : mTabList) { //noinspection deprecation tab.freeMemory(); } } /** * Shutdown the manager. This destroys * all tabs and clears the references * to those tabs. Current tab is also * released for garbage collection. */ public synchronized void shutdown() { for (LightningView tab : mTabList) { tab.onDestroy(); } mTabList.clear(); mIsInitialized = false; mCurrentTab = null; } /** * Forwards network connection status to the WebViews. * * @param isConnected whether there is a network * connection or not. */ public synchronized void notifyConnectionStatus(final boolean isConnected) { for (LightningView tab : mTabList) { final WebView webView = tab.getWebView(); if (webView != null) { webView.setNetworkAvailable(isConnected); } } } /** * The current number of tabs in the manager. * * @return the number of tabs in the list. */ public synchronized int size() { return mTabList.size(); } /** * The index of the last tab in the manager. * * @return the last tab in the list or -1 if there are no tabs. */ public synchronized int last() { return mTabList.size() - 1; } /** * The last tab in the tab manager. * * @return the last tab, or null if * there are no tabs. */ @Nullable public synchronized LightningView lastTab() { if (last() < 0) { return null; } return mTabList.get(last()); } /** * Create and return a new tab. The tab is * automatically added to the tabs list. * * @param activity the activity needed to create the tab. * @param url the URL to initialize the tab with. * @param isIncognito whether the tab is an incognito * tab or not. * @return a valid initialized tab. */ @NonNull public synchronized LightningView newTab(@NonNull final Activity activity, @Nullable final String url, final boolean isIncognito) { Log.d(TAG, "New tab"); final LightningView tab = new LightningView(activity, url, isIncognito); mTabList.add(tab); if (mTabNumberListener != null) { mTabNumberListener.tabNumberChanged(size()); } return tab; } /** * Removes a tab from the list and destroys the tab. * If the tab removed is the current tab, the reference * to the current tab will be nullified. * * @param position The position of the tab to remove. */ private synchronized void removeTab(final int position) { if (position >= mTabList.size()) { return; } final LightningView tab = mTabList.remove(position); if (mCurrentTab == tab) { mCurrentTab = null; } tab.onDestroy(); } /** * Deletes a tab from the manager. If the tab * being deleted is the current tab, this method * will switch the current tab to a new valid tab. * * @param position the position of the tab to delete. * @return returns true if the current tab * was deleted, false otherwise. */ public synchronized boolean deleteTab(int position) { Log.d(TAG, "Delete tab: " + position); final LightningView currentTab = getCurrentTab(); int current = positionOf(currentTab); if (current == position) { if (size() == 1) { mCurrentTab = null; } else if (current < size() - 1) { // There is another tab after this one switchToTab(current + 1); } else { switchToTab(current - 1); } } removeTab(position); if (mTabNumberListener != null) { mTabNumberListener.tabNumberChanged(size()); } return current == position; } /** * Return the position of the given tab. * * @param tab the tab to look for. * @return the position of the tab or -1 * if the tab is not in the list. */ public synchronized int positionOf(final LightningView tab) { return mTabList.indexOf(tab); } /** * Saves the state of the current WebViews, * to a bundle which is then stored in persistent * storage and can be unparceled. */ public void saveState() { Bundle outState = new Bundle(ClassLoader.getSystemClassLoader()); Log.d(Constants.TAG, "Saving tab state"); for (int n = 0; n < mTabList.size(); n++) { LightningView tab = mTabList.get(n); if (TextUtils.isEmpty(tab.getUrl())) { continue; } Bundle state = new Bundle(ClassLoader.getSystemClassLoader()); if (tab.getWebView() != null && !UrlUtils.isSpecialUrl(tab.getUrl())) { tab.getWebView().saveState(state); outState.putBundle(BUNDLE_KEY + n, state); } else if (tab.getWebView() != null) { state.putString(URL_KEY, tab.getUrl()); outState.putBundle(BUNDLE_KEY + n, state); } } FileUtils.writeBundleToStorage(mApp, outState, BUNDLE_STORAGE); } /** * Use this method to clear the saved * state if you do not wish it to be * restored when the browser next starts. */ public void clearSavedState() { FileUtils.deleteBundleInStorage(mApp, BUNDLE_STORAGE); } /** * Restores the previously saved tabs from the * bundle stored in peristent file storage. * It will create new tabs for each tab saved * and will delete the saved instance file when * restoration is complete. */ private Observable<Bundle> restoreState() { return Observable.create(new Action<Bundle>() { @Override public void onSubscribe(@NonNull Subscriber<Bundle> subscriber) { Bundle savedState = FileUtils.readBundleFromStorage(mApp, BUNDLE_STORAGE); if (savedState != null) { Log.d(Constants.TAG, "Restoring previous WebView state now"); for (String key : savedState.keySet()) { if (key.startsWith(BUNDLE_KEY)) { subscriber.onNext(savedState.getBundle(key)); } } } FileUtils.deleteBundleInStorage(mApp, BUNDLE_STORAGE); subscriber.onComplete(); } }); } /** * Return the {@link WebView} associated to the current tab, * or null if there is no current tab. * * @return a {@link WebView} or null if there is no current tab. */ @Nullable public synchronized WebView getCurrentWebView() { return mCurrentTab != null ? mCurrentTab.getWebView() : null; } /** * Returns the index of the current tab. * * @return Return the index of the current tab, or -1 if the * current tab is null. */ public synchronized int indexOfCurrentTab() { return mTabList.indexOf(mCurrentTab); } /** * Returns the index of the tab. * * @return Return the index of the tab, or -1 if the tab isn't in the list. */ public synchronized int indexOfTab(LightningView tab) { return mTabList.indexOf(tab); } /** * Return the current {@link LightningView} or null if * no current tab has been set. * * @return a {@link LightningView} or null if there * is no current tab. */ @Nullable public synchronized LightningView getCurrentTab() { return mCurrentTab; } /** * Switch the current tab to the one at the given position. * It returns the selected tab that has been switced to. * * @return the selected tab or null if position is out of tabs range. */ @Nullable public synchronized LightningView switchToTab(final int position) { Log.d(TAG, "switch to tab: " + position); if (position < 0 || position >= mTabList.size()) { Log.e(TAG, "Returning a null LightningView requested for position: " + position); return null; } else { final LightningView tab = mTabList.get(position); if (tab != null) { mCurrentTab = tab; } return tab; } } }
package cat.xojan.random1.ui.activity; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import javax.inject.Inject; import cat.xojan.random1.R; import cat.xojan.random1.injection.HasComponent; import cat.xojan.random1.injection.component.DaggerHomeComponent; import cat.xojan.random1.injection.component.HomeComponent; import cat.xojan.random1.injection.module.HomeModule; import cat.xojan.random1.ui.adapter.HomePagerAdapter; import cat.xojan.random1.ui.fragment.BaseFragment; import cat.xojan.random1.ui.fragment.DownloadsFragment; import cat.xojan.random1.ui.fragment.HourByHourListFragment; import cat.xojan.random1.ui.fragment.PodcastListFragment; import cat.xojan.random1.ui.fragment.ProgramFragment; import cat.xojan.random1.ui.fragment.SectionFragment; import cat.xojan.random1.viewmodel.PodcastsViewModel; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class HomeActivity extends BaseActivity implements HasComponent { private static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 20; @Inject PodcastsViewModel mViewModel; private HomeComponent mComponent; private ViewPager mViewPager; private TabLayout mTabLayout; HomePagerAdapter mFragmentAdapter; private Subscription mSubscription; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = getIntent(); if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0 && intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intent.getAction() != null && intent.getAction().equals(Intent.ACTION_MAIN)) { finish(); return; } setContentView(R.layout.activity_home); findView(); initView(); initInjector(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.home, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_export_podcasts: if (ContextCompat.checkSelfPermission(this, Manifest.permission. WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestWriteExternalStoragePermission(); } else { exportPodcasts(); } break; } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PERMISSION_WRITE_EXTERNAL_STORAGE: { exportPodcasts(); break; } } } private void requestWriteExternalStoragePermission() { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_STORAGE); } private void initInjector() { mComponent = DaggerHomeComponent.builder() .appComponent(getApplicationComponent()) .baseActivityModule(getActivityModule()) .homeModule(new HomeModule(this)) .build(); mComponent.inject(this); } private void findView() { mViewPager = (ViewPager) findViewById(R.id.viewpager); mTabLayout = (TabLayout) findViewById(R.id.tabs); } private void initView() { mFragmentAdapter = new HomePagerAdapter(getSupportFragmentManager(), this); mFragmentAdapter.addFragment(new ProgramFragment()); mFragmentAdapter.addFragment(new DownloadsFragment()); mViewPager.setAdapter(mFragmentAdapter); mTabLayout.setupWithViewPager(mViewPager); } @Override public HomeComponent getComponent() { return mComponent; } @Override public void onBackPressed() { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { Fragment fragment = getFragment(HourByHourListFragment.TAG); if (fragment == null) fragment = getFragment(SectionFragment.TAG); if (fragment != null && getSupportFragmentManager() .findFragmentByTag(PodcastListFragment.TAG) == null) { if (((BaseFragment) fragment).handleOnBackPressed()) { return; } } } super.onBackPressed(); } @Override protected void onStop() { super.onStop(); if (mSubscription != null && !mSubscription.isUnsubscribed()) { mSubscription.unsubscribe(); } } private void exportPodcasts() { mSubscription = mViewModel.exportPodcasts() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::notifyUser); } private void notifyUser(Boolean b) { Toast.makeText(this, getString(R.string.podcasts_exported), Toast.LENGTH_LONG).show(); } }
package com.a2017hkt15.sortaddr; import android.content.Intent; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.skp.Tmap.TMapData; import com.skp.Tmap.TMapPOIItem; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class FullAddressActivty extends AppCompatActivity { String address_text; TMapData tMapdata = new TMapData(); private ArrayList<String> addressList = new ArrayList<>(); String a; private ArrayList<String> address_List; private ArrayAdapter<String> Adapter; String fulladdress; String final_fulladdress; EditText edit_law; EditText edit_ex; int position; float lati_full; float lon_full; List<Address> addr = null; private ArrayList<String> address_list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_full_address_activty); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_auto_complete); setSupportActionBar(toolbar); toolbar.setTitle(R.string.app_name); String subtitle = " : "; toolbar.setSubtitle(subtitle); toolbar.setTitleTextColor(Color.WHITE); toolbar.setSubtitleTextColor(ContextCompat.getColor(FullAddressActivty.this, R.color.colorSubtitle)); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } Button button = (Button) findViewById(R.id.button); edit_ex = (EditText) findViewById(R.id.edit_ex); edit_law = (EditText) findViewById(R.id.edit); Adapter = new ArrayAdapter<String>(FullAddressActivty.this, android.R.layout.simple_list_item_1, addressList); Log.i("gggg2", "gggg"); edit_law.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { onClick(v); return true; } return false; } }); edit_ex.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { onPass(v); return true; } return false; } }); } @Override public boolean onOptionsItemSelected(android.view.MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent intent = new Intent(FullAddressActivty.this, InputActivity.class); setResult(RESULT_CANCELED, intent); finish(); break; } return super.onOptionsItemSelected(item); } public void onClick(View v) { // final EditText edit_law = (EditText) findViewById(R.id.edit); final ArrayList<String> addressList = new ArrayList<>(); fulladdress = edit_law.getText().toString(); Log.i("check123", fulladdress); tMapdata.findAddressPOI(fulladdress, 300, new TMapData.FindAddressPOIListenerCallback() { @Override public void onFindAddressPOI(ArrayList<TMapPOIItem> poiItem) { if(poiItem.size()==0) { addressList.clear(); addressList.add(" "); } for (int i = 0; i < poiItem.size(); i++) { TMapPOIItem item = poiItem.get(i); addressList.add(item.getPOIAddress().replace("null", "")); } HashSet hs = new HashSet(addressList); address_list = new ArrayList<String>(hs); // ArrayList<String> address_List = new ArrayList<String>(hs); runOnUiThread(new Runnable() { public void run() { ListView list = (ListView) findViewById(R.id.list); Adapter = new ArrayAdapter<String>(FullAddressActivty.this, android.R.layout.simple_list_item_1, address_list); list.setAdapter(Adapter); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { edit_law.setText(address_list.get(position)); fulladdress = edit_law.getText().toString(); } }); } }); } }); } public void onPass(View v) { final_fulladdress = fulladdress + edit_ex.getText().toString(); Log.i("final", final_fulladdress); //intent pos final Location loc = new Location(""); final Geocoder geocoder = new Geocoder(FullAddressActivty.this); Intent intent = getIntent(); position = intent.getIntExtra("position", 0); Log.i("position",position+""); Intent intent1 = new Intent(FullAddressActivty.this, InputActivity.class); runOnUiThread(new Runnable() { public void run() { try { addr = geocoder.getFromLocationName(fulladdress, 5); } catch (IOException e) { e.printStackTrace(); } if (addr != null) { if (addr.size() == 0) Log.i("error", "addr.size222 == 0"); for (int i = 0; i < addr.size(); i++) { Address lating = addr.get(i); double lat = lating.getLatitude(); double lon = lating.getLongitude(); loc.setLatitude(lat); loc.setLongitude(lon); lati_full = Float.parseFloat(String.valueOf(loc.getLatitude())); lon_full = Float.parseFloat(String.valueOf(loc.getLongitude())); Log.i("check20", String.valueOf(loc.getLatitude())); Log.i("check10", String.valueOf(loc.getLongitude())); } } } }); intent1.putExtra("lati_full",lati_full); intent1.putExtra("lon_full",lon_full); intent1.putExtra("position_full",position); intent1.putExtra("fulladdress",final_fulladdress); intent1.putExtra("division",2); setResult(RESULT_OK, intent1); finish(); } }
package com.alorma.github.ui.activity; import android.accounts.Account; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import com.alorma.github.AccountsHelper; import com.alorma.github.R; import com.alorma.github.StoreCredentials; import com.alorma.github.sdk.services.notifications.GetNotificationsClient; import com.alorma.github.ui.ErrorHandler; import com.alorma.github.ui.activity.base.BaseActivity; import com.alorma.github.ui.fragment.GeneralPeopleFragment; import com.alorma.github.ui.fragment.NavigationFragment; import com.alorma.github.ui.fragment.donate.DonateActivity; import com.alorma.github.ui.fragment.events.EventsListFragment; import com.alorma.github.ui.fragment.events.OrgsEventsListFragment; import com.alorma.github.ui.fragment.gists.AuthUserGistsFragment; import com.alorma.github.ui.fragment.gists.AuthUserStarredGistsFragment; import com.alorma.github.ui.fragment.issues.GeneralIssuesListFragment; import com.alorma.github.ui.fragment.orgs.OrgsMembersFragment; import com.alorma.github.ui.fragment.orgs.OrgsReposFragment; import com.alorma.github.ui.fragment.repos.GeneralReposFragment; import com.alorma.github.ui.utils.DrawerImage; import com.alorma.github.utils.AccountUtils; import com.mikepenz.actionitembadge.library.ActionItemBadge; import com.mikepenz.actionitembadge.library.utils.BadgeStyle; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.materialdrawer.AccountHeader; import com.mikepenz.materialdrawer.AccountHeaderBuilder; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.holder.StringHolder; import com.mikepenz.materialdrawer.model.DividerDrawerItem; import com.mikepenz.materialdrawer.model.ExpandableDrawerItem; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.SecondaryDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import com.mikepenz.materialdrawer.util.DrawerImageLoader; import com.mikepenz.octicons_typeface_library.Octicons; import core.User; import core.notifications.Notification; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends BaseActivity implements NavigationFragment.NavigationCallback { private Account selectedAccount; private Fragment lastUsedFragment; private Drawer resultDrawer; private int notificationsSizeCount = 0; private NavigationFragment navigationFragment; private AccountHeader accountHeader; private Map<String, List<IDrawerItem>> drawerItems; public static void startActivity(Activity context) { Intent intent = new Intent(context, MainActivity.class); context.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AccountsManager accountsFragment = new AccountsManager(); List<Account> accounts = accountsFragment.getAccounts(this); if (accounts.isEmpty()) { Intent intent = new Intent(this, WelcomeActivity.class); startActivity(intent); finish(); } setContentView(R.layout.generic_toolbar_responsive); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public void onStart() { super.onStart(); if (resultDrawer == null) { List<Account> accounts = getAccounts(); if (!accounts.isEmpty()) { selectedAccount = accounts.get(0); createDrawer(); selectAccount(selectedAccount); onUserEventsSelected(); } } navigationFragment.setNavigationCallback(this); } @Override protected void onStop() { navigationFragment.setNavigationCallback(null); super.onStop(); } private String getUserExtraName(Account account) { String accountName = getNameFromAccount(account); String userMail = AccountsHelper.getUserMail(this, account); String userName = AccountsHelper.getUserName(this, account); if (!TextUtils.isEmpty(userMail)) { return userMail; } else if (!TextUtils.isEmpty(userName)) { return userName; } return accountName; } private String getNameFromAccount(Account account) { return new AccountUtils().getNameFromAccount(account.name); } private void createDrawer() { accountHeader = buildHeader(); DrawerBuilder drawer = new DrawerBuilder(); drawer.withActivity(this); drawer.withToolbar(getToolbar()); drawer.withAccountHeader(accountHeader, true); List<IDrawerItem> userItems = getUserDrawerItems(); for (IDrawerItem userItem : userItems) { drawer.addDrawerItems(userItem); } List<IDrawerItem> allProfilesItems = getStickyDrawerItems(); for (IDrawerItem allProfilesItem : allProfilesItems) { drawer.addStickyDrawerItems(allProfilesItem); } Drawer.OnDrawerItemClickListener drawerListener = (view, position, drawerItem) -> { if (drawerItem != null) { long identifier = drawerItem.getIdentifier(); switch ((int) identifier) { case R.id.nav_drawer_notifications: openNotifications(); break; case R.id.nav_drawer_settings: onSettingsSelected(); break; case R.id.nav_drawer_donate: onDonateSelected(); break; case R.id.nav_drawer_sign_out: signOut(); return true; } } return false; }; drawer.withOnDrawerItemClickListener(drawerListener); resultDrawer = drawer.build(); resultDrawer.setSelection(R.id.nav_drawer_events); } private List<IDrawerItem> getUserDrawerItems() { int iconColor = ContextCompat.getColor(this, R.color.icons); List<IDrawerItem> items = new ArrayList<>(); items.add(new PrimaryDrawerItem().withName(R.string.menu_events) .withIcon(Octicons.Icon.oct_calendar) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_events) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onUserEventsSelected(); return false; })); items.add(new PrimaryDrawerItem().withName(R.string.navigation_general_repositories) .withIcon(Octicons.Icon.oct_repo) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_repositories) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onReposSelected(); return false; })); items.add(new PrimaryDrawerItem().withName(R.string.navigation_people) .withIcon(Octicons.Icon.oct_organization) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_people) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onPeopleSelected(); return false; })); items.add(new PrimaryDrawerItem().withName(R.string.navigation_issues) .withIcon(Octicons.Icon.oct_issue_opened) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_issues) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onIssuesSelected(); return false; })); PrimaryDrawerItem myGistsDrawerItem = new PrimaryDrawerItem().withName(R.string.navigation_my_gists) .withIdentifier(R.id.nav_drawer_gists) .withLevel(2) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onGistsSelected(); return false; }); PrimaryDrawerItem starredGistsDrawerItem = new PrimaryDrawerItem().withName(R.string.navigation_gists_starred) .withIdentifier(R.id.nav_drawer_gists_starred) .withLevel(2) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onStarredGistsSelected(); return false; }); items.add(new ExpandableDrawerItem().withName(R.string.navigation_gists) .withSubItems(myGistsDrawerItem, starredGistsDrawerItem) .withIcon(Octicons.Icon.oct_gist) .withIconColor(iconColor) .withSelectable(false)); return items; } private List<IDrawerItem> getStickyDrawerItems() { int iconColor = ContextCompat.getColor(this, R.color.icons); List<IDrawerItem> items = new ArrayList<>(); items.add(new SecondaryDrawerItem().withName(R.string.menu_enable_notifications) .withIdentifier(R.id.nav_drawer_notifications) .withSelectable(false) .withIcon(Octicons.Icon.oct_bell) .withIconColor(iconColor)); items.add(new SecondaryDrawerItem().withName(R.string.navigation_settings) .withIcon(Octicons.Icon.oct_gear) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_settings) .withSelectable(false)); items.add(new SecondaryDrawerItem().withName(R.string.action_donate) .withIcon(Octicons.Icon.oct_heart) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_donate) .withSelectable(false)); items.add(new DividerDrawerItem()); items.add(new SecondaryDrawerItem().withName(R.string.navigation_sign_out) .withIcon(Octicons.Icon.oct_sign_out) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_sign_out) .withSelectable(false)); return items; } private AccountHeader buildHeader() { DrawerImageLoader.init(new DrawerImage()); AccountHeaderBuilder headerBuilder = new AccountHeaderBuilder().withActivity(this).withHeaderBackground(R.color.md_grey_600); headerBuilder.withOnAccountHeaderListener((view, profile, current) -> { if (current) { User user = new User(); user.setLogin(profile.getName().getText()); Intent launcherIntent = ProfileActivity.createLauncherIntent(MainActivity.this, selectedAccount); startActivity(launcherIntent); return true; } else { if (profile instanceof ProfileDrawerItem) { List<IDrawerItem> subItems = drawerItems.get(profile.getName().getText()); if (subItems != null && !subItems.isEmpty()) { resultDrawer.removeAllItems(); for (IDrawerItem subItem : subItems) { resultDrawer.addItems(subItem); } try { ((PrimaryDrawerItem) subItems.get(0)).getOnDrawerItemClickListener().onItemClick(null, 0, subItems.get(0)); } catch (Exception e) { e.printStackTrace(); } resultDrawer.setSelection(R.id.nav_drawer_events, true); } } return false; } }); ProfileDrawerItem userDrawerItem = getUserDrawerItem(); drawerItems = new HashMap<>(); drawerItems.put(userDrawerItem.getName().getText(), getUserDrawerItems()); userDrawerItem.withSubItems(); headerBuilder.addProfiles(userDrawerItem); return headerBuilder.build(); } @NonNull private ProfileDrawerItem getOrganizationProfileDrawerItem(User user) { return new ProfileDrawerItem().withName(user.getLogin()).withIcon(getUserAvatarUrl(user.getAvatar(), user.getLogin())); } private Uri getUserAvatarUrl(String avatar, String name) { return Uri.parse(avatar).buildUpon().appendQueryParameter("username", name).build(); } private List<IDrawerItem> getOrganizationProfileSubItems(User user) { int iconColor = ContextCompat.getColor(this, R.color.icons); List<IDrawerItem> items = new ArrayList<>(); items.add(new PrimaryDrawerItem().withName("Events") .withIcon(Octicons.Icon.oct_calendar) .withIconColor(iconColor) .withIdentifier(R.id.nav_drawer_events) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onOrgEventsSelected(user.getLogin()); return false; })); items.add(new PrimaryDrawerItem().withName("Repositories") .withIcon(Octicons.Icon.oct_repo) .withIconColor(iconColor) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onOrgReposSelected(user.getLogin()); return false; })); items.add(new PrimaryDrawerItem().withName("Members") .withIcon(Octicons.Icon.oct_organization) .withIconColor(iconColor) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onOrgPeopleSelected(user.getLogin()); return false; })); items.add(new PrimaryDrawerItem().withName("Teams") .withIcon(Octicons.Icon.oct_jersey) .withIconColor(iconColor) .withEnabled(false) .withOnDrawerItemClickListener((view, position, drawerItem) -> { onOrgTeamsSelected(user.getLogin()); return false; })); return items; } private ProfileDrawerItem getUserDrawerItem() { String userName = getNameFromAccount(selectedAccount); String userAvatar = AccountsHelper.getUserAvatar(this, selectedAccount); ProfileDrawerItem userDrawerItem = new ProfileDrawerItem().withName(getUserExtraName(selectedAccount)) .withEmail(userName) .withNameShown(false) .withIdentifier(selectedAccount.hashCode()); if (!TextUtils.isEmpty(userAvatar)) { userDrawerItem.withIcon(getUserAvatarUrl(userAvatar, userName)); } return userDrawerItem; } private void selectAccount(final Account account) { boolean changingUser = selectedAccount != null && !getNameFromAccount(selectedAccount).equals(getNameFromAccount(account)); this.selectedAccount = account; accountNameProvider.setName(getNameFromAccount(account)); loadUserOrgs(); StoreCredentials credentials = new StoreCredentials(MainActivity.this); credentials.clear(); String authToken = AccountsHelper.getUserToken(this, account); credentials.storeToken(authToken); credentials.storeUsername(getNameFromAccount(account)); credentials.storeUrl(AccountsHelper.getUrl(this, account)); String url = AccountsHelper.getUrl(this, account); credentials.storeUrl(url); if (changingUser) { lastUsedFragment = null; } } private void loadUserOrgs() { navigationFragment = new NavigationFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(new NavigationFragment(), "navigation"); ft.commit(); navigationFragment.setNavigationCallback(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.main_menu, menu); menu.findItem(R.id.action_search) .setIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_search).color(Color.WHITE).sizeDp(24).respectFontBounds(true)); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (notificationsSizeCount > 0) { BadgeStyle badgeStyle = new BadgeStyle(BadgeStyle.Style.DEFAULT, R.layout.menu_action_item_badge, getResources().getColor(R.color.accent), getResources().getColor(R.color.accent_dark), Color.WHITE, getResources().getDimensionPixelOffset(R.dimen.gapMicro)); ActionItemBadge.update(this, menu.findItem(R.id.action_notifications), Octicons.Icon.oct_bell, badgeStyle, notificationsSizeCount); } else { ActionItemBadge.hide(menu.findItem(R.id.action_notifications)); } return super.onPrepareOptionsMenu(menu); } @Override protected void onResume() { super.onResume(); checkNotifications(); } private void checkNotifications() { GetNotificationsClient client = new GetNotificationsClient(); client.observable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<List<Notification>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<Notification> notifications) { notificationsSizeCount = notifications.size(); invalidateOptionsMenu(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_search) { Intent intent = SearchActivity.launchIntent(this); startActivity(intent); } else if (item.getItemId() == R.id.action_notifications) { openNotifications(); } return false; } private void openNotifications() { Intent intent = NotificationsActivity.launchIntent(this); startActivity(intent); } private void setFragment(Fragment fragment) { setFragment(fragment, true); } private void setFragment(Fragment fragment, boolean addToBackStack) { try { if (fragment != null && getSupportFragmentManager() != null) { this.lastUsedFragment = fragment; FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (ft != null) { ft.replace(R.id.content, fragment); if (addToBackStack) { ft.addToBackStack("navigation"); } ft.commit(); } } } catch (Exception e) { ErrorHandler.onError(this, "MainActivity.setFragment()", e); } } public void onDonateSelected() { Intent intent = new Intent(this, DonateActivity.class); startActivity(intent); } public boolean onReposSelected() { setFragment(GeneralReposFragment.newInstance(), false); return true; } public boolean onPeopleSelected() { setFragment(GeneralPeopleFragment.newInstance(), false); return false; } public boolean onIssuesSelected() { setFragment(GeneralIssuesListFragment.newInstance(), false); return false; } public boolean onGistsSelected() { AuthUserGistsFragment gistsFragment = AuthUserGistsFragment.newInstance(); setFragment(gistsFragment); return false; } public boolean onStarredGistsSelected() { AuthUserStarredGistsFragment gistsFragment = AuthUserStarredGistsFragment.newInstance(); setFragment(gistsFragment); return false; } public boolean onUserEventsSelected() { String user = new StoreCredentials(this).getUserName(); if (user != null) { setFragment(EventsListFragment.newInstance(user), false); } return true; } public void onOrgEventsSelected(String orgName) { OrgsEventsListFragment orgsEventsListFragment = OrgsEventsListFragment.newInstance(orgName); setFragment(orgsEventsListFragment, true); } public void onOrgReposSelected(String orgName) { OrgsReposFragment orgsReposFragment = OrgsReposFragment.newInstance(orgName); setFragment(orgsReposFragment, true); } public void onOrgPeopleSelected(String orgName) { OrgsMembersFragment orgsMembersFragment = OrgsMembersFragment.newInstance(orgName); setFragment(orgsMembersFragment, true); } public void onOrgTeamsSelected(String orgName) { } public boolean onSettingsSelected() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return false; } public void signOut() { if (selectedAccount != null) { removeAccount(selectedAccount, () -> { StoreCredentials storeCredentials = new StoreCredentials(MainActivity.this); storeCredentials.clear(); Intent intent = new Intent(MainActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); }); } } @Override public void onBackPressed() { if (resultDrawer != null && resultDrawer.isDrawerOpen()) { resultDrawer.closeDrawer(); } else { if (lastUsedFragment instanceof EventsListFragment || lastUsedFragment instanceof OrgsEventsListFragment) { finish(); } else if (resultDrawer != null) { StringHolder name = accountHeader.getActiveProfile().getEmail(); if (name == null) { name = accountHeader.getActiveProfile().getName(); } String nameForAccount = new AccountUtils().getNameFromAccount(selectedAccount.name); boolean isCurrentUser = nameForAccount != null && nameForAccount.equals(name.getText()); if (isCurrentUser) { onUserEventsSelected(); } else { onOrgEventsSelected(name.getText()); } } } } @Override public void onOrganizationsLoaded(List<User> organizations) { if (accountHeader != null) { for (User organization : organizations) { ProfileDrawerItem drawerItem = getOrganizationProfileDrawerItem(organization); if (!drawerItems.containsKey(drawerItem.getName().getText())) { drawerItems.put(drawerItem.getName().getText(), getOrganizationProfileSubItems(organization)); drawerItem.withSubItems(); accountHeader.addProfiles(drawerItem); } } } } }
package com.example.isacclee.firsthello; import android.content.Context; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import static android.content.Context.MODE_PRIVATE; public class Controller { public int SignUp(String email,String password,String phone) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("email", email); ToServer.put("password", password); ToServer.put("phone", phone); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("SignUp",ToServerString); JSONObject fromServer=new JSONObject(line); String result=fromServer.getString("result"); if (result.equals("Y")){ answer=1; }else{ answer=0; } }catch(Exception e){ e.printStackTrace(); } return answer; } public int ForgetPassword(String email) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("email", email); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("ForgetPassword",ToServerString); JSONObject fromServer=new JSONObject(line); String result=fromServer.getString("result"); if (result.equals("Y")){ answer=1; }else{ answer=0; } }catch(Exception e){ e.printStackTrace(); } return answer; } public int SignIn(String email,String password) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("email", email); ToServer.put("password", password); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("SignIn",ToServerString); JSONObject fromServer=new JSONObject(line); String result=fromServer.getString("result"); if (result.equals("Y")){ answer=1; }else{ answer=0; } }catch(Exception e){ e.printStackTrace(); } return answer; } public int EditInfo(String email,String oPassword,String nPassword,String phone) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("email", email); ToServer.put("oPassword", oPassword); ToServer.put("nPassword", nPassword); ToServer.put("phone", phone); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("EditInfo",ToServerString); JSONObject fromServer=new JSONObject(line); String result=fromServer.getString("result"); if (result.equals("Y")){ answer=1; }else{ answer=0; } }catch(Exception e){ e.printStackTrace(); } return answer; } public int CheckDevice(String email,String aksID) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("email", email); ToServer.put("aksID", aksID); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("CheckDevice",ToServerString); JSONObject fromServer=new JSONObject(line); String state=fromServer.getString("state"); if (state.equals("New")){ answer=-1; }else{ if (state.equals("Yes")){ answer=1; }else{ answer=0; } } }catch(Exception e){ e.printStackTrace(); } return answer; } public void GetDevice(DeviceStructure Device) { String ToServerString=null; JSONObject ToServer = new JSONObject(); try { ToServer.put("aksID", Device.aksID); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("GetDevice",ToServerString); JSONObject fromServer=new JSONObject(line); Device.goodsID=fromServer.getString("goodsID"); Device.number=fromServer.getInt("number"); Device.receiverName=fromServer.getString("receiverName"); Device.address=fromServer.getString("address"); Device.postCode=fromServer.getString("postCode"); Device.phone=fromServer.getString("phone"); Device.orderLimit=fromServer.getInt("orderLimit"); }catch(Exception e){ e.printStackTrace(); } } public int UpdateDevice(DeviceStructure Device) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("aksID", Device.aksID); ToServer.put("goodsID", Device.goodsID); ToServer.put("number", Device.number); ToServer.put("receiverName", Device.receiverName); ToServer.put("address", Device.address); ToServer.put("postCode", Device.postCode); ToServer.put("phone", Device.phone); ToServer.put("orderLimit", Device.orderLimit); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("UpdateDevice",ToServerString); JSONObject fromServer=new JSONObject(line); String result=fromServer.getString("result"); if (result.equals("Y")){ answer=1; }else{ answer=0; } }catch(Exception e){ e.printStackTrace(); } return answer; } public int ResetDevice(String aksID) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("aksID", aksID); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("ResetDevice",ToServerString); JSONObject fromServer=new JSONObject(line); String result=fromServer.getString("result"); if (result.equals("Y")){ answer=1; }else{ answer=0; } }catch(Exception e){ e.printStackTrace(); } return answer; } public int OrderList(String email, ArrayList<OrderStructure> result) { String ToServerString=null; JSONObject ToServer = new JSONObject(); int answer=0; try { ToServer.put("email", email); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("OrderList",ToServerString); JSONObject fromServer=new JSONObject(line); JSONArray orderList=fromServer.getJSONArray("orderList"); answer=orderList.length(); for (int i=0;i<answer;i++) { JSONObject order=orderList.getJSONObject(i); OrderStructure ans=new OrderStructure(); ans.orderID=order.getString("orderID"); ans.goodsID=order.getString("goodsID"); ans.number=order.getInt("number"); ans.state=order.getString("state"); result.add(ans); } //*/ }catch(Exception e){ e.printStackTrace(); } return answer; } public void OrderInfo(OrderStructure order) { String ToServerString=null; JSONObject ToServer = new JSONObject(); try { ToServer.put("orderID", order.orderID); ToServerString = ToServer.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ String line=new Bridge().Connect("OrderInfo",ToServerString); JSONObject fromServer=new JSONObject(line); order.goodsID=fromServer.getString("goodsID"); order.number=fromServer.getInt("number"); order.creatingTime=fromServer.getString("creatingTime"); order.sendingTime=fromServer.getString("sendingTime"); order.receiver=fromServer.getString("receiver"); order.address=fromServer.getString("address"); order.supplier=fromServer.getString("supplier"); order.expressID=fromServer.getString("expressID"); JSONArray statesList=fromServer.getJSONArray("statesList"); order.numOfStates=statesList.length(); for (int i=0;i<order.numOfStates;i++) { JSONObject state=statesList.getJSONObject(i); order.statesList[i].time=state.getString("time"); order.statesList[i].state=state.getString("state"); } }catch(Exception e){ e.printStackTrace(); } } public int GoodsList(ArrayList<String> result, Context mContext) { int answer=0; try{ String line=new Bridge().Connect("GoodsList",""); JSONObject fromServer=new JSONObject(line); JSONArray goodsList=fromServer.getJSONArray("goodsList"); answer=goodsList.length(); for (int i=0;i<answer;i++) { JSONObject goods=goodsList.getJSONObject(i); result.add(goods.getString("goodsID")); } //goodsList FileCacheUtil fileCacheUtil = new FileCacheUtil(); ArrayList<String> cacheFile = new ArrayList<>(); if(!fileCacheUtil.cacheIsOutDate(mContext,FileCacheUtil.docCache)){ //JSON String Cache = fileCacheUtil.getCache(mContext,FileCacheUtil.docCache); Toast.makeText(mContext, Cache, Toast.LENGTH_SHORT).show(); JSONObject goodsObjectInCache = new JSONObject(Cache); JSONArray goodsListInCache = goodsObjectInCache.getJSONArray("goodsList"); for (int i = 0; i< goodsListInCache.length(); i++){ JSONObject goodsInCache = goodsListInCache.getJSONObject(i); cacheFile.add(goodsInCache.getString("goodsID")); } //resultcacheFileGoodsStructure GoodsStructure.clearGoodsList(); for (String itemInResult: result) { if(!cacheFile.contains(itemInResult)){ GoodsStructure.addGoodsList(itemInResult); } } }else{ GoodsStructure.clearGoodsList(); for (String itemInResult: result) { GoodsStructure.addGoodsList(itemInResult); } } JSONArray newCache = new JSONArray(); for (String newItem:GoodsStructure.getGoodsList()){ JSONObject json = new JSONObject(); json.put("goodsID",newItem); newCache.put(json); } FileCacheUtil.setCache(newCache.toString(), mContext, FileCacheUtil.docCache, MODE_PRIVATE); }catch(Exception e){ e.printStackTrace(); } return answer; } public void GoodsInfo(GoodsStructure[] goods, Context mContext) { String ToServerString; FileCacheUtil fileCacheUtil = new FileCacheUtil(); //JSON ToServerString = fileCacheUtil.getCache(mContext,FileCacheUtil.docCache); try{ String line=new Bridge().Connect("GoodsInfo",ToServerString); JSONObject fromServer=new JSONObject(line); JSONArray goodsList = fromServer.getJSONArray("goodList"); for (int i = 0; i < goodsList.length(); i++){ JSONObject oneGoods=goodsList.getJSONObject(i); goods[i].setGoodsID(oneGoods.getString("goodsID")); goods[i].setGoodsName(oneGoods.getString("name")); goods[i].setDescription(oneGoods.getString("description")); goods[i].setPrice(oneGoods.getDouble("price")); goods[i].setPicture(oneGoods.getString("picture")); } }catch(Exception e){ e.printStackTrace(); } } }
package com.example.prashant.monolith; import android.support.design.widget.TabLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.Toast; import com.example.prashant.monolith.fragments.ArticleFragment; import com.example.prashant.monolith.fragments.GalleryFragment; import com.joaquimley.faboptions.FabOptions; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; private View.OnClickListener mListener; /** * The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; private TabLayout tabLayout; public static String POSITION = "position"; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(POSITION, tabLayout.getSelectedTabPosition()); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mViewPager.setCurrentItem(savedInstanceState.getInt(POSITION)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); // Create the adapter that will return a fragment for each of the two // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setupWithViewPager(mViewPager); FabOptions fabOptions = (FabOptions) findViewById(R.id.fab_options); fabOptions.setButtonsMenu(R.menu.gallery_fab); fabOptions.setOnClickListener(this); // FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); // fab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) // .setAction("Action", null).show(); } @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; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.fab_page: GalleryFragment. Toast.makeText(this, "Page", Toast.LENGTH_SHORT).show(); break; case R.id.fab_refresh: Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show(); break; default: // no-op } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { int mNumOfTabs; public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) { super(fm); this.mNumOfTabs = NumOfTabs; } @Override public Fragment getItem(int position) { switch (position) { case 0: GalleryFragment tab1 = new GalleryFragment(); return tab1; case 1: ArticleFragment tab2 = new ArticleFragment(); return tab2; default: return null; } } @Override public int getCount() { // Show total pages. return mNumOfTabs; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Gallery"; case 1: return "Article"; } return null; } } }
package com.kickstarter.services; import com.google.gson.GsonBuilder; import com.kickstarter.BuildConfig; import com.kickstarter.libs.Build; import com.kickstarter.services.ApiResponses.InternalBuildEnvelope; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit.Endpoint; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; import rx.Observable; public class KickstarterClient { private final Build build; private final Endpoint endpoint; private final KickstarterService service; public KickstarterClient(final Build build, final Endpoint endpoint) { this.build = build; this.endpoint = endpoint; service = kickstarterService(); } private KickstarterService kickstarterService() { return restAdapter().create(KickstarterService.class); } public Observable<InternalBuildEnvelope> pingBeta() { return service.pingBeta(); } private RestAdapter restAdapter() { return new RestAdapter.Builder() .setConverter(gsonConverter()) .setEndpoint(endpoint) .setRequestInterceptor(requestInterceptor()) .setLogLevel(BuildConfig.DEBUG ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE) .build(); } private GsonConverter gsonConverter() { return new GsonConverter(new GsonBuilder().create()); } private RequestInterceptor requestInterceptor() { return request -> { request.addHeader("Accept", "application/json"); request.addHeader("Kickstarter-Android-App", build.versionCode().toString()); // Add authorization if it's a Hivequeen environment (not production). final Matcher matcher = Pattern.compile("\\Ahttps:\\/\\/([a-z]+)\\.kickstarter.com\\z") .matcher(endpoint.getUrl()); if (matcher.matches() && !matcher.group(1).equals("www")) { request.addHeader("Authorization", "Basic ZnV6enk6d3V6enk="); } // TODO: Check whether device is mobile or tablet, append to user agent final StringBuilder userAgent = new StringBuilder() .append("Kickstarter Android Mobile Variant/") .append(build.variant()) .append(" Code/") .append(build.versionCode()) .append(" Version/") .append(build.versionName()); request.addHeader("User-Agent", userAgent.toString()); }; } }
package com.noprestige.kanaquiz; import android.content.Context; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TableLayout; import static com.noprestige.kanaquiz.Diacritic.CONSONANT; import static com.noprestige.kanaquiz.Diacritic.DAKUTEN; import static com.noprestige.kanaquiz.Diacritic.HANDAKUTEN; import static com.noprestige.kanaquiz.Diacritic.NO_DIACRITIC; abstract class QuestionManagement { private static final int CATEGORY_COUNT = 10; private KanaQuestion[][][][] kanaSets = new KanaQuestion[CATEGORY_COUNT][Diacritic.values().length][2][]; private int[] prefIds; private static final int SET_1_TITLE = R.string.set_1_title; private static final int SET_2_TITLE = R.string.set_2_title; private static final int SET_3_TITLE = R.string.set_3_title; private static final int SET_4_TITLE = R.string.set_4_title; private static final int SET_5_TITLE = R.string.set_5_title; private static final int SET_6_TITLE = R.string.set_6_title; private static final int SET_7_TITLE = R.string.set_7_title; private static final int SET_8_TITLE = R.string.set_8_title; private static final int SET_9_TITLE = R.string.set_9_title; private static final int SET_10_TITLE = R.string.set_10_title; private static final int[] SET_TITLES = {SET_1_TITLE, SET_2_TITLE, SET_3_TITLE, SET_4_TITLE, SET_5_TITLE, SET_6_TITLE, SET_7_TITLE, SET_8_TITLE, SET_9_TITLE, SET_10_TITLE}; void addKanaSet(KanaQuestion[] kanaSet, int number) { addKanaSet(kanaSet, number, NO_DIACRITIC); } void addKanaSet(KanaQuestion[] kanaSet, int number, Diacritic diacritic) { addKanaSet(kanaSet, number, diacritic, false); } void addKanaSet(KanaQuestion[] kanaSet, int number, Diacritic diacritic, boolean isDigraphs) { int a = number - 1; int b = diacritic.ordinal(); int c = isDigraphs ? 1 : 0; if (kanaSets[a][b][c] != null) throw new IllegalArgumentException("Kana set " + number + " " + diacritic.name() + (isDigraphs ? " digraphs" : " monographs") + " already exists"); else kanaSets[a][b][c] = kanaSet; } void addPrefIds(int[] prefIds) { if (this.prefIds != null) throw new IllegalArgumentException(); else this.prefIds = prefIds; } private KanaQuestion[] getKanaSet(int number) { return getKanaSet(number, NO_DIACRITIC); } private KanaQuestion[] getKanaSet(int number, Diacritic diacritic) { return getKanaSet(number, diacritic, false); } private KanaQuestion[] getKanaSet(int number, Diacritic diacritic, boolean isDigraphs) { KanaQuestion[] value = kanaSets[number - 1][diacritic.ordinal()][isDigraphs ? 1 : 0]; if (value != null && value.length > 0) return value; else throw new NullPointerException("Kana set " + number + " " + diacritic.name() + (isDigraphs ? " digraphs" : " monographs") + " does not exist"); } private int getPrefId(int number) { return prefIds[number - 1]; } private int getSetTitle(int number) { return SET_TITLES[number - 1]; } private boolean getPref(int number) { return OptionsControl.getBoolean(getPrefId(number)); } KanaQuestionBank getQuestionBank() { KanaQuestionBank questionBank = new KanaQuestionBank(); boolean isDigraphs = OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9); boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics); if (getPref(1)) questionBank.addQuestions(getKanaSet(1)); for (int i = 2; i <= 8; i++) if (getPref(i)) { questionBank.addQuestions(getKanaSet(i)); if (isDigraphs) questionBank.addQuestions(getKanaSet(i, NO_DIACRITIC, true)); } if (isDiacritics) { for (int i = 2; i <= 4; i++) if (getPref(i)) { questionBank.addQuestions(getKanaSet(i, DAKUTEN)); if (isDigraphs) questionBank.addQuestions(getKanaSet(i, DAKUTEN, true)); } if (getPref(6)) { questionBank.addQuestions(getKanaSet(6, DAKUTEN), getKanaSet(6, HANDAKUTEN)); if (isDigraphs) questionBank.addQuestions(getKanaSet(6, DAKUTEN, true), getKanaSet(6, HANDAKUTEN, true)); } } if (getPref(9)) questionBank.addQuestions(getKanaSet(9)); if (getPref(10)) questionBank.addQuestions(getKanaSet(10), getKanaSet(10, CONSONANT)); return questionBank; } boolean anySelected() { for (int i = 1; i <= CATEGORY_COUNT; i++) if (getPref(i)) return true; return false; } boolean diacriticsSelected() { return (OptionsControl.getBoolean(R.string.prefid_diacritics) && (getPref(2) || getPref(3) || getPref(4) || getPref(6))); } boolean digraphsSelected() { if (OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9)) for (int i = 2; i <= 8; i++) if (getPref(i)) return true; return false; } boolean diacriticDigraphsSelected() { return (OptionsControl.getBoolean(R.string.prefid_diacritics) && OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9) && (getPref(2) || getPref(3) || getPref(4) || getPref(6))); } private String getKanaSetDisplay(int setNumber) { return getKanaSetDisplay(setNumber, NO_DIACRITIC); } private String getKanaSetDisplay(int setNumber, Diacritic diacritic) { String returnValue = ""; for (KanaQuestion question : getKanaSet(setNumber, diacritic)) returnValue += question.getKana() + " "; return returnValue; } private String displayContents(int setNumber) { String returnValue = ""; boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics); returnValue += getKanaSetDisplay(setNumber); if (isDiacritics && (setNumber >= 2 && setNumber <= 4 || setNumber == 6)) { returnValue += getKanaSetDisplay(setNumber, DAKUTEN); if (setNumber == 6) returnValue += getKanaSetDisplay(setNumber, HANDAKUTEN); } if (setNumber == 10) returnValue += getKanaSetDisplay(setNumber, CONSONANT); return returnValue; } TableLayout getMainReferenceTable(Context context) { TableLayout table = new TableLayout(context); table.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference); for (int i = 1; i <= 7; i++) if (isFullReference || getPref(i)) table.addView(ReferenceCell.buildRow(context, getKanaSet(i))); if (isFullReference || getPref(9)) table.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(9))); if (isFullReference || getPref(8)) table.addView(ReferenceCell.buildRow(context, getKanaSet(8))); if (isFullReference || getPref(10)) { table.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(10))); table.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(10, CONSONANT))); } return table; } TableLayout getDiacriticReferenceTable(Context context) { TableLayout table = new TableLayout(context); table.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference); for (int i = 2; i <= 4; i++) if (isFullReference || getPref(i)) table.addView(ReferenceCell.buildRow(context, getKanaSet(i, DAKUTEN))); if (isFullReference || getPref(6)) { table.addView(ReferenceCell.buildRow(context, getKanaSet(6, DAKUTEN))); table.addView(ReferenceCell.buildRow(context, getKanaSet(6, HANDAKUTEN))); } return table; } TableLayout getMainDigraphsReferenceTable(Context context) { TableLayout table = new TableLayout(context); table.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference); for (int i = 2; i <= 8; i++) if (isFullReference || getPref(i)) table.addView(ReferenceCell.buildRow(context, getKanaSet(i, NO_DIACRITIC, true))); return table; } TableLayout getDiacriticDigraphsReferenceTable(Context context) { TableLayout table = new TableLayout(context); table.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); boolean isFullReference = OptionsControl.getBoolean(R.string.prefid_full_reference); for (int i = 2; i <= 4; i++) if (isFullReference || getPref(i)) table.addView(ReferenceCell.buildRow(context, getKanaSet(i, DAKUTEN, true))); if (isFullReference || getPref(6)) { table.addView(ReferenceCell.buildRow(context, getKanaSet(6, DAKUTEN, true))); table.addView(ReferenceCell.buildRow(context, getKanaSet(6, HANDAKUTEN, true))); } return table; } LinearLayout getSelectionScreen(Context context) { LinearLayout layout = new LinearLayout(context); layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); layout.setOrientation(LinearLayout.VERTICAL); for (int i = 1; i <= CATEGORY_COUNT; i++) { KanaSelectionItem item = new KanaSelectionItem(context); item.setTitle(getSetTitle(i)); item.setContents(displayContents(i)); item.setPrefId(getPrefId(i)); layout.addView(item); } return layout; } }
package com.noprestige.kanaquiz; import android.content.Context; import android.view.Gravity; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TableLayout; import static com.noprestige.kanaquiz.Diacritic.CONSONANT; import static com.noprestige.kanaquiz.Diacritic.NO_DIACRITIC; import static com.noprestige.kanaquiz.Diacritic.DAKUTEN; import static com.noprestige.kanaquiz.Diacritic.HANDAKUTEN; abstract class QuestionManagement { private static final int CATEGORY_COUNT = 10; private KanaQuestion[][][][] kanaSets; private int[] prefIds; //TODO: Simplify QuestionManagement( KanaQuestion[] KANA_SET_1, KanaQuestion[] KANA_SET_2_BASE, KanaQuestion[] KANA_SET_2_DAKUTEN, KanaQuestion[] KANA_SET_2_BASE_DIGRAPHS, KanaQuestion[] KANA_SET_2_DAKUTEN_DIGRAPHS, KanaQuestion[] KANA_SET_3_BASE, KanaQuestion[] KANA_SET_3_DAKUTEN, KanaQuestion[] KANA_SET_3_BASE_DIGRAPHS, KanaQuestion[] KANA_SET_3_DAKUTEN_DIGRAPHS, KanaQuestion[] KANA_SET_4_BASE, KanaQuestion[] KANA_SET_4_DAKUTEN, KanaQuestion[] KANA_SET_4_BASE_DIGRAPHS, KanaQuestion[] KANA_SET_4_DAKUTEN_DIGRAPHS, KanaQuestion[] KANA_SET_5, KanaQuestion[] KANA_SET_5_DIGRAPHS, KanaQuestion[] KANA_SET_6_BASE, KanaQuestion[] KANA_SET_6_DAKUTEN, KanaQuestion[] KANA_SET_6_HANDAKETEN, KanaQuestion[] KANA_SET_6_BASE_DIGRAPHS, KanaQuestion[] KANA_SET_6_DAKUTEN_DIGRAPHS, KanaQuestion[] KANA_SET_6_HANDAKETEN_DIGRAPHS, KanaQuestion[] KANA_SET_7, KanaQuestion[] KANA_SET_7_DIGRAPHS, KanaQuestion[] KANA_SET_8, KanaQuestion[] KANA_SET_8_DIGRAPHS, KanaQuestion[] KANA_SET_9, KanaQuestion[] KANA_SET_10_W_GROUP, KanaQuestion[] KANA_SET_10_N_CONSONANT, int PREFID_1, int PREFID_2, int PREFID_3, int PREFID_4, int PREFID_5, int PREFID_6, int PREFID_7, int PREFID_8, int PREFID_9, int PREFID_10) { kanaSets = new KanaQuestion[CATEGORY_COUNT][Diacritic.values().length][2][]; kanaSets[0][NO_DIACRITIC.ordinal()][0] = KANA_SET_1; kanaSets[1][NO_DIACRITIC.ordinal()][0] = KANA_SET_2_BASE; kanaSets[1][DAKUTEN.ordinal()][0] = KANA_SET_2_DAKUTEN; kanaSets[1][NO_DIACRITIC.ordinal()][1] = KANA_SET_2_BASE_DIGRAPHS; kanaSets[1][DAKUTEN.ordinal()][1] = KANA_SET_2_DAKUTEN_DIGRAPHS; kanaSets[2][NO_DIACRITIC.ordinal()][0] = KANA_SET_3_BASE; kanaSets[2][DAKUTEN.ordinal()][0] = KANA_SET_3_DAKUTEN; kanaSets[2][NO_DIACRITIC.ordinal()][1] = KANA_SET_3_BASE_DIGRAPHS; kanaSets[2][DAKUTEN.ordinal()][1] = KANA_SET_3_DAKUTEN_DIGRAPHS; kanaSets[3][NO_DIACRITIC.ordinal()][0] = KANA_SET_4_BASE; kanaSets[3][DAKUTEN.ordinal()][0] = KANA_SET_4_DAKUTEN; kanaSets[3][NO_DIACRITIC.ordinal()][1] = KANA_SET_4_BASE_DIGRAPHS; kanaSets[3][DAKUTEN.ordinal()][1] = KANA_SET_4_DAKUTEN_DIGRAPHS; kanaSets[4][NO_DIACRITIC.ordinal()][0] = KANA_SET_5; kanaSets[4][NO_DIACRITIC.ordinal()][1] = KANA_SET_5_DIGRAPHS; kanaSets[5][NO_DIACRITIC.ordinal()][0] = KANA_SET_6_BASE; kanaSets[5][DAKUTEN.ordinal()][0] = KANA_SET_6_DAKUTEN; kanaSets[5][HANDAKUTEN.ordinal()][0] = KANA_SET_6_HANDAKETEN; kanaSets[5][NO_DIACRITIC.ordinal()][1] = KANA_SET_6_BASE_DIGRAPHS; kanaSets[5][DAKUTEN.ordinal()][1] = KANA_SET_6_DAKUTEN_DIGRAPHS; kanaSets[5][HANDAKUTEN.ordinal()][1] = KANA_SET_6_HANDAKETEN_DIGRAPHS; kanaSets[6][NO_DIACRITIC.ordinal()][0] = KANA_SET_7; kanaSets[6][NO_DIACRITIC.ordinal()][1] = KANA_SET_7_DIGRAPHS; kanaSets[7][NO_DIACRITIC.ordinal()][0] = KANA_SET_8; kanaSets[7][NO_DIACRITIC.ordinal()][1] = KANA_SET_8_DIGRAPHS; kanaSets[8][NO_DIACRITIC.ordinal()][0] = KANA_SET_9; kanaSets[9][NO_DIACRITIC.ordinal()][0] = KANA_SET_10_W_GROUP; kanaSets[9][CONSONANT.ordinal()][0] = KANA_SET_10_N_CONSONANT; prefIds = new int[CATEGORY_COUNT]; prefIds[0] = PREFID_1; prefIds[1] = PREFID_2; prefIds[2] = PREFID_3; prefIds[3] = PREFID_4; prefIds[4] = PREFID_5; prefIds[5] = PREFID_6; prefIds[6] = PREFID_7; prefIds[7] = PREFID_8; prefIds[8] = PREFID_9; prefIds[9] = PREFID_10; } private KanaQuestion[] getKanaSet(int number) { return getKanaSet(number, NO_DIACRITIC); } private KanaQuestion[] getKanaSet(int number, Diacritic diacritic) { return getKanaSet(number, diacritic, false); } private KanaQuestion[] getKanaSet(int number, Diacritic diacritic, boolean isDigraphs) { KanaQuestion[] value = kanaSets[number - 1][diacritic.ordinal()][isDigraphs?1:0]; if (value.length > 0) return value; else throw new NullPointerException(); } private int getPrefId(int number) { return prefIds[number - 1]; } private boolean getPref(int number) { return OptionsControl.getBoolean(getPrefId(number)); } KanaQuestionBank getQuestionBank() { KanaQuestionBank questionBank = new KanaQuestionBank(); boolean isDigraphs = OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9); boolean isDiacritics = OptionsControl.getBoolean(R.string.prefid_diacritics); if (getPref(1)) questionBank.addQuestions(getKanaSet(1)); for (int i = 2; i <= 4; i++) { if (getPref(i)) { questionBank.addQuestions(getKanaSet(i)); if (isDiacritics) questionBank.addQuestions(getKanaSet(i, DAKUTEN)); if (isDigraphs) questionBank.addQuestions(getKanaSet(i, NO_DIACRITIC, true)); if (isDigraphs && isDiacritics) questionBank.addQuestions(getKanaSet(i, DAKUTEN, true)); } } if (getPref(5)) { questionBank.addQuestions(getKanaSet(5)); if (isDigraphs) questionBank.addQuestions(getKanaSet(5, NO_DIACRITIC, true)); } if (getPref(6)) { questionBank.addQuestions(getKanaSet(6)); if (isDiacritics) questionBank.addQuestions(getKanaSet(6, DAKUTEN), getKanaSet(6, HANDAKUTEN)); if (isDigraphs) questionBank.addQuestions(getKanaSet(6, NO_DIACRITIC, true)); if (isDigraphs && isDiacritics) questionBank.addQuestions(getKanaSet(6, DAKUTEN, true), getKanaSet(6, HANDAKUTEN, true)); } for (int i = 7; i <= 8; i++) { if (getPref(i)) { questionBank.addQuestions(getKanaSet(i)); if (isDigraphs) questionBank.addQuestions(getKanaSet(i, NO_DIACRITIC, true)); } } if (getPref(9)) questionBank.addQuestions(getKanaSet(9)); if (getPref(10)) questionBank.addQuestions(getKanaSet(10), getKanaSet(10, CONSONANT)); return questionBank; } boolean anySelected() { for (int i = 1; i <= CATEGORY_COUNT; i++) { if (getPref(i)) return true; } return false; } LinearLayout getReferenceTable(Context context) { LinearLayout layout = new LinearLayout(context); layout.setOrientation(LinearLayout.VERTICAL); layout.setGravity(Gravity.CENTER); TableLayout tableOne = new TableLayout(context); tableOne.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TableLayout tableTwo = new TableLayout(context); tableTwo.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); TableLayout tableThree = new TableLayout(context); tableThree.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); for (int i = 1; i <= 8; i++) { if (getPref(i)) tableOne.addView(ReferenceCell.buildRow(context, getKanaSet(i))); } if (getPref(9)) tableOne.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(9))); if (getPref(10)) { tableOne.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(10))); tableOne.addView(ReferenceCell.buildSpecialRow(context, getKanaSet(10, CONSONANT))); } if (OptionsControl.getBoolean(R.string.prefid_diacritics)) { for (int i = 2; i <= 4; i++) { if (getPref(i)) tableTwo.addView(ReferenceCell.buildRow(context, getKanaSet(i, DAKUTEN))); } if (getPref(6)) { tableTwo.addView(ReferenceCell.buildRow(context, getKanaSet(6, DAKUTEN))); tableTwo.addView(ReferenceCell.buildRow(context, getKanaSet(6, HANDAKUTEN))); } } if (OptionsControl.getBoolean(R.string.prefid_digraphs) && getPref(9)) { for (int i = 2; i <= 8; i++) { if (getPref(i)) tableThree.addView(ReferenceCell.buildRow(context, getKanaSet(i, NO_DIACRITIC, true))); } if (OptionsControl.getBoolean(R.string.prefid_diacritics)) { for (int i = 2; i <= 4; i++) { if (getPref(i)) tableThree.addView(ReferenceCell.buildRow(context, getKanaSet(i, DAKUTEN, true))); } if (getPref(6)) { tableThree.addView(ReferenceCell.buildRow(context, getKanaSet(6, DAKUTEN, true))); tableThree.addView(ReferenceCell.buildRow(context, getKanaSet(6, HANDAKUTEN, true))); } } } layout.addView(tableOne); if (tableTwo.getChildCount() > 0) { layout.addView(ReferenceCell.buildHeader(context, R.string.diacritics_title)); layout.addView(tableTwo); } if (tableThree.getChildCount() > 0) { layout.addView(ReferenceCell.buildHeader(context, R.string.digraphs_title)); layout.addView(tableThree); } return layout; } }
package dt.call.aclient.screens; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.ColorDrawable; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.os.Build; import android.os.Bundle; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedOutputStream; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import dt.call.aclient.CallState; import dt.call.aclient.Const; import dt.call.aclient.R; import dt.call.aclient.Utils; import dt.call.aclient.Vars; import dt.call.aclient.background.async.CallEndAsync; import dt.call.aclient.background.async.CallTimeoutAsync; import dt.call.aclient.background.async.KillSocketsAsync; import io.kvh.media.amr.AmrDecoder; import io.kvh.media.amr.AmrEncoder; public class CallMain extends AppCompatActivity implements View.OnClickListener, SensorEventListener { private static final String tag = "CallMain"; private static final int SAMPLESAMR = 8000; private static final int FORMAT = AudioFormat.ENCODING_PCM_16BIT; private static final int STREAMCALL = AudioManager.STREAM_VOICE_CALL; private static final int WAVBUFFERSIZE = 160; private static final int AMRBUFFERSIZE = 32; //ui stuff private FloatingActionButton end, mic, speaker; private volatile boolean micMute = false; private boolean micStatusNew = false; private boolean onSpeaker = false; private boolean screenShowing; private TextView status, callerid, time; private int min=0, sec=0; private Timer counter = new Timer(); private BroadcastReceiver myReceiver; //proximity sensor stuff private SensorManager sensorManager; private Sensor proximity; //related to audio playback and recording private AudioManager audioManager; private AudioRecord wavRecorder; private AudioTrack wavPlayer; //the first time start encoding thread is called nothing would've set shouldEncode (mute button wouldn'tve been touched) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_call_main); //allow this screen to show even when there is a password/pattern lock screen Window window = this.getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); end = (FloatingActionButton)findViewById(R.id.call_main_end_call); end.setOnClickListener(this); mic = (FloatingActionButton)findViewById(R.id.call_main_mic); mic.setOnClickListener(this); mic.setEnabled(false); speaker = (FloatingActionButton)findViewById(R.id.call_main_spk); speaker.setOnClickListener(this); speaker.setEnabled(false); status = (TextView)findViewById(R.id.call_main_status); //by default ringing. change it when in a call callerid = (TextView)findViewById(R.id.call_main_callerid); time = (TextView)findViewById(R.id.call_main_time); callerid.setText(Vars.callWith.toString()); /** * The stuff under here might look like a lot which has the potential to seriously slow down onCreate() * but it's really just long because defining some of the setup is long (like encode feed, decode feed * broadcast receiver etc...) * * It's not as bad as it looks */ //proximity sensor sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); proximity = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); //Start showing the counter for how long it's taking to answer the call or how long // the call has been going for TimerTask counterTask = new TimerTask() { @Override public void run() { if(sec == 59) {//seconds should never hit 60. 60 is time to regroup into minutes sec = 0; min++; } else { sec++; } //if the person hasn't answered after 60 seconds give up. it's probably not going to happen. if((Vars.state == CallState.INIT) && (sec == Const.CALL_TIMEOUT)) { new CallTimeoutAsync().execute(); Vars.state = CallState.NONE; //guarantee state == NONE. don't leave it to chance onStop(); } if(screenShowing) { runOnUiThread(new Runnable() { @Override public void run() { updateTime(); } }); } } }; counter.schedule(counterTask, 0, 1000); //listen for call accepted or rejected myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Utils.logcat(Const.LOGD, tag, "received a broadcast intent"); String response = intent.getStringExtra(Const.BROADCAST_CALL_RESP); if(response.equals(Const.BROADCAST_CALL_START)) { min = 0; sec = 0; uiCallMode(); startMediaDecodeThread(); startMediaEncodeThread(); } else if(response.equals(Const.BROADCAST_CALL_END)) { //whether the call was rejected or time to end, it's the same result //so share the same variable to avoid 2 sendBroadcast chunks of code that are almost the same //media read/write are stopped in command listener when it got the call end //Vars.state would've already been set by the server command that's broadcasting a call end onStop(); } } }; registerReceiver(myReceiver, new IntentFilter(Const.BROADCAST_CALL)); /** * Audio setup from here */ //make it possible to use the earpiece and to switch back and forth audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); audioManager.setSpeakerphoneOn(false); //now that the setup has been complete: //set the ui to call mode: if you got to this screen after accepting an incoming call if(Vars.state == CallState.INCALL) { uiCallMode(); startMediaDecodeThread(); startMediaEncodeThread(); } } @Override protected void onResume() { super.onResume(); screenShowing = true; sensorManager.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); screenShowing = false; sensorManager.unregisterListener(this); } @Override protected void onStop() { super.onStop(); screenShowing = false; /** * onStop() is called when the CallMain screen isn't visible anymore. Either from ending a call * or from going to another app during a call. To make sure the call doesn't stop, only do the * cleanup if you're leaving the screen because the call ended. * * Vars.state = NONE will be set before calling onStop() manually to guarantee that onStop() sees * the call state as none. The 2 async calls: end, timeout will set state = NONE, BUT BECAUSE they're * async there is a chance that onStop() is called before the async is. Don't leave it to dumb luck. */ if(Vars.state == CallState.NONE) { new CallEndAsync().execute(); //no longer in a call audioManager.setMode(AudioManager.MODE_NORMAL); counter.cancel(); try { unregisterReceiver(myReceiver); } catch (IllegalArgumentException i) { Utils.logcat(Const.LOGW, tag, "don't unregister you get a leak, do unregister you get an exception... "); } //go back to the home screen and clear the back history so there is no way to come back to //call main Intent goHome = new Intent(this, UserHome.class); goHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(goHome); } } @Override public void onClick(View v) { if(v == end) { Vars.state = CallState.NONE; //guarantee onStop sees state == NONE onStop(); } else if (v == mic) { micMute = !micMute; micStatusNew = true; //update the mic icon in the encoder thread when the actual mute/unmute happens. //it can take up to 1 second to change the status because of the sleep when going from mute-->unmute //notify the user of this so their "dirty laundry" doesn't unintentionally get aired Toast checkMic = Toast.makeText(this, getString(R.string.call_main_toast_micstatus), Toast.LENGTH_LONG); checkMic.show(); } else if (v == speaker) { onSpeaker = !onSpeaker; if(onSpeaker) { speaker.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_volume_up_white_48dp)); audioManager.setSpeakerphoneOn(true); } else { speaker.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_phone_in_talk_white_48dp)); audioManager.setSpeakerphoneOn(false); } } } private void updateTime() { if(sec < 10) { time.setText(min + ":0" + sec); } else { time.setText(min + ":" + sec); } } private void uiCallMode() { //it is impossible to change the status bar @ run time below 5.0, only the action bar color. //results in a weird blue/green look. only change the look for >= 5.0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try {//apparently this line has the possibility of a null pointer exception as warned by android studio...??? getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(CallMain.this, R.color.material_green))); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(ContextCompat.getColor(CallMain.this, R.color.material_dark_green)); window.setNavigationBarColor(ContextCompat.getColor(CallMain.this, R.color.material_dark_green)); } catch (NullPointerException n) { Utils.dumpException(tag, n); } } status.setText(getString(R.string.call_main_status_incall)); mic.setEnabled(true); speaker.setEnabled(true); } private void startMediaEncodeThread() { Thread recordThread = new Thread(new Runnable() { private static final String encTag = "EncodingThread"; private static final int CLUMPSIZE = 500; @Override public void run() { Utils.logcat(Const.LOGD, encTag, "MediaCodec encoder thread has started"); byte[] amrbuffer = new byte[AMRBUFFERSIZE]; short[] wavbuffer = new short[WAVBUFFERSIZE]; BufferedOutputStream bufferedOutputStream = null; //https://en.wikipedia.org/wiki/Silly_window_syndrome#Send-side_silly_window_avoidance //for each 32 bytes of voice, 40bytes of header will be written which means > 50% of data IO is //headers (not useful)!!! a waste of ridiculously overpriced canadian lte //use the wikipedia clumping strategy try { bufferedOutputStream = new BufferedOutputStream(Vars.mediaSocket.getOutputStream(), CLUMPSIZE); } catch (Exception e) { //no point of doing the call if the clumping strategy can't be used. //don't waste data falling back to sending 32bytes @ a time. hang up and try again Vars.state = CallState.NONE; try {//must guarantee that the sockets are killed before going to the home screen. otherwise //the userhome's crash recovery won't kick in. don't leave it to dumb luck (race condition) new KillSocketsAsync().execute().get(); onStop(); //don't know whether encode or decode will call onStop() first. the second one will get a null exception //because the main ui thead will be gone after the first onStop() is called. catch the exception } catch (Exception e2) { Utils.logcat(Const.LOGE, encTag, "Trying to kill sockets because of an exception but got another exception in the process"); Utils.dumpException(encTag, e2); } } //setup the wave audio recorder. since it is released and restarted, it needs to be setup here and not onCreate wavRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLESAMR, AudioFormat.CHANNEL_IN_MONO, FORMAT, WAVBUFFERSIZE); wavRecorder.startRecording(); //my dying i9300 on CM12.1 sometimes can't get the audio record on its first try int recorderRetries = 5; while(wavRecorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING && recorderRetries > 0) { wavRecorder.stop(); wavRecorder.release(); wavRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLESAMR, AudioFormat.CHANNEL_IN_MONO, FORMAT, WAVBUFFERSIZE); wavRecorder.startRecording(); Utils.logcat(Const.LOGW, encTag, "audiorecord failed to initialized. retried"); recorderRetries } //if the wav recorder can't be initialized hang up and try again //nothing i can do when the cell phone itself has problems if(recorderRetries == 0) { Utils.logcat(Const.LOGE, encTag, "couldn't get the microphone from the cell phone. hanging up"); endThread(); return; } AmrEncoder.init(0); while(Vars.state == CallState.INCALL) { if(!micMute) { if (micStatusNew) { runOnUiThread(new Runnable() { @Override public void run() { mic.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_mic_white_48dp)); } }); micStatusNew = false; } int totalRead = 0, dataRead; while (totalRead < WAVBUFFERSIZE) {//although unlikely to be necessary, buffer the mic input dataRead = wavRecorder.read(wavbuffer, totalRead, WAVBUFFERSIZE - totalRead); totalRead = totalRead + dataRead; } int encodeLength = AmrEncoder.encode(AmrEncoder.Mode.MR122.ordinal(), wavbuffer, amrbuffer); try { bufferedOutputStream.write(amrbuffer, 0, encodeLength); } catch (Exception e) { Utils.logcat(Const.LOGE, encTag, "Cannot send amr out the media socket"); Utils.dumpException(encTag, e); //if the socket died it's impossible to continue the call. //the other person will get a dropped call and you can start the call again. //kill the sockets so that UserHome's crash recovery will reinitialize them endThread(); } } else { //instead of going into a crazy while no-op loop, wait 1 second before checking //if the mute has been released. this is the simplest implementation i can think of //that doesn't involve thread starting/stopping and making sure only 1 encode thread is running if (micStatusNew) { runOnUiThread(new Runnable() { @Override public void run() { mic.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_mic_off_white_48dp)); } }); micStatusNew = false; } SystemClock.sleep(1000); } } //see media decoder thread for explanation of a try/catch here AmrEncoder.exit(); try { wavRecorder.stop(); wavRecorder.release(); } catch (NullPointerException n) { Utils.logcat(Const.LOGE, encTag, "Call Main ui exited before the encoder thread. Cleanup of AudioRecord wavRecorder will fail"); Utils.dumpException(encTag, n); } Utils.logcat(Const.LOGD, encTag, "MediaCodec encoder thread has stopped"); } private void endThread() { Vars.state = CallState.NONE; try {//must guarantee that the sockets are killed before going to the home screen. otherwise //the userhome's crash recovery won't kick in. don't leave it to dumb luck (race condition) new KillSocketsAsync().execute().get(); onStop(); //don't know whether encode or decode will call onStop() first. the second one will get a null exception //because the main ui thead will be gone after the first onStop() is called. catch the exception } catch (Exception e2) { Utils.logcat(Const.LOGE, encTag, "Trying to kill sockets because of an exception but got another exception in the process"); Utils.dumpException(encTag, e2); } } }); recordThread.setName("Media_Encoder"); recordThread.start(); } private void startMediaDecodeThread() { Thread playbackThread = new Thread(new Runnable() { private static final String decTag = "DecodingThread"; @Override public void run() { Utils.logcat(Const.LOGD, decTag, "MediaCodec decoder thread has started"); byte[] amrbuffer = new byte[AMRBUFFERSIZE]; short[] wavbuffer = new short[WAVBUFFERSIZE]; //setup the wave audio track int buffer = AudioTrack.getMinBufferSize(SAMPLESAMR, AudioFormat.CHANNEL_OUT_MONO, FORMAT); Utils.logcat(Const.LOGD, decTag, "wave audio buffer for mono @ 8000sample/sec: " + buffer); wavPlayer = new AudioTrack(STREAMCALL, SAMPLESAMR, AudioFormat.CHANNEL_OUT_MONO, FORMAT, buffer, AudioTrack.MODE_STREAM); wavPlayer.play(); /* * Detect when a bunch of audio starts rushing in. This happens because the network connection that went bad is suddenly "good" * and all the missing packets are flooding. This will create an audio backlog and delay the audio from the real conversation. * Discard the audio flood and just ask "what did you say. my connection was bad" */ long start, elapsed, minNanos = (long)(32/3700*1000000000); //~ (5629(avg)+1764(stddev))/2 long amrstate = AmrDecoder.init(); while(Vars.state == CallState.INCALL) { int totalRead=0, dataRead; try { //guarantee you have AMRBUFFERSIZE(32) bytes to send to the native library start = System.nanoTime(); while(totalRead < AMRBUFFERSIZE) { dataRead = Vars.mediaSocket.getInputStream().read(amrbuffer, totalRead, AMRBUFFERSIZE -totalRead); totalRead = totalRead + dataRead; if(dataRead == -1) { throw new IOException("read from media socket thought it was the end of file (-1)"); } } elapsed = System.nanoTime() - start; if(elapsed > minNanos) { AmrDecoder.decode(amrstate, amrbuffer, wavbuffer); wavPlayer.write(wavbuffer, 0, WAVBUFFERSIZE); } else { Utils.logcat(Const.LOGD, decTag, "Detected rushing in of audio... probably from network lag. Discard to get to realtime position"); } } catch (Exception i) //io or null pointer depending on when the connection dies { Utils.logcat(Const.LOGE, decTag, "exception reading media: "); Utils.dumpException(decTag, i); //if the socket died it's impossible to continue the call. //the other person will get a dropped call and you can start the call again. //kill the sockets so that UserHome's crash recovery will reinitialize them Vars.state = CallState.NONE; try {//must guarantee that the sockets are killed before going to the home screen. otherwise //the userhome's crash recovery won't kick in. don't leave it to dumb luck (race condition) new KillSocketsAsync().execute().get(); onStop(); //see encoder thread for why onStop() is called in a try } catch (Exception e) { Utils.logcat(Const.LOGE, decTag, "Trying to kill sockets because of an exception but got another exception in the process"); Utils.dumpException(decTag, e); } } } AmrDecoder.exit(amrstate); //if the call main ui exits first, then there is no way to stop the wavPlayer. //it IS a race condition but not one that produces any bad results for the app. //just catch the null and pretend like nothing happened. no point of making onStop wait //for these 2 dec/enc threads to stop first. more complicated, doesn't add anything useful try { wavPlayer.stop(); wavPlayer.flush(); //must flush after stop wavPlayer.release(); //mandatory cleanup to prevent wavPlayer from outliving its usefulness wavPlayer = null; } catch (NullPointerException n) { Utils.logcat(Const.LOGE, decTag, "CallMain is already gone. Cleanup of AudioTrack wavPlayer will fail."); Utils.dumpException(decTag, n); } Utils.logcat(Const.LOGD, decTag, "MediaCodec decoder thread has stopped, state:" + Vars.state); } }); playbackThread.setName("Media_Decoder"); playbackThread.start(); } @Override public void onBackPressed() { /* * Do nothing. If you're in a call then there's no reason to go back to the User Home */ } @Override public void onSensorChanged(SensorEvent event) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; if(x < 5) { //with there being no good information on turning the screen on and off //go with the next best thing of disabling all the buttons Utils.logcat(Const.LOGD, tag, "proximity sensor NEAR: " + x + " " + y + " "+ z); screenShowing = false; end.setEnabled(false); mic.setEnabled(false); speaker.setEnabled(false); } else { Utils.logcat(Const.LOGD, tag, "proximity sensor FAR: " + x + " " + y + " "+ z); screenShowing = true; end.setEnabled(true); mic.setEnabled(true); speaker.setEnabled(true); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { //not relevant for proximity sensor so do nothing } }
package com.noprestige.kanaquiz.logs; import android.annotation.SuppressLint; import android.content.res.Configuration; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.TextView; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.formatter.ValueFormatter; import com.noprestige.kanaquiz.R; import com.noprestige.kanaquiz.themes.ThemeManager; import org.threeten.bp.LocalDate; import org.threeten.bp.ZoneId; import java.util.ArrayList; import java.util.List; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; public class LogDetailView extends AppCompatActivity { static class FetchLogDetails extends AsyncTask<LogDetailView, LogDetailItem, Integer> { @SuppressLint("StaticFieldLeak") LogDetailView activity; @SuppressLint("StaticFieldLeak") LinearLayout layout; @SuppressLint("StaticFieldLeak") TextView lblDetailMessage; @SuppressLint("StaticFieldLeak") BarChart logDetailChart; List<BarEntry> chartSeries; List<String> staticLabels; @Override protected void onPreExecute() { chartSeries = new ArrayList<>(); staticLabels = new ArrayList<>(); } public String formatXLabel(float value) { int key = Math.round(value); if ((key >= 0) && (key < staticLabels.size())) return staticLabels.get(key); return ""; } @Override protected Integer doInBackground(LogDetailView... activities) { activity = activities[0]; layout = activity.findViewById(R.id.logDetailViewLayout); lblDetailMessage = activity.findViewById(R.id.lblDetailMessage); logDetailChart = activity.findViewById(R.id.logDetailChart); QuestionRecord[] records = LogDatabase.DAO.getDatesQuestionRecords(activity.date); logDetailChart.getXAxis().setValueFormatter(new ValueFormatter() { @Override public String getFormattedValue(float value) { return formatXLabel(value); } }); if (records.length == 0) return 0; for (QuestionRecord record : records) { LogDetailItem output = new LogDetailItem(activity); output.setFromRecord(record); chartSeries.add(new BarEntry(staticLabels.size(), (record.getCorrectAnswers() * 100) / (record.getCorrectAnswers() + record.getIncorrectAnswers()))); staticLabels.add(record.getQuestion()); if (isCancelled()) return null; else publishProgress(output); } return records.length; } @Override protected void onProgressUpdate(LogDetailItem... item) { layout.addView(item[0], layout.getChildCount() - 1); } @Override protected void onCancelled() { layout = null; lblDetailMessage = null; logDetailChart = null; } @Override protected void onPostExecute(Integer count) { if (count > 0) { BarDataSet dataSet = new BarDataSet(chartSeries, null); dataSet.setColor(ThemeManager.getThemeColour(activity, R.attr.colorAccent)); BarData data = new BarData(dataSet); logDetailChart.setData(data); data.setBarWidth(0.8f); data.setDrawValues(false); logDetailChart.invalidate(); layout.removeView(lblDetailMessage); } else lblDetailMessage.setText(R.string.no_logs); } } FetchLogDetails fetchThread; LocalDate date; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ThemeManager.setTheme(this); setContentView(R.layout.activity_log_detail_view); onConfigurationChanged(getResources().getConfiguration()); Bundle extras = getIntent().getExtras(); date = (LocalDate) extras.get("date"); //Only needed because the threeten backport has a different package name than java.time, which would require // no modification. I blame anyone not Oreo or newer. //ref: https://developer.android.com/reference/java/util/Formatter#ddt String titleText = getString(R.string.log_detail_title, date.atStartOfDay(ZoneId.systemDefault()).toEpochSecond() * 1000L); String[] splitTitle = titleText.split(":"); getSupportActionBar().setTitle(splitTitle[0].trim() + ':'); getSupportActionBar().setSubtitle(splitTitle[1].trim()); fetchThread = new FetchLogDetails(); fetchThread.execute(this); BarChart logDetailChart = findViewById(R.id.logDetailChart); float labelFontSize = getResources().getDimensionPixelSize(R.dimen.chartLabelTextSize); logDetailChart.getAxisLeft().setAxisMaximum(100); logDetailChart.getAxisLeft().setAxisMinimum(0); logDetailChart.getAxisLeft().setTextColor(ThemeManager.getThemeColour(this, android.R.attr.textColorTertiary)); logDetailChart.getAxisLeft().setTypeface(ThemeManager.getDefaultThemeFont(this, Typeface.BOLD)); logDetailChart.getAxisLeft().setTextSize(labelFontSize); logDetailChart.getAxisRight().setEnabled(false); logDetailChart.getXAxis().setGranularity(1); logDetailChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM); logDetailChart.getXAxis().setDrawGridLines(false); logDetailChart.getXAxis().setTextColor(ThemeManager.getThemeColour(this, android.R.attr.textColorTertiary)); logDetailChart.getXAxis().setTypeface(ThemeManager.getDefaultThemeFont(this, Typeface.BOLD)); logDetailChart.getXAxis().setTextSize(labelFontSize); logDetailChart.setExtraBottomOffset( TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics())); logDetailChart.getLegend().setEnabled(false); logDetailChart.getDescription().setText(""); logDetailChart.setScaleYEnabled(false); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); int viewOrientation; int chartWidth; int chartHeight; int listWidth; int listHeight; if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { viewOrientation = LinearLayout.HORIZONTAL; chartWidth = getResources().getDimensionPixelSize(R.dimen.landscapeChartWidth); chartHeight = MATCH_PARENT; listWidth = 0; listHeight = MATCH_PARENT; } else { viewOrientation = LinearLayout.VERTICAL; chartWidth = MATCH_PARENT; chartHeight = getResources().getDimensionPixelSize(R.dimen.portraitChartHeight); listWidth = MATCH_PARENT; listHeight = 0; } ((LinearLayout) findViewById(R.id.activity_log_detail_view)).setOrientation(viewOrientation); findViewById(R.id.logDetailChart).setLayoutParams(new LinearLayout.LayoutParams(chartWidth, chartHeight)); findViewById(R.id.logDetailViewScroll).setLayoutParams(new LinearLayout.LayoutParams(listWidth, listHeight, 1)); } @Override protected void onDestroy() { if (fetchThread != null) fetchThread.cancel(true); super.onDestroy(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); ThemeManager.permissionRequestReturn(this, permissions, grantResults); } }
package com.odoo.addons.inventory; import android.os.Bundle; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.widget.Toolbar; import android.view.View; import com.odoo.App; import com.odoo.R; import com.odoo.addons.inventory.models.StockInventory; import com.odoo.core.orm.ODataRow; import com.odoo.core.orm.fields.OColumn; import com.odoo.core.support.OdooCompatActivity; import odoo.controls.OForm; public class AdjustmentDetail extends OdooCompatActivity implements View.OnClickListener { private OForm mForm; private Bundle extras; private Toolbar toolbar; private App app; private Boolean mEditMode = false; private ODataRow record = null; private StockInventory stockInventory; private CollapsingToolbarLayout collapsingToolbarLayout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.inventory_adjustment_detail); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); app = (App) getApplicationContext(); stockInventory = new StockInventory(this, null); extras = getIntent().getExtras(); // if (hasRecordInExtra()) // extras.getString(""); setupToolbar(); } private boolean hasRecordInExtra() { return extras != null && extras.containsKey(OColumn.ROW_ID); } private void setupToolbar() { System.out.println(" 111 my 1" + extras); mForm = (OForm) findViewById(R.id.inventoryForm); if (!hasRecordInExtra()) { // setMode(mEditMode); // userImage.setColorFilter(Color.parseColor("#ffffff")); // userImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE); mForm.setEditable(mEditMode); mForm.initForm(null); } else { int rowId = extras.getInt(OColumn.ROW_ID); record = stockInventory.browse(rowId); checkControls(); // setMode(mEditMode); mForm.setEditable(mEditMode); mForm.initForm(record); // collapsingToolbarLayout.setTitle(record.getString("name")); } } private void checkControls() { System.out.println(" 111 checkControls "); findViewById(R.id.name).setOnClickListener(this); findViewById(R.id.filter).setOnClickListener(this); findViewById(R.id.date).setOnClickListener(this); } @Override public void onClick(View v) { } }
package com.sanchez.fmf.fragment; import android.graphics.Color; import android.graphics.Rect; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; import com.sanchez.fmf.MarketListActivity; import com.sanchez.fmf.R; import com.sanchez.fmf.event.MarketsDetailsRetrievedEvent; import com.sanchez.fmf.event.PlaceTitleResolvedEvent; import com.sanchez.fmf.model.MarketDetailModel; import com.sanchez.fmf.model.MarketListItemModel; import com.sanchez.fmf.util.MarketUtils; import com.sanchez.fmf.util.ViewUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import de.greenrobot.event.EventBus; public class MarketMapFragment extends Fragment implements OnMapReadyCallback { public static final String TAG = MarketMapFragment.class.getSimpleName(); @Bind(R.id.toolbar_market_map_fragment) Toolbar mToolbar; @Bind(R.id.market_map) MapView mMapView; @Bind(R.id.progress_bar) View mProgressBar; private Bundle mBundle; private GoogleMap mMap; private double[] mCoordinates = null; private String mPlaceTitle = null; private HashMap<MarketListItemModel, MarketDetailModel> mMarkets = null; public static MarketMapFragment newInstance(double[] coords, String placeTitle) { MarketMapFragment frag = new MarketMapFragment(); Bundle args = new Bundle(); args.putDoubleArray(MarketListActivity.EXTRA_COORDINATES, coords); args.putString(MarketListActivity.EXTRA_PLACE_TITLE, placeTitle); frag.setArguments(args); return frag; } public MarketMapFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBundle = savedInstanceState; if (getArguments() != null) { mCoordinates = getArguments().getDoubleArray(MarketListActivity.EXTRA_COORDINATES); mPlaceTitle = getArguments().getString(MarketListActivity.EXTRA_PLACE_TITLE); } } @Override public void onStart() { super.onStart(); EventBus.getDefault().registerSticky(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } /** * Relay lifecycle methods to MapView as per Google guidelines */ @Override public void onResume() { super.onResume(); mMapView.onResume(); } @Override public void onPause() { super.onPause(); mMapView.onPause(); } @Override public void onDestroy() { mMapView.onDestroy(); super.onDestroy(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_market_map, container, false); ButterKnife.bind(this, view); MapsInitializer.initialize(getActivity()); mMapView.onCreate(mBundle); // give primary_dark a little transparency int color = getResources().getColor(R.color.primary_dark); mToolbar.setBackgroundColor(Color.argb(144, Color.red(color), Color.green(color), Color.blue(color))); if (null != mPlaceTitle) { mToolbar.setTitle(mPlaceTitle); } mToolbar.setNavigationIcon(R.drawable.ic_clear_white_24dp); mToolbar.setNavigationOnClickListener((v) -> { getActivity().getSupportFragmentManager().popBackStackImmediate(); }); mMapView.getMapAsync(this); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { // Pad toolbar because fitsSystemWindows="true" isn't respected for some reason Rect insets = new Rect(); Window window = getActivity().getWindow(); try { Class clazz = Class.forName("com.android.internal.policy.impl.PhoneWindow"); Field field = clazz.getDeclaredField("mDecor"); field.setAccessible(true); Object decorView = field.get(window); Field insetsField = decorView.getClass().getDeclaredField("mFrameOffsets"); insetsField.setAccessible(true); insets = (Rect) insetsField.get(decorView); } catch (Exception e) { Log.e(TAG, e.getMessage()); } mToolbar.setPadding(0, insets.top, 0, 0); } @Override public void onMapReady(GoogleMap map) { mMap = map; if (null != mMarkets) { setUpMap(); } } private void setUpMap() { double lowestLat = mCoordinates[0]; double highestLat = mCoordinates[0]; double lowestLng = mCoordinates[1]; double highestLng = mCoordinates[1]; ArrayList<MarketListItemModel> keys = new ArrayList<>(mMarkets.keySet()); for (int i = 0; i < keys.size(); i++) { double[] coords = MarketUtils.getCoordinatesFromMapUrl(mMarkets.get(keys.get(i)).getMapLink()); if (coords[0] < lowestLat) { lowestLat = coords[0]; } else if (coords[0] > highestLat) { highestLat = coords[0]; } if (coords[1] < lowestLng) { lowestLng = coords[1]; } else if (coords[1] > highestLng) { highestLng = coords[1]; } mMap.addMarker(new MarkerOptions() .title(MarketUtils.getNameFromMarketString(keys.get(i).getName())) .position(new LatLng(coords[0], coords[1]))); } mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds( new LatLng(lowestLat, lowestLng), new LatLng(highestLat, highestLng)), 100)); mMapView.setVisibility(View.GONE); ViewUtils.crossfadeTwoViews(mMapView, mProgressBar, getResources().getInteger(android.R.integer.config_mediumAnimTime)); } public void onEvent(MarketsDetailsRetrievedEvent event) { mMarkets = event.getMarketDetailModels(); if (null != mMap) { setUpMap(); } } public void onEvent(PlaceTitleResolvedEvent event) { if(null != mToolbar) { mToolbar.setTitle(event.getPlaceTitle()); } } }
package com.slothnull.android.medox; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.slothnull.android.medox.model.AbstractProfile; public class MedicalProfile extends AppCompatActivity { private static final String TAG = "ProfileActivity"; private TextView name; private TextView sex; private TextView birth; private TextView height; private TextView weight; private TextView blood; private TextView address; private TextView phone; private TextView emergency; private TextView martial; private TextView diseases; private TextView allergic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_medical_profile); name = (TextView) findViewById(R.id.name); sex = (TextView) findViewById(R.id.sex); birth = (TextView) findViewById(R.id.birth); height = (TextView) findViewById(R.id.height); weight = (TextView) findViewById(R.id.weight); blood = (TextView) findViewById(R.id.blood); address = (TextView) findViewById(R.id.address); phone = (TextView) findViewById(R.id.phone); emergency = (TextView) findViewById(R.id.emergency); martial = (TextView) findViewById(R.id.martial); diseases = (TextView) findViewById(R.id.diseases); allergic = (TextView) findViewById(R.id.allergic); String UID = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); //data ValueEventListener dataListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI AbstractProfile profile = dataSnapshot.getValue(AbstractProfile.class); if (profile != null) { if (profile.name != null) name.setText("Name: " + profile.name); if (profile.sex != null) sex.setText("Sex: " + profile.sex); if (profile.birth != null) birth.setText("Birth Date: " + profile.birth); if (profile.height != null) height.setText("Height: " + profile.height); if (profile.weight != null) weight.setText("Weight: " + profile.weight); if (profile.blood != null) blood.setText("Blood Type: " + profile.blood); if (profile.address != null) address.setText("Address: " + profile.address); if (profile.phone != null) phone.setText("Phonr: " + profile.phone); if (profile.emergency != null) emergency.setText("Emergency Contact: " + profile.emergency); if (profile.martial != null) martial.setText("Martial Status: " + profile.martial); if (profile.diseases != null) diseases.setText("Diseases: " + profile.diseases); if (profile.allergic != null) allergic.setText("Allergic To: " + profile.allergic); } } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); } }; mDatabase.child("users").child(UID).child("profile") .addValueEventListener(dataListener); } }
package de.gebatzens.ggvertretungsplan; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Intent; import android.os.*; import android.os.Process; import android.util.Log; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.Message; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; import java.net.URISyntaxException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import de.gebatzens.ggvertretungsplan.provider.GGProvider; import de.gebatzens.ggvertretungsplan.provider.VPProvider; public class MQTTService extends IntentService { int id = 1000; public MQTTService() { super("GGService"); } @Override protected void onHandleIntent(Intent intent) { Log.w("ggmqtt", "MQTT Service started"); VPProvider provider = GGApp.GG_APP.provider; if(!(provider instanceof GGProvider)) { Log.w("ggmqtt", "Provider not GGProvider " + provider); return; } String token; if((token = provider.prefs.getString("token", null)) == null) { Log.w("ggmqtt", "Not Logged in"); return; } MQTT client = new MQTT(); try { client.setSslContext(sc); client.setHost("tlsv1://gymnasium-glinde.logoip.de:1883"); } catch (URISyntaxException e) { Log.e("ggmqtt", "Failed to set Host", e); } client.setConnectAttemptsMax(1); BlockingConnection con = client.blockingConnection(); try { con.connect(); Log.w("ggmqtt", "Connected " + token); con.subscribe(new Topic[]{new Topic("gg/schulinfoapp/" + token, QoS.AT_LEAST_ONCE)}); Log.w("ggmqtt", "Subscribed to gg/schulinfoapp/"+token); while(true) { Message message = con.receive(); String msg = new String(message.getPayload(), "UTF-8"); Log.i("ggmqtt", "RECEIVED MESSAGE " + message.getTopic() + " " + msg); String[] s = msg.split(";"); if(s.length > 1) GGApp.GG_APP.createNotification(R.drawable.ic_gg_star, s[0], s[1], new Intent(this, MainActivity.class), id++, "test"); message.ack(); } } catch (Exception e) { Log.e("ggmqtt", "Failed to connect to server", e); } } @Override public void onTaskRemoved(Intent paramIntent) { try { if(!paramIntent.getStringExtra("runtimeLevel").trim().equals("exit")) { Intent localIntent = new Intent(getApplicationContext(), getClass()); localIntent.setPackage(getPackageName()); PendingIntent localPendingIntent = PendingIntent.getService(getApplicationContext(), 1, localIntent, PendingIntent.FLAG_ONE_SHOT); ((AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE)).set(3, 1000L + SystemClock.elapsedRealtime(), localPendingIntent); super.onTaskRemoved(paramIntent); } } catch(NullPointerException e) { Intent localIntent = new Intent(getApplicationContext(), getClass()); localIntent.setPackage(getPackageName()); PendingIntent localPendingIntent = PendingIntent.getService(getApplicationContext(), 1, localIntent, PendingIntent.FLAG_ONE_SHOT); ((AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE)).set(3, 1000L + SystemClock.elapsedRealtime(), localPendingIntent); super.onTaskRemoved(paramIntent); } } private static TrustManager[] mqttTrustMgr = new TrustManager[]{ new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; public static SSLContext sc; static { try { sc = SSLContext.getInstance("TLS"); sc.init(null, mqttTrustMgr, new java.security.SecureRandom()); } catch(Exception e) { throw new RuntimeException(e); } } }
package org.ieatta.activity; import android.content.Intent; import android.content.res.Resources; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.View; import org.ieatta.IEAApp; import org.ieatta.activity.editing.EditHandler; import org.ieatta.activity.search.SearchBarHideHandler; import org.ieatta.activity.leadimages.LeadImagesHandler; import org.ieatta.views.ObservableWebView; import org.wikipedia.util.log.L; import org.wikipedia.views.SwipeRefreshLayoutWithScroll; import java.util.ArrayList; import java.util.List; /** * Our old page load strategy, which uses the JSON MW API directly and loads a page in multiple steps: * First it loads the lead section (sections=0). * Then it loads the remaining sections (sections=1-). * <p/> * This class tracks: * - the states the page loading goes through, * - a backstack of pages and page positions visited, * - and many handlers. */ public class DetailPageLoadStrategy implements PageLoadStrategy { private interface ErrorCallback { void call(@Nullable Throwable error); } private static final String BRIDGE_PAYLOAD_SAVED_PAGE = "savedPage"; /** * List of lightweight history items to serve as the backstack for this fragment. * Since the list consists of Parcelable objects, it can be saved and restored from the * savedInstanceState of the fragment. */ @NonNull private List<PageBackStackItem> backStack = new ArrayList<>(); @NonNull private final SequenceNumber sequenceNumber = new SequenceNumber(); /** * The y-offset position to which the page will be scrolled once it's fully loaded * (or loaded to the point where it can be scrolled to the correct position). */ private int stagedScrollY; private int sectionTargetFromIntent; private String sectionTargetFromTitle; /** * Whether to write the page contents to cache as soon as it's loaded. */ private boolean cacheOnComplete = true; private ErrorCallback networkErrorCallback; // copied fields private PageViewModel model; private PageFragment fragment; private PageActivity activity; private ObservableWebView webView; private SwipeRefreshLayoutWithScroll refreshView; @NonNull private final IEAApp app = IEAApp.getInstance(); private LeadImagesHandler leadImagesHandler; private SearchBarHideHandler searchBarHideHandler; private EditHandler editHandler; @Override @SuppressWarnings("checkstyle:parameternumber") public void setUp(@NonNull PageViewModel model, @NonNull PageFragment fragment, @NonNull SwipeRefreshLayoutWithScroll refreshView, @NonNull ObservableWebView webView, @NonNull SearchBarHideHandler searchBarHideHandler, @NonNull LeadImagesHandler leadImagesHandler, @NonNull List<PageBackStackItem> backStack) { this.model = model; this.fragment = fragment; activity = (PageActivity) fragment.getActivity(); this.refreshView = refreshView; this.webView = webView; this.searchBarHideHandler = searchBarHideHandler; this.leadImagesHandler = leadImagesHandler; this.backStack = backStack; // if we already have pages in the backstack (whether it's from savedInstanceState, or // from being stored in the activity's fragment backstack), then load the topmost page // on the backstack. loadFromBackStack(); } @Override public void load(boolean pushBackStack, int stagedScrollY) { if (pushBackStack) { // update the topmost entry in the backstack, before we start overwriting things. updateCurrentBackStackItem(); pushBackStack(); } // increment our sequence number, so that any async tasks that depend on the sequence // will invalidate themselves upon completion. sequenceNumber.increase(); // If this is a refresh, don't clear the webview contents this.stagedScrollY = stagedScrollY; } @Override public void loadFromBackStack() { if (backStack.isEmpty()) { return; } PageBackStackItem item = backStack.get(backStack.size() - 1); // display the page based on the backstack item, stage the scrollY position based on // the backstack item. fragment.loadPage(item.getHistoryEntry(), false, item.getScrollY()); L.d("Loaded page " + item.getHistoryEntry().getSource() + " from backstack"); } @Override public void updateCurrentBackStackItem() { if (backStack.isEmpty()) { return; } PageBackStackItem item = backStack.get(backStack.size() - 1); item.setScrollY(webView.getScrollY()); } @Override public void setBackStack(@NonNull List<PageBackStackItem> backStack) { this.backStack = backStack; } public boolean popBackStack() { if (!backStack.isEmpty()) { backStack.remove(backStack.size() - 1); } if (!backStack.isEmpty()) { loadFromBackStack(); return true; } return false; } @Override public void onHidePageContent() { } @Override public void setEditHandler(EditHandler editHandler) { this.editHandler = editHandler; } @Override public void backFromEditing(Intent data) { //Retrieve section ID from intent, and find correct section, so where know where to scroll to // sectionTargetFromIntent = data.getIntExtra(EditSectionActivity.EXTRA_SECTION_ID, 0); //reset our scroll offset, since we have a section scroll target stagedScrollY = 0; } @Override public void layoutLeadImage() { leadImagesHandler.beginLayout(new LeadImagesHandler.OnLeadImageLayoutListener() { @Override public void onLayoutComplete(int sequence) { if (fragment.isAdded()) { searchBarHideHandler.setFadeEnabled(leadImagesHandler.isLeadImageEnabled()); } } }, sequenceNumber.get()); } private void layoutLeadImage(@Nullable Runnable runnable) { leadImagesHandler.beginLayout(new LeadImageLayoutListener(runnable), sequenceNumber.get()); } // private void updateThumbnail(String thumbUrl) { // model.getTitle().setThumbUrl(thumbUrl); // model.getTitleOriginal().setThumbUrl(thumbUrl); // fragment.invalidateTabs(); private boolean isFirstPage() { return backStack.size() <= 1; // && !webView.canGoBack(); } /** * Push the current page title onto the backstack. */ private void pushBackStack() { PageBackStackItem item = new PageBackStackItem(model.getCurEntry()); backStack.add(item); } // private boolean isPageEditable(Page page) { // return (app.getUserInfoStorage().isLoggedIn() || !isAnonEditingDisabled()) // && !page.isFilePage() // && !page.isMainPage(); private float getDimension(@DimenRes int id) { return getResources().getDimension(id); } private Resources getResources() { return activity.getResources(); } /** * Monotonically increasing sequence number to maintain synchronization when loading page * content asynchronously between the Java and JavaScript layers, as well as between synchronous * methods and asynchronous callbacks on the UI thread. */ private static class SequenceNumber { private int sequence; void increase() { ++sequence; } int get() { return sequence; } boolean inSync(int sequence) { return this.sequence == sequence; } } public void onLeadSectionLoaded(int startSequenceNum) { // if (!fragment.isAdded() || !sequenceNumber.inSync(startSequenceNum)) { // return; if (!fragment.isAdded() ) { return; } layoutLeadImage(new Runnable() { @Override public void run() { } }); } private class LeadImageLayoutListener implements LeadImagesHandler.OnLeadImageLayoutListener { @Nullable private final Runnable runnable; LeadImageLayoutListener(@Nullable Runnable runnable) { this.runnable = runnable; } @Override public void onLayoutComplete(int sequence) { if (!fragment.isAdded() || !sequenceNumber.inSync(sequence)) { return; } searchBarHideHandler.setFadeEnabled(leadImagesHandler.isLeadImageEnabled()); if (runnable != null) { // when the lead image is laid out, load the lead section and the rest // of the sections into the webview. displayLeadSection(); runnable.run(); } } } private void displayLeadSection() { Page page = model.getPage(); if (webView.getVisibility() != View.VISIBLE) { webView.setVisibility(View.VISIBLE); } refreshView.setRefreshing(false); // activity.updateProgressBar(true, true, 0); // leadImagesHandler.updateNavigate(page.getPageProperties().getGeo()); } }
package org.commcare.dalvik.activities; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.android.fragments.SetupEnterURLFragment; import org.commcare.android.fragments.SetupInstallFragment; import org.commcare.android.fragments.SetupKeepInstallFragment; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.framework.ManagedUi; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.logic.BarcodeScanListenerDefaultImpl; import org.commcare.android.logic.GlobalConstants; import org.commcare.android.models.notifications.NotificationMessage; import org.commcare.android.models.notifications.NotificationMessageFactory; import org.commcare.android.tasks.ResourceEngineListener; import org.commcare.android.tasks.ResourceEngineTask; import org.commcare.android.tasks.ResourceEngineTask.ResourceEngineOutcomes; import org.commcare.android.tasks.RetrieveParseVerifyMessageListener; import org.commcare.android.tasks.RetrieveParseVerifyMessageTask; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.dalvik.application.CommCareApp; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.resources.model.ResourceTable; import org.commcare.resources.model.UnresolvedResourceException; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.util.PropertyUtils; import org.joda.time.DateTime; import java.io.IOException; import java.security.SignatureException; import java.util.List; /** * Responsible for identifying the state of the application (uninstalled, * installed) and performing any necessary setup to get to a place where * CommCare can load normally. * * If the startup activity identifies that the app is installed properly it * should not ever require interaction or be visible to the user. * * @author ctsims */ @ManagedUi(R.layout.first_start_screen_modern) public class CommCareSetupActivity extends CommCareActivity<CommCareSetupActivity> implements ResourceEngineListener, SetupEnterURLFragment.URLInstaller, SetupKeepInstallFragment.StartStopInstallCommands, RetrieveParseVerifyMessageListener { private static final String TAG = CommCareSetupActivity.class.getSimpleName(); public static final String RESOURCE_STATE = "resource_state"; public static final String KEY_PROFILE_REF = "app_profile_ref"; public static final String KEY_UPGRADE_MODE = "app_upgrade_mode"; public static final String KEY_ERROR_MODE = "app_error_mode"; private static final String KEY_UI_STATE = "current_install_ui_state"; private static final String KEY_OFFLINE = "offline_install"; private static final String KEY_FROM_EXTERNAL = "from_external"; private static final String KEY_FROM_MANAGER = "from_manager"; /** * Should the user be logged out when this activity is done? */ public static final String KEY_REQUIRE_REFRESH = "require_referesh"; public static final String KEY_INSTALL_FAILED = "install_failed"; /** * Activity is being launched by auto update, instead of being triggered * manually. */ public static final String KEY_AUTO = "is_auto_update"; private static final String KEY_START_OVER = "start_over_uprgrade"; private static final String KEY_LAST_INSTALL = "last_install_time"; /** * How many sms messages to scan over looking for commcare install link */ private static final int SMS_CHECK_COUNT = 100; /** * UI configuration states. */ public enum UiState { IN_URL_ENTRY, CHOOSE_INSTALL_ENTRY_METHOD, READY_TO_INSTALL, ERROR, /** * App installed already. Buttons aren't shown, trying to update app * with no user input */ UPGRADE } private UiState uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD; public static final int MODE_BASIC = Menu.FIRST; public static final int MODE_ADVANCED = Menu.FIRST + 1; private static final int MODE_ARCHIVE = Menu.FIRST + 2; private static final int MODE_SMS = Menu.FIRST + 3; public static final int BARCODE_CAPTURE = 1; private static final int ARCHIVE_INSTALL = 3; private static final int DIALOG_INSTALL_PROGRESS = 4; private boolean startAllowed = true; private boolean inUpgradeMode = false; private String incomingRef; private CommCareApp ccApp; /** * Indicates that this activity was launched from the AppManagerActivity */ private boolean fromManager; /** * Indicates that this activity was launched from an outside application (such as a bit.ly * url entered in a browser) */ private boolean fromExternal; /** * Indicates that the current install attempt will be made from a .ccz file, so we do * not need to check for internet connectivity */ private boolean offlineInstall; /** * Whether this needs to be interactive (if it's automatic, we want to skip * a lot of the UI stuff */ private boolean isAuto = false; /** * Keeps track of whether the previous resource table was in a 'fresh' * (empty or installed) state before the last install ran. */ private boolean resourceTableWasFresh; private static final long START_OVER_THRESHOLD = 604800000; //1 week in milliseconds //region UIState fragments private final FragmentManager fm = getSupportFragmentManager(); private final SetupKeepInstallFragment startInstall = new SetupKeepInstallFragment(); private final SetupInstallFragment installFragment = new SetupInstallFragment(); //endregion @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CommCareSetupActivity oldActivity = (CommCareSetupActivity)this.getDestroyedActivityState(); this.fromManager = this.getIntent(). getBooleanExtra(AppManagerActivity.KEY_LAUNCH_FROM_MANAGER, false); //Retrieve instance state if(savedInstanceState == null) { Log.v("UiState", "SavedInstanceState is null, not getting anything from it =/"); if(Intent.ACTION_VIEW.equals(this.getIntent().getAction())) { //We got called from an outside application, it's gonna be a wild ride! fromExternal = true; incomingRef = this.getIntent().getData().toString(); if(incomingRef.contains(".ccz")) { // make sure this is in the file system boolean isFile = incomingRef.contains("file: if (isFile) { // remove file:// prepend incomingRef = incomingRef.substring(incomingRef.indexOf(" Intent i = new Intent(this, InstallArchiveActivity.class); i.putExtra(InstallArchiveActivity.ARCHIVE_REFERENCE, incomingRef); startActivityForResult(i, ARCHIVE_INSTALL); } else{ fail(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Bad_Archive_File), true); } } else { this.uiState = UiState.READY_TO_INSTALL; //Now just start up normally. } } else { incomingRef = this.getIntent().getStringExtra(KEY_PROFILE_REF); } inUpgradeMode = this.getIntent().getBooleanExtra(KEY_UPGRADE_MODE, false); isAuto = this.getIntent().getBooleanExtra(KEY_AUTO, false); } else { String uiStateEncoded = savedInstanceState.getString(KEY_UI_STATE); this.uiState = uiStateEncoded == null ? UiState.CHOOSE_INSTALL_ENTRY_METHOD : UiState.valueOf(UiState.class, uiStateEncoded); Log.v("UiState","uiStateEncoded is: " + uiStateEncoded + ", so my uiState is: " + uiState); incomingRef = savedInstanceState.getString("profileref"); inUpgradeMode = savedInstanceState.getBoolean(KEY_UPGRADE_MODE); isAuto = savedInstanceState.getBoolean(KEY_AUTO); fromExternal = savedInstanceState.getBoolean(KEY_FROM_EXTERNAL); fromManager = savedInstanceState.getBoolean(KEY_FROM_MANAGER); offlineInstall = savedInstanceState.getBoolean(KEY_OFFLINE); // Uggggh, this might not be 100% legit depending on timing, what // if we've already reconnected and shut down the dialog? startAllowed = savedInstanceState.getBoolean("startAllowed"); } // if we are in upgrade mode we want the UiState to reflect that, // unless we are showing an error if (inUpgradeMode && this.uiState != UiState.ERROR){ this.uiState = UiState.UPGRADE; } // reclaim ccApp for resuming installation if(oldActivity != null) { this.ccApp = oldActivity.ccApp; } Log.v("UiState", "Current vars: " + "UIState is: " + this.uiState + " " + "incomingRef is: " + incomingRef + " " + "startAllowed is: " + startAllowed + " " ); uiStateScreenTransition(); performSMSInstall(false); } @Override public void onAttachFragment(Fragment fragment) { super.onAttachFragment(fragment); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar actionBar = getActionBar(); if (actionBar != null) { // removes the back button from the action bar actionBar.setDisplayHomeAsUpEnabled(false); } } } @Override protected void onResume() { super.onResume(); // If clicking the regular app icon brought us to CommCareSetupActivity // (because that's where we were last time the app was up), but there are now // 1 or more available apps, we want to redirect to CCHomeActivity if (!fromManager && !fromExternal && !inUpgradeMode && CommCareApplication._().usableAppsPresent()) { Intent i = new Intent(this, CommCareHomeActivity.class); startActivity(i); } } @Override public void onURLChosen(String url) { if(BuildConfig.DEBUG) { Log.d(TAG, "SetupEnterURLFragment returned: " + url); } incomingRef = url; this.uiState = UiState.READY_TO_INSTALL; uiStateScreenTransition(); } private void uiStateScreenTransition() { Fragment fragment; FragmentTransaction ft = fm.beginTransaction(); switch (uiState){ case UPGRADE: case READY_TO_INSTALL: if(incomingRef == null || incomingRef.length() == 0){ Log.e(TAG,"During install: IncomingRef is empty!"); Toast.makeText(getApplicationContext(), "Invalid URL: '" + incomingRef + "'", Toast.LENGTH_SHORT).show(); return; } // the buttonCommands were already set when the fragment was // attached, no need to set them here fragment = startInstall; break; case IN_URL_ENTRY: fragment = restoreInstallSetupFragment(); this.offlineInstall = false; break; case CHOOSE_INSTALL_ENTRY_METHOD: fragment = installFragment; this.offlineInstall = false; break; default: return; } ft.replace(R.id.setup_fragment_container, fragment); ft.commit(); } private Fragment restoreInstallSetupFragment() { Fragment fragment = null; List<Fragment> fgmts = fm.getFragments(); int lastIndex = fgmts != null ? fgmts.size() - 1 : -1; if(lastIndex > -1) { fragment = fgmts.get(lastIndex); if (BuildConfig.DEBUG) { Log.v(TAG, "Last fragment: " + fragment); } } if(!(fragment instanceof SetupEnterURLFragment)){ // last fragment wasn't url entry, so default to the installation method chooser fragment = installFragment; } return fragment; } @Override protected void onStart() { super.onStart(); uiStateScreenTransition(); // upgrade app if needed if(uiState == UiState.UPGRADE && incomingRef != null && incomingRef.length() != 0) { if (isNetworkNotConnected()){ CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Remote_NoNetwork, "INSTALL_NO_NETWORK")); finish(); } else { startResourceInstall(true); } } } @Override protected int getWakeLockLevel() { return PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_UI_STATE, uiState.toString()); outState.putString("profileref", incomingRef); outState.putBoolean(KEY_AUTO, isAuto); outState.putBoolean("startAllowed", startAllowed); outState.putBoolean(KEY_UPGRADE_MODE, inUpgradeMode); outState.putBoolean(KEY_OFFLINE, offlineInstall); outState.putBoolean(KEY_FROM_EXTERNAL, fromExternal); outState.putBoolean(KEY_FROM_MANAGER, fromManager); Log.v("UiState", "Saving instance state: " + outState); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String result = null; switch(requestCode) { case BARCODE_CAPTURE: if (resultCode == Activity.RESULT_OK) { result = data.getStringExtra(BarcodeScanListenerDefaultImpl.SCAN_RESULT); String dbg = "Got url from barcode scanner: " + result; Log.i(TAG, dbg); } break; case ARCHIVE_INSTALL: if (resultCode == Activity.RESULT_OK) { offlineInstall = true; result = data.getStringExtra(InstallArchiveActivity.ARCHIVE_REFERENCE); } break; } if(result == null) return; incomingRef = result; this.uiState = UiState.READY_TO_INSTALL; try { // check if the reference can be derived without erroring out ReferenceManager._().DeriveReference(incomingRef); } catch (InvalidReferenceException ire) { // Couldn't process reference, return to basic ui state to ask user // for new install reference incomingRef = null; Toast.makeText(getApplicationContext(), Localization.get("install.bad.ref"), Toast.LENGTH_LONG).show(); this.uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD; } uiStateScreenTransition(); } private String getRef(){ return incomingRef; } private CommCareApp getCommCareApp(){ if (inUpgradeMode) { return CommCareApplication._().getCurrentApp(); } ApplicationRecord newRecord = new ApplicationRecord(PropertyUtils.genUUID().replace("-",""), ApplicationRecord.STATUS_UNINITIALIZED); return new CommCareApp(newRecord); } private void startResourceInstall() { CommCareApp ccApp = getCommCareApp(); long lastInstallTime = ccApp.getAppPreferences().getLong(KEY_LAST_INSTALL, -1); if (System.currentTimeMillis() - lastInstallTime > START_OVER_THRESHOLD) { // If we are triggering a start over install due to the time // threshold when there is a partial resource table that we could // be using, send a message to log this. ResourceTable temporary = ccApp.getCommCarePlatform().getUpgradeResourceTable(); if (temporary.getTableReadiness() == ResourceTable.RESOURCE_TABLE_PARTIAL) { Logger.log(AndroidLogger.TYPE_RESOURCES, "A start-over on installation has been " + "triggered by the time threshold when there is an existing partial " + "resource table that could be used."); } startResourceInstall(true); } else { startResourceInstall(ccApp.getAppPreferences().getBoolean(KEY_START_OVER, true)); } } @Override public void startBlockingForTask(int id) { super.startBlockingForTask(id); this.startAllowed = false; } @Override public void stopBlockingForTask(int id) { super.stopBlockingForTask(id); this.startAllowed = true; } /** * @param startOverUpgrade When set CommCarePlatform.stageUpgradeTable() * will clear the last version of the upgrade table * and start over. Otherwise install reuses the * last version of the upgrade table. */ private void startResourceInstall(boolean startOverUpgrade) { if(startAllowed) { CommCareApp app = getCommCareApp(); ccApp = app; // store what the state of the resource table was before this // install, so we can compare it to the state after and decide if // this should count as a 'last install time' int tableStateBeforeInstall = ccApp.getCommCarePlatform().getUpgradeResourceTable().getTableReadiness(); this.resourceTableWasFresh = (tableStateBeforeInstall == ResourceTable.RESOURCE_TABLE_EMPTY) || (tableStateBeforeInstall == ResourceTable.RESOURCE_TABLE_INSTALLED); CustomProgressDialog lastDialog = getCurrentDialog(); // used to tell the ResourceEngineTask whether or not it should // sleep before it starts, set based on whether we are currently // in keep trying mode. boolean shouldSleep = (lastDialog != null) && lastDialog.isChecked(); ResourceEngineTask<CommCareSetupActivity> task = new ResourceEngineTask<CommCareSetupActivity>(inUpgradeMode, app, startOverUpgrade, DIALOG_INSTALL_PROGRESS, shouldSleep) { @Override protected void deliverResult(CommCareSetupActivity receiver, ResourceEngineOutcomes result) { boolean startOverInstall = false; switch (result) { case StatusInstalled: receiver.reportSuccess(true); break; case StatusUpToDate: receiver.reportSuccess(false); break; case StatusMissingDetails: // fall through to more general case: case StatusMissing: CustomProgressDialog lastDialog = receiver.getCurrentDialog(); if ((lastDialog != null) && lastDialog.isChecked()) { // 'Keep Trying' installation mode is set receiver.startResourceInstall(false); } else { receiver.failMissingResource(this.missingResourceException, result); } break; case StatusBadReqs: receiver.failBadReqs(badReqCode, vRequired, vAvailable, majorIsProblem); break; case StatusFailState: startOverInstall = true; receiver.failWithNotification(ResourceEngineOutcomes.StatusFailState); break; case StatusNoLocalStorage: startOverInstall = true; receiver.failWithNotification(ResourceEngineOutcomes.StatusNoLocalStorage); break; case StatusBadCertificate: receiver.failWithNotification(ResourceEngineOutcomes.StatusBadCertificate); break; case StatusDuplicateApp: startOverInstall = true; receiver.failWithNotification(ResourceEngineOutcomes.StatusDuplicateApp); break; default: startOverInstall = true; receiver.failUnknown(ResourceEngineOutcomes.StatusFailUnknown); break; } // Did the install fail in a way where the existing // resource table should be reused in the next install // attempt? receiver.ccApp.getAppPreferences().edit().putBoolean(KEY_START_OVER, startOverInstall).commit(); // Check if we want to record this as a 'last install // time', based on the state of the resource table before // and after this install took place ResourceTable temporary = receiver.ccApp.getCommCarePlatform().getUpgradeResourceTable(); if (temporary.getTableReadiness() == ResourceTable.RESOURCE_TABLE_PARTIAL && receiver.resourceTableWasFresh) { receiver.ccApp.getAppPreferences().edit().putLong(KEY_LAST_INSTALL, System.currentTimeMillis()).commit(); } } @Override protected void deliverUpdate(CommCareSetupActivity receiver, int[]... update) { receiver.updateResourceProgress(update[0][0], update[0][1], update[0][2]); } @Override protected void deliverError(CommCareSetupActivity receiver, Exception e) { receiver.failUnknown(ResourceEngineOutcomes.StatusFailUnknown); } }; task.connect(this); task.execute(getRef()); } else { Log.i(TAG, "During install: blocked a resource install press since a task was already running"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MODE_ARCHIVE, 0, Localization.get("menu.archive")).setIcon(android.R.drawable.ic_menu_upload); menu.add(0, MODE_SMS, 1, Localization.get("menu.sms")).setIcon(android.R.drawable.stat_notify_chat); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); return true; } /** * Scan SMS messages for texts with profile references. * @param installTriggeredManually if scan was triggered manually, then * install automatically if reference is found */ private void performSMSInstall(boolean installTriggeredManually){ this.scanSMSLinks(installTriggeredManually); } /** * Scan the most recent incoming text messages for a message with a * verified link to a commcare app and install it. Message scanning stops * after the number of scanned messages reaches 'SMS_CHECK_COUNT'. * * @param installTriggeredManually don't install the found app link */ private void scanSMSLinks(final boolean installTriggeredManually){ final Uri SMS_INBOX = Uri.parse("content://sms/inbox"); DateTime oneDayAgo = (new DateTime()).minusDays(1); Cursor cursor = getContentResolver().query(SMS_INBOX, null, "date >? ", new String[] {"" + oneDayAgo.getMillis() }, "date DESC"); if (cursor == null) { return; } int messageIterationCount = 0; try { boolean attemptedInstall = false; while (cursor.moveToNext() && messageIterationCount <= SMS_CHECK_COUNT) { // must check the result to prevent exception messageIterationCount++; String textMessageBody = cursor.getString(cursor.getColumnIndex("body")); if (textMessageBody.contains(GlobalConstants.SMS_INSTALL_KEY_STRING)) { attemptedInstall = true; RetrieveParseVerifyMessageTask mTask = new RetrieveParseVerifyMessageTask<CommCareSetupActivity>(this, installTriggeredManually) { @Override protected void deliverResult(CommCareSetupActivity receiver, String result) { if (installTriggeredManually) { if (result != null) { receiver.incomingRef = result; receiver.uiState = UiState.READY_TO_INSTALL; receiver.uiStateScreenTransition(); receiver.startResourceInstall(); } else { // only notify if this was manually triggered, since most people won't use this Toast.makeText(receiver, Localization.get("menu.sms.not.found"), Toast.LENGTH_LONG).show(); } } else { if (result != null) { receiver.incomingRef = result; receiver.uiState = UiState.READY_TO_INSTALL; receiver.uiStateScreenTransition(); Toast.makeText(receiver, Localization.get("menu.sms.ready"), Toast.LENGTH_LONG).show(); } } } @Override protected void deliverUpdate(CommCareSetupActivity receiver, Void... update) { //do nothing for now } @Override protected void deliverError(CommCareSetupActivity receiver, Exception e) { if (e instanceof SignatureException) { e.printStackTrace(); Toast.makeText(receiver, Localization.get("menu.sms.not.verified"), Toast.LENGTH_LONG).show(); } else if (e instanceof IOException) { e.printStackTrace(); Toast.makeText(receiver, Localization.get("menu.sms.not.retrieved"), Toast.LENGTH_LONG).show(); } else { e.printStackTrace(); Toast.makeText(receiver, Localization.get("notification.install.unknown.title"), Toast.LENGTH_LONG).show(); } } }; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, textMessageBody); } else { mTask.execute(textMessageBody); } break; } } // attemptedInstall will only be true if we found no texts with the SMS_INSTALL_KEY_STRING tag // if we found one, notification will be handle by the task receiver if(!attemptedInstall) { Toast.makeText(this, Localization.get("menu.sms.not.found"), Toast.LENGTH_LONG).show(); } } finally { cursor.close(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == MODE_ARCHIVE) { Intent i = new Intent(getApplicationContext(), InstallArchiveActivity.class); startActivityForResult(i, ARCHIVE_INSTALL); } if (item.getItemId() == MODE_SMS) { performSMSInstall(true); } return true; } /** * Return to or launch home activity. * * @param requireRefresh should the user be logged out upon returning to * home activity? * @param failed did installation occur successfully? */ private void done(boolean requireRefresh, boolean failed) { if (Intent.ACTION_VIEW.equals(CommCareSetupActivity.this.getIntent().getAction())) { //Call out to CommCare Home Intent i = new Intent(getApplicationContext(), CommCareHomeActivity.class); i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh); startActivity(i); } else { //Good to go Intent i = new Intent(getIntent()); i.putExtra(KEY_REQUIRE_REFRESH, requireRefresh); i.putExtra(KEY_INSTALL_FAILED, failed); setResult(RESULT_OK, i); } finish(); } /** * Raise failure message and return to the home activity with cancel code */ private void fail(NotificationMessage message, boolean alwaysNotify) { Toast.makeText(this, message.getTitle(), Toast.LENGTH_LONG).show(); if (isAuto || alwaysNotify) { CommCareApplication._().reportNotificationMessage(message); } // Last install attempt failed, so restore to starting uistate to try again uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD; uiStateScreenTransition(); } // All final paths from the Update are handled here (Important! Some // interaction modes should always auto-exit this activity) Everything here // should call one of: fail() or done() /* All methods for implementation of ResourceEngineListener */ @Override public void reportSuccess(boolean appChanged) { //If things worked, go ahead and clear out any warnings to the contrary CommCareApplication._().clearNotifications("install_update"); if(!appChanged) { Toast.makeText(this, Localization.get("updates.success"), Toast.LENGTH_LONG).show(); } done(appChanged, false); } @Override public void failMissingResource(UnresolvedResourceException ure, ResourceEngineOutcomes statusMissing) { fail(NotificationMessageFactory.message(statusMissing, new String[] {null, ure.getResource().getDescriptor(), ure.getMessage()}), ure.isMessageUseful()); } @Override public void failBadReqs(int code, String vRequired, String vAvailable, boolean majorIsProblem) { String versionMismatch = Localization.get("install.version.mismatch", new String[] {vRequired,vAvailable}); String error; if (majorIsProblem){ error=Localization.get("install.major.mismatch"); } else { error=Localization.get("install.minor.mismatch"); } fail(NotificationMessageFactory.message(ResourceEngineOutcomes.StatusBadReqs, new String[] {null, versionMismatch, error}), true); } @Override public void failUnknown(ResourceEngineOutcomes unknown) { fail(NotificationMessageFactory.message(unknown), false); } @Override public void updateResourceProgress(int done, int total, int phase) { if(inUpgradeMode) { if (phase == ResourceEngineTask.PHASE_DOWNLOAD) { updateProgress(Localization.get("updates.found", new String[] {""+done,""+total}), DIALOG_INSTALL_PROGRESS); } else if (phase == ResourceEngineTask.PHASE_COMMIT) { updateProgress(Localization.get("updates.downloaded"), DIALOG_INSTALL_PROGRESS); } } else { updateProgress(Localization.get("profile.found", new String[]{""+done,""+total}), DIALOG_INSTALL_PROGRESS); updateProgressBar(done, total, DIALOG_INSTALL_PROGRESS); } } @Override public void failWithNotification(ResourceEngineOutcomes statusfailstate) { fail(NotificationMessageFactory.message(statusfailstate), true); } /** * {@inheritDoc} * * Implementation of generateProgressDialog() for DialogController -- * all other methods handled entirely in CommCareActivity */ @Override public CustomProgressDialog generateProgressDialog(int taskId) { if (taskId != DIALOG_INSTALL_PROGRESS) { Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareSetupActivity"); return null; } String title, message; if (uiState == UiState.UPGRADE) { title = Localization.get("updates.title"); message = Localization.get("updates.checking"); } else { title = Localization.get("updates.resources.initialization"); message = Localization.get("updates.resources.profile"); } CustomProgressDialog dialog = CustomProgressDialog.newInstance(title, message, taskId); dialog.setCancelable(false); String checkboxText = Localization.get("updates.keep.trying"); CustomProgressDialog lastDialog = getCurrentDialog(); boolean isChecked = (lastDialog != null) && lastDialog.isChecked(); dialog.addCheckbox(checkboxText, isChecked); dialog.addProgressBar(); return dialog; } //region StartStopInstallCommands implementation @Override public void onStartInstallClicked() { if (!offlineInstall && isNetworkNotConnected()) { failWithNotification(ResourceEngineOutcomes.StatusNoConnection); } else { startResourceInstall(); } } @Override public void onStopInstallClicked() { incomingRef = null; uiState = UiState.CHOOSE_INSTALL_ENTRY_METHOD; uiStateScreenTransition(); } public void setUiState(UiState newState) { uiState = newState; } @Override public void downloadLinkReceived(String url) { if (url != null) { incomingRef = url; uiState = UiState.READY_TO_INSTALL; uiStateScreenTransition(); Toast.makeText(this, Localization.get("menu.sms.ready"), Toast.LENGTH_LONG).show(); } } @Override public void downloadLinkReceivedAutoInstall(String url) { if(url != null){ incomingRef = url; uiState = UiState.READY_TO_INSTALL; uiStateScreenTransition(); startResourceInstall(); } else{ // only notify if this was manually triggered, since most people won't use this Toast.makeText(this, Localization.get("menu.sms.not.found"), Toast.LENGTH_LONG).show(); } } @Override public void exceptionReceived(Exception e) { if(e instanceof SignatureException){ e.printStackTrace(); Toast.makeText(this, Localization.get("menu.sms.not.verified"), Toast.LENGTH_LONG).show(); } else if(e instanceof IOException){ e.printStackTrace(); Toast.makeText(this, Localization.get("menu.sms.not.retrieved"), Toast.LENGTH_LONG).show(); } else{ e.printStackTrace(); Toast.makeText(this, Localization.get("notification.install.unknown.title"), Toast.LENGTH_LONG).show(); } } }
package org.odk.collect.android.activities; import android.annotation.SuppressLint; import android.app.ActionBar; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Rect; import android.location.LocationManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore.Images; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.SpannableStringBuilder; import android.util.Log; import android.util.Pair; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextThemeWrapper; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.analytics.GoogleAnalyticsFields; import org.commcare.android.analytics.GoogleAnalyticsUtils; import org.commcare.android.analytics.TimedStatsTracker; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.framework.SaveSessionCommCareActivity; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.util.FormUploadUtil; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.CommCareHomeActivity; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.AlertDialogFactory; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.dialogs.DialogChoiceItem; import org.commcare.dalvik.dialogs.HorizontalPaneledChoiceDialog; import org.commcare.dalvik.dialogs.PaneledChoiceDialog; import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns; import org.commcare.dalvik.odk.provider.InstanceProviderAPI; import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns; import org.commcare.dalvik.utils.UriToFilePath; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.activities.components.FormFileSystemHelpers; import org.odk.collect.android.activities.components.FormLayoutHelpers; import org.odk.collect.android.activities.components.FormNavigationController; import org.odk.collect.android.activities.components.FormNavigationUI; import org.odk.collect.android.activities.components.FormRelevancyUpdating; import org.odk.collect.android.activities.components.ImageCaptureProcessing; import org.odk.collect.android.application.ODKStorage; import org.odk.collect.android.jr.extensions.IntentCallout; import org.odk.collect.android.jr.extensions.PollSensorAction; import org.odk.collect.android.listeners.AdvanceToNextListener; import org.odk.collect.android.listeners.FormSaveCallback; import org.odk.collect.android.listeners.FormSavedListener; import org.odk.collect.android.listeners.WidgetChangedListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.PropertyManager; import org.odk.collect.android.preferences.FormEntryPreferences; import org.odk.collect.android.tasks.FormLoaderTask; import org.odk.collect.android.tasks.SaveToDiskTask; import org.odk.collect.android.utilities.Base64Wrapper; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.GeoUtils; import org.odk.collect.android.views.QuestionsView; import org.odk.collect.android.views.ResizingImageView; import org.odk.collect.android.widgets.IntentWidget; import org.odk.collect.android.widgets.QuestionWidget; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.crypto.spec.SecretKeySpec; /** * Displays questions, animates transitions between * questions, and allows the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends SaveSessionCommCareActivity<FormEntryActivity> implements AnimationListener, FormSavedListener, FormSaveCallback, AdvanceToNextListener, WidgetChangedListener { private static final String TAG = FormEntryActivity.class.getSimpleName(); // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_VIDEO_FETCH = 3; public static final int LOCATION_CAPTURE = 5; private static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; private static final int FORM_PREFERENCES_KEY = 8; public static final int INTENT_CALLOUT = 10; private static final int HIERARCHY_ACTIVITY_FIRST_START = 11; public static final int SIGNATURE_CAPTURE = 12; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; // Identifies the gp of the form used to launch form entry private static final String KEY_FORMPATH = "formpath"; public static final String KEY_INSTANCEDESTINATION = "instancedestination"; public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment"; public static final String KEY_FORM_CONTENT_URI = "form_content_uri"; public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri"; public static final String KEY_AES_STORAGE_KEY = "key_aes_storage"; public static final String KEY_HEADER_STRING = "form_header"; public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management"; public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled"; private static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved"; /** * Intent extra flag to track if this form is an archive. Used to trigger * return logic when this activity exits to the home screen, such as * whether to redirect to archive view or sync the form. */ public static final String IS_ARCHIVED_FORM = "is-archive-form"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String KEY_FORM_LOAD_HAS_TRIGGERED = "newform"; private static final String KEY_FORM_LOAD_FAILED = "form-failed"; private static final String KEY_LOC_ERROR = "location-not-enabled"; private static final String KEY_LOC_ERROR_PATH = "location-based-xpath-error"; private static final int MENU_LANGUAGES = Menu.FIRST + 1; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 2; private static final int MENU_SAVE = Menu.FIRST + 3; private static final int MENU_PREFERENCES = Menu.FIRST + 4; public static final String NAV_STATE_NEXT = "next"; public static final String NAV_STATE_DONE = "done"; public static final String NAV_STATE_QUIT = "quit"; public static final String NAV_STATE_BACK = "back"; private String mFormPath; // Path to a particular form instance public static String mInstancePath; private String mInstanceDestination; private GestureDetector mGestureDetector; private SecretKeySpec symetricKey = null; public static FormController mFormController; private Animation mInAnimation; private Animation mOutAnimation; private ViewGroup mViewPane; private QuestionsView questionsView; private boolean mIncompleteEnabled = true; private boolean hasFormLoadBeenTriggered = false; private boolean hasFormLoadFailed = false; private String locationRecieverErrorAction = null; private String badLocationXpath = null; // used to limit forward/backward swipes to one per question private boolean isAnimatingSwipe; private boolean isDialogShowing; private FormLoaderTask<FormEntryActivity> mFormLoaderTask; private SaveToDiskTask<FormEntryActivity> mSaveToDiskTask; private Uri formProviderContentURI = FormsColumns.CONTENT_URI; private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI; private static String mHeaderString; // Was the form saved? Used to set activity return code. private boolean hasSaved = false; private BroadcastReceiver mLocationServiceIssueReceiver; // marked true if we are in the process of saving a form because the user // database & key session are expiring. Being set causes savingComplete to // broadcast a form saving intent. private boolean savingFormOnKeySessionExpiration = false; private boolean mGroupForcedInvisible = false; private boolean mGroupNativeVisibility = false; enum AnimationType { LEFT, RIGHT, FADE } @Override @SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addBreadcrumbBar(); // must be at the beginning of any activity that can be called from an external intent try { ODKStorage.createODKDirs(); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } setupUI(); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager( getApplicationContext())); loadStateFromBundle(savedInstanceState); // Check to see if this is a screen flip or a new form load. Object data = this.getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; mSaveToDiskTask.setFormSavedListener(this); } else if (hasFormLoadBeenTriggered && !hasFormLoadFailed) { // Screen orientation change refreshCurrentView(); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { /* * EventLog accepts only proper Strings as input, but prior to this version, * Android would try to send SpannedStrings to it, thus crashing the app. * This makes sure the title is actually a String. * This fixes bug 174626. */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 && item.getTitleCondensed() != null) { item.setTitleCondensed(item.getTitleCondensed().toString()); } return super.onMenuItemSelected(featureId, item); } @Override public void formSaveCallback() { // note that we have started saving the form savingFormOnKeySessionExpiration = true; // start saving form, which will call the key session logout completion // function when it finishes. saveIncompleteFormToDisk(); } private void registerFormEntryReceiver() { //BroadcastReceiver for: // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged // b) Checking if GPS services are not available mLocationServiceIssueReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.removeStickyBroadcast(intent); badLocationXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH); locationRecieverErrorAction = intent.getAction(); } }; IntentFilter filter = new IntentFilter(); filter.addAction(PollSensorAction.XPATH_ERROR_ACTION); filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED); registerReceiver(mLocationServiceIssueReceiver, filter); } private void setupUI() { setContentView(R.layout.screen_form_entry); ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!NAV_STATE_DONE.equals(v.getTag())) { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_ARROW, GoogleAnalyticsFields.VALUE_FORM_NOT_DONE); FormEntryActivity.this.showNextView(); } else { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_ARROW, GoogleAnalyticsFields.VALUE_FORM_DONE); triggerUserFormComplete(); } } }); prevButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!NAV_STATE_QUIT.equals(v.getTag())) { GoogleAnalyticsUtils.reportFormNavBackward(GoogleAnalyticsFields.LABEL_ARROW); FormEntryActivity.this.showPreviousView(true); } else { GoogleAnalyticsUtils.reportFormQuitAttempt(GoogleAnalyticsFields.LABEL_PROGRESS_BAR_ARROW); FormEntryActivity.this.triggerUserQuitInput(); } } }); mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane); requestMajorLayoutUpdates(); if (questionsView != null) { questionsView.teardownView(); } // re-set defaults in case the app got in a bad state. isAnimatingSwipe = false; isDialogShowing = false; questionsView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); outState.putBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, hasFormLoadBeenTriggered); outState.putBoolean(KEY_FORM_LOAD_FAILED, hasFormLoadFailed); outState.putString(KEY_LOC_ERROR, locationRecieverErrorAction); outState.putString(KEY_LOC_ERROR_PATH, badLocationXpath); outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString()); outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString()); outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination); outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled); outState.putBoolean(KEY_HAS_SAVED, hasSaved); outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod); if(symetricKey != null) { try { outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded())); } catch (ClassNotFoundException e) { // we can't really get here anyway, since we couldn't have decoded the string to begin with throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key"); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == FORM_PREFERENCES_KEY) { refreshCurrentView(false); return; } if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { // They pressed 'back' on the first hierarchy screen, so we should assume they want // to back out of form entry all together finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } // request was canceled, so do nothing return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); questionsView.setBinaryData(sb, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), true); break; case SIGNATURE_CAPTURE: ImageCaptureProcessing.processCaptureResponse(this, getInstanceFolder(), false); break; case IMAGE_CHOOSER: ImageCaptureProcessing.processImageChooserResponse(this, getInstanceFolder(), intent); break; case AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); questionsView.setBinaryData(sl, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: case HIERARCHY_ACTIVITY_FIRST_START: // We may have jumped to a new index in hierarchy activity, so refresh refreshCurrentView(false); break; } } private String getInstanceFolder() { return mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); } public void saveImageWidgetAnswer(ContentValues values) { Uri imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(TAG, "Inserting image returned uri = " + imageURI); questionsView.setBinaryData(imageURI, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } private void processChooserResponse(Intent intent) { // For audio/video capture/chooser, we get the URI from the content provider // then the widget copies the file and makes a new entry in the content provider. Uri media = intent.getData(); String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { // don't let the user select a file that won't be included in the // upload to the server questionsView.clearAnswer(); Toast.makeText(FormEntryActivity.this, Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); } else { questionsView.setBinaryData(media, mFormController); } saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } /** * Search the the current view's widgets for one that has registered a * pending callout with the form controller */ public QuestionWidget getPendingWidget() { FormIndex pendingIndex = mFormController.getPendingCalloutFormIndex(); if (pendingIndex == null) { Logger.log(AndroidLogger.SOFT_ASSERT, "getPendingWidget called when pending callout form index was null"); return null; } for (QuestionWidget q : questionsView.getWidgets()) { if (q.getFormId().equals(pendingIndex)) { return q; } } Logger.log(AndroidLogger.SOFT_ASSERT, "getPendingWidget couldn't find question widget with a form index that matches the pending callout."); return null; } private void processIntentResponse(Intent response){ processIntentResponse(response, false); } private void processIntentResponse(Intent response, boolean cancelled) { // keep track of whether we should auto advance boolean advance = false; boolean quick = false; IntentWidget pendingIntentWidget = (IntentWidget)getPendingWidget(); TreeReference context; if (mFormController.getPendingCalloutFormIndex() != null) { context = mFormController.getPendingCalloutFormIndex().getReference(); } else { context = null; } if(pendingIntentWidget != null) { //Set our instance destination for binary data if needed String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); //get the original intent callout IntentCallout ic = pendingIntentWidget.getIntentCallout(); quick = "quick".equals(ic.getAppearance()); //And process it advance = ic.processResponse(response, context, new File(destination)); ic.setCancelled(cancelled); } refreshCurrentView(); // auto advance if we got a good result and are in quick mode if(advance && quick){ showNextView(); } } private void updateFormRelevancies() { ArrayList<QuestionWidget> oldWidgets = questionsView.getWidgets(); // These 2 calls need to be made here, rather than in the for loop below, because at that // point the widgets will have already started being updated to the values for the new view ArrayList<Vector<SelectChoice>> oldSelectChoices = FormRelevancyUpdating.getOldSelectChoicesForEachWidget(oldWidgets); ArrayList<String> oldQuestionTexts = FormRelevancyUpdating.getOldQuestionTextsForEachWidget(oldWidgets); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> promptsLeftInView = new HashSet<>(); ArrayList<Integer> shouldRemoveFromView = new ArrayList<>(); // Loop through all of the old widgets to determine which ones should stay in the new view for (int i = 0; i < oldWidgets.size(); i++) { FormEntryPrompt oldPrompt = oldWidgets.get(i).getPrompt(); String priorQuestionTextForThisWidget = oldQuestionTexts.get(i); Vector<SelectChoice> priorSelectChoicesForThisWidget = oldSelectChoices.get(i); FormEntryPrompt equivalentNewPrompt = FormRelevancyUpdating.getEquivalentPromptInNewList(newValidPrompts, oldPrompt, priorQuestionTextForThisWidget, priorSelectChoicesForThisWidget); if (equivalentNewPrompt != null) { promptsLeftInView.add(equivalentNewPrompt); } else { // If there is no equivalent prompt in the list of new prompts, then this prompt is // no longer relevant in the new view, so it should get removed shouldRemoveFromView.add(i); } } // Remove "atomically" to not mess up iterations questionsView.removeQuestionsFromIndex(shouldRemoveFromView); // Now go through add add any new prompts that we need for (int i = 0; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if (!promptsLeftInView.contains(prompt)) { // If the old version of this prompt was NOT left in the view, then add it questionsView.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView() { refreshCurrentView(true); } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView(boolean animateLastView) { if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); } int event = mFormController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back to the previous // question. // Also, if we're within a group labeled 'field list', step back to the beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not field-lists, // repeat events, and indexes in field-lists that is not the containing group. while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT || (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList()) || event == FormEntryController.EVENT_REPEAT || (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) { event = mFormController.stepToPreviousEvent(); } //If we're at the beginning of form event, but don't show the screen for that, we need //to get the next valid screen if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { showNextView(true); } else if(event == FormEntryController.EVENT_END_OF_FORM) { showPreviousView(false); } else { QuestionsView current = createView(); showView(current, AnimationType.FADE, animateLastView); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { GoogleAnalyticsUtils.reportOptionsMenuEntry(GoogleAnalyticsFields.CATEGORY_FORM_ENTRY); menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); menu.removeItem(MENU_PREFERENCES); if(mIncompleteEnabled) { menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon( android.R.drawable.ic_menu_save); } menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon( R.drawable.ic_menu_goto); boolean hasMultipleLanguages = (!(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1)); menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled(hasMultipleLanguages); menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.form_entry_settings)).setIcon( android.R.drawable.ic_menu_preferences); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Map<Integer, String> menuIdToAnalyticsEventLabel = createMenuItemToEventMapping(); GoogleAnalyticsUtils.reportOptionsMenuItemEntry( GoogleAnalyticsFields.CATEGORY_FORM_ENTRY, menuIdToAnalyticsEventLabel.get(item.getItemId())); switch (item.getItemId()) { case MENU_LANGUAGES: createLanguageDialog(); return true; case MENU_SAVE: saveFormToDisk(DO_NOT_EXIT); return true; case MENU_HIERARCHY_VIEW: if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Intent pref = new Intent(this, FormEntryPreferences.class); startActivityForResult(pref, FORM_PREFERENCES_KEY); return true; case android.R.id.home: GoogleAnalyticsUtils.reportFormQuitAttempt(GoogleAnalyticsFields.LABEL_NAV_BAR_ARROW); triggerUserQuitInput(); return true; } return super.onOptionsItemSelected(item); } private static Map<Integer, String> createMenuItemToEventMapping() { Map<Integer, String> menuIdToAnalyticsEvent = new HashMap<>(); menuIdToAnalyticsEvent.put(MENU_LANGUAGES, GoogleAnalyticsFields.LABEL_CHANGE_LANGUAGE); menuIdToAnalyticsEvent.put(MENU_SAVE, GoogleAnalyticsFields.LABEL_SAVE_FORM); menuIdToAnalyticsEvent.put(MENU_HIERARCHY_VIEW, GoogleAnalyticsFields.LABEL_FORM_HIERARCHY); menuIdToAnalyticsEvent.put(MENU_PREFERENCES, GoogleAnalyticsFields.LABEL_CHANGE_SETTINGS); return menuIdToAnalyticsEvent; } /** * @return true If the current index of the form controller contains questions */ private boolean currentPromptIsQuestion() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController .getEvent() == FormEntryController.EVENT_GROUP); } private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { return saveAnswersForCurrentScreen(evaluateConstraints, true, false); } /** * Attempt to save the answer(s) in the current screen to into the data model. * * @param failOnRequired Whether or not the constraint evaluation * should return false if the question is only * required. (this is helpful for incomplete * saves) * @param headless running in a process that can't display graphics * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { // only try to save if the current event is a question or a field-list // group boolean success = true; if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION) || ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) && mFormController.indexIsInFieldList())) { HashMap<FormIndex, IAnswerData> answers = questionsView.getAnswers(); // Sort the answers so if there are multiple errors, we can // bring focus to the first one List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, new Comparator<FormIndex>() { @Override public int compare(FormIndex arg0, FormIndex arg1) { return arg0.compareTo(arg1); } }); for (FormIndex index : indexKeys) { // Within a group, you can only save for question events if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } return success; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { qw.clearAnswer(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer)); menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { // We don't have the right view here, so we store the View's ID as the // item ID and loop through the possible views to find the one the user // clicked on. for (QuestionWidget qw : questionsView.getWidgets()) { if (item.getItemId() == qw.getId()) { createClearDialog(qw); } } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainCustomNonConfigurationInstance() { // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (mFormController != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } private String getHeaderString() { if(mHeaderString != null) { //Localization? return mHeaderString; } else { return StringUtils.getStringRobust(this, R.string.application_name) + " > " + mFormController.getFormTitle(); } } private QuestionsView createView() { setTitle(getHeaderString()); QuestionsView odkv; // should only be a group here if the event_group is a field-list try { odkv = new QuestionsView(this, mFormController.getQuestionPrompts(), mFormController.getGroupsForCurrentIndex(), mFormController.getWidgetFactory(), this); Log.i(TAG, "created view for group"); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); // this is badness to avoid a crash. // really a next view should increment the formcontroller, create the view // if the view is null, then keep the current view and pop an error. return new QuestionsView(this); } // Makes a "clear answer" menu pop up on long-click of // select-one/select-multiple questions for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly() && !mFormController.isFormReadOnly() && (qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE || qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) { registerForContextMenu(qw); } } FormNavigationUI.updateNavigationCues(this, mFormController, odkv); return odkv; } @SuppressLint("NewApi") @Override public boolean dispatchTouchEvent(MotionEvent mv) { //We need to ignore this even if it's processed by the action //bar (if one exists) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar bar = getActionBar(); if (bar != null) { View customView = bar.getCustomView(); if (customView != null && customView.dispatchTouchEvent(mv)) { return true; } } } boolean handled = mGestureDetector.onTouchEvent(mv); return handled || super.dispatchTouchEvent(mv); } /** * Determines what should be displayed on the screen. Possible options are: a question, an ask * repeat dialog, or the submit screen. Also saves answers to the data model after checking * constraints. */ private void showNextView() { showNextView(false); } private void showNextView(boolean resuming) { if (currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. return; } } if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) { int event; try{ group_skip: do { event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP); switch (event) { case FormEntryController.EVENT_QUESTION: QuestionsView next = createView(); if (!resuming) { showView(next, AnimationType.RIGHT); } else { showView(next, AnimationType.FADE, false); } break group_skip; case FormEntryController.EVENT_END_OF_FORM: // auto-advance questions might advance past the last form quesion triggerUserFormComplete(); break group_skip; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break group_skip; case FormEntryController.EVENT_GROUP: //We only hit this event if we're at the _opening_ of a field //list, so it seems totally fine to do it this way, technically //though this should test whether the index is the field list //host. if (mFormController.indexIsInFieldList() && mFormController.getQuestionPrompts().length != 0) { QuestionsView nextGroupView = createView(); if(!resuming) { showView(nextGroupView, AnimationType.RIGHT); } else { showView(nextGroupView, AnimationType.FADE, false); } break group_skip; } // otherwise it's not a field-list group, so just skip it break; case FormEntryController.EVENT_REPEAT: Log.i(TAG, "repeat: " + mFormController.getFormIndex().getReference()); // skip repeats break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(TAG, "repeat juncture: " + mFormController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(TAG, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } while (event != FormEntryController.EVENT_END_OF_FORM); }catch(XPathTypeMismatchException e){ Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); } } } /** * Determines what should be displayed between a question, or the start screen and displays the * appropriate view. Also saves answers to the data model without checking constraints. */ private void showPreviousView(boolean showSwipeAnimation) { // The answer is saved on a back swipe, but question constraints are ignored. if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } FormIndex startIndex = mFormController.getFormIndex(); FormIndex lastValidIndex = startIndex; if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = mFormController.stepToPreviousEvent(); //Step backwards until we either find a question, the beginning of the form, //or a field list with valid questions inside while (event != FormEntryController.EVENT_BEGINNING_OF_FORM && event != FormEntryController.EVENT_QUESTION && !(event == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList() && mFormController .getQuestionPrompts().length != 0)) { event = mFormController.stepToPreviousEvent(); lastValidIndex = mFormController.getFormIndex(); } if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { // we can't go all the way back to the beginning, so we've // gotta hit the last index that was valid mFormController.jumpToIndex(lastValidIndex); //Did we jump at all? (not sure how we could have, but there might be a mismatch) if(lastValidIndex.equals(startIndex)) { //If not, don't even bother changing the view. //NOTE: This needs to be the same as the //exit condition below, in case either changes FormEntryActivity.this.triggerUserQuitInput(); return; } //We might have walked all the way back still, which isn't great, //so keep moving forward again until we find it if(lastValidIndex.isBeginningOfFormIndex()) { //there must be a repeat between where we started and the beginning of hte form, walk back up to it this.showNextView(true); return; } } QuestionsView next = createView(); if (showSwipeAnimation) { showView(next, AnimationType.LEFT); } else { showView(next, AnimationType.FADE, false); } } else { FormEntryActivity.this.triggerUserQuitInput(); } } /** * Displays the View specified by the parameter 'next', animating both the current view and next * appropriately given the AnimationType. Also updates the progress bar. */ private void showView(QuestionsView next, AnimationType from) { showView(next, from, true); } private void showView(QuestionsView next, AnimationType from, boolean animateLastView) { switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } if (questionsView != null) { if(animateLastView) { questionsView.startAnimation(mOutAnimation); } mViewPane.removeView(questionsView); questionsView.teardownView(); } mInAnimation.setAnimationListener(this); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); questionsView = next; mViewPane.addView(questionsView, lp); questionsView.startAnimation(mInAnimation); FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); this.mGroupNativeVisibility = false; FormLayoutHelpers.updateGroupViewVisibility(this, mGroupNativeVisibility, mGroupForcedInvisible); questionsView.setFocus(this); SpannableStringBuilder groupLabelText = questionsView.getGroupLabel(); if (groupLabelText != null && !groupLabelText.toString().trim().equals("")) { groupLabel.setText(groupLabelText); this.mGroupNativeVisibility = true; FormLayoutHelpers.updateGroupViewVisibility(this, mGroupNativeVisibility, mGroupForcedInvisible); } } /** * Creates and displays a dialog displaying the violated constraint. */ private void showConstraintWarning(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) { switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: if (constraintText == null) { constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error); } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error); break; } boolean displayed = false; //We need to see if question in violation is on the screen, so we can show this cleanly. for(QuestionWidget q : questionsView.getWidgets()) { if(index.equals(q.getFormId())) { q.notifyInvalid(constraintText, requestFocus); displayed = true; break; } } if(!displayed) { showCustomToast(constraintText, Toast.LENGTH_SHORT); } isAnimatingSwipe = false; } public void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a repeat of the * current group. */ private void createRepeatDialog() { isDialogShowing = true; // Determine the effect that back and next buttons should have FormNavigationController.NavigationDetails details; try { details = FormNavigationController.calculateNavigationStatus(mFormController, questionsView); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } final boolean backExitsForm = !details.relevantBeforeCurrentScreen; final boolean nextExitsForm = details.relevantAfterCurrentScreen == 0; // Assign title and text strings based on the current state String title, addAnotherText, skipText, backText; backText = StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back).toString(); if (mFormController.getLastRepeatCount() > 0) { title = StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat, mFormController.getLastGroupText()).toString(); addAnotherText = StringUtils.getStringSpannableRobust(this, R.string.add_another).toString(); if (!nextExitsForm) { skipText = StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes).toString(); } else { skipText = StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits).toString(); } } else { title = StringUtils.getStringSpannableRobust(this, R.string.add_repeat, mFormController.getLastGroupText()).toString(); addAnotherText = StringUtils.getStringSpannableRobust(this, R.string.entering_repeat).toString(); if (!nextExitsForm) { skipText = StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no).toString(); } else { skipText = StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits).toString(); } } // Create the choice dialog ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme); final PaneledChoiceDialog dialog = new HorizontalPaneledChoiceDialog(wrapper, title); // Panel 1: Back option View.OnClickListener backListener = new OnClickListener() { @Override public void onClick(View v) { if (backExitsForm) { FormEntryActivity.this.triggerUserQuitInput(); } else { dialog.dismiss(); FormEntryActivity.this.refreshCurrentView(false); } } }; int backIconId; if (backExitsForm) { backIconId = R.drawable.icon_exit; } else { backIconId = R.drawable.icon_back; } DialogChoiceItem backItem = new DialogChoiceItem(backText, backIconId, backListener); // Panel 2: Add another option View.OnClickListener addAnotherListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); try { mFormController.newRepeat(); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT); return; } showNextView(); } }; DialogChoiceItem addAnotherItem = new DialogChoiceItem(addAnotherText, R.drawable.icon_new, addAnotherListener); // Panel 3: Skip option View.OnClickListener skipListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (!nextExitsForm) { showNextView(); } else { triggerUserFormComplete(); } } }; int skipIconId; if (nextExitsForm) { skipIconId = R.drawable.icon_done; } else { skipIconId = R.drawable.icon_next; } DialogChoiceItem skipItem = new DialogChoiceItem(skipText, skipIconId, skipListener); dialog.setChoiceItems(new DialogChoiceItem[]{backItem, addAnotherItem, skipItem}); dialog.makeNotCancelable(); dialog.setOnDismissListener( new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface d) { isDialogShowing = false; } } ); dialog.show(); } private void saveFormToDisk(boolean exit) { if (formHasLoaded()) { boolean isFormComplete = isInstanceComplete(); saveDataToDisk(exit, isFormComplete, null, false); } else if (exit) { showSaveErrorAndExit(); } } private void saveCompletedFormToDisk(String updatedSaveName) { saveDataToDisk(EXIT, true, updatedSaveName, false); } private void saveIncompleteFormToDisk() { saveDataToDisk(EXIT, false, null, true); } private void showSaveErrorAndExit() { Toast.makeText(this, Localization.get("form.entry.save.error"), Toast.LENGTH_SHORT).show(); hasSaved = false; finishReturnInstance(); } /** * Saves form data to disk. * * @param exit If set, will exit program after save. * @param complete Has the user marked the instances as complete? * @param updatedSaveName Set name of the instance's content provider, if * non-null * @param headless Disables GUI warnings and lets answers that * violate constraints be saved. */ private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) { if (!formHasLoaded()) { if (exit) { showSaveErrorAndExit(); } return; } // save current answer; if headless, don't evaluate the constraints // before doing so. if (headless && (!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) { return; } else if (!headless && !saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) { Toast.makeText(this, Localization.get("form.entry.save.error"), Toast.LENGTH_SHORT).show(); return; } // If a save task is already running, just let it do its thing if ((mSaveToDiskTask != null) && (mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) { return; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless); if (!headless){ mSaveToDiskTask.connect(this); } mSaveToDiskTask.setFormSavedListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSaveToDiskTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { mSaveToDiskTask.execute(); } } /** * Create a dialog with options to save and exit, save, or quit without saving */ private void createQuitDialog() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, StringUtils.getStringRobust(this, R.string.quit_form_title)); View.OnClickListener stayInFormListener = new View.OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_BACK_TO_FORM); dialog.dismiss(); } }; DialogChoiceItem stayInFormItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.do_not_exit), R.drawable.ic_blue_forward, stayInFormListener); View.OnClickListener exitFormListener = new View.OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_EXIT_NO_SAVE); discardChangesAndExit(); } }; DialogChoiceItem quitFormItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.do_not_save), R.drawable.ic_trashcan, exitFormListener); DialogChoiceItem[] items; if (mIncompleteEnabled) { View.OnClickListener saveIncompleteListener = new View.OnClickListener() { @Override public void onClick(View v) { GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_SAVE_AND_EXIT); saveFormToDisk(EXIT); } }; DialogChoiceItem saveIncompleteItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.keep_changes), R.drawable.ic_incomplete_orange, saveIncompleteListener); items = new DialogChoiceItem[] {stayInFormItem, quitFormItem, saveIncompleteItem}; } else { items = new DialogChoiceItem[] {stayInFormItem, quitFormItem}; } dialog.setChoiceItems(items); dialog.show(); } private void discardChangesAndExit() { FormFileSystemHelpers.removeMediaAttachedToUnsavedForm(this, mInstancePath, instanceProviderContentURI); finishReturnInstance(false); } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { String title = StringUtils.getStringRobust(this, R.string.clear_answer_ask); String question = qw.getPrompt().getLongText(); if (question.length() > 50) { question = question.substring(0, 50) + "..."; } String msg = StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question).toString(); AlertDialogFactory factory = new AlertDialogFactory(this, title, msg); factory.setIcon(android.R.drawable.ic_dialog_info); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON_NEGATIVE: break; } dialog.dismiss(); } }; factory.setPositiveButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener); factory.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener); showAlertDialog(factory); } /** * Creates and displays a dialog allowing the user to set the language for the form. */ private void createLanguageDialog() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, StringUtils.getStringRobust(this, R.string.choose_language)); final String[] languages = mFormController.getLanguages(); DialogChoiceItem[] choiceItems = new DialogChoiceItem[languages.length]; for (int i = 0; i < languages.length; i++) { final int index = i; View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { // Update the language in the content provider when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[index]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update(formProviderContentURI, values, selection, selectArgs); Log.i(TAG, "Updated language to: " + languages[index] + " in " + updated + " rows"); mFormController.setLanguage(languages[index]); dialog.dismiss(); if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }; choiceItems[i] = new DialogChoiceItem(languages[i], -1, listener); } dialog.addButton(StringUtils.getStringSpannableRobust(this, R.string.cancel).toString(), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } } ); dialog.setChoiceItems(choiceItems); dialog.show(); } @Override public CustomProgressDialog generateProgressDialog(int id) { CustomProgressDialog dialog = null; switch (id) { case FormLoaderTask.FORM_LOADER_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.loading_form), StringUtils.getStringRobust(this, R.string.please_wait), id); dialog.addCancelButton(); break; case SaveToDiskTask.SAVING_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.saving_form), StringUtils.getStringRobust(this, R.string.please_wait), id); break; } return dialog; } @Override public void taskCancelled(int id) { finish(); } @Override protected void onPause() { super.onPause(); if (questionsView != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (mLocationServiceIssueReceiver != null) { unregisterReceiver(mLocationServiceIssueReceiver); } } @Override protected void onResume() { super.onResume(); if (!hasFormLoadBeenTriggered) { loadForm(); } registerFormEntryReceiver(); if (questionsView != null) { questionsView.restoreTimePickerData(); } if (mFormController != null) { // clear pending callout post onActivityResult processing mFormController.setPendingCalloutFormIndex(null); } } private void loadForm() { mFormController = null; mInstancePath = null; Intent intent = getIntent(); if (intent != null) { loadIntentFormData(intent); setTitleToLoading(); Uri uri = intent.getData(); final String contentType = getContentResolver().getType(uri); Uri formUri; if (contentType == null){ CommCareHomeActivity.createErrorDialog(this, "form URI resolved to null", EXIT); return; } boolean isInstanceReadOnly = false; try { switch (contentType) { case InstanceColumns.CONTENT_ITEM_TYPE: Pair<Uri, Boolean> instanceAndStatus = getInstanceUri(uri); formUri = instanceAndStatus.first; isInstanceReadOnly = instanceAndStatus.second; break; case FormsColumns.CONTENT_ITEM_TYPE: formUri = uri; mFormPath = FormFileSystemHelpers.getFormPath(this, uri); break; default: Log.e(TAG, "unrecognized URI"); CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT); return; } } catch (FormQueryException e) { CommCareHomeActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } if(formUri == null) { Log.e(TAG, "unrecognized URI"); CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask<FormEntryActivity>(symetricKey, isInstanceReadOnly, this) { @Override protected void deliverResult(FormEntryActivity receiver, FECWrapper wrapperResult) { receiver.handleFormLoadCompletion(wrapperResult.getController()); } @Override protected void deliverUpdate(FormEntryActivity receiver, String... update) { } @Override protected void deliverError(FormEntryActivity receiver, Exception e) { receiver.setFormLoadFailure(); receiver.dismissProgressDialog(); if (e != null) { CommCareActivity.createErrorDialog(receiver, e.getMessage(), EXIT); } else { CommCareActivity.createErrorDialog(receiver, StringUtils.getStringRobust(receiver, R.string.parse_error), EXIT); } } }; mFormLoaderTask.connect(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mFormLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, formUri); } else { mFormLoaderTask.execute(formUri); } hasFormLoadBeenTriggered = true; } } private void handleFormLoadCompletion(FormController fc) { if (GeoUtils.ACTION_CHECK_GPS_ENABLED.equals(locationRecieverErrorAction)) { handleNoGpsBroadcast(); } else if (PollSensorAction.XPATH_ERROR_ACTION.equals(locationRecieverErrorAction)) { handleXpathErrorBroadcast(); } mFormController = fc; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ // Newer menus may have already built the menu, before all data was ready invalidateOptionsMenu(); } Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced(); if(mLocalizer != null){ String mLocale = mLocalizer.getLocale(); if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){ fc.setLanguage(mLocale); } else{ Logger.log("formloader", "The current locale is not set"); } } else{ Logger.log("formloader", "Could not get the localizer"); } registerSessionFormSaveCallback(); // Set saved answer path if (mInstancePath == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss") .format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = mInstanceDestination + file + "_" + time; if (FileUtils.createFolder(path)) { mInstancePath = path + "/" + file + "_" + time + ".xml"; } } else { // we've just loaded a saved form, so start in the hierarchy view Intent i = new Intent(FormEntryActivity.this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START); return; // so we don't show the intro screen before jumping to the hierarchy } reportFormEntry(); refreshCurrentView(); FormNavigationUI.updateNavigationCues(this, mFormController, questionsView); } private void handleNoGpsBroadcast() { LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Set<String> providers = GeoUtils.evaluateProviders(manager); if (providers.isEmpty()) { DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { if (i == DialogInterface.BUTTON_POSITIVE) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } dialog.dismiss(); } }; GeoUtils.showNoGpsDialog(this, onChangeListener); } } private void handleXpathErrorBroadcast() { CommCareActivity.createErrorDialog(FormEntryActivity.this, "There is a bug in one of your form's XPath Expressions \n" + badLocationXpath, EXIT); } /** * Call when the user provides input that they want to quit the form */ private void triggerUserQuitInput() { if(!formHasLoaded()) { finish(); } else if (mFormController.isFormReadOnly()) { // If we're just reviewing a read only form, don't worry about saving // or what not, just quit // It's possible we just want to "finish" here, but // I don't really wanna break any c compatibility finishReturnInstance(false); } else { createQuitDialog(); return; } GoogleAnalyticsUtils.reportFormExit(GoogleAnalyticsFields.LABEL_NO_DIALOG); } /** * Get the default title for ODK's "Form title" field */ private String getDefaultFormTitle() { String saveName = mFormController.getFormTitle(); if (InstanceColumns.CONTENT_ITEM_TYPE.equals(getContentResolver().getType(getIntent().getData()))) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance != null && instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } return saveName; } /** * Call when the user is ready to save and return the current form as complete */ private void triggerUserFormComplete() { if (mFormController.isFormReadOnly()) { finishReturnInstance(false); } else { saveCompletedFormToDisk(getDefaultFormTitle()); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: GoogleAnalyticsUtils.reportFormQuitAttempt(GoogleAnalyticsFields.LABEL_DEVICE_BUTTON); triggerUserQuitInput(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showPreviousView(true); return true; } break; } return super.onKeyDown(keyCode, event); } private boolean shouldIgnoreSwipeAction() { return isAnimatingSwipe || isDialogShowing; } @Override protected void onDestroy() { if (mFormLoaderTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } super.onDestroy(); } @Override public void onAnimationEnd(Animation arg0) { isAnimatingSwipe = false; } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } private void registerSessionFormSaveCallback() { if (mFormController != null && !mFormController.isFormReadOnly()) { try { // CommCareSessionService will call this.formSaveCallback when // the key session is closing down and we need to save any // intermediate results before they become un-saveable. CommCareApplication._().getSession().registerFormSaveCallback(this); } catch (SessionUnavailableException e) { Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Couldn't register form save callback because session doesn't exist"); } } } /** * {@inheritDoc} * * Display save status notification and exit or continue on in the form. * If form entry is being saved because key session is expiring then * continue closing the session/logging out. */ @Override public void savingComplete(SaveToDiskTask.SaveStatus saveStatus) { // Did we just save a form because the key session // (CommCareSessionService) is ending? if (savingFormOnKeySessionExpiration) { savingFormOnKeySessionExpiration = false; // Notify the key session that the form state has been saved (or at // least attempted to be saved) so CommCareSessionService can // continue closing down key pool and user database. CommCareApplication._().expireUserSession(); } else { switch (saveStatus) { case SAVED_COMPLETE: Toast.makeText(this, Localization.get("form.entry.complete.save.success"), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SAVED_INCOMPLETE: Toast.makeText(this, Localization.get("form.entry.incomplete.save.success"), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SAVED_AND_EXIT: Toast.makeText(this, Localization.get("form.entry.complete.save.success"), Toast.LENGTH_SHORT).show(); hasSaved = true; finishReturnInstance(); break; case SAVE_ERROR: Toast.makeText(this, Localization.get("form.entry.save.error"), Toast.LENGTH_LONG).show(); break; case INVALID_ANSWER: // an answer constraint was violated, so try to save the // current question to trigger the constraint violation message refreshCurrentView(); saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS); return; } refreshCurrentView(); } } /** * Attempts to save an answer to the specified index. * * @param evaluateConstraints Should form contraints be checked when saving answer? * @return status as determined in FormEntryController */ private int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { try { if (evaluateConstraints) { return mFormController.answerQuestion(index, answer); } else { mFormController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } catch (XPathException e) { //this is where runtime exceptions get triggered after the form has loaded CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT); //We're exiting anyway return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has already been * 'marked completed'. A form can be 'unmarked' complete and then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete() { // default to false if we're mid form boolean complete = false; // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } private void next() { if (!shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showNextView(); } } private void finishReturnInstance() { finishReturnInstance(true); } /** * Returns the instance that was just filled out to the calling activity, * if requested. * * @param reportSaved was a form saved? Delegates the result code of the * activity */ private void finishReturnInstance(boolean reportSaved) { String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id); Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly()); if (reportSaved || hasSaved) { setResult(RESULT_OK, formReturnIntent.setData(instance)); } else { setResult(RESULT_CANCELED, formReturnIntent.setData(instance)); } } } finally { if (c != null) { c.close(); } } } try { CommCareApplication._().getSession().unregisterFormSaveCallback(); } catch (SessionUnavailableException sue) { // looks like the session expired } dismissProgressDialog(); reportFormExit(); finish(); } @Override protected boolean onBackwardSwipe() { GoogleAnalyticsUtils.reportFormNavBackward(GoogleAnalyticsFields.LABEL_SWIPE); showPreviousView(true); return true; } @Override protected boolean onForwardSwipe() { //We've already computed the "is there more coming" stuff intensely in the the nav details //and set the forward button tag appropriately, so use that to determine whether we can //swipe forward. ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); if(nextButton.getTag().equals(NAV_STATE_NEXT)) { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_SWIPE, GoogleAnalyticsFields.VALUE_FORM_NOT_DONE); next(); return true; } else { GoogleAnalyticsUtils.reportFormNavForward( GoogleAnalyticsFields.LABEL_SWIPE, GoogleAnalyticsFields.VALUE_FORM_DONE); FormNavigationUI.animateFinishArrow(this); return true; } } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long pressed. // We don't wnat that, so cancel it. if (questionsView != null) { questionsView.cancelLongPress(); } return false; } @Override public void advance() { next(); } @Override public void widgetEntryChanged() { try { updateFormRelevancies(); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } FormNavigationUI.updateNavigationCues(this, mFormController, questionsView); } /** * Has form loading (via FormLoaderTask) completed? */ private boolean formHasLoaded() { return mFormController != null; } private void addBreadcrumbBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final String fragmentClass = this.getIntent().getStringExtra(TITLE_FRAGMENT_TAG); if (fragmentClass != null) { final FragmentManager fm = this.getSupportFragmentManager(); Fragment bar = fm.findFragmentByTag(TITLE_FRAGMENT_TAG); if (bar == null) { try { bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance(); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit(); } catch(Exception e) { Log.w(TAG, "couldn't instantiate fragment: " + fragmentClass); } } } } } private void loadStateFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_HAS_TRIGGERED)) { hasFormLoadBeenTriggered = savedInstanceState.getBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, false); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_FAILED)) { hasFormLoadFailed = savedInstanceState.getBoolean(KEY_FORM_LOAD_FAILED, false); } locationRecieverErrorAction = savedInstanceState.getString(KEY_LOC_ERROR); badLocationXpath = savedInstanceState.getString(KEY_LOC_ERROR_PATH); if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) { formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) { instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) { mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION); } if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) { mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED); } if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED); } if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) { String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(savedInstanceState.containsKey(KEY_HEADER_STRING)) { mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING); } if(savedInstanceState.containsKey(KEY_HAS_SAVED)) { hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED); } } } private Pair<Uri, Boolean> getInstanceUri(Uri uri) throws FormQueryException { Cursor instanceCursor = null; Cursor formCursor = null; Boolean isInstanceReadOnly = false; Uri formUri = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor == null) { throw new FormQueryException("Bad URI: resolved to null"); } else if (instanceCursor.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { instanceCursor.moveToFirst(); mInstancePath = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String jrFormId = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); //If this form is both already completed if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) { if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) { isInstanceReadOnly = true; } } final String[] selectionArgs = { jrFormId }; final String selection = FormsColumns.JR_FORM_ID + " like ?"; formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null); if (formCursor == null || formCursor.getCount() < 1) { throw new FormQueryException("Parent form does not exist"); } else if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor.getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID))); } else if (formCursor.getCount() > 1) { throw new FormQueryException("More than one possible parent form"); } } } finally { if (instanceCursor != null) { instanceCursor.close(); } if (formCursor != null) { formCursor.close(); } } return new Pair<>(formUri, isInstanceReadOnly); } private void loadIntentFormData(Intent intent) { if(intent.hasExtra(KEY_FORM_CONTENT_URI)) { this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) { this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCEDESTINATION)) { this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION); } else { mInstanceDestination = ODKStorage.INSTANCES_PATH; } if(intent.hasExtra(KEY_AES_STORAGE_KEY)) { String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(intent.hasExtra(KEY_HEADER_STRING)) { FormEntryActivity.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING); } if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) { this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true); } if(intent.hasExtra(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED); } } private void setTitleToLoading() { if(mHeaderString != null) { setTitle(mHeaderString); } else { setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form)); } } public static class FormQueryException extends Exception { public FormQueryException(String msg) { super(msg); } } private void setFormLoadFailure() { hasFormLoadFailed = true; } @Override protected void onMajorLayoutChange(Rect newRootViewDimensions) { mGroupForcedInvisible = FormLayoutHelpers.determineNumberOfValidGroupLines(this, newRootViewDimensions, mGroupNativeVisibility, mGroupForcedInvisible); } private void reportFormEntry() { TimedStatsTracker.registerEnterForm(getCurrentFormID()); } private void reportFormExit() { TimedStatsTracker.registerExitForm(getCurrentFormID()); } private int getCurrentFormID() { return mFormController.getFormID(); } /** * For Testing purposes only */ public QuestionsView getODKView() { if (BuildConfig.DEBUG) { return questionsView; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } }
package com.mapswithme.maps.editor; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v7.app.AlertDialog; import android.text.format.DateUtils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Locale; import com.mapswithme.maps.R; import com.mapswithme.maps.editor.data.UserStats; import com.mapswithme.util.BottomSheetHelper; import com.mapswithme.util.Constants; import com.mapswithme.util.UiUtils; public class ProfileFragment extends AuthFragment implements View.OnClickListener, OsmOAuth.OnUserStatsChanged { private View mSentBlock; private TextView mEditsSent; private TextView mEditsSentDate; private View mMore; private View mAuthBlock; private View mRatingBlock; private TextView mEditorRank; private TextView mEditorLevelUp; private enum MenuItem { LOGOUT(R.drawable.ic_logout, R.string.logout) { @Override void invoke(final ProfileFragment fragment) { new AlertDialog.Builder(fragment.getContext()) .setMessage(R.string.are_you_sure) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { OsmOAuth.clearAuthorization(); fragment.refreshViews(); } }) .setNegativeButton(android.R.string.no, null) .create() .show(); } }, REFRESH(R.drawable.ic_update, R.string.refresh) { @Override void invoke(ProfileFragment fragment) { OsmOAuth.nativeUpdateOsmUserStats(OsmOAuth.getUsername(), true /* forceUpdate */); } }; final @DrawableRes int icon; final @StringRes int title; MenuItem(@DrawableRes int icon, @StringRes int title) { this.icon = icon; this.title = title; } abstract void invoke(ProfileFragment fragment); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mToolbarController.setTitle(R.string.profile); initViews(view); refreshViews(); OsmOAuth.setUserStatsListener(this); OsmOAuth.nativeUpdateOsmUserStats(OsmOAuth.getUsername(), false /* forceUpdate */); } private void initViews(View view) { mMore = mToolbarController.findViewById(R.id.more); mMore.setOnClickListener(this); View editsBlock = view.findViewById(R.id.block_edits); UiUtils.show(editsBlock); mSentBlock = editsBlock.findViewById(R.id.sent_edits); mEditsSent = (TextView) mSentBlock.findViewById(R.id.edits_count); mEditsSentDate = (TextView) mSentBlock.findViewById(R.id.date_sent); mAuthBlock = view.findViewById(R.id.block_auth); mRatingBlock = view.findViewById(R.id.block_rating); mEditorRank = (TextView) mRatingBlock.findViewById(R.id.rating); // FIXME show when it will be implemented on server // mEditorLevelUp = mRatingBlock.findViewById(R.id.level_up_feat); view.findViewById(R.id.about_osm).setOnClickListener(this); } private void refreshViews() { if (OsmOAuth.isAuthorized()) { UiUtils.show(mMore, mRatingBlock, mSentBlock); UiUtils.hide(mAuthBlock); } else { UiUtils.show(mAuthBlock); UiUtils.hide(mMore, mRatingBlock, mSentBlock); } refreshRatings(0, 0, 0, ""); } private void refreshRatings(long uploadedCount, long uploadSeconds, long rank, String levelFeat) { String edits, editsDate; if (uploadedCount == 0) { edits = editsDate = " } else { edits = String.valueOf(uploadedCount); editsDate = DateUtils.formatDateTime(getActivity(), uploadSeconds * 1000, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME); } mEditsSent.setText(edits); mEditsSentDate.setText(getString(R.string.last_update, editsDate)); mEditorRank.setText(String.valueOf(rank)); // FIXME show when it will be implemented on server // mEditorLevelUp.setText(levelFeat); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.more: showBottomSheet(); break; case R.id.about_osm: startActivity(new Intent((Intent.ACTION_VIEW), Uri.parse(Constants.Url.OSM_ABOUT))); break; } } @Override public void onStatsChange(final UserStats stats) { if (!isAdded()) return; if (stats == null) refreshRatings(0, 0, 0, ""); else refreshRatings(stats.editsCount, stats.uploadTimestampSeconds, stats.editorRank, stats.levelUp); } private void showBottomSheet() { List<MenuItem> items = new ArrayList<>(); items.add(MenuItem.REFRESH); items.add(MenuItem.LOGOUT); BottomSheetHelper.Builder bs = BottomSheetHelper.create(getActivity()); for (MenuItem item: items) bs.sheet(item.ordinal(), item.icon, item.title); bs.listener(new android.view.MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(android.view.MenuItem item) { MenuItem.values()[item.getItemId()].invoke(ProfileFragment.this); return false; } }).tint().show(); } }
package com.tradle.react; import android.os.AsyncTask; import android.util.Base64; import android.util.Pair; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * This is a specialized AsyncTask that receives data from a socket in the background, and * notifies it's listener when data is received. This is not threadsafe, the listener * should handle synchronicity. */ public class UdpReceiverTask extends AsyncTask<Pair<DatagramSocket, UdpReceiverTask.OnDataReceivedListener>, Void, Void> { private static final String TAG = "UdpReceiverTask"; private static final int MAX_UDP_DATAGRAM_LEN = 0xffff; /** * An infinite loop to block and read data from the socket. */ @Override protected Void doInBackground(Pair<DatagramSocket, UdpReceiverTask.OnDataReceivedListener>... params) { if (params.length > 1) { throw new IllegalArgumentException("This task is only for a single socket/listener pair."); } DatagramSocket socket = params[0].first; OnDataReceivedListener receiverListener = params[0].second; final byte[] buffer = new byte[MAX_UDP_DATAGRAM_LEN]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while (!isCancelled()) { try { socket.receive(packet); final InetAddress address = packet.getAddress(); final String base64Data = Base64.encodeToString(packet.getData(), packet.getOffset(), packet.getLength(), Base64.NO_WRAP); receiverListener.didReceiveData(base64Data, address.getHostAddress(), packet.getPort()); } catch (IOException ioe) { if (receiverListener != null) { receiverListener.didReceiveError(ioe.getMessage()); } this.cancel(false); } catch (RuntimeException rte) { if (receiverListener != null) { receiverListener.didReceiveRuntimeException(rte); } this.cancel(false); } } return null; } /** * Listener interface for receive events. */ public interface OnDataReceivedListener { void didReceiveData(String data, String host, int port); void didReceiveError(String message); void didReceiveRuntimeException(RuntimeException exception); } }
package dev.mcodex.RNSensitiveInfo; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.hardware.fingerprint.FingerprintManager; import android.os.Build; import android.os.CancellationSignal; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyInfo; import java.security.InvalidKeyException; import android.security.KeyPairGeneratorSpec; import android.security.keystore.KeyProperties; import android.util.Base64; import android.util.Log; import androidx.annotation.NonNull; import androidx.biometric.BiometricConstants; import androidx.biometric.BiometricManager; import androidx.biometric.BiometricPrompt; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.math.BigInteger; import java.security.Key; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Calendar; import java.security.UnrecoverableKeyException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.IvParameterSpec; import androidx.fragment.app.FragmentActivity; import javax.security.auth.x500.X500Principal; import dev.mcodex.RNSensitiveInfo.utils.AppConstants; public class RNSensitiveInfoModule extends ReactContextBaseJavaModule { // This must have 'AndroidKeyStore' as value. Unfortunately there is no predefined constant. private static final String ANDROID_KEYSTORE_PROVIDER = "AndroidKeyStore"; // This is the default transformation used throughout this sample project. private static final String AES_DEFAULT_TRANSFORMATION = KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7; private static final String AES_GCM = "AES/GCM/NoPadding"; private static final String RSA_ECB = "RSA/ECB/PKCS1Padding"; private static final String DELIMITER = "]"; private static final byte[] FIXED_IV = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1}; private static final String KEY_ALIAS = "MySharedPreferenceKeyAlias"; private static final String KEY_ALIAS_AES = "MyAesKeyAlias"; private FingerprintManager mFingerprintManager; private KeyStore mKeyStore; private CancellationSignal mCancellationSignal; // Keep it true by default to maintain backwards compatibility with existing users. private boolean invalidateEnrollment = true; public RNSensitiveInfoModule(ReactApplicationContext reactContext) { super(reactContext); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { Exception cause = new RuntimeException("Keystore is not supported!"); throw new RuntimeException("Android version is too low", cause); } try { mKeyStore = KeyStore.getInstance(ANDROID_KEYSTORE_PROVIDER); mKeyStore.load(null); } catch (Exception e) { e.printStackTrace(); } initKeyStore(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { mFingerprintManager = (FingerprintManager) reactContext.getSystemService(Context.FINGERPRINT_SERVICE); initFingerprintKeyStore(); } catch (Exception e) { Log.d("RNSensitiveInfo", "Fingerprint not supported"); } } } @Override public String getName() { return "RNSensitiveInfo"; } /** * Checks whether the device supports Biometric authentication and if the user has * enrolled at least one credential. * * @return true if the user has a biometric capable device and has enrolled * one or more credentials */ private boolean hasSetupBiometricCredential() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { ReactApplicationContext reactApplicationContext = getReactApplicationContext(); BiometricManager biometricManager = BiometricManager.from(reactApplicationContext); int canAuthenticate = biometricManager.canAuthenticate(); return canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS; } else { return false; } } catch (Exception e) { return false; } } @ReactMethod public void setInvalidatedByBiometricEnrollment(final boolean invalidatedByBiometricEnrollment, final Promise pm) { this.invalidateEnrollment = invalidatedByBiometricEnrollment; try { prepareKey(); } catch (Exception e) { pm.reject(e); } } // @ReactMethod // public void isHardwareDetected(final Promise pm) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // ReactApplicationContext reactApplicationContext = getReactApplicationContext(); // BiometricManager biometricManager = BiometricManager.from(reactApplicationContext); // int canAuthenticate = biometricManager.canAuthenticate(); // pm.resolve(canAuthenticate != BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE); // } else { // pm.resolve(false); @ReactMethod public void hasEnrolledFingerprints(final Promise pm) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && mFingerprintManager != null) { pm.resolve(mFingerprintManager.hasEnrolledFingerprints()); } else { pm.resolve(false); } } @ReactMethod public void isSensorAvailable(final Promise promise) { promise.resolve(hasSetupBiometricCredential()); } @ReactMethod public void getItem(String key, ReadableMap options, Promise pm) { String name = sharedPreferences(options); String value = prefs(name).getString(key, null); if (value != null && options.hasKey("touchID") && options.getBoolean("touchID")) { boolean showModal = options.hasKey("showModal") && options.getBoolean("showModal"); HashMap strings = options.hasKey("strings") ? options.getMap("strings").toHashMap() : new HashMap(); decryptWithAes(value, showModal, strings, pm, null); } else if (value != null) { try { pm.resolve(decrypt(value)); } catch (Exception e) { pm.reject(e); } } else { pm.resolve(value); } } @ReactMethod public void setItem(String key, String value, ReadableMap options, Promise pm) { String name = sharedPreferences(options); if (options.hasKey("touchID") && options.getBoolean("touchID")) { boolean showModal = options.hasKey("showModal") && options.getBoolean("showModal"); HashMap strings = options.hasKey("strings") ? options.getMap("strings").toHashMap() : new HashMap(); putExtraWithAES(key, value, prefs(name), showModal, strings, pm, null); } else { try { putExtra(key, encrypt(value), prefs(name)); pm.resolve(value); } catch (Exception e) { e.printStackTrace(); pm.reject(e); } } } @ReactMethod public void deleteItem(String key, ReadableMap options, Promise pm) { String name = sharedPreferences(options); SharedPreferences.Editor editor = prefs(name).edit(); editor.remove(key).apply(); pm.resolve(null); } @ReactMethod public void getAllItems(ReadableMap options, Promise pm) { String name = sharedPreferences(options); Map<String, ?> allEntries = prefs(name).getAll(); WritableMap resultData = new WritableNativeMap(); for (Map.Entry<String, ?> entry : allEntries.entrySet()) { String value = entry.getValue().toString(); try { value = decrypt(value); } catch (Exception e) { Log.d("RNSensitiveInfo", Log.getStackTraceString(e)); } resultData.putString(entry.getKey(), value); } pm.resolve(resultData); } @ReactMethod public void cancelFingerprintAuth() { if (mCancellationSignal != null && !mCancellationSignal.isCanceled()) { mCancellationSignal.cancel(); } } private SharedPreferences prefs(String name) { return getReactApplicationContext().getSharedPreferences(name, Context.MODE_PRIVATE); } @NonNull private String sharedPreferences(ReadableMap options) { String name = options.hasKey("sharedPreferencesName") ? options.getString("sharedPreferencesName") : "shared_preferences"; if (name == null) { name = "shared_preferences"; } return name; } private void putExtra(String key, String value, SharedPreferences mSharedPreferences) { SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putString(key, value).apply(); } /** * Generates a new RSA key and stores it under the { @code KEY_ALIAS } in the * Android Keystore. */ private void initKeyStore() { try { if (!mKeyStore.containsAlias(KEY_ALIAS)) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER); keyGenerator.init( new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setRandomizedEncryptionRequired(false) .build()); keyGenerator.generateKey(); } else { Calendar notBefore = Calendar.getInstance(); Calendar notAfter = Calendar.getInstance(); notAfter.add(Calendar.YEAR, 10); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getReactApplicationContext()) .setAlias(KEY_ALIAS) .setSubject(new X500Principal("CN=" + KEY_ALIAS)) .setSerialNumber(BigInteger.valueOf(1337)) .setStartDate(notBefore.getTime()) .setEndDate(notAfter.getTime()) .build(); KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", ANDROID_KEYSTORE_PROVIDER); kpGenerator.initialize(spec); kpGenerator.generateKeyPair(); } } } catch (Exception e) { e.printStackTrace(); } } private void showDialog(final HashMap strings, final BiometricPrompt.CryptoObject cryptoObject, final BiometricPrompt.AuthenticationCallback callback) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { UiThreadUtil.runOnUiThread( new Runnable() { @Override public void run() { try { Activity activity = getCurrentActivity(); if (activity == null) { callback.onAuthenticationError(BiometricConstants.ERROR_CANCELED, strings.containsKey("cancelled") ? strings.get("cancelled").toString() : "Authentication was cancelled"); return; } FragmentActivity fragmentActivity = (FragmentActivity) getCurrentActivity(); Executor executor = Executors.newSingleThreadExecutor(); BiometricPrompt biometricPrompt = new BiometricPrompt(fragmentActivity, executor, callback); BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder() .setDeviceCredentialAllowed(false) .setNegativeButtonText(strings.containsKey("cancel") ? strings.get("cancel").toString() : "Cancel") .setDescription(strings.containsKey("description") ? strings.get("description").toString() : null) .setTitle(strings.containsKey("header") ? strings.get("header").toString() : "Unlock with your fingerprint") .build(); biometricPrompt.authenticate(promptInfo, cryptoObject); } catch (Exception e) { throw e; } } } ); } } /** * Generates a new AES key and stores it under the { @code KEY_ALIAS_AES } in the * Android Keystore. */ private void initFingerprintKeyStore() { try { // Check if a generated key exists under the KEY_ALIAS_AES . if (!mKeyStore.containsAlias(KEY_ALIAS_AES)) { prepareKey(); } } catch (Exception e) { } } private void prepareKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER); KeyGenParameterSpec.Builder builder = null; builder = new KeyGenParameterSpec.Builder( KEY_ALIAS_AES, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT); builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setKeySize(256) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) // forces user authentication with fingerprint .setUserAuthenticationRequired(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { try { builder.setInvalidatedByBiometricEnrollment(invalidateEnrollment); } catch (Exception e) { Log.d("RNSensitiveInfo", "Error setting setInvalidatedByBiometricEnrollment: " + e.getMessage()); } } keyGenerator.init(builder.build()); keyGenerator.generateKey(); } private void putExtraWithAES(final String key, final String value, final SharedPreferences mSharedPreferences, final boolean showModal, final HashMap strings, final Promise pm, Cipher cipher) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && hasSetupBiometricCredential()) { try { if (cipher == null) { SecretKey secretKey = (SecretKey) mKeyStore.getKey(KEY_ALIAS_AES, null); cipher = Cipher.getInstance(AES_DEFAULT_TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey); // Retrieve information about the SecretKey from the KeyStore. SecretKeyFactory factory = SecretKeyFactory.getInstance( secretKey.getAlgorithm(), ANDROID_KEYSTORE_PROVIDER); KeyInfo info = (KeyInfo) factory.getKeySpec(secretKey, KeyInfo.class); if (info.isUserAuthenticationRequired() && info.getUserAuthenticationValidityDurationSeconds() <= 0) { if (showModal) { class PutExtraWithAESCallback extends BiometricPrompt.AuthenticationCallback { @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { putExtraWithAES(key, value, mSharedPreferences, true, strings, pm, result.getCryptoObject().getCipher()); } } @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { pm.reject(String.valueOf(errorCode), errString.toString()); } @Override public void onAuthenticationFailed() { getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(AppConstants.E_AUTHENTICATION_NOT_RECOGNIZED, "Authentication not recognized."); } } showDialog(strings, new BiometricPrompt.CryptoObject(cipher), new PutExtraWithAESCallback()); } else { mCancellationSignal = new CancellationSignal(); mFingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() { @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(AppConstants.E_AUTHENTICATION_NOT_RECOGNIZED, "Fingerprint not recognized."); } @Override public void onAuthenticationError(int errorCode, CharSequence errString) { super.onAuthenticationError(errorCode, errString); pm.reject(String.valueOf(errorCode), errString.toString()); } @Override public void onAuthenticationHelp(int helpCode, CharSequence helpString) { super.onAuthenticationHelp(helpCode, helpString); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(AppConstants.FINGERPRINT_AUTHENTICATION_HELP, helpString.toString()); } @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { super.onAuthenticationSucceeded(result); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { putExtraWithAES(key, value, mSharedPreferences, false, strings, pm, result.getCryptoObject().getCipher()); } } }, null); } } return; } byte[] encryptedBytes = cipher.doFinal(value.getBytes()); // Encode the initialization vector (IV) and encryptedBytes to Base64. String base64IV = Base64.encodeToString(cipher.getIV(), Base64.DEFAULT); String base64Cipher = Base64.encodeToString(encryptedBytes, Base64.DEFAULT); String result = base64IV + DELIMITER + base64Cipher; putExtra(key, result, mSharedPreferences); pm.resolve(value); } catch (InvalidKeyException | UnrecoverableKeyException e) { try { mKeyStore.deleteEntry(KEY_ALIAS_AES); prepareKey(); } catch (Exception keyResetError) { pm.reject(keyResetError); } pm.reject(e); } catch (IllegalBlockSizeException e){ if(e.getCause() != null && e.getCause().getMessage().contains("Key user not authenticated")) { try { mKeyStore.deleteEntry(KEY_ALIAS_AES); prepareKey(); pm.reject(AppConstants.KM_ERROR_KEY_USER_NOT_AUTHENTICATED, e.getCause().getMessage()); } catch (Exception keyResetError) { pm.reject(keyResetError); } } else { pm.reject(e); } } catch (SecurityException e) { pm.reject(e); } catch (Exception e) { pm.reject(e); } } else { pm.reject(AppConstants.E_BIOMETRIC_NOT_SUPPORTED, "Biometrics not supported"); } } private void decryptWithAes(final String encrypted, final boolean showModal, final HashMap strings, final Promise pm, Cipher cipher) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M && hasSetupBiometricCredential()) { String[] inputs = encrypted.split(DELIMITER); if (inputs.length < 2) { pm.reject("DecryptionFailed", "DecryptionFailed"); } try { byte[] iv = Base64.decode(inputs[0], Base64.DEFAULT); byte[] cipherBytes = Base64.decode(inputs[1], Base64.DEFAULT); if (cipher == null) { SecretKey secretKey = (SecretKey) mKeyStore.getKey(KEY_ALIAS_AES, null); cipher = Cipher.getInstance(AES_DEFAULT_TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); SecretKeyFactory factory = SecretKeyFactory.getInstance( secretKey.getAlgorithm(), ANDROID_KEYSTORE_PROVIDER); KeyInfo info = (KeyInfo) factory.getKeySpec(secretKey, KeyInfo.class); if (info.isUserAuthenticationRequired() && info.getUserAuthenticationValidityDurationSeconds() <= 0) { if (showModal) { class DecryptWithAesCallback extends BiometricPrompt.AuthenticationCallback { @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { decryptWithAes(encrypted, true, strings, pm, result.getCryptoObject().getCipher()); } } @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { pm.reject(String.valueOf(errorCode), errString.toString()); } @Override public void onAuthenticationFailed() { getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(AppConstants.E_AUTHENTICATION_NOT_RECOGNIZED, "Authentication not recognized."); } } showDialog(strings, new BiometricPrompt.CryptoObject(cipher), new DecryptWithAesCallback()); } else { mCancellationSignal = new CancellationSignal(); mFingerprintManager.authenticate(new FingerprintManager.CryptoObject(cipher), mCancellationSignal, 0, new FingerprintManager.AuthenticationCallback() { @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(AppConstants.E_AUTHENTICATION_NOT_RECOGNIZED, "Fingerprint not recognized."); } @Override public void onAuthenticationError(int errorCode, CharSequence errString) { super.onAuthenticationError(errorCode, errString); pm.reject(String.valueOf(errorCode), errString.toString()); } @Override public void onAuthenticationHelp(int helpCode, CharSequence helpString) { super.onAuthenticationHelp(helpCode, helpString); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(AppConstants.FINGERPRINT_AUTHENTICATION_HELP, helpString.toString()); } @Override public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) { super.onAuthenticationSucceeded(result); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { decryptWithAes(encrypted, false, strings, pm, result.getCryptoObject().getCipher()); } } }, null); } } return; } byte[] decryptedBytes = cipher.doFinal(cipherBytes); pm.resolve(new String(decryptedBytes)); } catch (InvalidKeyException | UnrecoverableKeyException e) { try { mKeyStore.deleteEntry(KEY_ALIAS_AES); prepareKey(); } catch (Exception keyResetError) { pm.reject(keyResetError); } pm.reject(e); } catch (IllegalBlockSizeException e){ if(e.getCause() != null && e.getCause().getMessage().contains("Key user not authenticated")) { try { mKeyStore.deleteEntry(KEY_ALIAS_AES); prepareKey(); pm.reject(AppConstants.KM_ERROR_KEY_USER_NOT_AUTHENTICATED, e.getCause().getMessage()); } catch (Exception keyResetError) { pm.reject(keyResetError); } } else { pm.reject(e); } } catch (SecurityException e) { pm.reject(e); } catch (Exception e) { pm.reject(e); } } else { pm.reject(AppConstants.E_BIOMETRIC_NOT_SUPPORTED, "Biometrics not supported"); } } public String encrypt(String input) throws Exception { byte[] bytes = input.getBytes(); Cipher c; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Key secretKey = ((KeyStore.SecretKeyEntry) mKeyStore.getEntry(KEY_ALIAS, null)).getSecretKey(); c = Cipher.getInstance(AES_GCM); c.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(128, FIXED_IV)); } else { PublicKey publicKey = ((KeyStore.PrivateKeyEntry)mKeyStore.getEntry(KEY_ALIAS, null)).getCertificate().getPublicKey(); c = Cipher.getInstance(RSA_ECB); c.init(Cipher.ENCRYPT_MODE, publicKey); } byte[] encodedBytes = c.doFinal(bytes); String encryptedBase64Encoded = Base64.encodeToString(encodedBytes, Base64.DEFAULT); return encryptedBase64Encoded; } public String decrypt(String encrypted) throws Exception { if (encrypted == null) { Exception cause = new RuntimeException("Invalid argument at decrypt function"); throw new RuntimeException("encrypted argument can't be null", cause); } Cipher c; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Key secretKey = ((KeyStore.SecretKeyEntry) mKeyStore.getEntry(KEY_ALIAS, null)).getSecretKey(); c = Cipher.getInstance(AES_GCM); c.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(128, FIXED_IV)); } else { PrivateKey privateKey = ((KeyStore.PrivateKeyEntry)mKeyStore.getEntry(KEY_ALIAS, null)).getPrivateKey(); c = Cipher.getInstance(RSA_ECB); c.init(Cipher.DECRYPT_MODE, privateKey); } byte[] decodedBytes = c.doFinal(Base64.decode(encrypted, Base64.DEFAULT)); return new String(decodedBytes); } }
package au.gov.amsa.util.nmea; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import com.github.davidmoten.guavamini.Sets; import au.gov.amsa.ais.AisParseException; public final class NmeaUtil { private static final String[] EMPTY = new String[] {}; private static final char BACKSLASH = '\\'; private NmeaUtil() { // private constructor to prevent instantiation } static void forTestCoverageOnly() { new NmeaUtil(); } private static final Set<Integer> invalidFieldCharacters = Sets.newHashSet(33, 36, 42, 44, 92, 94, 126, 127); private static final Set<Character> validCharacterSymbols = createValidCharacterSymbols(); private static Set<Character> createValidCharacterSymbols() { String s = "AaBCcDdEFfGgHhIJKkLlMmNnPQRrSsTtUuVWxyZ"; Set<Character> set = Sets.newHashSet(); for (char ch : s.toCharArray()) set.add(ch); return set; } static boolean isValidFieldCharacter(char ch) { return ch <= 127 && ch >= 32 && !invalidFieldCharacters.contains((int) ch); } static boolean isValidCharacterSymbol(char ch) { return validCharacterSymbols.contains(ch); } /** * Returns true if and only if the sentence's checksum matches the * calculated checksum. * * @param sentence * @return */ public static boolean isValid(String sentence) { // Compare the characters after the asterisk to the calculation try { return sentence.substring(sentence.lastIndexOf("*") + 1) .equals(getChecksum(sentence)); } catch (AisParseException e) { return false; } } public static String getChecksum(String sentence) { return getChecksum(sentence, true); } public static String getChecksumWhenHasNoTagBlock(String sentence) { return getChecksumWhenHasNoTagBlock(sentence, true, 0); } public static String getChecksum(String sentence, boolean ignoreLeadingDollarOrExclamation) { int startIndex; // Start after tag block if (sentence.startsWith("\\")) { startIndex = sentence.indexOf('\\', 1) + 1; if (startIndex == 0) throw new AisParseException("no closing \\ for tag block"); } else startIndex = 0; return getChecksumWhenHasNoTagBlock(sentence, ignoreLeadingDollarOrExclamation, startIndex); } private static String getChecksumWhenHasNoTagBlock(String sentenceWithoutTagBlock, boolean ignoreLeadingDollarOrExclamation, int startIndex) { // Loop through all chars to get a checksum int checksum = 0; for (int i = startIndex; i < sentenceWithoutTagBlock.length(); i++) { char ch = sentenceWithoutTagBlock.charAt(i); if (ignoreLeadingDollarOrExclamation && (ch == '$' || ch == '!')) { // Ignore the dollar sign } else if (ch == '*') { // Stop processing before the asterisk break; } else { // Is this the first value for the checksum? if (checksum == 0) { // Yes. Set the checksum to the value checksum = ch; } else { // No. XOR the checksum with this character's value checksum = checksum ^ ch; } } } // Return the checksum formatted as a two-character hexadecimal return toUpperCaseHexString(checksum % 256); } private static final String[] hexes = IntStream .range(0, 256) .mapToObj(x -> { String s = Integer.toHexString(x).toUpperCase(); if (s.length() == 1) { s = "0" + s; } return s; }).collect(Collectors.toList()).toArray(EMPTY); private static String toUpperCaseHexString(int n) { return hexes[n]; } private static NmeaMessageParser nmeaParser = new NmeaMessageParser(); public static NmeaMessage parseNmea(String line) { return parseNmea(line, false); } public static NmeaMessage parseNmea(String line, boolean validateChecksum) { return nmeaParser.parse(line, validateChecksum); } public static String insertKeyValueInTagBlock(String line, String name, String value) { line = line.trim(); if (line.startsWith("\\")) { // insert time into tag block, and adjust the // hash for the tag block int i = line.indexOf(BACKSLASH, 1); if (i == -1) { //return line unchanged return line; } if (i < 4) { // tag block not long enough to have a checksum"); return line; } String content = line.substring(1, i - 3); StringBuilder s = new StringBuilder(content); s.append(","); s.append(name); s.append(":"); s.append(value); String checksum = NmeaUtil.getChecksum(s.toString(), false); s.append('*'); s.append(checksum); s.append(line.substring(i)); s.insert(0, BACKSLASH); return s.toString(); } else { return line; } } public static String supplementWithTime(String line, long arrivalTime) { line = line.trim(); final String amendedLine; NmeaMessage m = parseNmea(line); Long t = m.getUnixTimeMillis(); Long a = m.getArrivalTimeMillis(); if (t == null) { // use arrival time if not present t = arrivalTime; // if has tag block if (line.startsWith("\\")) { // insert time into tag block, and adjust the // hash for the tag block int i = line.indexOf(BACKSLASH, 1); if (i == -1) throw new RuntimeException( "line starts with \\ but does not have closing tag block delimiter \\"); if (i < 4) throw new RuntimeException("tag block not long enough to have a checksum"); String content = line.substring(1, i - 3); StringBuilder s = new StringBuilder(content); s.append(","); appendTimes(arrivalTime, t, s); String checksum = NmeaUtil.getChecksum(s.toString(), false); s.append('*'); s.append(checksum); s.append(line.substring(i)); s.insert(0, BACKSLASH); amendedLine = s.toString(); } else { StringBuilder s = new StringBuilder(); appendTimes(t, arrivalTime, s); String checksum = NmeaUtil.getChecksum(s.toString(), false); s.append("*"); s.append(checksum); s.append(BACKSLASH); s.append(line); s.insert(0, BACKSLASH); amendedLine = s.toString(); } } else if (a == null) { // must have a proper tag block because t != null // insert time into tag block, and adjust the // hash for the tag block int i = line.indexOf(BACKSLASH, 1); String content = line.substring(1, i - 3); StringBuilder s = new StringBuilder(content); s.append(",a:"); s.append(arrivalTime); String checksum = NmeaUtil.getChecksum(s.toString(), false); s.append('*'); s.append(checksum); s.append(line.substring(i)); s.insert(0, BACKSLASH); amendedLine = s.toString(); } else { amendedLine = line; } return amendedLine; } private static void appendTimes(long arrivalTime, Long t, StringBuilder s) { s.append("c:"); s.append(t / 1000); s.append(",a:"); s.append(arrivalTime); } private static final Map<String, Talker> talkers = Arrays.asList(Talker.values()).stream() .collect(Collectors.toMap(t -> t.name(), t -> t)); public static Talker getTalker(String s) { if (s == null) return Talker.UNKNOWN; else { // don't use Talker.valueOf because it throws when s not valid Talker // and thrown exceptions are bad for performance due allocations Talker t = talkers.get(s); if (t == null) { return Talker.UNKNOWN; } else { return t; } } } public static String createTagBlock(LinkedHashMap<String, String> tags) { if (tags == null || tags.size() == 0) return ""; StringBuilder s = new StringBuilder(128); s.append("\\"); int startChecksum = s.length(); boolean first = true; for (Entry<String, String> entry : tags.entrySet()) { if (!first) s.append(","); s.append(entry.getKey()); s.append(":"); s.append(entry.getValue()); first = false; } String checksum = NmeaUtil.getChecksum(s.substring(startChecksum)); s.append("*"); s.append(checksum); s.append("\\"); return s.toString(); } public static String createNmeaLine(LinkedHashMap<String, String> tags, List<String> items) { StringBuilder s = new StringBuilder(40); s.append(createTagBlock(tags)); int startForChecksum = s.length(); boolean first = true; for (String item : items) { if (!first) s.append(","); s.append(item); first = false; } String checksum = NmeaUtil.getChecksum(s.substring(startForChecksum)); s.append("*"); s.append(checksum); return s.toString(); } }
package org.openmrs.test; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Skips over the {@link BaseContextSensitiveTest#baseSetupWithStandardDataAndAuthentication()} * method when applied to "@Test" methods. This allows classes that extend * {@link BaseContextSensitiveTest} to not be forced into running * baseSetupWithStandardDataAndAuthentication(). This magic happens because of the * {@link SkipBaseSetupAnnotationExecutionListener} that is registered on the * {@link BaseContextSensitiveTest} * * @see BaseContextSensitiveTest */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target( { ElementType.METHOD, ElementType.TYPE }) public @interface SkipBaseSetup { }
package com.google.rolecall.models; import com.google.rolecall.jsonobjects.PerformanceInfo; import com.google.rolecall.jsonobjects.PerformanceSectionInfo; import com.google.rolecall.restcontrollers.exceptionhandling.RequestExceptions.InvalidParameterException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table public class Performance { public enum Status { PUBLISHED, CANCLED, DRAFT; } @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(nullable = false) private String title; @Column(length=1024) private String description; @Column(nullable = false) private String location; @Column(nullable = false) private Timestamp dateTime; @Enumerated(EnumType.ORDINAL) private Status status; // This as a set masks a larger issue PerformanceRepository.getById duplicates sections @OneToMany(mappedBy = "performance", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) private Set<PerformanceSection> performanceSections = new HashSet<>(); public Integer getId() { return id; } public String getTitle() { return title; } public String getDescription() { return description == null ? "" : description; } public String getLocation() { return location; } public Timestamp getDate() { return dateTime; } public Status getStatus() { return status; } public List<PerformanceSection> getProgram() { return new ArrayList<>(performanceSections); } public void publish() { if(status == Status.DRAFT) { this.status = Status.PUBLISHED; } } public void cancel() { this.status = Status.CANCLED; } public void addPerformanceSection(PerformanceSection performanceSection) { performanceSection.setPerformance(this); performanceSections.add(performanceSection); } public void removePerformanceSection(PerformanceSection performanceSection) { performanceSection.setPerformance(null); performanceSections.remove(performanceSection); } public void addPerformanceCastMember(PerformanceCastMember member) { member.setPerformance(this); } public void removePerformanceCastMember(PerformanceCastMember member) { member.setPerformance(null); } public PerformanceInfo toPerformanceInfo() { List<PerformanceSectionInfo> sections = performanceSections .stream().map(s -> s.toPerformanceSectionInfo()) .collect(Collectors.toList()); PerformanceInfo info = PerformanceInfo.newBuilder() .setId(id) .setTitle(getTitle()) .setDescription(getDescription()) .setLocation(getLocation()) .setDateTime(getDate().getTime()) .setStatus(getStatus()) .setPerformanceSections(sections) .build(); return info; } public Builder toBuilder() { return new Builder(this); } public Performance() { } public static Builder newBuilder() { return new Builder(); } public static class Builder { private Performance performance; private String title; private String description; private String location; private Timestamp dateTime; public Builder setTitle(String title) { if(title != null) { this.title = title; } return this; } public Builder setDescription(String description) { if(description != null) { this.description = description; } return this; } public Builder setLocation(String location) { if(location != null) { this.location = location; } return this; } public Builder setDateTime(Long dateTimeMilis) { if(dateTimeMilis != null) { this.dateTime = new Timestamp(dateTimeMilis); } return this; } public Performance build() throws InvalidParameterException { if(title == null || location == null || dateTime == null) { throw new InvalidParameterException("Performance requires a Title, Location, and a Time"); } performance.title = this.title; performance.description = this.description; performance.location = this.location; performance.dateTime = this.dateTime; return performance; } public Builder(Performance performance) { this.performance = performance; this.title = performance.getTitle(); this.description = performance.getDescription(); this.location = performance.getLocation(); this.dateTime = performance.getDate(); } public Builder() { this.performance = new Performance(); performance.status = Status.DRAFT; } } }
package com.mutualmobile.barricade; import android.content.Context; import android.content.Intent; import com.mutualmobile.barricade.activity.BarricadeActivity; import com.mutualmobile.barricade.response.BarricadeResponse; import com.mutualmobile.barricade.response.BarricadeResponseSet; import com.mutualmobile.barricade.utils.AndroidAssetFileManager; import com.mutualmobile.barricade.utils.AssetFileManager; import com.mutualmobile.barricade.utils.BarricadeShakeListener; import java.io.File; import java.util.HashMap; import java.util.logging.Logger; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; /** * Local server for your application. * * You should typically initialize it once, preferably in your Application class using Builder * class. * * @author Mustafa Ali, 12/07/16. */ public class Barricade { static final String TAG = "Barricade"; private static final String ROOT_DIRECTORY = "barricade"; private static final long DEFAULT_DELAY = 150; private static Barricade instance; private IBarricadeConfig barricadeConfig; private AssetFileManager fileManager; private long delay = DEFAULT_DELAY; private boolean enabled = false; /** * @return The singleton instance of the Barricade */ public static Barricade getInstance() { if (instance == null) { throw new IllegalStateException("Barricade not installed, install using Builder"); } return instance; } // Disable instance creation by using empty constructor private Barricade() { } private Barricade(AssetFileManager fileManager, IBarricadeConfig barricadeConfig, long delay, Context context) { this.barricadeConfig = barricadeConfig; this.fileManager = fileManager; this.delay = delay; if (context != null) { new BarricadeShakeListener(context); } } boolean isEnabled() { return enabled; } /** * Builder class for Barricade */ public static class Builder { private IBarricadeConfig barricadeConfig; private AssetFileManager fileManager; private long delay = DEFAULT_DELAY; private Context context; public Builder(Context context, IBarricadeConfig barricadeConfig) { this(barricadeConfig, new AndroidAssetFileManager(context)); } public Builder(IBarricadeConfig barricadeConfig, AssetFileManager fileManager) { this.barricadeConfig = barricadeConfig; this.fileManager = fileManager; } public Builder enableShakeToStart(Context context) { this.context = context; return this; } public Builder setGlobalDelay(long delay) { this.delay = delay; return this; } /** * Create Barricade instance if not exist and return it * It should be called once in project, next call will be ignored * * @return Barricade instance */ public Barricade install() { if (instance == null) { instance = new Barricade(fileManager, barricadeConfig, delay, context); } else { Logger.getLogger(TAG).info("Barricade already installed, install() will be ignored."); } return instance; } } /** * Returns a barricaded response for an endpoint * * @param chain OkHttp Interceptor chain * @param endpoint Endpoint that is being hit * @return Barricaded response (if available), null otherwise */ okhttp3.Response getResponse(Interceptor.Chain chain, String endpoint) { BarricadeResponse barricadeResponse = barricadeConfig.getResponseForEndpoint(endpoint); if (barricadeResponse == null) { return null; } String fileResponse = getResponseFromFile(endpoint, barricadeResponse.responseFileName); return new okhttp3.Response.Builder().code(barricadeResponse.statusCode) .request(chain.request()) .protocol(Protocol.HTTP_1_0) .body(ResponseBody.create(MediaType.parse(barricadeResponse.contentType), fileResponse.getBytes())) .addHeader("content-type", barricadeResponse.contentType) .build(); } public HashMap<String, BarricadeResponseSet> getConfig() { return barricadeConfig.getConfigs(); } public long getDelay() { return delay; } private String getResponseFromFile(String endpoint, String variant) { // TODO: 4/4/17 Check with other file formats other than JSON String fileName = ROOT_DIRECTORY + File.separator + endpoint + File.separator + variant + ".json"; return fileManager.getContentsOfFileAsString(fileName); } /** * Change Barricade status * * @param enabled true to enable, false otherwise */ public Barricade setEnabled(boolean enabled) { this.enabled = enabled; return this; } /** * Set delay for responses sent by Barricade * * @param delay Delay in milliseconds */ public Barricade setDelay(long delay) { this.delay = delay; return this; } /** * Change response to be returned for an endpoint * * @param endPoint The endpoint whose response you want to change. Use BarricadeConfig$EndPoints * to * get endpoint strings rather than passing string directly * @param defaultIndex The index of the response you want to get for endPoint. Use * BarricadeConfig$Responses to get responses for an endpoint instead of passing an int directly */ public Barricade withResponse(String endPoint, int defaultIndex) { if (getConfig().containsKey(endPoint)) { getConfig().get(endPoint).defaultIndex = defaultIndex; return this; } else { throw new IllegalArgumentException(endPoint + " doesn't exist"); } } /** * Resets any configuration changes done at run-time */ public void reset() { HashMap<String, BarricadeResponseSet> configs = getConfig(); for (String key : configs.keySet()) { BarricadeResponseSet set = configs.get(key); set.defaultIndex = set.originalDefaultIndex; } } /** * Launches the Barricade configuration UI * * @param context Activity context */ public void launchConfigActivity(Context context) { Intent intent = new Intent(context, BarricadeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }
package org.basex.http.restxq; import static org.basex.http.restxq.RestXqText.*; import static org.basex.util.Token.*; import java.io.*; import org.basex.http.*; import org.basex.io.out.*; import org.basex.io.serial.*; import org.basex.query.*; import org.basex.query.expr.*; import org.basex.query.func.*; import org.basex.query.iter.*; import org.basex.query.scope.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.value.type.*; import org.basex.util.http.*; final class RestXqResponse { /** Function. */ final RestXqFunction func; /** Query context. */ final QueryContext qc; /** HTTP connection. */ final HTTPConnection conn; /** Output stream. */ private OutputStream out; /** Status message. */ private String message; /** Status code. */ private Integer status; /** * Constructor. * @param func function * @param qc query context * @param conn HTTP connection */ RestXqResponse(final RestXqFunction func, final QueryContext qc, final HTTPConnection conn) { this.func = func; this.qc = qc; this.conn = conn; } /** * Evaluates the specified function and serializes the result. * @param qe query exception (optional) * @throws Exception exception (including unexpected ones) */ void create(final QueryException qe) throws Exception { // bind variables final StaticFunc sf = func.function; final Expr[] args = new Expr[sf.args.length]; func.bind(conn, args, qe, qc); // assign function call and http context and register process qc.mainModule(MainModule.get(sf, args)); qc.http(conn); qc.jc().type(RESTXQ); final String singleton = func.singleton; final RestXqSession session = new RestXqSession(conn, singleton, qc); String redirect = null, forward = null; qc.register(qc.context); try { // evaluate query final Iter iter = qc.iter(); // handle response element final Item first = iter.next(); if(first instanceof ANode) { final ANode node = (ANode) first; if(REST_REDIRECT.eq(node)) { // send redirect to browser final ANode ch = node.children().next(); if(ch == null || ch.type != NodeType.TXT) throw func.error(NO_VALUE, node.name()); redirect = string(ch.string()).trim(); } else if(REST_FORWARD.eq(node)) { // server-side forwarding final ANode ch = node.children().next(); if(ch == null || ch.type != NodeType.TXT) throw func.error(NO_VALUE, node.name()); forward = string(ch.string()).trim(); } else if(REST_RESPONSE.eq(node)) { // custom response build(node, iter); } else { // standard serialization serialize(first, iter, false); } } else if(singleton != null) { // cached serialization serialize(first, iter, true); } else { // standard serialization serialize(first, iter, false); } } finally { qc.close(); qc.unregister(qc.context); session.close(); if(redirect != null) { conn.redirect(redirect); } else if(forward != null) { conn.forward(forward); } else { qc.checkStop(); finish(); } } } /** * Builds a response element and creates the serialization parameters. * @param response response element * @param iter result iterator * @throws Exception exception (including unexpected ones) */ private void build(final ANode response, final Iter iter) throws Exception { // don't allow attributes for(final ANode a : response.attributes()) throw func.error(UNEXP_NODE, a); // parse response and serialization parameters SerializerOptions sp = func.output; String cType = null; for(final ANode n : response.children()) { // process http:response element if(HTTP_RESPONSE.eq(n)) { // check status and reason byte[] sta = null, msg = null; for(final ANode a : n.attributes()) { final QNm qnm = a.qname(); if(qnm.eq(Q_STATUS)) sta = a.string(); else if(qnm.eq(Q_REASON) || qnm.eq(Q_MESSAGE)) msg = a.string(); else throw func.error(UNEXP_NODE, a); } if(sta != null) { status = toInt(sta); message = msg != null ? string(msg) : null; } for(final ANode c : n.children()) { // process http:header elements if(HTTP_HEADER.eq(c)) { final byte[] nam = c.attribute(Q_NAME); final byte[] val = c.attribute(Q_VALUE); if(nam != null && val != null) { final String key = string(nam), value = string(val); if(key.equalsIgnoreCase(HttpText.CONTENT_TYPE)) { cType = value; } else { conn.res.setHeader(key, key.equalsIgnoreCase(HttpText.LOCATION) ? conn.resolve(value) : value); } } } else { throw func.error(UNEXP_NODE, c); } } } else if(OUTPUT_SERIAL.eq(n)) { // parse output:serialization-parameters sp = FuncOptions.serializer(n, func.output, func.function.info); } else { throw func.error(UNEXP_NODE, n); } } // set content type and serialize data if(cType != null) sp.set(SerializerOptions.MEDIA_TYPE, cType); final Item first = iter.next(); if(first != null) checkHead(); serialize(first, iter, sp, true); } /** * Serializes the first and all remaining items. * @param first first item * @param iter iterator * @param cache cache result * @throws Exception exception (including unexpected ones) */ private void serialize(final Item first, final Iter iter, final boolean cache) throws Exception { checkHead(); serialize(first, iter, func.output, cache); } /** * Serializes the first and all remaining items. * @param first first item * @param iter iterator * @param sp serialization parameters * @param cache cache result * @throws Exception exception (including unexpected ones) */ private void serialize(final Item first, final Iter iter, final SerializerOptions sp, final boolean cache) throws Exception { conn.sopts(sp); conn.initResponse(); out = cache ? new ArrayOutput() : conn.res.getOutputStream(); Item item = first; try(Serializer ser = Serializer.get(out, sp)) { for(; item != null; item = iter.next()) { qc.checkStop(); ser.serialize(item); } } } /** * Checks if the HEAD method was specified. * @throws QueryException query exception */ private void checkHead() throws QueryException { if(func.methods.size() == 1 && func.methods.contains(HttpMethod.HEAD.name())) throw func.error(HEAD_METHOD); } /** * Finalizes result generation. * @throws IOException I/O exception */ private void finish() throws IOException { if(status != null) conn.status(status, message); if(out instanceof ArrayOutput) { final ArrayOutput ao = (ArrayOutput) out; if(ao.size() > 0) conn.res.getOutputStream().write(ao.finish()); } } }
package org.basex.query.func; import static org.basex.query.QueryError.*; import static org.basex.query.QueryText.*; import java.lang.reflect.*; import org.basex.query.*; import org.basex.query.QueryModule.Deterministic; import org.basex.query.QueryModule.FocusDependent; import org.basex.query.expr.*; import org.basex.query.value.*; import org.basex.query.value.node.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; final class JavaModuleFunc extends JavaMapping { /** Java module. */ private final Object module; /** Method to be called. */ private final Method method; /** Method parameters. */ private final Class<?>[] params; /** Indicates if function parameters are of (sub)class {@link Value}. */ private final boolean[] vTypes; /** * Constructor. * @param sc static context * @param info input info * @param module Java module * @param method Java method/field * @param args arguments */ JavaModuleFunc(final StaticContext sc, final InputInfo info, final Object module, final Method method, final Expr[] args) { super(sc, info, args); this.module = module; this.method = method; params = method.getParameterTypes(); vTypes = JavaFunc.values(params); } @Override public boolean isVacuous() { return method.getReturnType() == Void.TYPE; } @Override protected Object eval(final Value[] vals, final QueryContext qc) throws QueryException { // assign context if module is inheriting {@link QueryModule} if(module instanceof QueryModule) { final QueryModule mod = (QueryModule) module; mod.staticContext = sc; mod.queryContext = qc; } final Object[] args = JavaFunc.args(params, vTypes, vals, true); if(args != null) { try { return method.invoke(module, args); } catch(final Exception ex) { Throwable e = ex; if(e.getCause() != null) { Util.debug(e); e = e.getCause(); } if(e instanceof QueryException) throw ((QueryException) e).info(info); Util.stack(e); throw JAVAERROR_X.get(info, Util.className(e) + ": " + e.getMessage()); } } // compose error message: expected arguments final TokenBuilder expect = new TokenBuilder(); for(final Class<?> c : method.getParameterTypes()) { if(!expect.isEmpty()) expect.add(", "); expect.add(Util.className(c)); } throw JAVAARGS_X_X.get(info, method.getName() + '(' + expect + ')', method.getName() + '(' + foundArgs(vals) + ')'); } @Override public Expr copy(final QueryContext qc, final VarScope scp, final IntObjMap<Var> vs) { return new JavaModuleFunc(sc, info, module, method, copyAll(qc, scp, vs, exprs)); } @Override public void plan(final FElem plan) { addPlan(plan, planElem(NAM, name()), exprs); } @Override public String description() { return name() + " method"; } /** * Returns the function descriptor. * @return string */ private String name() { return Util.className(module) + ':' + method.getName(); } @Override public String toString() { return name() + PAREN1 + toString(SEP) + PAREN2; } @Override public boolean has(final Flag f) { return f == Flag.NDT && method.getAnnotation(Deterministic.class) == null || (f == Flag.CTX || f == Flag.FCS) && method.getAnnotation(FocusDependent.class) == null || super.has(f); } }
package org.biojava3.core.util; import java.lang.reflect.Array; /** * Contains helper methods for generating a HashCode without having to resort to * the commons lang hashcode builders. * * Example where the property name is a String and the property age is an int * * <pre> * public int hashCode() { * int result = Hashcoder.SEED; * result = Hashcoder.hash(result, this.getName()); * result = Hashcoder.hash(result, this.getAge()); * return result; * } * </pre> * * @author ayates */ public class Hashcoder { /** * An initial value for a <code>hashCode</code>, to which we add * contributions from fields. Using a non-zero value decreases collisions of * <code>hashCode</code> values. */ public static final int SEED = 9; /** * The prime number used to multiply any calculated hashcode seed by * * i.e. result = PRIME*result + c * * Where result is the result of the previous calculation (at first this will * be seed) and c is the calculated int to add to result */ public static final int PRIME = 79; public static int hash(int seed, boolean b) { return (PRIME * seed) + (b ? 1 : 0); } public static int hash(int seed, char c) { return (PRIME * seed) + (int) c; } /** * Used for ints, bytes and shorts */ public static int hash(int seed, int i) { return (PRIME * seed) + i; } /** * long support done by shifting by 32 (using unsigned shift) */ public static int hash(int seed, long l) { return (PRIME * seed) + (int) (l ^ (l >>> 32)); } /** * float support done via {@link Float#floatToIntBits(float)} which allows * the encoding of a float as an int. We can then hash as normal. */ public static int hash(int seed, float f) { return hash(seed, Float.floatToIntBits(f)); } /** * double support which is done using the same techinque as float hashing * except we convert to a long not to an int. */ public static int hash(int seed, double d) { return hash(seed, Double.doubleToLongBits(d)); } /** * <code>o</code> is a possibly-null object field, and possibly an * array. * * If <code>o</code> is an array, then each element may be a primitive * or a possibly-null object. */ public static int hash(int seed, Object o) { int result = seed; //If it was null then this is the result 0 if (o == null) { result = hash(result, 0); } //If it wasn't an array then calculate the hashcode else if (!o.getClass().isArray()) { result = hash(result, o.hashCode()); } //Otherwise loop & else { int length = Array.getLength(o); for (int i = 0; i < length; i++) { Object item = Array.get(o, i); result = hash(result, item);// recursive call! } } return result; } }
package bndtools.launch; import java.io.File; import java.text.MessageFormat; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import org.bndtools.api.ILogger; import org.bndtools.api.Logger; import org.bndtools.api.RunMode; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobFunction; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.IStatusHandler; import org.eclipse.debug.core.model.IProcess; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaLaunchDelegate; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.environments.IExecutionEnvironment; import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager; import org.osgi.framework.FrameworkUtil; import aQute.bnd.build.Project; import aQute.bnd.build.ProjectLauncher; import aQute.bnd.build.Run; import bndtools.Plugin; import bndtools.StatusCode; import bndtools.central.Central; import bndtools.launch.util.LaunchUtils; import bndtools.preferences.BndPreferences; public abstract class AbstractOSGiLaunchDelegate extends JavaLaunchDelegate { @SuppressWarnings("deprecation") private static final String ATTR_LOGLEVEL = LaunchConstants.ATTR_LOGLEVEL; private static final ILogger logger = Logger.getLogger(AbstractOSGiLaunchDelegate.class); protected Run run; protected abstract ProjectLauncher getProjectLauncher() throws CoreException; protected abstract void initialiseBndLauncher(ILaunchConfiguration configuration, Project model) throws Exception; protected abstract IStatus getLauncherStatus(); protected abstract RunMode getRunMode(); @Override public boolean preLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { // override AbstractJavaLaunchConfigurationDelegate#preLaunchCheck, to // avoid loading the Java project (which is not required when we are // using a bndrun file). return true; } @Override protected IProject[] getBuildOrder(ILaunchConfiguration configuration, String mode) throws CoreException { return new IProject[0]; } @Override protected IProject[] getProjectsForProblemSearch(ILaunchConfiguration configuration, String mode) throws CoreException { return new IProject[0]; } @Override public IVMInstall getVMInstall(ILaunchConfiguration configuration) throws CoreException { IExecutionEnvironmentsManager eeMgr = JavaRuntime.getExecutionEnvironmentsManager(); // Look for a matching JVM install from the -runee setting String runee = run.getRunee(); if (runee != null) { IExecutionEnvironment ee = eeMgr.getEnvironment(runee); if (ee != null) { // Return the default VM for this EE if the user has selected // one IVMInstall defaultVm = ee.getDefaultVM(); if (defaultVm != null) return defaultVm; IVMInstall[] compatibleVMs = ee.getCompatibleVMs(); if (compatibleVMs != null && compatibleVMs.length > 0) { // Return the strictly compatible VM (i.e. perfect match) if // there is one for (IVMInstall vm : compatibleVMs) { if (ee.isStrictlyCompatible(vm)) return vm; } // No strictly compatible VM, just return the last in the // list. return compatibleVMs[compatibleVMs.length - 1]; } } throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, StatusCode.NoVMForEE.getCode(), "Could not find JRE installation matching Execution Environment: " + runee, null)); } // Still nothing? Use the default JVM from the workspace. // Eclipse tries really hard to force you to set a default VM, but this // can still be null if the default has // been disposed somehow. IVMInstall defaultVm = JavaRuntime.getDefaultVMInstall(); if (defaultVm != null) { return defaultVm; } // You still here?? The superclass will look into the Java project, if // the run file is in one. try { return super.getVMInstall(configuration); } catch (CoreException e) { // ignore } throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, StatusCode.NoVMForEE.getCode(), "Could not select a JRE for launch. No Execution Environment is specified\n(using '-runee'), there is no default JRE in preferences and no relevant\nJava project settings.", null)); } @Override public String[][] getBootpathExt(ILaunchConfiguration configuration) throws CoreException { // TODO: support deriving bootclasspath extensions from the bndrun file return new String[][] { null, null, null }; } @Override public boolean buildForLaunch(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { BndPreferences prefs = new BndPreferences(); boolean result = !prefs.getBuildBeforeLaunch() || super.buildForLaunch(configuration, mode, monitor); try { run = LaunchUtils.createRun(configuration, getRunMode()); initialiseBndLauncher(configuration, run); } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error initialising bnd launcher", e)); } return result; } @Override public boolean finalLaunchCheck(ILaunchConfiguration configuration, String mode, IProgressMonitor monitor) throws CoreException { // Check for existing launches of same resource BndPreferences prefs = new BndPreferences(); if (prefs.getWarnExistingLaunches()) { IResource launchResource = LaunchUtils.getTargetResource(configuration); if (launchResource == null) throw new CoreException(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Bnd launch target was not specified or does not exist.", null)); int processCount = 0; for (ILaunch l : DebugPlugin.getDefault() .getLaunchManager() .getLaunches()) { // ... is it the same launch resource? ILaunchConfiguration launchConfig = l.getLaunchConfiguration(); if (launchConfig == null) { continue; } if (launchResource.equals(LaunchUtils.getTargetResource(launchConfig))) { // Iterate existing processes for (IProcess process : l.getProcesses()) { if (!process.isTerminated()) processCount++; } } } // Warn if existing processes running if (processCount > 0) { Status status = new Status(IStatus.WARNING, Plugin.PLUGIN_ID, 0, "One or more OSGi Frameworks have already been launched for this configuration. Additional framework instances may interfere with each other due to the shared storage directory.", null); IStatusHandler prompter = DebugPlugin.getDefault() .getStatusHandler(status); if (prompter != null) { boolean okay = (Boolean) prompter.handleStatus(status, launchResource); if (!okay) return okay; } } } IStatus launchStatus = getLauncherStatus(); IStatusHandler prompter = DebugPlugin.getDefault() .getStatusHandler(launchStatus); if (prompter != null) return (Boolean) prompter.handleStatus(launchStatus, run); return true; } @Override public void launch(ILaunchConfiguration configuration, String mode, final ILaunch launch, IProgressMonitor monitor) throws CoreException { try { boolean dynamic = configuration.getAttribute(LaunchConstants.ATTR_DYNAMIC_BUNDLES, LaunchConstants.DEFAULT_DYNAMIC_BUNDLES); if (dynamic) registerLaunchPropertiesRegenerator(run, launch); } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error obtaining OSGi project launcher.", e)); } // Register listener to clean up temp files on exit of launched JVM final ProjectLauncher launcher = getProjectLauncher(); IDebugEventSetListener listener = new IDebugEventSetListener() { @Override public void handleDebugEvents(DebugEvent[] events) { for (DebugEvent event : events) { if (event.getKind() == DebugEvent.TERMINATE) { Object source = event.getSource(); if (source instanceof IProcess) { ILaunch processLaunch = ((IProcess) source).getLaunch(); if (processLaunch == launch) { // Not interested in any further events => // unregister this listener DebugPlugin.getDefault() .removeDebugEventListener(this); // Cleanup. Guard with a draconian catch because // changes in the ProjectLauncher API // *may* cause LinkageErrors. try { launcher.cleanup(); } catch (Throwable t) { logger.logError("Error cleaning launcher temporary files", t); } LaunchUtils.endRun((Run) launcher.getProject()); } } } } } }; DebugPlugin.getDefault() .addDebugEventListener(listener); // Now actually launch super.launch(configuration, mode, launch, monitor); } /* * This method is deprecated in Eclipse 4.11 and no longer called there. * Instead getClasspathAndModulepath is called. We need it here for older * versions of Eclipse. */ @Override public String[] getClasspath(ILaunchConfiguration configuration) throws CoreException { Collection<String> paths = getProjectLauncher().getClasspath(); return paths.toArray(new String[0]); } @Override public String[][] getClasspathAndModulepath(ILaunchConfiguration config) throws CoreException { String[][] classpathAndModulepath = super.getClasspathAndModulepath(config); if (classpathAndModulepath == null) { classpathAndModulepath = new String[2][]; classpathAndModulepath[1] = new String[0]; } classpathAndModulepath[0] = getClasspath(config); return classpathAndModulepath; } @Override public String getMainTypeName(ILaunchConfiguration configuration) throws CoreException { return getProjectLauncher().getMainTypeName(); } @Override public File verifyWorkingDirectory(ILaunchConfiguration configuration) throws CoreException { try { return (run != null) ? run.getBase() : null; } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error getting working directory for Bnd project.", e)); } } @Override public String getVMArguments(ILaunchConfiguration configuration) throws CoreException { StringBuilder builder = new StringBuilder(); Collection<String> runVM = getProjectLauncher().getRunVM(); for (Iterator<String> iter = runVM.iterator(); iter.hasNext();) { builder.append(iter.next()); if (iter.hasNext()) builder.append(" "); } String args = builder.toString(); return args; } @Override public String getProgramArguments(ILaunchConfiguration configuration) throws CoreException { StringBuilder builder = new StringBuilder(); Collection<String> args = getProjectLauncher().getRunProgramArgs(); for (Iterator<String> iter = args.iterator(); iter.hasNext();) { builder.append(iter.next()); if (iter.hasNext()) builder.append(" "); } return builder.toString(); } /** * This was first always overriding -runkeep. Now it can only override it if * -runkeep is set to false. However, I think this option should go away in * bndtools. Anyway, removed the actual clearing since this was already done * in the launcher. */ protected void configureLauncher(ILaunchConfiguration configuration) throws CoreException { if (getProjectLauncher().isKeep() == false) { boolean clean = configuration.getAttribute(LaunchConstants.ATTR_CLEAN, LaunchConstants.DEFAULT_CLEAN); getProjectLauncher().setKeep(!clean); } enableTraceOptionIfSetOnConfiguration(configuration, getProjectLauncher()); } private AtomicBoolean updatePending = new AtomicBoolean(false); /** * Registers a resource listener with the project model file to update the * launcher when the model or any of the run-bundles changes. The resource * listener is automatically unregistered when the launched process * terminates. * * @param project * @param launch * @throws CoreException */ private void registerLaunchPropertiesRegenerator(final Project project, final ILaunch launch) throws CoreException { final IResource targetResource = LaunchUtils.getTargetResource(launch.getLaunchConfiguration()); if (targetResource == null) return; final IPath bndbndPath; try { bndbndPath = Central.toPath(project.getPropertiesFile()); } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error querying bnd.bnd file location", e)); } try { Central.toPath(project.getTarget()); } catch (Exception e) { throw new CoreException( new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error querying project output folder", e)); } final IResourceChangeListener resourceListener = event -> { try { if (updatePending.get()) { return; } // Was the properties file (bnd.bnd or *.bndrun) included in // the delta? IResourceDelta propsDelta = event.getDelta() .findMember(bndbndPath); if (propsDelta == null && targetResource.getType() == IResource.FILE) propsDelta = event.getDelta() .findMember(targetResource.getFullPath()); if (propsDelta != null) { if (propsDelta.getKind() == IResourceDelta.CHANGED) { scheduleUpdate(); return; } } // Check for bundles included in the launcher's runbundles // list final Set<String> runBundleSet = new HashSet<>(); for (String bundlePath : getProjectLauncher().getRunBundles()) { runBundleSet.add(new org.eclipse.core.runtime.Path(bundlePath).toPortableString()); } event.getDelta() .accept(delta -> { // Short circuit if we have already found a // match if (updatePending.get()) { return false; } IResource resource = delta.getResource(); if (resource.getType() == IResource.FILE) { IPath location = resource.getLocation(); boolean isRunBundle = location != null ? runBundleSet.contains(location.toPortableString()) : false; if (isRunBundle) { scheduleUpdate(); } return false; } // Recurse into containers return true; }); } catch (CoreException e) { logger.logError("Error while processing resource changes.", e); } }; updatePending.set(false); ResourcesPlugin.getWorkspace() .addResourceChangeListener(resourceListener); // Register a listener for termination of the launched process DebugPlugin.getDefault() .addDebugEventListener(new TerminationListener(launch, () -> { ResourcesPlugin.getWorkspace() .removeResourceChangeListener(resourceListener); updatePending.set(false); })); } private void scheduleUpdate() { if (updatePending.compareAndSet(false, true)) { Job job = Job.create("Update launched application...", (IJobFunction) monitor -> { try { Job.getJobManager() .join(ResourcesPlugin.FAMILY_MANUAL_BUILD, monitor); if (updatePending.get() && !monitor.isCanceled()) { Job.getJobManager() .join(ResourcesPlugin.FAMILY_AUTO_BUILD, monitor); if (updatePending.get() && !monitor.isCanceled()) { // Just in case we've been shut down in the // meantime. getProjectLauncher().update(); return Status.OK_STATUS; } } return Status.CANCEL_STATUS; } catch (InterruptedException | OperationCanceledException e) { return Status.CANCEL_STATUS; } catch (CoreException e) { IStatus st = e.getStatus(); return new Status(st.getSeverity(), st.getPlugin(), st.getCode(), st.getMessage(), e); } catch (Exception e) { logger.logError("Error updating launch properties file.", e); return new Status(IStatus.ERROR, FrameworkUtil.getBundle(AbstractOSGiLaunchDelegate.class) .getSymbolicName(), "Error updating launch properties file.", e); } finally { updatePending.set(false); } }); job.schedule(); } } protected static void enableTraceOptionIfSetOnConfiguration(ILaunchConfiguration configuration, ProjectLauncher launcher) throws CoreException { if (configuration.hasAttribute(LaunchConstants.ATTR_TRACE)) { launcher.setTrace(configuration.getAttribute(LaunchConstants.ATTR_TRACE, LaunchConstants.DEFAULT_TRACE)); } String logLevelStr = configuration.getAttribute(ATTR_LOGLEVEL, (String) null); if (logLevelStr != null) { Plugin.getDefault() .getLog() .log(new Status(IStatus.WARNING, Plugin.PLUGIN_ID, 0, MessageFormat.format("The {0} attribute is no longer supported, use {1} instead.", ATTR_LOGLEVEL, LaunchConstants.ATTR_TRACE), null)); Level logLevel = Level.parse(logLevelStr); launcher.setTrace(launcher.getTrace() || logLevel.intValue() <= Level.FINE.intValue()); } } protected static MultiStatus createStatus(String message, List<String> errors, List<String> warnings) { MultiStatus status = new MultiStatus(Plugin.PLUGIN_ID, 0, message, null); for (String error : errors) { status.add(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, error, null)); } for (String warning : warnings) { status.add(new Status(IStatus.WARNING, Plugin.PLUGIN_ID, 0, warning, null)); } return status; } }
package com.browseengine.bobo.sort; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.TermFreqVector; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.SortField; import com.browseengine.bobo.api.BoboIndexReader; import com.browseengine.bobo.api.Browsable; import com.browseengine.bobo.api.BrowseFacet; import com.browseengine.bobo.api.BrowseHit; import com.browseengine.bobo.api.BrowseHit.TermFrequencyVector; import com.browseengine.bobo.api.FacetAccessible; import com.browseengine.bobo.api.FacetSpec; import com.browseengine.bobo.facets.data.FacetDataCache; import com.browseengine.bobo.facets.impl.GroupByFacetCountCollector; import com.browseengine.bobo.facets.impl.SimpleFacetHandler; import com.browseengine.bobo.facets.CombinedFacetAccessible; import com.browseengine.bobo.facets.FacetCountCollector; import com.browseengine.bobo.facets.FacetHandler; import com.browseengine.bobo.util.ListMerger; public class SortCollectorImpl extends SortCollector { private static final Comparator<MyScoreDoc> MERGE_COMPATATOR = new Comparator<MyScoreDoc>() { public int compare(MyScoreDoc o1, MyScoreDoc o2) { Comparable s1 = o1.getValue(); Comparable s2 = o2.getValue(); int r; if (s1 == null) { if (s2 == null) { r = 0; } else { r = -1; } } else if (s2 == null) { r = 1; } else{ int v = s1.compareTo(s2); if (v==0){ r = o1.doc + o1.queue.base - o2.doc - o2.queue.base; } else { r = v; } } return r; } }; private final LinkedList<DocIDPriorityQueue> _pqList; private final int _numHits; private int _totalHits; private int _totalGroups; private ScoreDoc _bottom; private ScoreDoc _tmpScoreDoc; private boolean _queueFull; private DocComparator _currentComparator; private DocComparatorSource _compSource; private DocIDPriorityQueue _currentQueue; private BoboIndexReader _currentReader=null; private FacetCountCollector _facetCountCollector; private final boolean _doScoring; private Scorer _scorer; private final int _offset; private final int _count; private final Browsable _boboBrowser; private final boolean _collectDocIdCache; private CombinedFacetAccessible _groupAccessible; private final List<FacetAccessible> _facetAccessibles; private final Map<Integer, ScoreDoc> _currentValueDocMaps; static class MyScoreDoc extends ScoreDoc { private static final long serialVersionUID = 1L; DocIDPriorityQueue queue; BoboIndexReader reader; Comparable sortValue; public MyScoreDoc(){ this(0,0.0f,null,null); } public MyScoreDoc(int docid, float score, DocIDPriorityQueue queue,BoboIndexReader reader) { super(docid, score); this.queue = queue; this.reader = reader; this.sortValue = null; } Comparable getValue(){ if(sortValue == null) sortValue = queue.sortValue(this); return sortValue; } } private CollectorContext _currentContext; private int[] _currentDocIdArray; private float[] _currentScoreArray; private int _docIdArrayCursor = 0; private int _docIdCacheCapacity = 0; private Set<String> _termVectorsToFetch; public SortCollectorImpl(DocComparatorSource compSource, SortField[] sortFields, Browsable boboBrowser, int offset, int count, boolean doScoring, boolean fetchStoredFields, Set<String> termVectorsToFetch, String groupBy, int maxPerGroup, boolean collectDocIdCache) { super(sortFields,fetchStoredFields); assert (offset>=0 && count>=0); _boboBrowser = boboBrowser; _compSource = compSource; _pqList = new LinkedList<DocIDPriorityQueue>(); _numHits = offset + count; _offset = offset; _count = count; _totalHits = 0; _totalGroups = 0; _queueFull = false; _doScoring = doScoring; _tmpScoreDoc = new MyScoreDoc(); _termVectorsToFetch = termVectorsToFetch; _collectDocIdCache = collectDocIdCache; // TODO: take maxPerGroup into consideration. if (groupBy != null) { this.groupBy = boboBrowser.getFacetHandler(groupBy); if (groupBy != null && _count > 0) { _currentValueDocMaps = new HashMap<Integer, ScoreDoc>(_count); _facetAccessibles = new LinkedList<FacetAccessible>(); if (collectDocIdCache) { contextList = new LinkedList<CollectorContext>(); docidarraylist = new LinkedList<int[]>(); if (doScoring) scorearraylist = new LinkedList<float[]>(); } } else { _currentValueDocMaps = null; _facetAccessibles = null; } } else { this.groupBy = null; _currentValueDocMaps = null; _facetAccessibles = null; } } @Override public boolean acceptsDocsOutOfOrder() { return _collector == null ? true : _collector.acceptsDocsOutOfOrder(); } @Override public void collect(int doc) throws IOException { ++_totalHits; if (groupBy != null) { if (_facetCountCollector != null) _facetCountCollector.collect(doc); //Object val = groupBy.getRawFieldValues(_currentReader, doc)[0]; if (_count > 0) { final float score = (_doScoring ? _scorer.score() : 0.0f); if (_collectDocIdCache) { if (_totalHits > _docIdCacheCapacity) { _currentDocIdArray = intarraymgr.get(BLOCK_SIZE); docidarraylist.add(_currentDocIdArray); if (_doScoring) { _currentScoreArray = floatarraymgr.get(BLOCK_SIZE); scorearraylist.add(_currentScoreArray); } _docIdCacheCapacity += BLOCK_SIZE; _docIdArrayCursor = 0; } _currentDocIdArray[_docIdArrayCursor] = doc; if (_doScoring) _currentScoreArray[_docIdArrayCursor] = score; ++_docIdArrayCursor; ++_currentContext.length; } _tmpScoreDoc.doc = doc; _tmpScoreDoc.score = score; if (!_queueFull || _currentComparator.compare(_bottom,_tmpScoreDoc) > 0) { final Integer order = ((FacetDataCache)groupBy.getFacetData(_currentReader)).orderArray.get(doc); ScoreDoc pre = _currentValueDocMaps.get(order); if (pre != null) { if ( _currentComparator.compare(pre, _tmpScoreDoc) > 0) { ScoreDoc tmp = pre; _bottom = _currentQueue.replace(_tmpScoreDoc, pre); _currentValueDocMaps.put(order, _tmpScoreDoc); _tmpScoreDoc = tmp; } } else { if (_queueFull){ MyScoreDoc tmp = (MyScoreDoc)_bottom; _currentValueDocMaps.remove(((FacetDataCache)groupBy.getFacetData(tmp.reader)).orderArray.get(tmp.doc)); _bottom = _currentQueue.replace(_tmpScoreDoc); _currentValueDocMaps.put(order, _tmpScoreDoc); _tmpScoreDoc = tmp; } else{ ScoreDoc tmp = new MyScoreDoc(doc,score,_currentQueue,_currentReader); _bottom = _currentQueue.add(tmp); _currentValueDocMaps.put(order, tmp); _queueFull = (_currentQueue.size >= _numHits); } } } } } else { if (_count > 0) { final float score = (_doScoring ? _scorer.score() : 0.0f); if (_queueFull){ _tmpScoreDoc.doc = doc; _tmpScoreDoc.score = score; if (_currentComparator.compare(_bottom,_tmpScoreDoc) > 0){ ScoreDoc tmp = _bottom; _bottom = _currentQueue.replace(_tmpScoreDoc); _tmpScoreDoc = tmp; } } else{ _bottom = _currentQueue.add(new MyScoreDoc(doc,score,_currentQueue,_currentReader)); _queueFull = (_currentQueue.size >= _numHits); } } } if (_collector != null) _collector.collect(doc); } private void collectTotalGroups() { if (_facetCountCollector instanceof GroupByFacetCountCollector) { _totalGroups += ((GroupByFacetCountCollector)_facetCountCollector).getTotalGroups(); return; } int[] count = _facetCountCollector.getCountDistribution(); for (int c : count) { if (c > 0) ++_totalGroups; } } @Override public void setNextReader(IndexReader reader, int docBase) throws IOException { assert reader instanceof BoboIndexReader; _currentReader = (BoboIndexReader)reader; _currentComparator = _compSource.getComparator(reader,docBase); _currentQueue = new DocIDPriorityQueue(_currentComparator, _numHits, docBase); if (groupBy != null) { if (_facetCountCollector != null) collectTotalGroups(); _facetCountCollector = ((SimpleFacetHandler)groupBy).getFacetCountCollectorSource(null, null, true).getFacetCountCollector(_currentReader, docBase); if (_facetAccessibles != null) _facetAccessibles.add(_facetCountCollector); if (_currentValueDocMaps != null) _currentValueDocMaps.clear(); if (contextList != null) { _currentContext = new CollectorContext(_currentReader, docBase, _currentComparator); contextList.add(_currentContext); } } MyScoreDoc myScoreDoc = (MyScoreDoc)_tmpScoreDoc; myScoreDoc.queue = _currentQueue; myScoreDoc.reader = _currentReader; myScoreDoc.sortValue = null; _pqList.add(_currentQueue); _queueFull = false; } @Override public void setScorer(Scorer scorer) throws IOException { _scorer = scorer; _currentComparator.setScorer(scorer); } @Override public int getTotalHits(){ return _totalHits; } @Override public int getTotalGroups(){ return _totalGroups; } @Override public CombinedFacetAccessible getGroupAccessible(){ return _groupAccessible; } @Override public BrowseHit[] topDocs() throws IOException{ ArrayList<Iterator<MyScoreDoc>> iterList = new ArrayList<Iterator<MyScoreDoc>>(_pqList.size()); for (DocIDPriorityQueue pq : _pqList){ int count = pq.size(); MyScoreDoc[] resList = new MyScoreDoc[count]; for (int i = count - 1; i >= 0; i resList[i] = (MyScoreDoc)pq.pop(); } iterList.add(Arrays.asList(resList).iterator()); } List<MyScoreDoc> resList; if (_count > 0) { if (groupBy == null) { resList = ListMerger.mergeLists(_offset, _count, iterList, MERGE_COMPATATOR); } else { if (_facetCountCollector != null) { collectTotalGroups(); _facetCountCollector = null; } _groupAccessible = new CombinedFacetAccessible(new FacetSpec(), _facetAccessibles); resList = new ArrayList<MyScoreDoc>(_count); Iterator<MyScoreDoc> mergedIter = ListMerger.mergeLists(iterList, MERGE_COMPATATOR); Set<Object> groupSet = new HashSet<Object>(_offset+_count); int offsetLeft = _offset; while(mergedIter.hasNext()) { MyScoreDoc scoreDoc = mergedIter.next(); Object[] vals = groupBy.getRawFieldValues(scoreDoc.reader, scoreDoc.doc); Object val = null; if (vals != null && vals.length > 0) val = vals[0]; if (!groupSet.contains(val)) { if (offsetLeft > 0) --offsetLeft; else resList.add(scoreDoc); groupSet.add(val); } if (resList.size() >= _count) break; } } } else resList = Collections.EMPTY_LIST; Map<String,FacetHandler<?>> facetHandlerMap = _boboBrowser.getFacetHandlerMap(); return buildHits(resList.toArray(new MyScoreDoc[resList.size()]), _sortFields, facetHandlerMap, _fetchStoredFields, _termVectorsToFetch,groupBy, _groupAccessible); } protected static BrowseHit[] buildHits(MyScoreDoc[] scoreDocs,SortField[] sortFields,Map<String,FacetHandler<?>> facetHandlerMap,boolean fetchStoredFields,Set<String> termVectorsToFetch, FacetHandler<?> groupBy, CombinedFacetAccessible groupAccessible) throws IOException { BrowseHit[] hits = new BrowseHit[scoreDocs.length]; Collection<FacetHandler<?>> facetHandlers= facetHandlerMap.values(); for (int i =scoreDocs.length-1; i >=0 ; i { MyScoreDoc fdoc = scoreDocs[i]; BoboIndexReader reader = fdoc.reader; BrowseHit hit=new BrowseHit(); if (fetchStoredFields){ hit.setStoredFields(reader.document(fdoc.doc)); } if (termVectorsToFetch!=null && termVectorsToFetch.size()>0){ Map<String,TermFrequencyVector> tvMap = new HashMap<String,TermFrequencyVector>(); hit.setTermFreqMap(tvMap); for (String field : termVectorsToFetch){ TermFreqVector tv = reader.getTermFreqVector(fdoc.doc, field); if (tv!=null){ int[] freqs = tv.getTermFrequencies(); String[] terms = tv.getTerms(); tvMap.put(field, new TermFrequencyVector(terms, freqs)); } } } Map<String,String[]> map = new HashMap<String,String[]>(); Map<String,Object[]> rawMap = new HashMap<String,Object[]>(); for (FacetHandler<?> facetHandler : facetHandlers) { map.put(facetHandler.getName(),facetHandler.getFieldValues(reader,fdoc.doc)); rawMap.put(facetHandler.getName(),facetHandler.getRawFieldValues(reader,fdoc.doc)); } hit.setFieldValues(map); hit.setRawFieldValues(rawMap); hit.setDocid(fdoc.doc+fdoc.queue.base); hit.setScore(fdoc.score); hit.setComparable(fdoc.getValue()); if (groupBy != null) { hit.setGroupValue(hit.getField(groupBy.getName())); hit.setRawGroupValue(hit.getRawField(groupBy.getName())); if (hit.getGroupValue() != null && groupAccessible != null) { BrowseFacet facet = groupAccessible.getFacet(hit.getGroupValue()); hit.setGroupHitsCount(facet.getFacetValueHitCount()); } } hits[i] = hit; } return hits; } }
package com.uber.okbuck.core.model.base; import com.android.build.api.attributes.VariantAttr; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.uber.okbuck.core.dependency.DependencyCache; import com.uber.okbuck.core.dependency.DependencyUtils; import com.uber.okbuck.core.dependency.ExternalDependency; import com.uber.okbuck.core.dependency.ExternalDependency.VersionlessDependency; import com.uber.okbuck.core.util.FileUtil; import com.uber.okbuck.core.util.ProjectUtil; import com.uber.okbuck.extension.OkBuckExtension; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.component.ComponentIdentifier; import org.gradle.api.artifacts.component.ModuleComponentIdentifier; import org.gradle.api.artifacts.component.ProjectComponentIdentifier; import org.gradle.api.artifacts.result.ResolvedArtifactResult; import org.gradle.api.attributes.Attribute; import org.gradle.api.specs.Spec; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public class Scope { private static final String EMPTY_GROUP = " private final Set<String> javaResources; private final Set<String> sources; private final Configuration configuration; private List<String> jvmArgs; private DependencyCache depCache; protected final Project project; private final Set<Target> targetDeps = new HashSet<>(); private final Set<ExternalDependency> external = new HashSet<>(); public final Set<String> getJavaResources() { return javaResources; } public final Set<String> getSources() { return sources; } public final Set<Target> getTargetDeps() { return targetDeps; } public List<String> getJvmArgs() { return jvmArgs; } public void setJvmArgs(List<String> jvmArgs) { this.jvmArgs = jvmArgs; } public final Set<ExternalDependency> getExternal() { return external; } /** * Used to filter out only project dependencies when resolving a configuration. */ private static final Spec<ComponentIdentifier> PROJECT_FILTER = componentIdentifier -> componentIdentifier instanceof ProjectComponentIdentifier; /** * Used to filter out external & local jar/aar dependencies when resolving a configuration. */ private static final Spec<ComponentIdentifier> EXTERNAL_DEP_FILTER = componentIdentifier -> !(componentIdentifier instanceof ProjectComponentIdentifier); protected Scope( Project project, Configuration configuration, Set<File> sourceDirs, Set<File> javaResourceDirs, List<String> jvmArguments, DependencyCache depCache) { this.project = project; this.sources = FileUtil.available(project, sourceDirs); this.javaResources = FileUtil.available(project, javaResourceDirs); this.jvmArgs = jvmArguments; this.depCache = depCache; this.configuration = configuration; if (configuration != null) { extractConfiguration(configuration); } } protected Scope( Project project, Configuration configuration, Set<File> sourceDirs, Set<File> javaResourceDirs, List<String> jvmArguments) { this(project, configuration, sourceDirs, javaResourceDirs, jvmArguments, ProjectUtil.getDependencyCache(project)); } public static Scope from( Project project, String configuration, Set<File> sourceDirs, Set<File> javaResourceDirs, List<String> jvmArguments, DependencyCache depCache) { Configuration useful = DependencyUtils.useful(project, configuration); return from(project, useful, sourceDirs, javaResourceDirs, jvmArguments, depCache); } public static Scope from( Project project, String configuration, Set<File> sourceDirs, Set<File> javaResourceDirs, List<String> jvmArguments) { return Scope.from(project, configuration, sourceDirs, javaResourceDirs, jvmArguments, ProjectUtil.getDependencyCache(project)); } public static Scope from( Project project, String configuration, Set<File> sourceDirs, Set<File> javaResourceDirs) { return Scope.from(project, configuration, sourceDirs, javaResourceDirs, ImmutableList.of(), ProjectUtil.getDependencyCache(project)); } public static Scope from(Project project, String configuration, Set<File> sourceDirs) { return Scope.from(project, configuration, sourceDirs, ImmutableSet.of(), ImmutableList.of(), ProjectUtil.getDependencyCache(project)); } public static Scope from(Project project, String configuration) { return Scope.from(project, configuration, ImmutableSet.of(), ImmutableSet.of(), ImmutableList.of(), ProjectUtil.getDependencyCache(project)); } public static Scope from( Project project, Configuration configuration, Set<File> sourceDirs, Set<File> javaResourceDirs, List<String> jvmArguments, DependencyCache depCache) { Configuration useful = DependencyUtils.useful(configuration); String key = useful != null ? useful.getName() : "--none return ProjectUtil .getScopes(project) .computeIfAbsent(project, t -> new ConcurrentHashMap<>()) .computeIfAbsent(key, t -> new Scope(project, useful, sourceDirs, javaResourceDirs, jvmArguments, depCache) ); } public static Scope from( Project project, Configuration configuration, Set<File> sourceDirs, Set<File> javaResourceDirs, List<String> jvmArguments) { return Scope.from(project, configuration, sourceDirs, javaResourceDirs, jvmArguments, ProjectUtil.getDependencyCache(project)); } public static Scope from( Project project, Configuration configuration, Set<File> sourceDirs, Set<File> javaResourceDirs) { return Scope.from(project, configuration, sourceDirs, javaResourceDirs, ImmutableList.of(), ProjectUtil.getDependencyCache(project)); } public static Scope from(Project project, Configuration configuration, Set<File> sourceDirs) { return Scope.from(project, configuration, sourceDirs, ImmutableSet.of(), ImmutableList.of(), ProjectUtil.getDependencyCache(project)); } public static Scope from(Project project, Configuration configuration) { return Scope.from(project, configuration, ImmutableSet.of(), ImmutableSet.of(), ImmutableList.of(), ProjectUtil.getDependencyCache(project)); } public Set<String> getExternalDeps() { return external .stream() .map(depCache::get) .collect(Collectors.toSet()); } public Set<String> getPackagedLintJars() { return external .stream() .filter(i -> i.depFile.getName().endsWith("aar")) .map(depCache::getLintJar) .filter(StringUtils::isNotEmpty) .collect(Collectors.toSet()); } public Set<String> getAnnotationProcessors() { if (configuration == null) { return ImmutableSet.of(); } Set<ExternalDependency.VersionlessDependency> firstLevelDependencies = configuration .getAllDependencies() .stream() .map(i -> new ExternalDependency.VersionlessDependency( i.getGroup() == null ? EMPTY_GROUP : i.getGroup(), i.getName()) ) .collect(Collectors.toSet()); return Streams.concat( external .stream() .filter(i -> firstLevelDependencies.contains(i.versionless)) .map(depCache::getAnnotationProcessors) .flatMap(Set::stream), targetDeps .stream() .filter(i -> { VersionlessDependency versionless = new ExternalDependency.VersionlessDependency( (String) i.getProject().getGroup(), i.getProject().getName() ); return firstLevelDependencies.contains(versionless); }) .map(target -> { OkBuckExtension okBuckExtension = ProjectUtil.getOkBuckExtension(project); return target.getProp(okBuckExtension.annotationProcessors, ImmutableList.of()); }) .flatMap(List::stream)) .filter(StringUtils::isNotEmpty) .collect(Collectors.toSet()); } private static Set<ResolvedArtifactResult> getArtifacts( Configuration configuration, final String value, final Spec<ComponentIdentifier> filter) { return configuration.getIncoming().artifactView(config -> { config.attributes(container -> container.attribute(Attribute.of("artifactType", String.class), value)); config.componentFilter(filter); }).getArtifacts().getArtifacts(); } private static Set<ResolvedArtifactResult> getArtifacts( final Configuration configuration, final Spec<ComponentIdentifier> filter, ImmutableList<String> artifactTypes) { ImmutableSet.Builder<ResolvedArtifactResult> artifactResultsBuilder = ImmutableSet.builder(); // We need to individually add these sets to the final set so as to maintain the order. // for eg. All aar artifact should come before jar artifacts. artifactTypes.forEach(artifactType -> artifactResultsBuilder.addAll( getArtifacts(configuration, artifactType, filter) .stream() .filter(it -> !it.getFile().getName().equals("classes.jar")) .collect(Collectors.toSet()) )); return artifactResultsBuilder.build(); } private void extractConfiguration(Configuration configuration) { Set<ComponentIdentifier> artifactIds = new HashSet<>(); Set<ResolvedArtifactResult> artifacts = getArtifacts(configuration, PROJECT_FILTER, ImmutableList.of("jar")); artifacts.forEach(artifact -> { if (!DependencyUtils.isConsumable(artifact.getFile())) { return; } ProjectComponentIdentifier identifier = (ProjectComponentIdentifier) artifact.getId() .getComponentIdentifier(); VariantAttr variantAttr = artifact.getVariant().getAttributes() .getAttribute(VariantAttr.ATTRIBUTE); String variant = variantAttr == null ? null : variantAttr.getName(); targetDeps.add(ProjectUtil.getTargetForVariant( project.project(identifier.getProjectPath()), variant)); }); artifacts = getArtifacts( configuration, EXTERNAL_DEP_FILTER, ImmutableList.of("aar", "jar")); artifacts.forEach( artifact -> { if (!DependencyUtils.isConsumable(artifact.getFile())) { return; } ComponentIdentifier identifier = artifact.getId().getComponentIdentifier(); artifactIds.add(identifier); if (identifier instanceof ModuleComponentIdentifier && ((ModuleComponentIdentifier) identifier).getVersion().length() > 0) { ModuleComponentIdentifier moduleIdentifier = (ModuleComponentIdentifier) identifier; String version = DependencyUtils.getModuleVersion( artifact.getFile().getName(), moduleIdentifier.getVersion()); ExternalDependency externalDependency = new ExternalDependency( moduleIdentifier.getGroup(), moduleIdentifier.getModule(), version, artifact.getFile() ); external.add(externalDependency); } else { String rootProjectPath = project.getRootProject().getProjectDir().getAbsolutePath(); String artifactPath = artifact.getFile().getAbsolutePath(); try { if (!FilenameUtils.directoryContains(rootProjectPath, artifactPath) && !DependencyUtils.isWhiteListed(artifact.getFile())) { throw new IllegalStateException(String.format( "Local dependencies should be under project root. Dependencies " + "outside the project can cause hard to reproduce builds" + ". Please move dependency: %s inside %s", artifact.getFile(), project.getRootProject().getProjectDir())); } external.add(ExternalDependency.fromLocal(artifact.getFile())); } catch (IOException e) { throw new RuntimeException(e); } } }); if (ProjectUtil.getOkBuckExtension(project).getIntellijExtension().sources) { ProjectUtil.downloadSources(project, artifactIds); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Scope scope = (Scope) o; return Objects.equals(javaResources, scope.javaResources) && Objects.equals(sources, scope.sources) && Objects.equals(jvmArgs, scope.jvmArgs) && Objects.equals(project, scope.project); } @Override public int hashCode() { return Objects.hash(javaResources, sources, jvmArgs, project); } }
package plugins.CENO.FreenetInterface; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.apache.commons.compress.utils.IOUtils; import org.freenetproject.freemail.wot.ConcurrentWoTConnection; import plugins.CENO.FreenetInterface.ConnectionOverview.NodeConnections; import freenet.client.ClientMetadata; import freenet.client.DefaultMIMETypes; import freenet.client.FetchContext; import freenet.client.FetchException; import freenet.client.FetchResult; import freenet.client.InsertBlock; import freenet.client.InsertContext; import freenet.client.InsertException; import freenet.client.async.ClientGetCallback; import freenet.client.async.ClientGetter; import freenet.client.async.ClientPutCallback; import freenet.keys.FreenetURI; import freenet.keys.InsertableClientSSK; import freenet.node.Node; import freenet.node.RequestClient; import freenet.node.RequestStarter; import freenet.pluginmanager.PluginRespirator; import freenet.support.api.Bucket; import freenet.support.api.RandomAccessBucket; import freenet.support.io.BucketTools; public class NodeInterface implements FreenetInterface { private Node node; private PluginRespirator pr; private FetchContext ULPRFC, localFC; private ConnectionOverview connectionOverview; private ConcurrentWoTConnection wotConnection; public NodeInterface(Node node, PluginRespirator pr) { this.node = node; this.pr = pr; this.connectionOverview = new ConnectionOverview(node); } public void initFetchContexts() { // Set up a FetchContext instance for Ultra-lightweight passive requests this.ULPRFC = HighLevelSimpleClientInterface.getFetchContext(); this.ULPRFC.canWriteClientCache = true; this.ULPRFC.maxNonSplitfileRetries = -1; this.ULPRFC.followRedirects = true; this.ULPRFC.allowSplitfiles = true; this.ULPRFC.maxRecursionLevel = 10; this.ULPRFC.maxTempLength = Long.MAX_VALUE; this.ULPRFC.maxOutputLength = Long.MAX_VALUE; this.localFC = HighLevelSimpleClientInterface.getFetchContext(); this.localFC.localRequestOnly = true; this.localFC.followRedirects = true; this.localFC.allowSplitfiles = true; this.localFC.maxRecursionLevel = 10; this.localFC.maxTempLength = Long.MAX_VALUE; this.localFC.maxOutputLength = Long.MAX_VALUE; wotConnection = new ConcurrentWoTConnection(pr); } @Override public FetchResult fetchURI(FreenetURI uri) throws FetchException { return HighLevelSimpleClientInterface.fetchURI(uri); } @Override public ClientGetter localFetchURI(FreenetURI uri, ClientGetCallback callback) throws FetchException { return HighLevelSimpleClientInterface.fetchURI(uri, Long.MAX_VALUE, callback, localFC); } @Override public ClientGetter fetchULPR(FreenetURI uri, ClientGetCallback callback) throws FetchException { return HighLevelSimpleClientInterface.fetchURI(uri, Long.MAX_VALUE, callback, ULPRFC); } /** * Generate a new key pair for SSK insertions * * @return FreenetURI array where first element is the insertURI and second element is the requestURI */ @Override public FreenetURI[] generateKeyPair() { InsertableClientSSK key = InsertableClientSSK.createRandom(node.random, ""); FreenetURI insertURI = key.getInsertURI(); FreenetURI requestURI = key.getURI(); return new FreenetURI[]{insertURI, requestURI}; } @Override public RequestClient getRequestClient() { return HighLevelSimpleClientInterface.getRequestClient(); } @Override public Bucket makeBucket(int length) throws IOException { return node.clientCore.persistentTempBucketFactory.makeBucket(length); } @Override public FreenetURI insertBundleManifest(FreenetURI insertURI, String content, String defaultName, ClientPutCallback insertCb) throws IOException, InsertException { String defName; if (defaultName == null || defaultName.isEmpty()) { defName = "default.html"; } else { defName = defaultName; } Bucket bucket = node.clientCore.tempBucketFactory.makeBucket(content.getBytes().length); BucketTools.copyFrom(bucket, new ByteArrayInputStream(content.getBytes()), content.getBytes().length); HashMap<String, Object> bucketsByName = new HashMap<String, Object>(); bucketsByName.put(defName, bucket); FreenetURI requestURI = HighLevelSimpleClientInterface.insertManifestCb(insertURI, bucketsByName, defName, RequestStarter.INTERACTIVE_PRIORITY_CLASS, null, insertCb); return requestURI; } @Override public boolean insertFreesite(FreenetURI insertURI, String docName, String content, ClientPutCallback insertCallback) throws IOException, InsertException { String mimeType = DefaultMIMETypes.guessMIMEType(docName, true); if(mimeType == null) { mimeType = "text/html"; } RandomAccessBucket bucket = node.clientCore.tempBucketFactory.makeBucket(content.length()); BucketTools.copyFrom(bucket, new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8), 0, content.length()), content.length()); InsertBlock ib = new InsertBlock(bucket, new ClientMetadata(mimeType), insertURI); InsertContext ictx = HighLevelSimpleClientInterface.getInsertContext(true); HighLevelSimpleClientInterface.insert(ib, docName, false, ictx, insertCallback, RequestStarter.INTERACTIVE_PRIORITY_CLASS); return true; } @Override public FreenetURI insertBlock(InsertBlock insert, boolean getCHKOnly, String filenameHint) throws InsertException { return HighLevelSimpleClientInterface.insert(insert, getCHKOnly, filenameHint); } @Override public FreenetURI insertManifest(FreenetURI insertURI, HashMap<String, Object> bucketsByName, String defaultName, short priorityClass) throws InsertException { return HighLevelSimpleClientInterface.insertManifest(insertURI, bucketsByName, defaultName, priorityClass); } @Override public NodeConnections getConnections() { return connectionOverview.getConnections(); } @Override public boolean sendFreemail(String freemailFrom, String freemailTo[], String subject, String content, String password) { return FreemailAPI.sendFreemail(freemailFrom, freemailTo, subject, content, password); } @Override public String[] getUnreadMailsSubject(String freemail, String password, String inboxFolder, boolean shouldDelete) { return FreemailAPI.getUnreadMailsSubject(freemail, password, inboxFolder, shouldDelete); } @Override public String[] getMailsContentFrom(String freemail, String freemailFrom, String password, String mailFolder) { return FreemailAPI.getMailsContentFrom(freemail, freemailFrom, password, mailFolder); } @Override public boolean copyAccprops(String freemailAccount) { return FreemailAPI.copyAccprops(freemailAccount); } @Override public boolean setRandomNextMsgNumber(String freemailAccount, String freemailTo) { return FreemailAPI.setRandomNextMsgNumber(freemailAccount, freemailTo); } @Override public boolean clearOutboxLog(String freemailAccount, String identityFrom) { return FreemailAPI.clearOutboxLog(freemailAccount, identityFrom); } @Override public boolean clearOutboxMessages(String freemailAccount, String freemailTo) { return FreemailAPI.clearOutboxMessages(freemailAccount, freemailTo); } }
package com.newsblur.network; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.text.TextUtils; import android.util.Log; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.newsblur.database.DatabaseConstants; import com.newsblur.database.FeedProvider; import com.newsblur.domain.Classifier; import com.newsblur.domain.Comment; import com.newsblur.domain.Feed; import com.newsblur.domain.FeedResult; import com.newsblur.domain.Reply; import com.newsblur.domain.SocialFeed; import com.newsblur.domain.Story; import com.newsblur.domain.UserProfile; import com.newsblur.domain.ValueMultimap; import com.newsblur.network.domain.CategoriesResponse; import com.newsblur.network.domain.FeedFolderResponse; import com.newsblur.network.domain.FeedRefreshResponse; import com.newsblur.network.domain.NewsBlurResponse; import com.newsblur.network.domain.ProfileResponse; import com.newsblur.network.domain.RegisterResponse; import com.newsblur.network.domain.StoriesResponse; import com.newsblur.network.domain.StoryTextResponse; import com.newsblur.network.domain.UnreadStoryHashesResponse; import com.newsblur.serialization.BooleanTypeAdapter; import com.newsblur.serialization.ClassifierMapTypeAdapter; import com.newsblur.serialization.DateStringTypeAdapter; import com.newsblur.serialization.FeedListTypeAdapter; import com.newsblur.serialization.StoryTypeAdapter; import com.newsblur.util.AppConstants; import com.newsblur.util.FeedSet; import com.newsblur.util.NetworkUtils; import com.newsblur.util.PrefConstants; import com.newsblur.util.PrefsUtils; import com.newsblur.util.ReadFilter; import com.newsblur.util.StoryOrder; public class APIManager { private Context context; private Gson gson; private ContentResolver contentResolver; private String customUserAgent; public APIManager(final Context context) { this.context = context; this.contentResolver = context.getContentResolver(); this.gson = new GsonBuilder() .registerTypeAdapter(Date.class, new DateStringTypeAdapter()) .registerTypeAdapter(Boolean.class, new BooleanTypeAdapter()) .registerTypeAdapter(boolean.class, new BooleanTypeAdapter()) .registerTypeAdapter(Story.class, new StoryTypeAdapter()) .registerTypeAdapter(new TypeToken<List<Feed>>(){}.getType(), new FeedListTypeAdapter()) .registerTypeAdapter(new TypeToken<Map<String,Classifier>>(){}.getType(), new ClassifierMapTypeAdapter()) .create(); String appVersion = context.getSharedPreferences(PrefConstants.PREFERENCES, 0).getString(AppConstants.LAST_APP_VERSION, "unknown_version"); this.customUserAgent = "NewsBlur Android app" + " (" + Build.MANUFACTURER + " " + Build.MODEL + " " + Build.VERSION.RELEASE + " " + appVersion + ")"; } public NewsBlurResponse login(final String username, final String password) { final ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_USERNAME, username); values.put(APIConstants.PARAMETER_PASSWORD, password); final APIResponse response = post(APIConstants.URL_LOGIN, values); NewsBlurResponse loginResponse = response.getResponse(gson); if (!response.isError()) { PrefsUtils.saveLogin(context, username, response.getCookie()); } return loginResponse; } public boolean setAutoFollow(boolean autofollow) { ContentValues values = new ContentValues(); values.put("autofollow_friends", autofollow ? "true" : "false"); final APIResponse response = post(APIConstants.URL_AUTOFOLLOW_PREF, values); return (!response.isError()); } public boolean addCategories(ArrayList<String> categories) { final ValueMultimap values = new ValueMultimap(); for (String category : categories) { values.put(APIConstants.PARAMETER_CATEGORY, URLEncoder.encode(category)); } final APIResponse response = post(APIConstants.URL_ADD_CATEGORIES, values, false); return (!response.isError()); } public NewsBlurResponse markFeedsAsRead(Set<String> feedIds, Long includeOlder, Long includeNewer) { ValueMultimap values = new ValueMultimap(); for (String feedId : feedIds) { values.put(APIConstants.PARAMETER_FEEDID, feedId); } if (includeOlder != null) { // the app uses milliseconds but the API wants seconds long cut = includeOlder.longValue(); values.put(APIConstants.PARAMETER_CUTOFF_TIME, Long.toString(cut/1000L)); values.put(APIConstants.PARAMETER_DIRECTION, APIConstants.VALUE_OLDER); } if (includeNewer != null) { // the app uses milliseconds but the API wants seconds long cut = includeNewer.longValue(); values.put(APIConstants.PARAMETER_CUTOFF_TIME, Long.toString(cut/1000L)); values.put(APIConstants.PARAMETER_DIRECTION, APIConstants.VALUE_NEWER); } APIResponse response = post(APIConstants.URL_MARK_FEED_AS_READ, values, false); // TODO: these calls use a different return format than others: the errors field is an array, not an object //return response.getResponse(gson, NewsBlurResponse.class); NewsBlurResponse nbr = new NewsBlurResponse(); if (response.isError()) nbr.message = "err"; return nbr; } public NewsBlurResponse markAllAsRead() { ValueMultimap values = new ValueMultimap(); values.put(APIConstants.PARAMETER_DAYS, "0"); APIResponse response = post(APIConstants.URL_MARK_ALL_AS_READ, values, false); // TODO: these calls use a different return format than others: the errors field is an array, not an object //return response.getResponse(gson, NewsBlurResponse.class); NewsBlurResponse nbr = new NewsBlurResponse(); if (response.isError()) nbr.message = "err"; return nbr; } public NewsBlurResponse markStoriesAsRead(List<String> storyHashes) { ValueMultimap values = new ValueMultimap(); for (String storyHash : storyHashes) { values.put(APIConstants.PARAMETER_STORY_HASH, storyHash); } APIResponse response = post(APIConstants.URL_MARK_STORIES_READ, values, false); return response.getResponse(gson, NewsBlurResponse.class); } public NewsBlurResponse markStoryAsRead(String storyHash) { ValueMultimap values = new ValueMultimap(); values.put(APIConstants.PARAMETER_STORY_HASH, storyHash); APIResponse response = post(APIConstants.URL_MARK_STORIES_READ, values, false); return response.getResponse(gson, NewsBlurResponse.class); } public NewsBlurResponse markStoryAsStarred(final String feedId, final String storyId) { final ValueMultimap values = new ValueMultimap(); values.put(APIConstants.PARAMETER_FEEDID, feedId); values.put(APIConstants.PARAMETER_STORYID, storyId); final APIResponse response = post(APIConstants.URL_MARK_STORY_AS_STARRED, values, false); return response.getResponse(gson, NewsBlurResponse.class); } public NewsBlurResponse markStoryAsUnstarred(final String feedId, final String storyId) { final ValueMultimap values = new ValueMultimap(); values.put(APIConstants.PARAMETER_FEEDID, feedId); values.put(APIConstants.PARAMETER_STORYID, storyId); final APIResponse response = post(APIConstants.URL_MARK_STORY_AS_UNSTARRED, values, false); return response.getResponse(gson, NewsBlurResponse.class); } public NewsBlurResponse markStoryAsUnread( String feedId, String storyId ) { final ValueMultimap values = new ValueMultimap(); values.put(APIConstants.PARAMETER_FEEDID, feedId); values.put(APIConstants.PARAMETER_STORYID, storyId); final APIResponse response = post(APIConstants.URL_MARK_STORY_AS_UNREAD, values, false); return response.getResponse(gson, NewsBlurResponse.class); } public NewsBlurResponse markStoryHashUnread(String hash) { final ValueMultimap values = new ValueMultimap(); values.put(APIConstants.PARAMETER_STORY_HASH, hash); APIResponse response = post(APIConstants.URL_MARK_STORY_HASH_UNREAD, values, false); return response.getResponse(gson, NewsBlurResponse.class); } public CategoriesResponse getCategories() { final APIResponse response = get(APIConstants.URL_CATEGORIES); if (!response.isError()) { CategoriesResponse categoriesResponse = (CategoriesResponse) response.getResponse(gson, CategoriesResponse.class); return categoriesResponse; } else { return null; } } public RegisterResponse signup(final String username, final String password, final String email) { final ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_USERNAME, username); values.put(APIConstants.PARAMETER_PASSWORD, password); values.put(APIConstants.PARAMETER_EMAIL, email); final APIResponse response = post(APIConstants.URL_SIGNUP, values); RegisterResponse registerResponse = ((RegisterResponse) response.getResponse(gson, RegisterResponse.class)); if (!response.isError()) { PrefsUtils.saveLogin(context, username, response.getCookie()); CookieSyncManager.createInstance(context.getApplicationContext()); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setCookie(APIConstants.COOKIE_DOMAIN, response.getCookie()); CookieSyncManager.getInstance().sync(); } return registerResponse; } public ProfileResponse updateUserProfile() { final APIResponse response = get(APIConstants.URL_MY_PROFILE); if (!response.isError()) { ProfileResponse profileResponse = (ProfileResponse) response.getResponse(gson, ProfileResponse.class); PrefsUtils.saveUserDetails(context, profileResponse.user); return profileResponse; } else { return null; } } public UnreadStoryHashesResponse getUnreadStoryHashes() { APIResponse response = get(APIConstants.URL_UNREAD_HASHES); return (UnreadStoryHashesResponse) response.getResponse(gson, UnreadStoryHashesResponse.class); } public StoriesResponse getStoriesByHash(List<String> storyHashes) { ValueMultimap values = new ValueMultimap(); for (String hash : storyHashes) { values.put(APIConstants.PARAMETER_H, hash); } APIResponse response = get(APIConstants.URL_RIVER_STORIES, values); return (StoriesResponse) response.getResponse(gson, StoriesResponse.class); } /** * Fetches stories for the given FeedSet, choosing the correct API and the right * request parameters as needed. */ public StoriesResponse getStories(FeedSet fs, int pageNumber, StoryOrder order, ReadFilter filter) { Uri uri = null; ValueMultimap values = new ValueMultimap(); // create the URI and populate request params depending on what kind of stories we want if (fs.getSingleFeed() != null) { uri = Uri.parse(APIConstants.URL_FEED_STORIES).buildUpon().appendPath(fs.getSingleFeed()).build(); values.put(APIConstants.PARAMETER_FEEDS, fs.getSingleFeed()); } else if (fs.getMultipleFeeds() != null) { uri = Uri.parse(APIConstants.URL_RIVER_STORIES); for (String feedId : fs.getMultipleFeeds()) values.put(APIConstants.PARAMETER_FEEDS, feedId); } else if (fs.getSingleSocialFeed() != null) { String feedId = fs.getSingleSocialFeed().getKey(); String username = fs.getSingleSocialFeed().getValue(); uri = Uri.parse(APIConstants.URL_SOCIALFEED_STORIES).buildUpon().appendPath(feedId).appendPath(username).build(); values.put(APIConstants.PARAMETER_USER_ID, feedId); values.put(APIConstants.PARAMETER_USERNAME, username); } else if (fs.getMultipleSocialFeeds() != null) { uri = Uri.parse(APIConstants.URL_SHARED_RIVER_STORIES); for (Map.Entry<String,String> entry : fs.getMultipleSocialFeeds().entrySet()) { values.put(APIConstants.PARAMETER_FEEDS, entry.getKey()); } } else if (fs.isAllNormal()) { uri = Uri.parse(APIConstants.URL_RIVER_STORIES); } else if (fs.isAllSocial()) { uri = Uri.parse(APIConstants.URL_SHARED_RIVER_STORIES); } else if (fs.isAllSaved()) { uri = Uri.parse(APIConstants.URL_STARRED_STORIES); } else { throw new IllegalStateException("Asked to get stories for FeedSet of unknown type."); } // request params common to all stories values.put(APIConstants.PARAMETER_PAGE_NUMBER, Integer.toString(pageNumber)); values.put(APIConstants.PARAMETER_ORDER, order.getParameterValue()); values.put(APIConstants.PARAMETER_READ_FILTER, filter.getParameterValue()); APIResponse response = get(uri.toString(), values); return (StoriesResponse) response.getResponse(gson, StoriesResponse.class); } public boolean followUser(final String userId) { final ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_USERID, userId); final APIResponse response = post(APIConstants.URL_FOLLOW, values); if (!response.isError()) { return true; } else { return false; } } public boolean unfollowUser(final String userId) { final ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_USERID, userId); final APIResponse response = post(APIConstants.URL_UNFOLLOW, values); if (!response.isError()) { return true; } else { return false; } } public Boolean shareStory(final String storyId, final String feedId, final String comment, final String sourceUserId) { final ContentValues values = new ContentValues(); if (!TextUtils.isEmpty(comment)) { values.put(APIConstants.PARAMETER_SHARE_COMMENT, comment); } if (!TextUtils.isEmpty(sourceUserId)) { values.put(APIConstants.PARAMETER_SHARE_SOURCEID, sourceUserId); } values.put(APIConstants.PARAMETER_FEEDID, feedId); values.put(APIConstants.PARAMETER_STORYID, storyId); final APIResponse response = post(APIConstants.URL_SHARE_STORY, values); if (!response.isError()) { return true; } else { return false; } } /** * Fetch the list of feeds/folders/socials from the backend. * * @param doUpdateCounts forces a refresh of unread counts. This has a high latency * cost and should not be set if the call is being used to display the UI for * the first time, in which case it is more appropriate to make a separate, * additional call to refreshFeedCounts(). */ public FeedFolderResponse getFolderFeedMapping(boolean doUpdateCounts) { ContentValues params = new ContentValues(); params.put( APIConstants.PARAMETER_UPDATE_COUNTS, (doUpdateCounts ? "true" : "false") ); APIResponse response = get(APIConstants.URL_FEEDS, params); if (response.isError()) { Log.e(this.getClass().getName(), "Error fetching feeds: " + response.getErrorMessage()); return null; } // note: this response is complex enough, we have to do a custom parse in the FFR return new FeedFolderResponse(response.getResponseBody(), gson); } public NewsBlurResponse trainClassifier(String feedId, String key, int type, int action) { String typeText = null; String actionText = null; switch (type) { case Classifier.AUTHOR: typeText = "author"; break; case Classifier.TAG: typeText = "tag"; break; case Classifier.TITLE: typeText = "title"; break; case Classifier.FEED: typeText = "feed"; break; } switch (action) { case Classifier.CLEAR_LIKE: actionText = "remove_like_"; break; case Classifier.CLEAR_DISLIKE: actionText = "remove_dislike_"; break; case Classifier.LIKE: actionText = "like_"; break; case Classifier.DISLIKE: actionText = "dislike_"; break; } StringBuilder builder = new StringBuilder();; builder.append(actionText); builder.append(typeText); ContentValues values = new ContentValues(); if (type == Classifier.FEED) { values.put(builder.toString(), feedId); } else { values.put(builder.toString(), key); } values.put(APIConstants.PARAMETER_FEEDID, feedId); final APIResponse response = post(APIConstants.URL_CLASSIFIER_SAVE, values); return response.getResponse(gson, NewsBlurResponse.class); } public ProfileResponse getUser(String userId) { final ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_USER_ID, userId); final APIResponse response = get(APIConstants.URL_USER_PROFILE, values); if (!response.isError()) { ProfileResponse profileResponse = (ProfileResponse) response.getResponse(gson, ProfileResponse.class); return profileResponse; } else { return null; } } public StoryTextResponse getStoryText(String feedId, String storyId) { final ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_FEEDID, feedId); values.put(APIConstants.PARAMETER_STORYID, storyId); final APIResponse response = get(APIConstants.URL_STORY_TEXT, values); if (!response.isError()) { StoryTextResponse storyTextResponse = (StoryTextResponse) response.getResponse(gson, StoryTextResponse.class); return storyTextResponse; } else { return null; } } public boolean favouriteComment(String storyId, String commentId, String feedId) { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_STORYID, storyId); values.put(APIConstants.PARAMETER_STORY_FEEDID, feedId); values.put(APIConstants.PARAMETER_COMMENT_USERID, commentId); final APIResponse response = post(APIConstants.URL_LIKE_COMMENT, values); return (!response.isError()); } public Boolean unFavouriteComment(String storyId, String commentId, String feedId) { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_STORYID, storyId); values.put(APIConstants.PARAMETER_STORY_FEEDID, feedId); values.put(APIConstants.PARAMETER_COMMENT_USERID, commentId); final APIResponse response = post(APIConstants.URL_UNLIKE_COMMENT, values); return (!response.isError()); } public boolean replyToComment(String storyId, String storyFeedId, String commentUserId, String reply) { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_STORYID, storyId); values.put(APIConstants.PARAMETER_STORY_FEEDID, storyFeedId); values.put(APIConstants.PARAMETER_COMMENT_USERID, commentUserId); values.put(APIConstants.PARAMETER_REPLY_TEXT, reply); final APIResponse response = post(APIConstants.URL_REPLY_TO, values); return (!response.isError()); } public boolean addFeed(String feedUrl, String folderName) { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_URL, feedUrl); if (!TextUtils.isEmpty(folderName)) { values.put(APIConstants.PARAMETER_FOLDER, folderName); } final APIResponse response = post(APIConstants.URL_ADD_FEED, values); return (!response.isError()); } public FeedResult[] searchForFeed(String searchTerm) throws ServerErrorException { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_FEED_SEARCH_TERM, searchTerm); final APIResponse response = get(APIConstants.URL_FEED_AUTOCOMPLETE, values); if (!response.isError()) { return gson.fromJson(response.getResponseBody(), FeedResult[].class); } else { return null; } } public NewsBlurResponse deleteFeed(long feedId, String folderName) { ContentValues values = new ContentValues(); values.put(APIConstants.PARAMETER_FEEDID, Long.toString(feedId)); if ((!TextUtils.isEmpty(folderName)) && (!folderName.equals(AppConstants.ROOT_FOLDER))) { values.put(APIConstants.PARAMETER_IN_FOLDER, folderName); } APIResponse response = post(APIConstants.URL_DELETE_FEED, values); return response.getResponse(gson, NewsBlurResponse.class); } /* HTTP METHODS */ private APIResponse get(final String urlString) { APIResponse response; int tryCount = 0; do { backoffSleep(tryCount++); response = get_single(urlString); } while ((response.isError()) && (tryCount < AppConstants.MAX_API_TRIES)); return response; } private APIResponse get_single(final String urlString) { if (!NetworkUtils.isOnline(context)) { return new APIResponse(context); } try { URL url = new URL(urlString); if (AppConstants.VERBOSE_LOG) { Log.d(this.getClass().getName(), "API GET " + url ); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); SharedPreferences preferences = context.getSharedPreferences(PrefConstants.PREFERENCES, 0); String cookie = preferences.getString(PrefConstants.PREF_COOKIE, null); if (cookie != null) { connection.setRequestProperty("Cookie", cookie); } connection.setRequestProperty("User-Agent", this.customUserAgent); return new APIResponse(context, url, connection); } catch (IOException e) { Log.e(this.getClass().getName(), "Error opening GET connection to " + urlString, e.getCause()); return new APIResponse(context); } } private APIResponse get(final String urlString, final ContentValues values) { List<String> parameters = new ArrayList<String>(); for (Entry<String, Object> entry : values.valueSet()) { StringBuilder builder = new StringBuilder(); builder.append((String) entry.getKey()); builder.append("="); builder.append(URLEncoder.encode((String) entry.getValue())); parameters.add(builder.toString()); } return this.get(urlString + "?" + TextUtils.join("&", parameters)); } private APIResponse get(final String urlString, final ValueMultimap valueMap) { return this.get(urlString + "?" + valueMap.getParameterString()); } private APIResponse post(String urlString, String postBodyString) { APIResponse response; int tryCount = 0; do { backoffSleep(tryCount++); response = post_single(urlString, postBodyString); } while ((response.isError()) && (tryCount < AppConstants.MAX_API_TRIES)); return response; } private APIResponse post_single(String urlString, String postBodyString) { if (!NetworkUtils.isOnline(context)) { return new APIResponse(context); } try { URL url = new URL(urlString); if (AppConstants.VERBOSE_LOG) { Log.d(this.getClass().getName(), "API POST " + url ); Log.d(this.getClass().getName(), "post body: " + postBodyString); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setFixedLengthStreamingMode(postBodyString.getBytes().length); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); SharedPreferences preferences = context.getSharedPreferences(PrefConstants.PREFERENCES, 0); String cookie = preferences.getString(PrefConstants.PREF_COOKIE, null); if (cookie != null) { connection.setRequestProperty("Cookie", cookie); } PrintWriter printWriter = new PrintWriter(connection.getOutputStream()); printWriter.print(postBodyString); printWriter.close(); return new APIResponse(context, url, connection); } catch (IOException e) { Log.e(this.getClass().getName(), "Error opening POST connection to " + urlString + ": " + e.getCause(), e.getCause()); return new APIResponse(context); } } private APIResponse post(final String urlString, final ContentValues values) { List<String> parameters = new ArrayList<String>(); for (Entry<String, Object> entry : values.valueSet()) { final StringBuilder builder = new StringBuilder(); builder.append((String) entry.getKey()); builder.append("="); try { builder.append(URLEncoder.encode((String) entry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { Log.e(this.getClass().getName(), e.getLocalizedMessage()); return new APIResponse(context); } parameters.add(builder.toString()); } final String parameterString = TextUtils.join("&", parameters); return this.post(urlString, parameterString); } private APIResponse post(final String urlString, final ValueMultimap valueMap, boolean jsonIfy) { String parameterString = jsonIfy ? valueMap.getJsonString() : valueMap.getParameterString(); return this.post(urlString, parameterString); } /** * Pause for the sake of exponential retry-backoff as apropriate before the Nth call as counted * by the zero-indexed tryCount. */ private void backoffSleep(int tryCount) { if (tryCount == 0) return; Log.i(this.getClass().getName(), "API call failed, pausing before retry number " + tryCount); try { // simply double the base sleep time for each subsequent try long factor = Math.round(Math.pow(2.0d, tryCount)); Thread.sleep(AppConstants.API_BACKOFF_BASE_MILLIS * factor); } catch (InterruptedException ie) { Log.w(this.getClass().getName(), "Abandoning API backoff due to interrupt."); } } /** * Convenience method to call contentResolver.bulkInsert using a list rather than an array. */ private int bulkInsertList(Uri uri, List<ContentValues> list) { if (list.size() > 0) { return contentResolver.bulkInsert(uri, list.toArray(new ContentValues[list.size()])); } return 0; } }
package io.cloudslang.lang.cli; import io.cloudslang.lang.runtime.events.LanguageEventData; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.log4j.Logger; import io.cloudslang.lang.cli.services.ScoreServices; import io.cloudslang.lang.cli.utils.CompilerHelper; import io.cloudslang.score.events.EventConstants; import io.cloudslang.score.events.ScoreEvent; import io.cloudslang.score.events.ScoreEventListener; import io.cloudslang.lang.entities.CompilationArtifact; import io.cloudslang.lang.entities.ScoreLangConstants; import io.cloudslang.lang.entities.bindings.Input; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.*; /** * @author lesant * @since 11/07/2014 * @version $Id$ */ @Component public class SlangCLI implements CommandMarker { public static final String TRIGGERED_FLOW_MSG = "Triggered flow : "; public static final String WITH_EXECUTION_ID_MSG = "Execution id: "; public static final String FLOW_EXECUTION_TIME_TOOK = ", duration: "; private static final String CURRENTLY = "You are CURRENTLY running CloudSlang version: "; private final static Logger logger = Logger.getLogger(SlangCLI.class); @Autowired private ScoreServices scoreServices; @Autowired private CompilerHelper compilerHelper; @Value("${slang.version}") private String slangVersion; /** * This global param holds the state of the CLI, if flows need to run in ASYNC or in SYNC manner. */ private Boolean triggerAsync = false; @CliCommand(value = "run", help = "triggers a CloudSlang flow") public String run( @CliOption(key = {"", "f", "file"}, mandatory = true, help = "Path to filename. e.g. cslang run --f C:\\CloudSlang\\flow.yaml") final File file, @CliOption(key = {"cp", "classpath"}, mandatory = false, help = "Classpath , a directory comma separated list to flow dependencies, by default it will take flow file dir") final List<String> classPath, @CliOption(key = {"i", "inputs"}, mandatory = false, help = "inputs in a key=value comma separated list") final Map<String,? extends Serializable> inputs, @CliOption(key = {"if", "input-file"}, mandatory = false, help = "comma separated list of input file locations") final List<String> inputFiles, @CliOption(key = {"", "q", "quiet"}, mandatory = false, help = "quiet", specifiedDefaultValue = "true",unspecifiedDefaultValue = "false") final Boolean quiet, @CliOption(key = {"spf", "system-property-file"}, mandatory = false, help = "comma separated list of system property file locations") final List<String> systemPropertyFiles) throws IOException { CompilationArtifact compilationArtifact = compilerHelper.compile(file.getAbsolutePath(), classPath); Map<String, ? extends Serializable> systemProperties = compilerHelper.loadSystemProperties(systemPropertyFiles); Map<String, ? extends Serializable> inputsFromFile = compilerHelper.loadInputsFromFile(inputFiles); Map<String, Serializable> mergedInputs = new HashMap<>(); if(MapUtils.isNotEmpty(inputsFromFile)){ mergedInputs.putAll(inputsFromFile); } if(MapUtils.isNotEmpty(inputs)) { mergedInputs.putAll(inputs); } Long id; if (!triggerAsync) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); id = scoreServices.triggerSync(compilationArtifact, mergedInputs, systemProperties, quiet); stopWatch.stop(); return quiet ? StringUtils.EMPTY : triggerSyncMsg(id, stopWatch.toString()); } id = scoreServices.trigger(compilationArtifact, mergedInputs, systemProperties); return quiet ? StringUtils.EMPTY : triggerAsyncMsg(id, compilationArtifact.getExecutionPlan().getName()); } @CliCommand(value = "env", help = "Set environment var relevant to the CLI") public String setEnvVar( @CliOption(key = "setAsync", mandatory = true, help = "set the async") final boolean switchAsync) throws IOException { triggerAsync = switchAsync; return setEnvMessage(triggerAsync); } @CliCommand(value = "inputs", help = "Get flow inputs") public List<String> getFlowInputs( @CliOption(key = {"", "f", "file"}, mandatory = true, help = "Path to filename. e.g. cslang inputs --f C:\\CloudSlang\\flow.yaml") final File file, @CliOption(key = {"cp", "classpath"}, mandatory = false, help = "Classpath , a directory comma separated list to flow dependencies, by default it will take flow file dir") final List<String> classPath) throws IOException { CompilationArtifact compilationArtifact = compilerHelper.compile(file.getAbsolutePath(), classPath); List<Input> inputs = compilationArtifact.getInputs(); List<String> inputsResult = new ArrayList<>(); for (Input input : inputs) { if (input.isOverridable()) { inputsResult.add(input.getName()); } } return inputsResult; } @CliCommand(value = "cslang --version", help = "Prints the CloudSlang version used") public String version() { return CURRENTLY + slangVersion; } public static String triggerSyncMsg(Long id, String duration) { return WITH_EXECUTION_ID_MSG + id + FLOW_EXECUTION_TIME_TOOK + duration; } public static String triggerAsyncMsg(Long id, String flowName) { return TRIGGERED_FLOW_MSG + flowName + WITH_EXECUTION_ID_MSG + id; } public static String setEnvMessage(boolean triggerAsync) { return "flow execution ASYNC execution was changed to : " + triggerAsync; } @PostConstruct private void registerEventHandlers() { Set<String> slangHandlerTypes = new HashSet<>(); slangHandlerTypes.add(ScoreLangConstants.EVENT_ACTION_START); slangHandlerTypes.add(ScoreLangConstants.EVENT_ACTION_END); slangHandlerTypes.add(ScoreLangConstants.EVENT_ACTION_ERROR); slangHandlerTypes.add(ScoreLangConstants.EVENT_TASK_START); slangHandlerTypes.add(ScoreLangConstants.EVENT_INPUT_START); slangHandlerTypes.add(ScoreLangConstants.EVENT_INPUT_END); slangHandlerTypes.add(ScoreLangConstants.EVENT_OUTPUT_START); slangHandlerTypes.add(ScoreLangConstants.EVENT_OUTPUT_END); slangHandlerTypes.add(ScoreLangConstants.EVENT_BRANCH_START); slangHandlerTypes.add(ScoreLangConstants.EVENT_BRANCH_END); slangHandlerTypes.add(ScoreLangConstants.EVENT_SPLIT_BRANCHES); slangHandlerTypes.add(ScoreLangConstants.EVENT_JOIN_BRANCHES_START); slangHandlerTypes.add(ScoreLangConstants.EVENT_JOIN_BRANCHES_END); slangHandlerTypes.add(ScoreLangConstants.SLANG_EXECUTION_EXCEPTION); slangHandlerTypes.add(ScoreLangConstants.EVENT_EXECUTION_FINISHED); Set<String> scoreHandlerTypes = new HashSet<>(); scoreHandlerTypes.add(EventConstants.SCORE_FINISHED_EVENT); scoreHandlerTypes.add(EventConstants.SCORE_ERROR_EVENT); scoreHandlerTypes.add(EventConstants.SCORE_FAILURE_EVENT); scoreServices.subscribe(new ScoreEventListener() { @Override public void onEvent(ScoreEvent event) { logSlangEvent(event); } }, slangHandlerTypes); scoreServices.subscribe(new ScoreEventListener() { @Override public void onEvent(ScoreEvent event) { logScoreEvent(event); } }, scoreHandlerTypes); } private void logSlangEvent(ScoreEvent event) { LanguageEventData eventData = (LanguageEventData) event.getData(); logger.info(("[ " + eventData.getPath() + " - " + eventData.getStepName() + " ] " + event.getEventType() + " - Inputs: " + eventData.getInputs() + ", Outputs: " + eventData.getOutputs() + ", Result: " + eventData.getResult() + ", Raw Data: " + event.getData() )); } private void logScoreEvent(ScoreEvent event) { logger.info((event.getEventType() + " - " + event.getData())); } }
package org.col.resources; import java.util.List; import javax.validation.Valid; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import org.apache.ibatis.session.SqlSession; import org.col.api.model.Duplicate; import org.col.api.model.Page; import org.col.api.vocab.EqualityMode; import org.col.api.vocab.TaxonomicStatus; import org.col.dao.DuplicateDao; import org.gbif.nameparser.api.Rank; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/dataset/{datasetKey}/duplicate") @Produces(MediaType.APPLICATION_JSON) public class DuplicateResource { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(DuplicateResource.class); public DuplicateResource() { } @GET public List<Duplicate> find(@PathParam("datasetKey") int datasetKey, @QueryParam("mode") EqualityMode mode, @QueryParam("rank") Rank rank, @QueryParam("status1") TaxonomicStatus status1, @QueryParam("status2") TaxonomicStatus status2, @QueryParam("parentDifferent") Boolean parentDifferent, @Valid @BeanParam Page page, @Context SqlSession session) { DuplicateDao dao = new DuplicateDao(session); return dao.find(datasetKey, mode, rank, status1, status2, parentDifferent, page); } }
package com.pg85.otg.generator.resource; import com.pg85.otg.OTG; import com.pg85.otg.common.LocalWorld; import com.pg85.otg.configuration.ConfigFunction; import com.pg85.otg.configuration.biome.BiomeConfig; import com.pg85.otg.customobjects.CustomObject; import com.pg85.otg.exception.InvalidConfigException; import com.pg85.otg.logging.LogMarker; import com.pg85.otg.util.ChunkCoordinate; import java.util.ArrayList; import java.util.List; import java.util.Random; public class TreeGen extends Resource { private final List<Integer> treeChances; private final List<String> treeNames; private CustomObject[] treeObjects; private int[] treeObjectMinChances; private int[] treeObjectMaxChances; private boolean treesLoaded = false; public TreeGen(BiomeConfig biomeConfig, List<String> args) throws InvalidConfigException { super(biomeConfig); assureSize(3, args); frequency = readInt(args.get(0), 1, 100); treeNames = new ArrayList<String>(); treeChances = new ArrayList<Integer>(); for (int i = 1; i < args.size() - 1; i += 2) { treeNames.add(args.get(i)); treeChances.add(readInt(args.get(i + 1), 1, 100)); } } @Override public boolean equals(Object other) { if (!super.equals(other)) return false; if (other == null) return false; if (other == this) return true; if (getClass() != other.getClass()) return false; final TreeGen compare = (TreeGen) other; return (this.treeNames == null ? this.treeNames == compare.treeNames : this.treeNames.equals(compare.treeNames)) && (this.treeChances == null ? this.treeChances == compare.treeChances : this.treeChances.equals(compare.treeChances)); } @Override public int getPriority() { return -31; } @Override public int hashCode() { int hash = 3; hash = 53 * hash + super.hashCode(); hash = 53 * hash + (this.treeNames != null ? this.treeNames.hashCode() : 0); hash = 53 * hash + (this.treeChances != null ? this.treeChances.hashCode() : 0); return hash; } @Override public boolean isAnalogousTo(ConfigFunction<BiomeConfig> other) { if (getClass() == other.getClass()) { try { TreeGen otherO = (TreeGen) other; return otherO.treeNames.size() == this.treeNames.size() && otherO.treeNames.containsAll(this.treeNames); } catch (Exception ex) { OTG.log(LogMarker.WARN, ex.getMessage()); } } return false; } @Override public String toString() { String output = "Tree(" + frequency; for (int i = 0; i < treeNames.size(); i++) { output += "," + treeNames.get(i) + "," + treeChances.get(i); } return output + ")"; } @Override public void spawn(LocalWorld world, Random random, boolean villageInChunk, int x, int z, ChunkCoordinate chunkBeingPopulated) { // Left blank, as spawnInChunk already handles this } // TODO: Could this cause problems for developer mode / flushcache, trees not updating during a session? private void loadTrees(String worldName) { if(!treesLoaded) { treesLoaded = true; treeObjects = new CustomObject[treeNames.size()]; treeObjectMinChances = new int[treeNames.size()]; treeObjectMaxChances = new int[treeNames.size()]; for (int treeNumber = 0; treeNumber < treeNames.size(); treeNumber++) { String treeName = treeNames.get(treeNumber); CustomObject tree = null; int minHeight = -1; int maxHeight = -1; treeObjectMinChances[treeNumber] = minHeight; treeObjectMaxChances[treeNumber] = maxHeight; if(treeName.contains("(")) { String[] params = treeName.replace(")", "").split("\\("); treeName = params[0]; tree = OTG.getCustomObjectManager().getGlobalObjects().getObjectByName(treeName, worldName); treeObjects[treeNumber] = tree; if(tree == null) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "Error: Could not find BO3 for Tree, BO3: " + treeNames.get(treeNumber)); } continue; } params = params[1].split(";"); String sMinHeight = params[0].toLowerCase().replace("minheight=", ""); String sMaxHeight = params[1].toLowerCase().replace("maxheight=", ""); try { minHeight = Integer.parseInt(sMinHeight); maxHeight = Integer.parseInt(sMaxHeight); treeObjectMinChances[treeNumber] = minHeight; treeObjectMaxChances[treeNumber] = maxHeight; } catch(NumberFormatException ex) { } } else { tree = OTG.getCustomObjectManager().getGlobalObjects().getObjectByName(treeName, worldName); treeObjects[treeNumber] = tree; if(tree == null) { if(OTG.getPluginConfig().spawnLog) { OTG.log(LogMarker.WARN, "Error: Could not find BO3 for Tree, BO3: " + treeNames.get(treeNumber)); } continue; } } } } } @Override protected void spawnInChunk(LocalWorld world, Random random, boolean villageInChunk, ChunkCoordinate chunkCoord) { // TODO: Make sure we stay within population bounds, anything outside won't be spawned (unless it's in an existing chunk). loadTrees(world.getName()); for (int i = 0; i < frequency; i++) { for (int treeNumber = 0; treeNumber < treeNames.size(); treeNumber++) { if (random.nextInt(100) < treeChances.get(treeNumber)) { int x = chunkCoord.getBlockXCenter() + random.nextInt(ChunkCoordinate.CHUNK_SIZE); int z = chunkCoord.getBlockZCenter() + random.nextInt(ChunkCoordinate.CHUNK_SIZE); CustomObject tree = treeObjects[treeNumber]; // Min/Max == -1 means use bo2/bo3 internal min/max height, otherwise use the optional min/max height defined with Tree() if(tree != null && tree.spawnAsTree(world, random, x, z, treeObjectMinChances[treeNumber], treeObjectMaxChances[treeNumber], chunkCoord)) { // Success! break; } } } } } }
package org.ardverk.dht.storage; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.security.MessageDigest; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.http.Header; import org.ardverk.collection.CollectionUtils; import org.ardverk.dht.KUID; import org.ardverk.dht.rsrc.Key; import org.ardverk.dht.rsrc.KeyFactory; import org.ardverk.security.MessageDigestUtils; import org.ardverk.utils.StringUtils; public class Index implements Closeable { private static final String CREATE_KEYS = "CREATE TABLE keys (" + "id BINARY(20) PRIMARY KEY," // sha1(key) + "key VARCHAR(16384) UNIQUE NOT NULL," + "created DATETIME NOT NULL," + "modified TIMESTAMP NOT NULL" + ")"; private static final String CREATE_VALUES = "CREATE TABLE entries (" // Using 'entries' because 'values' is a reserved keyword + "id BINARY(20) PRIMARY KEY," + "kid BINARY(20) FOREIGN KEY REFERENCES keys(id)," + "created DATETIME NOT NULL" + ")"; private static final String CREATE_PROPERTIES = "CREATE TABLE properties (" + "id BIGINT PRIMARY KEY IDENTITY," + "vid BINARY(20) FOREIGN KEY REFERENCES entries(id)," + "name VARCHAR(256) NOT NULL," + "value VARCHAR(16384) NOT NULL," + ")"; public static Index create(File dir) { try { Class.forName("org.hsqldb.jdbcDriver"); String url = "jdbc:hsqldb:mem:index"; String user = "sa"; String password = ""; Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); statement.execute(CREATE_KEYS); statement.execute(CREATE_VALUES); statement.execute(CREATE_PROPERTIES); statement.close(); return new Index(connection); } catch (ClassNotFoundException e) { throw new IllegalStateException("ClassNotFoundException", e); } catch (SQLException e) { throw new IllegalStateException("SQLException", e); } } private final Connection connection; private Index(Connection connection) { this.connection = connection; } @Override public void close() throws IOException { try { connection.close(); } catch (SQLException err) { throw new IOException("SQLException", err); } } public boolean containsKey(Key key) throws SQLException { String path = key.getPath(); byte[] kid = hash(path); return containsKey(kid); } private boolean containsKey(byte[] kid) throws SQLException { return contains("SELECT COUNT(id) FROM keys WHERE id = ?", kid); } public boolean containsValue(KUID valueId) throws SQLException { return containsValue(valueId.getBytes(false)); } private boolean containsValue(byte[] vid) throws SQLException { return contains("SELECT COUNT(id) FROM entries WHERE id = ?", vid); } private boolean contains(String sql, byte[] key) throws SQLException { PreparedStatement ps = connection.prepareStatement(sql); try { ps.setBytes(1, key); ResultSet rs = ps.executeQuery(); try { if (rs.next()) { return 0 < rs.getInt(1); } } finally { close(rs); } } finally { close(ps); } return false; } @SuppressWarnings("unchecked") public Map.Entry<KUID, Context>[] get(Key key) throws SQLException { String path = key.getPath(); byte[] kid = hash(path); PreparedStatement ps = connection.prepareStatement( "SELECT e.id, p.name, p.value FROM entries e, properties p WHERE e.kid = ? AND e.id = p.vid"); try { ps.setBytes(1, kid); ResultSet rs = ps.executeQuery(); try { if (rs.next()) { Map<KUID, Context> map = new HashMap<KUID, Context>(); Context context = null; byte[] current = null; do { byte[] vid = rs.getBytes(1); if (!Arrays.equals(current, vid)) { context = new Context(); map.put(KUID.create(vid), context); } String name = rs.getString(2); String value = rs.getString(3); context.addHeader(name, value); } while (rs.next()); Set<Map.Entry<KUID, Context>> entries = map.entrySet(); return CollectionUtils.toArray(entries, Map.Entry.class); } return null; } finally { close(rs); } } finally { close(ps); } } public Context get(KUID valueId) throws SQLException { byte[] vid = valueId.getBytes(); PreparedStatement ps = connection.prepareStatement( "SELECT name, value FROM properties WHERE vid = ?"); try { ps.setBytes(1, vid); ResultSet rs = ps.executeQuery(); try { Context context = null; if (rs.next()) { context = new Context(); do { String name = rs.getString(1); String value = rs.getString(2); context.addHeader(name, value); } while (rs.next()); } return context; } finally { close(rs); } } finally { close(ps); } } public void add(Key key, Context context, KUID valueId) throws SQLException { long now = System.currentTimeMillis(); Date created = new Date(now); Timestamp modified = new Timestamp(now); String path = key.getPath(); byte[] kid = hash(path); try { connection.setAutoCommit(false); // KEYS { PreparedStatement ps = null; try { if (!containsKey(kid)) { ps = connection.prepareStatement( "INSERT INTO keys NAMES(id, key, created, modified) VALUES(?, ?, ?, ?)"); ps.setBytes(1, kid); ps.setString(2, path); ps.setDate(3, created); ps.setTimestamp(4, modified); } else { ps = connection.prepareStatement( "UPDATE keys SET modified = ? WHERE id = ?"); ps.setTimestamp(1, modified); ps.setBytes(2, kid); } ps.executeUpdate(); } finally { close(ps); } } byte[] vid = valueId.getBytes(false); // ENTRIES { PreparedStatement ps = connection.prepareStatement( "INSERT INTO entries NAMES(id, kid, created) VALUES(?, ?, ?)"); try { ps.setBytes(1, vid); ps.setBytes(2, kid); ps.setDate(3, created); ps.executeUpdate(); } finally { close(ps); } } // PROPERTIES { PreparedStatement ps = connection.prepareStatement( "INSERT INTO properties NAMES(vid, name, value) VALUES(?, ?, ?)"); try { for (Header header : context.getHeaders()) { ps.setBytes(1, vid); ps.setString(2, header.getName()); ps.setString(3, header.getValue()); ps.addBatch(); } ps.executeBatch(); } finally { close(ps); } } connection.commit(); } finally { connection.setAutoCommit(true); } } private static byte[] hash(String value) { MessageDigest md = MessageDigestUtils.createSHA1(); return md.digest(StringUtils.getBytes(value)); } public static void main(String[] args) throws Exception { Index index = Index.create(null); Key key = KeyFactory.parseKey("ardverk:///hello/world"); for (int i = 0; i < 10; i++) { KUID valueId = KUID.createRandom(key.getId()); Context context = new Context(); context.addHeader("name1-" + i, "value1"); context.addHeader("name2-" + i, "value2"); index.add(key, context, valueId); System.out.println(index.get(valueId)); } System.out.println(Arrays.toString(index.get(key))); } private static void close(Statement s) { if (s != null) { try { s.close(); } catch (SQLException err) {} } } private static void close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException err) {} } } }
package com.yahoo.vespa.model.admin; import com.yahoo.cloud.config.SlobroksConfig; import com.yahoo.cloud.config.ZookeepersConfig; import com.yahoo.cloud.config.log.LogdConfig; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.model.ConfigModelContext.ApplicationType; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.AbstractService; import com.yahoo.vespa.model.ConfigProxy; import com.yahoo.vespa.model.ConfigSentinel; import com.yahoo.vespa.model.HostResource; import com.yahoo.vespa.model.Logd; import com.yahoo.vespa.model.admin.clustercontroller.ClusterControllerContainerCluster; import com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainer; import com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster; import com.yahoo.vespa.model.admin.monitoring.Monitoring; import com.yahoo.vespa.model.admin.monitoring.builder.Metrics; import com.yahoo.vespa.model.filedistribution.FileDistributionConfigProducer; import com.yahoo.vespa.model.filedistribution.FileDistributionConfigProvider; import com.yahoo.vespa.model.filedistribution.FileDistributor; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * This is the admin pseudo-plugin of the Vespa model, responsible for * creating all admin services. * * @author gjoranv */ public class Admin extends AbstractConfigProducer implements Serializable { private static final long serialVersionUID = 1L; private final boolean isHostedVespa; private final Monitoring monitoring; private final Metrics metrics; private final List<Configserver> configservers = new ArrayList<>(); private final List<Slobrok> slobroks = new ArrayList<>(); private Configserver defaultConfigserver; /** The log server, or null if none */ private Logserver logserver; private LogForwarder.Config logForwarderConfig = null; private ApplicationType applicationType = ApplicationType.DEFAULT; public void setLogForwarderConfig(LogForwarder.Config cfg) { this.logForwarderConfig = cfg; } /** * The single cluster controller cluster shared by all content clusters by default when not multitenant. * If multitenant, this is null. */ private ClusterControllerContainerCluster clusterControllers; // Cluster of logserver containers. If enabled, exactly one container is running on each logserver host. private Optional<LogserverContainerCluster> logServerContainerCluster = Optional.empty(); // Cluster of metricsproxy containers. Exactly one container is set up on all hosts. private MetricsProxyContainerCluster metricsProxyContainerCluster; private ZooKeepersConfigProvider zooKeepersConfigProvider; private FileDistributionConfigProducer fileDistribution; private final boolean multitenant; public Admin(AbstractConfigProducer parent, Monitoring monitoring, Metrics metrics, boolean multitenant, FileDistributionConfigProducer fileDistributionConfigProducer, boolean isHostedVespa) { super(parent, "admin"); this.isHostedVespa = isHostedVespa; this.monitoring = monitoring; this.metrics = metrics; this.multitenant = multitenant; this.fileDistribution = fileDistributionConfigProducer; } public Configserver getConfigserver() { return defaultConfigserver; } /** Returns the configured monitoring endpoint, or null if not configured */ public Monitoring getMonitoring() { return monitoring; } public Metrics getUserMetrics() { return metrics; } /** Returns a list of all config servers */ public List<Configserver> getConfigservers() { return configservers; } public void removeSlobroks() { slobroks.clear(); } /** Returns an immutable list of the slobroks in this */ public List<Slobrok> getSlobroks() { return Collections.unmodifiableList(slobroks); } public void setLogserver(Logserver logserver) { this.logserver = logserver; } /** Returns the log server for this, or null if none */ public Logserver getLogserver() { return logserver; } public void addConfigservers(List<Configserver> configservers) { this.configservers.addAll(configservers); if (this.configservers.size() > 0) { this.defaultConfigserver = configservers.get(0); } this.zooKeepersConfigProvider = new ZooKeepersConfigProvider(configservers); } public void addSlobroks(List<Slobrok> slobroks) { this.slobroks.addAll(slobroks); } public ClusterControllerContainerCluster getClusterControllers() { return clusterControllers; } public void setClusterControllers(ClusterControllerContainerCluster clusterControllers) { if (multitenant) throw new RuntimeException("Should not use admin cluster controller in a multitenant environment"); this.clusterControllers = clusterControllers; } public Optional<LogserverContainerCluster> getLogServerContainerCluster() { return logServerContainerCluster; } public void setLogserverContainerCluster(LogserverContainerCluster logServerContainerCluster) { this.logServerContainerCluster = Optional.of(logServerContainerCluster); } public ZooKeepersConfigProvider getZooKeepersConfigProvider() { return zooKeepersConfigProvider; } public void getConfig(LogdConfig.Builder builder) { if (logserver == null) { builder.logserver(new LogdConfig.Logserver.Builder().use(false)); } else { builder. logserver(new LogdConfig.Logserver.Builder(). use(logServerContainerCluster.isPresent() || !isHostedVespa). host(logserver.getHostName()). rpcport(logserver.getRelativePort(0)). port(logserver.getRelativePort(1))); } } public void getConfig(SlobroksConfig.Builder builder) { for (Slobrok slob : slobroks) { builder. slobrok(new SlobroksConfig.Slobrok.Builder(). connectionspec(slob.getConnectionSpec())); } } public void getConfig(ZookeepersConfig.Builder builder) { zooKeepersConfigProvider.getConfig(builder); } public FileDistributionConfigProducer getFileDistributionConfigProducer() { return fileDistribution; } public List<HostResource> getClusterControllerHosts() { List<HostResource> hosts = new ArrayList<>(); if (multitenant) { if (logserver != null) hosts.add(logserver.getHostResource()); } else { for (Configserver configserver : getConfigservers()) { hosts.add(configserver.getHostResource()); } } return hosts; } /** * Adds services to all hosts in the system. */ public void addPerHostServices(List<HostResource> hosts, DeployState deployState) { if (slobroks.isEmpty()) // TODO: Move to caller slobroks.addAll(createDefaultSlobrokSetup(deployState.getDeployLogger())); if (deployState.getProperties().enableMetricsProxyContainer()) addMetricsProxyCluster(hosts, deployState); for (HostResource host : hosts) { if (!host.getHost().runsConfigServer()) { addCommonServices(host, deployState); } } } private void addMetricsProxyCluster(List<HostResource> hosts, DeployState deployState) { var metricsProxyCluster = new MetricsProxyContainerCluster(this, "metrics", deployState); int index = 0; for (var host : hosts) { var container = new MetricsProxyContainer(metricsProxyCluster, index++); addAndInitializeService(deployState.getDeployLogger(), host, container); metricsProxyCluster.addContainer(container); } } private void addCommonServices(HostResource host, DeployState deployState) { addConfigSentinel(deployState.getDeployLogger(), host, deployState.getProperties().applicationId(), deployState.zone()); addLogd(deployState.getDeployLogger(), host); addConfigProxy(deployState.getDeployLogger(), host); addFileDistribution(host); if (logForwarderConfig != null) { addLogForwarder(deployState.getDeployLogger(), host); } } private void addConfigSentinel(DeployLogger deployLogger, HostResource host, ApplicationId applicationId, Zone zone) { ConfigSentinel configSentinel = new ConfigSentinel(host.getHost(), applicationId, zone); addAndInitializeService(deployLogger, host, configSentinel); host.getHost().setConfigSentinel(configSentinel); } private void addLogForwarder(DeployLogger deployLogger, HostResource host) { addAndInitializeService(deployLogger, host, new LogForwarder(host.getHost(), logForwarderConfig)); } private void addLogd(DeployLogger deployLogger, HostResource host) { addAndInitializeService(deployLogger, host, new Logd(host.getHost())); } private void addConfigProxy(DeployLogger deployLogger, HostResource host) { addAndInitializeService(deployLogger, host, new ConfigProxy(host.getHost())); } public void addAndInitializeService(DeployLogger deployLogger, HostResource host, AbstractService service) { service.setHostResource(host); service.initService(deployLogger); } private void addFileDistribution(HostResource host) { FileDistributor fileDistributor = fileDistribution.getFileDistributor(); HostResource deployHost = getHostSystem().getHostByHostname(fileDistributor.fileSourceHost()); if (deployHostIsMissing(deployHost)) { throw new RuntimeException("Could not find host in the application's host system: '" + fileDistributor.fileSourceHost() + "'. Hostsystem=" + getHostSystem()); } FileDistributionConfigProvider configProvider = new FileDistributionConfigProvider(fileDistribution, fileDistributor, host == deployHost, host.getHost()); fileDistribution.addFileDistributionConfigProducer(host.getHost(), configProvider); } private boolean deployHostIsMissing(HostResource deployHost) { return !multitenant && deployHost == null; } // If not configured by user: Use default setup: max 3 slobroks, 1 on the default configserver host private List<Slobrok> createDefaultSlobrokSetup(DeployLogger deployLogger) { List<HostResource> hosts = getHostSystem().getHosts(); List<Slobrok> slobs = new ArrayList<>(); if (logserver != null) { Slobrok slobrok = new Slobrok(this, 0); addAndInitializeService(deployLogger, logserver.getHostResource(), slobrok); slobs.add(slobrok); } int n = 0; while ((n < hosts.size()) && (slobs.size() < 3)) { HostResource host = hosts.get(n); if ((logserver== null || host != logserver.getHostResource()) && ! host.getHost().runsConfigServer()) { Slobrok newSlobrok = new Slobrok(this, slobs.size()); addAndInitializeService(deployLogger, host, newSlobrok); slobs.add(newSlobrok); } n++; } int j = 0; for (Slobrok s : slobs) { s.setProp("index", j); j++; } return slobs; } public boolean multitenant() { return multitenant; } public void setApplicationType(ApplicationType applicationType) { this.applicationType = applicationType; } public ApplicationType getApplicationType() { return applicationType; } }
package com.cloud.hypervisor.vmware.resource; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.channels.SocketChannel; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TimeZone; import java.util.UUID; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.BackupSnapshotAnswer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreateStoragePoolCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteSnapshotBackupAnswer; import com.cloud.agent.api.DeleteSnapshotBackupCommand; import com.cloud.agent.api.DeleteSnapshotsDirCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; import com.cloud.agent.api.GetStorageStatsCommand; import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; import com.cloud.agent.api.HostStatsEntry; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.NetworkUsageAnswer; import com.cloud.agent.api.NetworkUsageCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingTestCommand; import com.cloud.agent.api.PoolEjectCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.agent.api.UpgradeSnapshotCommand; import com.cloud.agent.api.ValidateSnapshotAnswer; import com.cloud.agent.api.ValidateSnapshotCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.check.CheckSshAnswer; import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.routing.DhcpEntryCommand; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRulesAnswer; import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.Vlan; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.vmware.manager.VmwareHostService; import com.cloud.hypervisor.vmware.manager.VmwareManager; import com.cloud.hypervisor.vmware.mo.ClusterMO; import com.cloud.hypervisor.vmware.mo.CustomFieldConstants; import com.cloud.hypervisor.vmware.mo.CustomFieldsManagerMO; import com.cloud.hypervisor.vmware.mo.DatacenterMO; import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.HostVirtualNicType; import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper; import com.cloud.hypervisor.vmware.mo.NetworkDetails; import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType; import com.cloud.hypervisor.vmware.mo.VirtualMachineMO; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostNetworkSummary; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostResourceSummary; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareGuestOsMapper; import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.network.HAProxyConfigurator; import com.cloud.network.LoadBalancerConfigurator; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.resource.ServerResource; import com.cloud.serializer.GsonHelper; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume; import com.cloud.storage.resource.StoragePoolResource; import com.cloud.storage.template.TemplateInfo; import com.cloud.utils.DateUtil; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExceptionUtil; import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.mgmt.PropertyMapDynamicBean; import com.cloud.utils.net.NetUtils; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineName; import com.cloud.vm.VmDetailConstants; import com.google.gson.Gson; import com.vmware.vim25.ClusterDasConfigInfo; import com.vmware.vim25.ComputeResourceSummary; import com.vmware.vim25.DatastoreSummary; import com.vmware.vim25.DynamicProperty; import com.vmware.vim25.HostNetworkTrafficShapingPolicy; import com.vmware.vim25.HostPortGroupSpec; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ObjectContent; import com.vmware.vim25.OptionValue; import com.vmware.vim25.PerfCounterInfo; import com.vmware.vim25.PerfEntityMetric; import com.vmware.vim25.PerfEntityMetricBase; import com.vmware.vim25.PerfMetricId; import com.vmware.vim25.PerfMetricIntSeries; import com.vmware.vim25.PerfMetricSeries; import com.vmware.vim25.PerfQuerySpec; import com.vmware.vim25.PerfSampleInfo; import com.vmware.vim25.RuntimeFault; import com.vmware.vim25.ToolsUnavailable; import com.vmware.vim25.VimPortType; import com.vmware.vim25.VirtualDevice; import com.vmware.vim25.VirtualDeviceConfigSpec; import com.vmware.vim25.VirtualDeviceConfigSpecOperation; import com.vmware.vim25.VirtualDisk; import com.vmware.vim25.VirtualEthernetCard; import com.vmware.vim25.VirtualLsiLogicController; import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualMachineFileInfo; import com.vmware.vim25.VirtualMachineGuestOsIdentifier; import com.vmware.vim25.VirtualMachinePowerState; import com.vmware.vim25.VirtualMachineRuntimeInfo; import com.vmware.vim25.VirtualSCSISharing; public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService { private static final Logger s_logger = Logger.getLogger(VmwareResource.class); protected String _name; protected final long _ops_timeout = 900000; // 15 minutes time out to time protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown // out an operation protected final int _retry = 24; protected final int _sleep = 10000; protected final int DEFAULT_DOMR_SSHPORT = 3922; protected final int MAX_CMD_MBEAN = 100; protected String _url; protected String _dcId; protected String _pod; protected String _cluster; protected String _username; protected String _password; protected String _guid; protected String _vCenterAddress; protected String _privateNetworkVSwitchName; protected String _publicNetworkVSwitchName; protected String _guestNetworkVSwitchName; protected float _cpuOverprovisioningFactor = 1; protected boolean _reserveCpu = false; protected float _memOverprovisioningFactor = 1; protected boolean _reserveMem = false; protected ManagedObjectReference _morHyperHost; protected VmwareContext _serviceContext; protected String _hostName; protected HashMap<String, State> _vms = new HashMap<String, State>(71); protected List<PropertyMapDynamicBean> _cmdMBeans = new ArrayList<PropertyMapDynamicBean>(); protected Gson _gson; protected volatile long _cmdSequence = 1; protected static HashMap<VirtualMachinePowerState, State> s_statesTable; static { s_statesTable = new HashMap<VirtualMachinePowerState, State>(); s_statesTable.put(VirtualMachinePowerState.poweredOn, State.Running); s_statesTable.put(VirtualMachinePowerState.poweredOff, State.Stopped); s_statesTable.put(VirtualMachinePowerState.suspended, State.Stopped); } public VmwareResource() { _gson = GsonHelper.getGsonLogger(); } @Override public Answer executeRequest(Command cmd) { if(s_logger.isTraceEnabled()) s_logger.trace("Begin executeRequest(), cmd: " + cmd.getClass().getSimpleName()); Answer answer = null; NDC.push(_hostName != null ? _hostName : _guid + "(" + ComponentLocator.class.getPackage().getImplementationVersion() + ")"); try { long cmdSequence = _cmdSequence++; Date startTime = DateUtil.currentGMTTime(); PropertyMapDynamicBean mbean = new PropertyMapDynamicBean(); mbean.addProp("StartTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), startTime)); mbean.addProp("Command", _gson.toJson(cmd)); mbean.addProp("Sequence", String.valueOf(cmdSequence)); mbean.addProp("Name", cmd.getClass().getSimpleName()); if (cmd instanceof CreateCommand) { answer = execute((CreateCommand) cmd); } else if (cmd instanceof SetPortForwardingRulesCommand) { answer = execute((SetPortForwardingRulesCommand) cmd); } else if (cmd instanceof SetStaticNatRulesCommand) { answer = execute((SetStaticNatRulesCommand) cmd); } else if (cmd instanceof LoadBalancerConfigCommand) { answer = execute((LoadBalancerConfigCommand) cmd); } else if (cmd instanceof IpAssocCommand) { answer = execute((IpAssocCommand) cmd); } else if (cmd instanceof SavePasswordCommand) { answer = execute((SavePasswordCommand) cmd); } else if (cmd instanceof DhcpEntryCommand) { answer = execute((DhcpEntryCommand) cmd); } else if (cmd instanceof VmDataCommand) { answer = execute((VmDataCommand) cmd); } else if (cmd instanceof ReadyCommand) { answer = execute((ReadyCommand) cmd); } else if (cmd instanceof GetHostStatsCommand) { answer = execute((GetHostStatsCommand) cmd); } else if (cmd instanceof GetVmStatsCommand) { answer = execute((GetVmStatsCommand) cmd); } else if (cmd instanceof CheckHealthCommand) { answer = execute((CheckHealthCommand) cmd); } else if (cmd instanceof StopCommand) { answer = execute((StopCommand) cmd); } else if (cmd instanceof RebootRouterCommand) { answer = execute((RebootRouterCommand) cmd); } else if (cmd instanceof RebootCommand) { answer = execute((RebootCommand) cmd); } else if (cmd instanceof CheckVirtualMachineCommand) { answer = execute((CheckVirtualMachineCommand) cmd); } else if (cmd instanceof PrepareForMigrationCommand) { answer = execute((PrepareForMigrationCommand) cmd); } else if (cmd instanceof MigrateCommand) { answer = execute((MigrateCommand) cmd); } else if (cmd instanceof DestroyCommand) { answer = execute((DestroyCommand) cmd); } else if (cmd instanceof CreateStoragePoolCommand) { return execute((CreateStoragePoolCommand) cmd); } else if (cmd instanceof ModifyStoragePoolCommand) { answer = execute((ModifyStoragePoolCommand) cmd); } else if (cmd instanceof DeleteStoragePoolCommand) { answer = execute((DeleteStoragePoolCommand) cmd); } else if (cmd instanceof CopyVolumeCommand) { answer = execute((CopyVolumeCommand) cmd); } else if (cmd instanceof AttachVolumeCommand) { answer = execute((AttachVolumeCommand) cmd); } else if (cmd instanceof AttachIsoCommand) { answer = execute((AttachIsoCommand) cmd); } else if (cmd instanceof ValidateSnapshotCommand) { answer = execute((ValidateSnapshotCommand) cmd); } else if (cmd instanceof ManageSnapshotCommand) { answer = execute((ManageSnapshotCommand) cmd); } else if (cmd instanceof BackupSnapshotCommand) { answer = execute((BackupSnapshotCommand) cmd); } else if (cmd instanceof DeleteSnapshotBackupCommand) { answer = execute((DeleteSnapshotBackupCommand) cmd); } else if (cmd instanceof CreateVolumeFromSnapshotCommand) { answer = execute((CreateVolumeFromSnapshotCommand) cmd); } else if (cmd instanceof DeleteSnapshotsDirCommand) { answer = execute((DeleteSnapshotsDirCommand) cmd); } else if (cmd instanceof CreatePrivateTemplateFromVolumeCommand) { answer = execute((CreatePrivateTemplateFromVolumeCommand) cmd); } else if (cmd instanceof CreatePrivateTemplateFromSnapshotCommand) { answer = execute((CreatePrivateTemplateFromSnapshotCommand) cmd); } else if (cmd instanceof UpgradeSnapshotCommand) { answer = execute((UpgradeSnapshotCommand) cmd); } else if (cmd instanceof GetStorageStatsCommand) { answer = execute((GetStorageStatsCommand) cmd); } else if (cmd instanceof PrimaryStorageDownloadCommand) { answer = execute((PrimaryStorageDownloadCommand) cmd); } else if (cmd instanceof GetVncPortCommand) { answer = execute((GetVncPortCommand) cmd); } else if (cmd instanceof SetupCommand) { answer = execute((SetupCommand) cmd); } else if (cmd instanceof MaintainCommand) { answer = execute((MaintainCommand) cmd); } else if (cmd instanceof PingTestCommand) { answer = execute((PingTestCommand) cmd); } else if (cmd instanceof CheckOnHostCommand) { answer = execute((CheckOnHostCommand) cmd); } else if (cmd instanceof ModifySshKeysCommand) { answer = execute((ModifySshKeysCommand) cmd); } else if (cmd instanceof PoolEjectCommand) { answer = execute((PoolEjectCommand) cmd); } else if (cmd instanceof NetworkUsageCommand) { answer = execute((NetworkUsageCommand) cmd); } else if (cmd instanceof StartCommand) { answer = execute((StartCommand) cmd); } else if (cmd instanceof RemoteAccessVpnCfgCommand) { answer = execute((RemoteAccessVpnCfgCommand) cmd); } else if (cmd instanceof VpnUsersCfgCommand) { answer = execute((VpnUsersCfgCommand) cmd); } else if (cmd instanceof CheckSshCommand) { answer = execute((CheckSshCommand) cmd); } else if (cmd instanceof CheckRouterCommand) { answer = execute((CheckRouterCommand) cmd); } else if (cmd instanceof SetFirewallRulesCommand) { answer = execute((SetFirewallRulesCommand)cmd); } else { answer = Answer.createUnsupportedCommandAnswer(cmd); } if(cmd.getContextParam("checkpoint") != null) { answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint")); } Date doneTime = DateUtil.currentGMTTime(); mbean.addProp("DoneTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), doneTime)); mbean.addProp("Answer", _gson.toJson(answer)); synchronized (this) { try { JmxUtil.registerMBean("VMware " + _morHyperHost.get_value(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); _cmdMBeans.add(mbean); if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); _cmdMBeans.remove(0); JmxUtil.unregisterMBean("VMware " + _morHyperHost.get_value(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); } } catch (Exception e) { if(s_logger.isTraceEnabled()) s_logger.trace("Unable to register JMX monitoring due to exception " + ExceptionUtil.toString(e)); } } } finally { NDC.pop(); } if(s_logger.isTraceEnabled()) s_logger.trace("End executeRequest(), cmd: " + cmd.getClass().getSimpleName()); return answer; } protected Answer execute(NetworkUsageCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource NetworkUsageCommand " + _gson.toJson(cmd)); } long[] stats = getNetworkStats(cmd.getPrivateIP()); NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); return answer; } protected Answer execute(SetPortForwardingRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesCommand: " + _gson.toJson(cmd)); } // String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); String args = ""; String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { args += rule.revoked() ? " -D " : " -A "; args += " -P " + rule.getProtocol().toLowerCase(); args += " -l " + rule.getSrcIp(); args += " -p " + rule.getStringSrcPortRange(); args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange(); try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); if (!result.first()) { s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e)); results[i++] = "Failed"; endResult = false; } } return new SetPortForwardingRulesAnswer(cmd, results, endResult); } protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { String controlIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; String[][] rules = cmd.generateFwRules(); String args = ""; args += " -F "; StringBuilder sb = new StringBuilder(); String[] fwRules = rules[0]; if (fwRules.length > 0) { for (int i = 0; i < fwRules.length; i++) { sb.append(fwRules[i]).append(','); } args += " -a " + sb.toString(); } try { VmwareManager mgr = getServiceContext().getStockObject( VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall_rule.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall_rule.sh " + args); if (!result.first()) { s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + args); //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails for (int i=0; i < results.length; i++) { results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); } } catch (Throwable e) { s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e)); //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails for (int i=0; i < results.length; i++) { results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); } return new SetFirewallRulesAnswer(cmd, true, results); } protected Answer execute(SetStaticNatRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); } // String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String args = null; String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (StaticNatRuleTO rule : cmd.getRules()) { // 1:1 NAT needs instanceip;publicip;domrip;op args = rule.revoked() ? " -D " : " -A "; args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); if (rule.getProtocol() != null) { args += " -P " + rule.getProtocol().toLowerCase(); } args += " -d " + rule.getStringSrcPortRange(); args += " -G "; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); if (!result.first()) { s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e)); results[i++] = "Failed"; endResult = false; } } return new SetStaticNatRulesAnswer(cmd, results, endResult); } protected Answer execute(final LoadBalancerConfigCommand cmd) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); assert(controlIp != null); LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); String[] config = cfgtr.generateConfiguration(cmd); String[][] rules = cfgtr.generateFwRules(cmd); String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; String tmpCfgFileContents = ""; for (int i = 0; i < config.length; i++) { tmpCfgFileContents += config[i]; tmpCfgFileContents += "\n"; } try { SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); try { String[] addRules = rules[LoadBalancerConfigurator.ADD]; String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; String[] statRules = rules[LoadBalancerConfigurator.STATS]; String args = ""; args += "-i " + routerIp; args += " -f " + tmpCfgFilePath; StringBuilder sb = new StringBuilder(); if (addRules.length > 0) { for (int i = 0; i < addRules.length; i++) { sb.append(addRules[i]).append(','); } args += " -a " + sb.toString(); } sb = new StringBuilder(); if (removeRules.length > 0) { for (int i = 0; i < removeRules.length; i++) { sb.append(removeRules[i]).append(','); } args += " -d " + sb.toString(); } sb = new StringBuilder(); if (statRules.length > 0) { for (int i = 0; i < statRules.length; i++) { sb.append(statRules[i]).append(','); } args += " -s " + sb.toString(); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + " /etc/haproxy/haproxy.cfg.new"); if (!result.first()) { s_logger.error("Unable to copy haproxy configuration file"); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); } result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); if (!result.first()) { String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new Answer(cmd, false, msg); } if (s_logger.isInfoEnabled()) { s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); } return new Answer(cmd); } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString(), e); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); } } protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress, String guestIp) throws Exception { String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); if (s_logger.isDebugEnabled()) { s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); } boolean addVif = false; boolean removeVif = false; if (add && publicNicInfo.first().intValue() == -1) { if (s_logger.isDebugEnabled()) { s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); } addVif = true; } else if (!add && firstIP) { removeVif = true; if (s_logger.isDebugEnabled()) { s_logger.debug("Unplug NIC " + publicNicInfo.first()); } } if (addVif) { plugPublicNic(vmMo, vlanId, vifMacAddress); publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); if (publicNicInfo.first().intValue() >= 0) { networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo.first()); } } if (publicNicInfo.first().intValue() < 0) { String msg = "Failed to find DomR VIF to associate/disassociate IP with."; s_logger.error(msg); throw new InternalErrorException(msg); } String args = null; if (add) { args = " -A "; } else { args = " -D "; } String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); if (sourceNat) { args += " -f "; args += " -l "; args += publicIpAddress + "/" + cidrSize; } else if (firstIP) { args += " -f "; args += " -l "; args += publicIpAddress + "/" + cidrSize; } else { args += " -l "; args += publicIpAddress; } args += " -c "; args += "eth" + publicNicInfo.first(); if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + privateIpAddress + ", /root/ipassoc.sh " + args); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/ipassoc.sh " + args); if (!result.first()) { s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); throw new Exception("ipassoc failed due to " + result.second()); } if (removeVif) { vmMo.tearDownDevice(publicNicInfo.second()); HostMO hostMo = vmMo.getRunningHost(); List<NetworkDetails> networks = vmMo.getNetworksWithDetails(); for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { cleanupNetwork(hostMo, netDetails); } } } } if (s_logger.isInfoEnabled()) { s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); } } private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { // TODO : probably need to set traffic shaping Pair<ManagedObjectReference, String> networkInfo = HypervisorHostHelper.preparePublicNetwork(this._publicNetworkVSwitchName, vmMo.getRunningHost(), vlanId, null, null, this._ops_timeout, true); VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // Note: public NIC is plugged inside system VM VirtualDevice nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), VirtualEthernetCardType.Vmxnet3, networkInfo.second(), vifMacAddress, -1, 1, true, true); vmMo.plugDevice(nic); } protected Answer execute(IpAssocCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IPAssocCommand: " + _gson.toJson(cmd)); } int i = 0; String[] results = new String[cmd.getIpAddresses().length]; VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); IpAddressTO[] ips = cmd.getIpAddresses(); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); // String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = VmwareResource.getRouterSshControlIp(cmd); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName); if (vmMo == null) { String msg = "Router " + routerName + " no longer exists to execute IPAssoc command"; s_logger.error(msg); throw new Exception(msg); } for (IpAddressTO ip : ips) { assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress(), ip.getGuestIp()); results[i++] = ip.getPublicIp() + " - success"; } } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); for (; i < cmd.getIpAddresses().length; i++) { results[i++] = IpAssocAnswer.errorResult; } } return new IpAssocAnswer(cmd, results); } protected Answer execute(SavePasswordCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } String controlIp = getRouterSshControlIp(cmd); final String password = cmd.getPassword(); final String vmIpAddress = cmd.getVmIpAddress(); // Run save_password_to_domr.sh String args = " -v " + vmIpAddress; if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + controlIp + ", /root/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } args += " -p " + password; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); if (!result.first()) { s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "SavePassword failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("savepassword command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(DhcpEntryCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd)); } String args = " " + cmd.getVmMac(); args += " " + cmd.getVmIpAddress(); args += " " + cmd.getVmName(); if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/edithosts.sh " + args); if (!result.first()) { s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(CheckRouterCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/checkrouter.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); result = SshHelper.sshExecute(cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP), DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/checkrouter.sh "); if (!result.first()) { s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new CheckRouterAnswer(cmd, "CheckRouter failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("check router command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "CheckRouterCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new CheckRouterAnswer(cmd, msg); } return new CheckRouterAnswer(cmd, result.second().startsWith("Status: MASTER"), result.second()); } protected Answer execute(VmDataCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd)); } String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); String vmIpAddress = cmd.getVmIpAddress(); List<String[]> vmData = cmd.getVmData(); String[] vmDataArgs = new String[vmData.size() * 2 + 4]; vmDataArgs[0] = "routerIP"; vmDataArgs[1] = routerPrivateIpAddress; vmDataArgs[2] = "vmIP"; vmDataArgs[3] = vmIpAddress; int i = 4; for (String[] vmDataEntry : vmData) { String folder = vmDataEntry[0]; String file = vmDataEntry[1]; String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; vmDataArgs[i] = folder + "," + file; vmDataArgs[i + 1] = contents; i += 2; } String content = encodeDataArgs(vmDataArgs); String tmpFileName = UUID.randomUUID().toString(); if (s_logger.isDebugEnabled()) { s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/userdata.py " + tmpFileName); if (!result.first()) { s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); } if (s_logger.isInfoEnabled()) { s_logger.info("vm_data command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } return new Answer(cmd); } private String encodeDataArgs(String[] dataArgs) { StringBuilder sb = new StringBuilder(); for (String arg : dataArgs) { sb.append(arg); sb.append("\n"); } return sb.toString(); } protected CheckSshAnswer execute(CheckSshCommand cmd) { String vmName = cmd.getName(); String privateIp = cmd.getIp(); int cmdPort = cmd.getPort(); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); } try { String result = connect(cmd.getName(), privateIp, cmdPort); if (result != null) { s_logger.error("Can not ping System vm " + vmName + "due to:" + result); return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); } } catch (Exception e) { s_logger.error("Can not ping System vm " + vmName + "due to exception"); return new CheckSshAnswer(cmd, e); } if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port succeeded for vm " + vmName); } if (VirtualMachineName.isValidRouterName(vmName)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Execute network usage setup command on " + vmName); } networkUsage(privateIp, "create", null); } return new CheckSshAnswer(cmd); } private VolumeTO[] validateDisks(VolumeTO[] disks) { List<VolumeTO> validatedDisks = new ArrayList<VolumeTO>(); for (VolumeTO vol : disks) { if (vol.getPoolUuid() != null && !vol.getPoolUuid().isEmpty()) { validatedDisks.add(vol); } else if (vol.getPoolType() == StoragePoolType.ISO && (vol.getPath() != null && !vol.getPath().isEmpty())) { validatedDisks.add(vol); } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Drop invalid disk option, volumeTO: " + _gson.toJson(vol)); } } } return validatedDisks.toArray(new VolumeTO[0]); } protected StartAnswer execute(StartCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource StartCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); State state = State.Stopped; VmwareContext context = getServiceContext(); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // mark VM as starting state so that sync() can know not to report stopped too early synchronized (_vms) { _vms.put(vmName, State.Starting); } VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.valueOf(vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER)); if(s_logger.isDebugEnabled()) s_logger.debug("VM " + vmName + " will be started with NIC device type: " + nicDeviceType); VmwareHypervisorHost hyperHost = getHyperHost(context); VolumeTO[] disks = validateDisks(vmSpec.getDisks()); assert (disks.length > 0); NicTO[] nics = vmSpec.getNics(); HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks); if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty()) ){ String msg = "Unable to locate datastore details of the volumes to be attached"; s_logger.error(msg); throw new Exception(msg); } VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo != null) { s_logger.info("VM " + vmName + " already exists, tear down devices for reconfiguration"); if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); } else { ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); assert (morDc != null); vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Found vm " + vmName + " at other host, relocate to " + hyperHost.getHyperHostName()); } takeVmFromOtherHyperHost(hyperHost, vmName); if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); } else { int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); Pair<ManagedObjectReference, DatastoreMO> rootDiskDataStoreDetails = null; for (VolumeTO vol : disks) { if (vol.getType() == Volume.Type.ROOT) { rootDiskDataStoreDetails = dataStoresDetails.get(vol.getPoolUuid()); } } assert (vmSpec.getSpeed() != null) && (rootDiskDataStoreDetails != null); if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), vmSpec.getLimitCpuUse(), ramMb, getReserveMemMB(ramMb), translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmName); } } vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo == null) { throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmName); } } int totalChangeDevices = disks.length + nics.length; VolumeTO volIso = null; if (vmSpec.getType() != VirtualMachine.Type.User) { // system VM needs a patch ISO totalChangeDevices++; } else { for (VolumeTO vol : disks) { if (vol.getType() == Volume.Type.ISO) { volIso = vol; break; } } if (volIso == null) totalChangeDevices++; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getSpeed().intValue(), getReserveCpuMHz(vmSpec.getSpeed().intValue()), ramMb, getReserveMemMB(ramMb), translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).toString(), vmSpec.getLimitCpuUse()); VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; int ideControllerKey = vmMo.getIDEDeviceControllerKey(); int scsiControllerKey = vmMo.getScsiDeviceControllerKey(); int controllerKey; String datastoreDiskPath; // prepare systemvm patch ISO if (vmSpec.getType() != VirtualMachine.Type.User) { // attach ISO (for patching of system VM) String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), true, true, i, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); } i++; } else { // we will always plugin a CDROM device if (volIso != null && volIso.getPath() != null && !volIso.getPath().isEmpty()) { Pair<String, ManagedObjectReference> isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, volIso.getPath()); assert (isoDatastoreInfo != null); assert (isoDatastoreInfo.second() != null); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, i, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); } } else { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, i, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.edit); } } i++; } for (VolumeTO vol : disks) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); if (vol.getType() == Volume.Type.ROOT || vol.getType() == Volume.Type.ISO) { controllerKey = ideControllerKey; } else { controllerKey = scsiControllerKey; } if (vol.getType() != Volume.Type.ISO) { Pair<ManagedObjectReference, DatastoreMO> volumeDsDetails = dataStoresDetails.get(vol.getPoolUuid()); assert (volumeDsDetails != null); VirtualDevice device; datastoreDiskPath = String.format("[%s] %s.vmdk", volumeDsDetails.second().getName(), vol.getPath()); String chainInfo = vol.getChainInfo(); if (chainInfo != null && !chainInfo.isEmpty()) { String[] diskChain = _gson.fromJson(chainInfo, String[].class); if (diskChain == null || diskChain.length < 1) { s_logger.warn("Empty previously-saved chain info, fall back to the original"); device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); } else { s_logger.info("Attach the disk with stored chain info: " + chainInfo); for (int j = 0; j < diskChain.length; j++) { diskChain[j] = String.format("[%s] %s", volumeDsDetails.second().getName(), diskChain[j]); } device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, diskChain, volumeDsDetails.first(), i, i + 1); } } else { device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), i, i + 1); } deviceConfigSpecArray[i].setDevice(device); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); i++; } } VirtualDevice nic; for (NicTO nicTo : sortNicsByDeviceId(nics)) { s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo)); Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo); nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), i, i + 1, true, true); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(nic); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.add); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i])); i++; } vmConfigSpec.setDeviceChange(deviceConfigSpecArray); // pass boot arguments through machine.id OptionValue[] machineIdOptions = new OptionValue[2]; machineIdOptions[0] = new OptionValue(); machineIdOptions[0].setKey("machine.id"); machineIdOptions[0].setValue(vmSpec.getBootArgs()); machineIdOptions[1] = new OptionValue(); machineIdOptions[1].setKey("devices.hotplug"); machineIdOptions[1].setValue("true"); String keyboardLayout = null; if(vmSpec.getDetails() != null) keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD); vmConfigSpec.setExtraConfig(configureVnc(machineIdOptions, hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout)); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure VM before start. vmName: " + vmName); } if (!vmMo.powerOn()) { throw new Exception("Failed to start VM. vmName: " + vmName); } state = State.Running; return new StartAnswer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "StartCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new StartAnswer(cmd, msg); } finally { synchronized (_vms) { if (state != State.Stopped) { _vms.put(vmName, state); } else { _vms.remove(vmName); } } } } private int getReserveCpuMHz(int cpuMHz) { if(this._reserveCpu) { return (int)(cpuMHz / this._cpuOverprovisioningFactor); } return 0; } private int getReserveMemMB(int memMB) { if(this._reserveMem) { return (int)(memMB / this._memOverprovisioningFactor); } return 0; } private NicTO[] sortNicsByDeviceId(NicTO[] nics) { List<NicTO> listForSort = new ArrayList<NicTO>(); for (NicTO nic : nics) { listForSort.add(nic); } Collections.sort(listForSort, new Comparator<NicTO>() { @Override public int compare(NicTO arg0, NicTO arg1) { if (arg0.getDeviceId() < arg1.getDeviceId()) { return -1; } else if (arg0.getDeviceId() == arg1.getDeviceId()) { return 0; } return 1; } }); return listForSort.toArray(new NicTO[0]); } private HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> inferDatastoreDetailsFromDiskInfo(VmwareHypervisorHost hyperHost, VmwareContext context, VolumeTO[] disks) throws Exception { HashMap<String ,Pair<ManagedObjectReference, DatastoreMO>> poolMors = new HashMap<String, Pair<ManagedObjectReference, DatastoreMO>>(); assert (hyperHost != null) && (context != null); for (VolumeTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { String poolUuid = vol.getPoolUuid(); if(poolMors.get(poolUuid) == null) { ManagedObjectReference morDataStore = hyperHost.findDatastore(poolUuid); if (morDataStore == null) { String msg = "Failed to get the mounted datastore for the volume's pool " + poolUuid; s_logger.error(msg); throw new Exception(msg); } poolMors.put(vol.getPoolUuid(), new Pair<ManagedObjectReference, DatastoreMO> (morDataStore, new DatastoreMO(context, morDataStore))); } } } return poolMors; } private String getVlanInfo(NicTO nicTo) { if (nicTo.getBroadcastType() == BroadcastDomainType.Native) { return Vlan.UNTAGGED; } if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan) { if (nicTo.getBroadcastUri() != null) { return nicTo.getBroadcastUri().getHost(); } else { s_logger.warn("BroadcastType is not claimed as VLAN, but without vlan info in broadcast URI"); return Vlan.UNTAGGED; } } s_logger.warn("Unrecognized broadcast type in VmwareResource, type: " + nicTo.getBroadcastType().toString()); return Vlan.UNTAGGED; } private Pair<ManagedObjectReference, String> prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo) throws Exception { if (nicTo.getType() == Networks.TrafficType.Guest) { return prepareGuestNetwork(hostMo, getVlanInfo(nicTo), nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps()); } else if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { return preparePrivateNetwork(hostMo); } else if (nicTo.getType() == Networks.TrafficType.Public) { return preparePublicNetwork(hostMo, getVlanInfo(nicTo), nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps()); } else if (nicTo.getType() == Networks.TrafficType.Storage) { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } else if (nicTo.getType() == Networks.TrafficType.Vpn) { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } else { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } } protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); StringBuffer argsBuf = new StringBuffer(); if (cmd.isCreate()) { argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) .append(" -c "); } else { argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); if (!result.first()) { s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected synchronized Answer execute(final VpnUsersCfgCommand cmd) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { StringBuffer argsBuf = new StringBuffer(); if (!userpwd.isAdd()) { argsBuf.append(" -U ").append(userpwd.getUsername()); } else { argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); } try { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); if (!result.first()) { s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } return new Answer(cmd); } private VirtualMachineMO takeVmFromOtherHyperHost(VmwareHypervisorHost hyperHost, String vmName) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo != null) { ManagedObjectReference morTargetPhysicalHost = hyperHost.findMigrationTarget(vmMo); if (morTargetPhysicalHost == null) { String msg = "VM " + vmName + " is on other host and we have no resource available to migrate and start it here"; s_logger.error(msg); throw new Exception(msg); } prepareNetworkForVmTargetHost(new HostMO(hyperHost.getContext(), morTargetPhysicalHost), vmMo); if (!vmMo.relocate(morTargetPhysicalHost)) { String msg = "VM " + vmName + " is on other host and we failed to relocate it here"; s_logger.error(msg); throw new Exception(msg); } return vmMo; } return null; } // isoUrl sample content : // nfs://192.168.10.231/export/home/kelven/vmware-test/secondary/template/tmpl/2/200//200-2-80f7ee58-6eff-3a2d-bcb0-59663edf6d26.iso private Pair<String, ManagedObjectReference> getIsoDatastoreInfo(VmwareHypervisorHost hyperHost, String isoUrl) throws Exception { assert (isoUrl != null); int isoFileNameStartPos = isoUrl.lastIndexOf("/"); if (isoFileNameStartPos < 0) { throw new Exception("Invalid ISO path info"); } String isoFileName = isoUrl.substring(isoFileNameStartPos); int templateRootPos = isoUrl.indexOf("template/tmpl"); if (templateRootPos < 0) { throw new Exception("Invalid ISO path info"); } String storeUrl = isoUrl.substring(0, templateRootPos - 1); String isoPath = isoUrl.substring(templateRootPos, isoFileNameStartPos); ManagedObjectReference morDs = prepareSecondaryDatastoreOnHost(storeUrl); DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); return new Pair<String, ManagedObjectReference>(String.format("[%s] %s%s", dsMo.getName(), isoPath, isoFileName), morDs); } protected Answer execute(ReadyCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ReadyCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); if(hyperHost.isHyperHostConnected()) { return new ReadyAnswer(cmd); } else { return new ReadyAnswer(cmd, "Host is not in connect state"); } } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new ReadyAnswer(cmd, VmwareHelper.getExceptionMessage(e)); } } protected Answer execute(GetHostStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetHostStatsCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), 0, 0, 0, "host", 0, 0, 0, 0); Answer answer = new GetHostStatsAnswer(cmd, hostStats); try { HostStatsEntry entry = getHyperHostStats(hyperHost); if(entry != null) { entry.setHostId(cmd.getHostId()); answer = new GetHostStatsAnswer(cmd, entry); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unable to execute GetHostStatsCommand due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); } if (s_logger.isTraceEnabled()) { s_logger.trace("GetHostStats Answer: " + _gson.toJson(answer)); } return answer; } protected Answer execute(GetVmStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVmStatsCommand: " + _gson.toJson(cmd)); } HashMap<String, VmStatsEntry> vmStatsMap = null; try { HashMap<String, State> newStates = getVmStates(); List<String> requestedVmNames = cmd.getVmNames(); List<String> vmNames = new ArrayList(); if (requestedVmNames != null) { for (String vmName : requestedVmNames) { if (newStates.get(vmName) != null) { vmNames.add(vmName); } } } if (vmNames != null) { vmStatsMap = getVmStats(vmNames); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to query host runtime info due to : " + VmwareHelper.getExceptionMessage(e)); } Answer answer = new GetVmStatsAnswer(cmd, vmStatsMap); if (s_logger.isTraceEnabled()) { s_logger.trace("Report GetVmStatsAnswer: " + _gson.toJson(answer)); } return answer; } protected Answer execute(CheckHealthCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckHealthCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); if (hyperHost.isHyperHostConnected()) { return new CheckHealthAnswer(cmd, true); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to query host runtime info due to " + VmwareHelper.getExceptionMessage(e)); } return new CheckHealthAnswer(cmd, false); } protected Answer execute(StopCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource StopCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { State state = null; synchronized (_vms) { state = _vms.get(cmd.getVmName()); _vms.put(cmd.getVmName(), State.Stopping); } try { if (getVmState(vmMo) != State.Stopped) { Long bytesSent = 0L; Long bytesRcvd = 0L; if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { if (cmd.getPrivateRouterIpAddress() != null) { long[] stats = getNetworkStats(cmd.getPrivateRouterIpAddress()); bytesSent = stats[0]; bytesRcvd = stats[1]; } } // before we stop VM, remove all possible snapshots on the VM to let // disk chain be collapsed s_logger.info("Remove all snapshot before stopping VM " + cmd.getVmName()); vmMo.removeAllSnapshots(); if (vmMo.safePowerOff(_shutdown_waitMs)) { state = State.Stopped; return new StopAnswer(cmd, "Stop VM " + cmd.getVmName() + " Succeed", 0, bytesSent, bytesRcvd); } else { String msg = "Have problem in powering off VM " + cmd.getVmName() + ", let the process continue"; s_logger.warn(msg); return new StopAnswer(cmd, msg, 0, 0L, 0L); } } else { state = State.Stopped; } String msg = "VM " + cmd.getVmName() + " is already in stopped state"; s_logger.info(msg); return new StopAnswer(cmd, msg, 0, 0L, 0L); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), state); } } } else { synchronized (_vms) { _vms.remove(cmd.getVmName()); } String msg = "VM " + cmd.getVmName() + " is no longer in vSphere"; s_logger.info(msg); return new StopAnswer(cmd, msg, 0, 0L, 0L); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "StopCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new StopAnswer(cmd, msg); } } protected Answer execute(RebootRouterCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource RebootRouterCommand: " + _gson.toJson(cmd)); } Long bytesSent = 0L; Long bytesRcvd = 0L; if (VirtualMachineName.isValidRouterName(cmd.getVmName())) { long[] stats = getNetworkStats(cmd.getPrivateIpAddress()); bytesSent = stats[0]; bytesRcvd = stats[1]; } RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); answer.setBytesSent(bytesSent); answer.setBytesReceived(bytesRcvd); if (answer.getResult()) { String connectResult = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); networkUsage(cmd.getPrivateIpAddress(), "create", null); if (connectResult == null) { return answer; } else { return new Answer(cmd, false, connectResult); } } return answer; } protected Answer execute(RebootCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource RebootCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { try { vmMo.rebootGuest(); return new RebootAnswer(cmd, "reboot succeeded", null, null); } catch(ToolsUnavailable e) { s_logger.warn("VMware tools is not installed at guest OS, we will perform hard reset for reboot"); } catch(Exception e) { s_logger.warn("We are not able to perform gracefull guest reboot due to " + VmwareHelper.getExceptionMessage(e)); } // continue to try with hard-reset if (vmMo.reset()) { return new RebootAnswer(cmd, "reboot succeeded", null, null); } String msg = "Reboot failed in vSphere. vm: " + cmd.getVmName(); s_logger.warn(msg); return new RebootAnswer(cmd, msg); } else { String msg = "Unable to find the VM in vSphere to reboot. vm: " + cmd.getVmName(); s_logger.warn(msg); return new RebootAnswer(cmd, msg); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "RebootCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new RebootAnswer(cmd, msg); } } protected Answer execute(CheckVirtualMachineCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckVirtualMachineCommand: " + _gson.toJson(cmd)); } final String vmName = cmd.getVmName(); State state = State.Unknown; Integer vncPort = null; VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo != null) { state = getVmState(vmMo); if (state == State.Running) { synchronized (_vms) { _vms.put(vmName, State.Running); } } return new CheckVirtualMachineAnswer(cmd, state, vncPort); } else { s_logger.warn("Can not find vm " + vmName + " to execute CheckVirtualMachineCommand"); return new CheckVirtualMachineAnswer(cmd, state, vncPort); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unexpected exception: " + VmwareHelper.getExceptionMessage(e)); return new CheckVirtualMachineAnswer(cmd, state, vncPort); } } protected Answer execute(PrepareForMigrationCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrepareForMigrationCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vm = cmd.getVirtualMachine(); if (s_logger.isDebugEnabled()) { s_logger.debug("Preparing host for migrating " + vm); } final String vmName = vm.getName(); try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } NicTO[] nics = vm.getNics(); for (NicTO nic : nics) { // prepare network on the host prepareNetworkFromNicInfo(new HostMO(getServiceContext(), _morHyperHost), nic); } synchronized (_vms) { _vms.put(vm.getName(), State.Migrating); } return new PrepareForMigrationAnswer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unexcpeted exception " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new PrepareForMigrationAnswer(cmd, msg); } } protected Answer execute(MigrateCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateCommand: " + _gson.toJson(cmd)); } final String vmName = cmd.getVmName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } VmwareHypervisorHost destHyperHost = getTargetHyperHost(new DatacenterMO(hyperHost.getContext(), morDc), cmd.getDestinationIp()); ManagedObjectReference morTargetPhysicalHost = destHyperHost.findMigrationTarget(vmMo); if (morTargetPhysicalHost == null) { throw new Exception("Unable to find a target capable physical host"); } prepareNetworkForVmTargetHost(new HostMO(hyperHost.getContext(), morTargetPhysicalHost), vmMo); if (!vmMo.migrate(destHyperHost.getHyperHostOwnerResourcePool(), morTargetPhysicalHost)) { throw new Exception("Migration failed"); } state = State.Stopping; return new MigrateAnswer(cmd, true, "migration succeeded", null); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg); return new MigrateAnswer(cmd, false, msg, null); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } private VmwareHypervisorHost getTargetHyperHost(DatacenterMO dcMo, String destIp) throws Exception { VmwareManager mgr = dcMo.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); ObjectContent[] ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj()); VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo)); if (destIp.equalsIgnoreCase(netSummary.getHostIp())) { return new HostMO(dcMo.getContext(), oc.getObj()); } } } throw new Exception("Unable to locate dest host by " + destIp); } protected Answer execute(CreateStoragePoolCommand cmd) { return new Answer(cmd, true, "success"); } protected Answer execute(ModifyStoragePoolCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ModifyStoragePoolCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); StorageFilerTO pool = cmd.getPool(); if (pool.getType() != StoragePoolType.NetworkFilesystem && pool.getType() != StoragePoolType.VMFS) { throw new Exception("Unsupported storage pool type " + pool.getType()); } ManagedObjectReference morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid()); assert (morDatastore != null); DatastoreSummary summary = new DatastoreMO(getServiceContext(), morDatastore).getSummary(); long capacity = summary.getCapacity(); long available = summary.getFreeSpace(); Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>(); ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "ModifyStoragePoolCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } protected Answer execute(DeleteStoragePoolCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DeleteStoragePoolCommand: " + _gson.toJson(cmd)); } StorageFilerTO pool = cmd.getPool(); try { // We will leave datastore cleanup management to vCenter. Since for cluster VMFS datastore, it will always // be mounted by vCenter. // VmwareHypervisorHost hyperHost = this.getHyperHost(getServiceContext()); // hyperHost.unmountDatastore(pool.getUuid()); Answer answer = new Answer(cmd, true, "success"); return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "DeleteStoragePoolCommand (pool: " + pool.getHost() + ", path: " + pool.getPath() + ") failed due to " + VmwareHelper.getExceptionMessage(e); return new Answer(cmd, false, msg); } } protected Answer execute(AttachVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource AttachVolumeCommand: " + _gson.toJson(cmd)); } /* * AttachVolumeCommand { "attach":true,"vmName":"i-2-1-KY","pooltype":"NetworkFilesystem", * "volumeFolder":"/export/home/kelven/vmware-test/primary", "volumePath":"uuid", * "volumeName":"volume name","deviceId":1 } */ try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { String msg = "Unable to find the VM to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getPoolUuid()); if (morDs == null) { String msg = "Unable to find the mounted datastore to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); String datastoreVolumePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getVolumePath()); AttachVolumeAnswer answer = new AttachVolumeAnswer(cmd, cmd.getDeviceId()); if (cmd.getAttach()) { vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); } else { vmMo.removeAllSnapshots(); vmMo.detachDisk(datastoreVolumePath, false); } return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "AttachVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new AttachVolumeAnswer(cmd, msg); } } protected Answer execute(AttachIsoCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } String storeUrl = cmd.getStoreUrl(); if (storeUrl == null) { if (!cmd.getIsoPath().equalsIgnoreCase("vmware-tools.iso")) { String msg = "ISO store root url is not found in AttachIsoCommand"; s_logger.error(msg); throw new Exception(msg); } else { if (cmd.isAttach()) { vmMo.mountToolsInstaller(); } else { vmMo.unmountToolsInstaller(); } return new Answer(cmd); } } ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl); String isoPath = cmd.getIsoPath(); if (!isoPath.startsWith(storeUrl)) { assert (false); String msg = "ISO path does not start with the secondary storage root"; s_logger.error(msg); throw new Exception(msg); } int isoNameStartPos = isoPath.lastIndexOf('/'); String isoFileName = isoPath.substring(isoNameStartPos + 1); String isoStorePathFromRoot = isoPath.substring(storeUrl.length(), isoNameStartPos); // TODO, check if iso is already attached, or if there is a previous // attachment String isoDatastorePath = String.format("[%s] %s%s", getSecondaryDatastoreUUID(storeUrl), isoStorePathFromRoot, isoFileName); if (cmd.isAttach()) { vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false); } else { vmMo.detachIso(isoDatastorePath); } return new Answer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } if(cmd.isAttach()) { String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } else { String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg); s_logger.warn("For detachment failure, we will eventually continue on to allow deassociating it from CloudStack DB"); return new Answer(cmd); } } } private synchronized ManagedObjectReference prepareSecondaryDatastoreOnHost(String storeUrl) throws Exception { String storeName = getSecondaryDatastoreUUID(storeUrl); URI uri = new URI(storeUrl); VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ManagedObjectReference morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), storeName); if (morDatastore == null) { throw new Exception("Unable to mount secondary storage on host. storeUrl: " + storeUrl); } return morDatastore; } private static String getSecondaryDatastoreUUID(String storeUrl) { return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString(); } protected Answer execute(ValidateSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ValidateSnapshotCommand: " + _gson.toJson(cmd)); } // the command is no longer available String expectedSnapshotBackupUuid = null; String actualSnapshotBackupUuid = null; String actualSnapshotUuid = null; return new ValidateSnapshotAnswer(cmd, false, "ValidateSnapshotCommand is not supported for vmware yet", expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); } protected Answer execute(ManageSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ManageSnapshotCommand: " + _gson.toJson(cmd)); } long snapshotId = cmd.getSnapshotId(); /* * "ManageSnapshotCommand", * "{\"_commandSwitch\":\"-c\",\"_volumePath\":\"i-2-3-KY-ROOT\",\"_snapshotName\":\"i-2-3-KY_i-2-3-KY-ROOT_20101102203827\",\"_snapshotId\":1,\"_vmName\":\"i-2-3-KY\"}" */ boolean success = false; String cmdSwitch = cmd.getCommandSwitch(); String snapshotOp = "Unsupported snapshot command." + cmdSwitch; if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { snapshotOp = "create"; } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { snapshotOp = "destroy"; } String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; String snapshotUUID = null; try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the owner VM for ManageSnapshotCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); } vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getVmName()); } if (vmMo == null) { // when no vm instance attached fake as if snapshot is taken, and handle actual taking snapshot as part of BackupSnapshotCommand snapshotUUID = UUID.randomUUID().toString(); success = true; details = null; } else { if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { snapshotUUID = UUID.randomUUID().toString(); if (!vmMo.createSnapshot(snapshotUUID, "Snapshot taken for " + cmd.getSnapshotName(), false, false)) { throw new Exception("Failed to take snapshot " + cmd.getSnapshotName() + " on vm: " + cmd.getVmName()); } success = true; details = null; } else if (cmd.getCommandSwitch().equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { snapshotUUID = cmd.getSnapshotPath(); if (!vmMo.removeSnapshot(snapshotUUID, false)) { throw new Exception("Failed to destroy snapshot: " + cmd.getSnapshotName()); } success = true; details = null; } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } details = "ManageSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, false, details); } return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); } protected Answer execute(BackupSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource BackupSnapshotCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "BackupSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); return new BackupSnapshotAnswer(cmd, false, details, null, true); } } protected Answer execute(DeleteSnapshotBackupCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DeleteSnapshotBackupCommand: " + _gson.toJson(cmd)); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "DeleteSnapshotBackupCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); return new DeleteSnapshotBackupAnswer(cmd, false, details); } } protected Answer execute(CreateVolumeFromSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateVolumeFromSnapshotCommand: " + _gson.toJson(cmd)); } String details = null; boolean success = false; String newVolumeName = UUID.randomUUID().toString(); try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } details = "CreateVolumeFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); } return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); } protected Answer execute(DeleteSnapshotsDirCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DeleteSnapshotsDirCommand: " + _gson.toJson(cmd)); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "DeleteSnapshotDirCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); return new Answer(cmd, false, details); } } protected Answer execute(CreatePrivateTemplateFromVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreatePrivateTemplateFromVolumeCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "CreatePrivateTemplateFromVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); return new CreatePrivateTemplateAnswer(cmd, false, details); } } protected Answer execute(final UpgradeSnapshotCommand cmd) { return new Answer(cmd, true, "success"); } protected Answer execute(CreatePrivateTemplateFromSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreatePrivateTemplateFromSnapshotCommand: " + _gson.toJson(cmd)); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "CreatePrivateTemplateFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details); return new CreatePrivateTemplateAnswer(cmd, false, details); } } protected Answer execute(GetStorageStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetStorageStatsCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); ManagedObjectReference morDs = hyperHost.findDatastore(cmd.getStorageId()); if (morDs != null) { DatastoreMO datastoreMo = new DatastoreMO(context, morDs); DatastoreSummary summary = datastoreMo.getSummary(); assert (summary != null); long capacity = summary.getCapacity(); long free = summary.getFreeSpace(); long used = capacity - free; if (s_logger.isDebugEnabled()) { s_logger.debug("Datastore summary info, storageId: " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ", capacity: " + capacity + ", free: " + free + ", used: " + used); } if (summary.getCapacity() <= 0) { s_logger.warn("Something is wrong with vSphere NFS datastore, rebooting ESX(ESXi) host should help"); } return new GetStorageStatsAnswer(cmd, capacity, used); } else { String msg = "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype(); s_logger.error(msg); return new GetStorageStatsAnswer(cmd, msg); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ") due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new GetStorageStatsAnswer(cmd, msg); } } protected Answer execute(GetVncPortCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); assert(hyperHost instanceof HostMO); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName()); if (vmMo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the owner VM for GetVncPortCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); } vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName()); if (vmMo == null) { throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName()); } } Pair<String, Integer> portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (s_logger.isTraceEnabled()) { s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second()); } return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second()); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new GetVncPortAnswer(cmd, msg); } } protected Answer execute(SetupCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetupCommand: " + _gson.toJson(cmd)); } return new SetupAnswer(cmd, false); } protected Answer execute(MaintainCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MaintainCommand: " + _gson.toJson(cmd)); } return new MaintainAnswer(cmd, "Put host in maintaince"); } protected Answer execute(PingTestCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PingTestCommand: " + _gson.toJson(cmd)); } return new Answer(cmd); } protected Answer execute(CheckOnHostCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckOnHostCommand: " + _gson.toJson(cmd)); } return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); } protected Answer execute(ModifySshKeysCommand cmd) { //do not log the command contents for this command. do NOT log the ssh keys if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ModifySshKeysCommand."); } return new Answer(cmd); } protected Answer execute(PoolEjectCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PoolEjectCommand: " + _gson.toJson(cmd)); } return new Answer(cmd, false, "PoolEjectCommand is not available for vmware"); } @Override public PrimaryStorageDownloadAnswer execute(PrimaryStorageDownloadCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrimaryStorageDownloadCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (PrimaryStorageDownloadAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "PrimaryStorageDownloadCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new PrimaryStorageDownloadAnswer(msg); } } @Override public Answer execute(DestroyCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DestroyCommand: " + _gson.toJson(cmd)); } /* * DestroyCommand content example * * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType": * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } } * * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem", * "poolId":0,"deviceId":0 } } */ try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VolumeTO vol = cmd.getVolume(); ManagedObjectReference morDs = hyperHost.findDatastore(vol.getPoolUuid()); if (morDs == null) { String msg = "Unable to find datastore based on volume mount point " + cmd.getVolume().getMountPoint(); s_logger.error(msg); throw new Exception(msg); } DatastoreMO dsMo = new DatastoreMO(context, morDs); ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO clusterMo = new ClusterMO(context, morCluster); if (cmd.getVolume().getType() == Volume.Type.ROOT) { String vmName = cmd.getVmName(); if (vmName != null) { VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName); if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume and VM itself. vmName " + vmName); } HostMO hostMo = vmMo.getRunningHost(); List<NetworkDetails> networks = vmMo.getNetworksWithDetails(); // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.destroy(); for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { cleanupNetwork(hostMo, netDetails); } } } } if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); // root volume may be created via linked-clone, delete the delta disk as well if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-delta.vmdk"); dsMo.deleteFile(cmd.getVolume().getPath() + "-delta.vmdk", morDc, true); return new Answer(cmd, true, "Success"); } if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume directly from datastore"); } } else { // evitTemplate will be converted into DestroyCommand, test if we are running in this case VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(cmd.getVolume().getPath()); if (vmMo != null) { if (s_logger.isInfoEnabled()) s_logger.info("Destroy template volume " + cmd.getVolume().getPath()); vmMo.destroy(); return new Answer(cmd, true, "Success"); } } String chainInfo = cmd.getVolume().getChainInfo(); if (chainInfo != null && !chainInfo.isEmpty()) { s_logger.info("Destroy volume by chain info: " + chainInfo); String[] diskChain = _gson.fromJson(chainInfo, String[].class); if (diskChain != null && diskChain.length > 0) { for (String backingName : diskChain) { if (s_logger.isInfoEnabled()) { s_logger.info("Delete volume backing file: " + backingName); } dsMo.deleteFile(backingName, morDc, true); } } else { if (s_logger.isInfoEnabled()) { s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name"); } dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-flat.vmdk"); } dsMo.deleteFile(cmd.getVolume().getPath() + "-flat.vmdk", morDc, true); } } else { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by original name: " + cmd.getVolume().getPath() + ".vmdk"); } dsMo.deleteFile(cmd.getVolume().getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + cmd.getVolume().getPath() + "-flat.vmdk"); } dsMo.deleteFile(cmd.getVolume().getPath() + "-flat.vmdk", morDc, true); } return new Answer(cmd, true, "Success"); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } private void cleanupNetwork(HostMO hostMo, NetworkDetails netDetails) { // we will no longer cleanup VLAN networks in order to support native VMware HA /* * assert(netDetails.getName() != null); try { synchronized(this) { NetworkMO networkMo = new * NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms = * networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) { * s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); } * * hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) { * s_logger.warn("Unable to cleanup network due to exception, skip for next time"); } */ } @Override public CopyVolumeAnswer execute(CopyVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CopyVolumeCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (CopyVolumeAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CopyVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new CopyVolumeAnswer(cmd, false, msg, null, null); } } @Override public synchronized CreateAnswer execute(CreateCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateCommand: " + _gson.toJson(cmd)); } StorageFilerTO pool = cmd.getPool(); DiskProfile dskch = cmd.getDiskCharacteristics(); try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); VmwareManager vmwareMgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); ManagedObjectReference morDatastore = hyperHost.findDatastore(pool.getUuid()); if (morDatastore == null) { throw new Exception("Unable to find datastore in vSphere"); } DatastoreMO dsMo = new DatastoreMO(context, morDatastore); if (cmd.getDiskCharacteristics().getType() == Volume.Type.ROOT) { if (cmd.getTemplateUrl() == null) { // create a root volume for blank VM String dummyVmName = getWorkerName(context, cmd); VirtualMachineMO vmMo = null; try { vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getDiskCharacteristics().getName()); synchronized (this) { s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, cmd.getDiskCharacteristics().getName(), dcMo); vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, -1); vmMo.detachDisk(volumeDatastorePath, false); } VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), cmd .getDiskCharacteristics().getName(), cmd.getDiskCharacteristics().getSize(), null); return new CreateAnswer(cmd, vol); } finally { vmMo.detachAllDisks(); s_logger.info("Destroy dummy VM after volume creation"); vmMo.destroy(); } } else { VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(cmd.getTemplateUrl()), true); if (vmTemplate == null) { s_logger.warn("Template host in vSphere is not in connected state, request template reload"); return new CreateAnswer(cmd, "Template host in vSphere is not in connected state, request template reload", true); } ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); if (morBaseSnapshot == null) { String msg = "Unable to find template base snapshot, invalid template"; s_logger.error(msg); throw new Exception(msg); } String name = cmd.getDiskCharacteristics().getName(); if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), name)) dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), name), dcMo.getMor(), false); s_logger.info("create linked clone from template"); if (!vmTemplate.createLinkedClone(name, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { String msg = "Unable to clone from the template"; s_logger.error(msg); throw new Exception(msg); } VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(name); assert (vmMo != null); // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), name, name), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s.vmdk", dsMo.getName(), name), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), name, name), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-delta.vmdk", dsMo.getName(), name), dcMo.getMor(), true); s_logger.info("detach disks from volume-wrapper VM " + name); vmMo.detachAllDisks(); s_logger.info("destroy volume-wrapper VM " + name); vmMo.destroy(); String srcFile = String.format("[%s] %s/", dsMo.getName(), name); dsMo.deleteFile(srcFile, dcMo.getMor(), true); VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), name, pool.getPath(), name, cmd.getDiskCharacteristics().getSize(), null); return new CreateAnswer(cmd, vol); } } else { // create data volume VirtualMachineMO vmMo = null; String volumeUuid = UUID.randomUUID().toString().replace("-", ""); String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeUuid); String dummyVmName = getWorkerName(context, cmd); try { vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } synchronized (this) { // s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo); vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, vmMo.getScsiDeviceControllerKey()); vmMo.detachDisk(volumeDatastorePath, false); } VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), volumeUuid, cmd .getDiskCharacteristics().getSize(), null); return new CreateAnswer(cmd, vol); } finally { s_logger.info("Destroy dummy VM after volume creation"); vmMo.detachAllDisks(); vmMo.destroy(); } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new CreateAnswer(cmd, new Exception(e)); } } protected VirtualMachineMO prepareVolumeHostDummyVm(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception { assert (hyperHost != null); VirtualMachineMO vmMo = null; VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); vmConfig.setName(vmName); vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB vmConfig.setNumCPUs(1); vmConfig.setGuestId(VirtualMachineGuestOsIdentifier._otherGuest.toString()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); scsiController.setSharedBus(VirtualSCSISharing.noSharing); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.add); vmConfig.setDeviceChange(new VirtualDeviceConfigSpec[] { scsiControllerSpec }); hyperHost.createVm(vmConfig); vmMo = hyperHost.findVmOnHyperHost(vmName); return vmMo; } @Override public void disconnected() { } @Override public IAgentControl getAgentControl() { return null; } @Override public PingCommand getCurrentStatus(long id) { HashMap<String, State> newStates = sync(); if (newStates == null) { return null; } try { // take the chance to do left-over dummy VM cleanup from previous run VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(hyperHost.isHyperHostConnected()) { mgr.gcLeftOverVMs(context); } else { s_logger.error("Host is no longer connected."); return null; } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); return null; } } return new PingRoutingCommand(getType(), id, newStates); } @Override public Type getType() { return com.cloud.host.Host.Type.Routing; } @Override public StartupCommand[] initialize() { StartupRoutingCommand cmd = new StartupRoutingCommand(); fillHostInfo(cmd); Map<String, State> changes = null; synchronized (_vms) { _vms.clear(); changes = sync(); } cmd.setHypervisorType(HypervisorType.VMware); cmd.setStateChanges(changes); cmd.setCluster(_cluster); List<StartupStorageCommand> storageCmds = initializeLocalStorage(); StartupCommand[] answerCmds = new StartupCommand[1 + storageCmds.size()]; answerCmds[0] = cmd; for (int i = 0; i < storageCmds.size(); i++) { answerCmds[i + 1] = storageCmds.get(i); } return answerCmds; } private List<StartupStorageCommand> initializeLocalStorage() { List<StartupStorageCommand> storageCmds = new ArrayList<StartupStorageCommand>(); VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); if (hyperHost instanceof HostMO) { HostMO hostMo = (HostMO) hyperHost; List<Pair<ManagedObjectReference, String>> dsList = hostMo.getLocalDatastoreOnHost(); for (Pair<ManagedObjectReference, String> dsPair : dsList) { DatastoreMO dsMo = new DatastoreMO(context, dsPair.first()); String poolUuid = dsMo.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID); if (poolUuid == null || poolUuid.isEmpty()) { poolUuid = UUID.randomUUID().toString(); dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid); } DatastoreSummary dsSummary = dsMo.getSummary(); String address = hostMo.getHostName(); StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, "", "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setName(poolUuid + "@" + hostMo.getHostName()); cmd.setPoolInfo(pInfo); cmd.setGuid(poolUuid); // give storage host the same UUID as the local storage pool itself cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); cmd.setDataCenter(_dcId); cmd.setPod(_pod); cmd.setCluster(_cluster); s_logger.info("Add local storage startup command: " + _gson.toJson(cmd)); storageCmds.add(cmd); } } else { s_logger.info("Cluster host does not support local storage, skip it"); } } catch (Exception e) { String msg = "initializing local storage failed due to : " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); invalidateServiceContext(); throw new CloudRuntimeException(msg); } return storageCmds; } protected void fillHostInfo(StartupRoutingCommand cmd) { VmwareContext serviceContext = getServiceContext(); Map<String, String> details = cmd.getHostDetails(); if (details == null) { details = new HashMap<String, String>(); } try { fillHostHardwareInfo(serviceContext, cmd); fillHostNetworkInfo(serviceContext, cmd); fillHostDetailsInfo(serviceContext, details); } catch (RuntimeFault e) { s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e); throw new CloudRuntimeException("RuntimeFault while retrieving host info"); } catch (RemoteException e) { s_logger.error("RemoteException while retrieving host info: " + e.toString(), e); invalidateServiceContext(); throw new CloudRuntimeException("RemoteException while retrieving host info"); } catch (Exception e) { s_logger.error("Exception while retrieving host info: " + e.toString(), e); invalidateServiceContext(); throw new CloudRuntimeException("Exception while retrieving host info: " + e.toString()); } cmd.setHostDetails(details); cmd.setName(_url); cmd.setGuid(_guid); cmd.setDataCenter(_dcId); cmd.setPod(_pod); cmd.setCluster(_cluster); cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); } private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException, Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary(); if (s_logger.isInfoEnabled()) { s_logger.info("Startup report on host hardware info. " + _gson.toJson(summary)); } cmd.setCaps("hvm"); cmd.setDom0MinMemory(0); cmd.setSpeed(summary.getCpuSpeed()); cmd.setCpus((int) summary.getCpuCount()); cmd.setMemory(summary.getMemoryBytes()); } private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFault, RemoteException { try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); assert(hyperHost instanceof HostMO); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareHypervisorHostNetworkSummary summary = hyperHost.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (summary == null) { throw new Exception("No ESX(i) host found"); } if (s_logger.isInfoEnabled()) { s_logger.info("Startup report on host network info. " + _gson.toJson(summary)); } cmd.setPrivateIpAddress(summary.getHostIp()); cmd.setPrivateNetmask(summary.getHostNetmask()); cmd.setPrivateMacAddress(summary.getHostMacAddress()); cmd.setStorageIpAddress(summary.getHostIp()); cmd.setStorageNetmask(summary.getHostNetmask()); cmd.setStorageMacAddress(summary.getHostMacAddress()); } catch (Throwable e) { String msg = "querying host network info failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); throw new CloudRuntimeException(msg); } } private void fillHostDetailsInfo(VmwareContext serviceContext, Map<String, String> details) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig(); if (dasConfig != null && dasConfig.getEnabled() != null && dasConfig.getEnabled().booleanValue()) { details.put("NativeHA", "true"); } } protected HashMap<String, State> sync() { HashMap<String, State> changes = new HashMap<String, State>(); HashMap<String, State> oldStates = null; try { synchronized (_vms) { HashMap<String, State> newStates = getVmStates(); oldStates = new HashMap<String, State>(_vms.size()); oldStates.putAll(_vms); for (final Map.Entry<String, State> entry : newStates.entrySet()) { final String vm = entry.getKey(); State newState = entry.getValue(); final State oldState = oldStates.remove(vm); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + ": vSphere has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); } if (vm.startsWith("migrating")) { s_logger.debug("Migrating detected. Skipping"); continue; } if (oldState == null) { _vms.put(vm, newState); s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); changes.put(vm, newState); } else if (oldState == State.Starting) { if (newState == State.Running) { _vms.put(vm, newState); } else if (newState == State.Stopped) { s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); } } else if (oldState == State.Migrating) { if (newState == State.Running) { s_logger.debug("Detected that an migrating VM is now running: " + vm); _vms.put(vm, newState); } } else if (oldState == State.Stopping) { if (newState == State.Stopped) { _vms.put(vm, newState); } else if (newState == State.Running) { s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); } } else if (oldState != newState) { _vms.put(vm, newState); if (newState == State.Stopped) { /* * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); * newState = State.Error; } */ } changes.put(vm, newState); } } for (final Map.Entry<String, State> entry : oldStates.entrySet()) { final String vm = entry.getKey(); final State oldState = entry.getValue(); if (isVmInCluster(vm)) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report but we detected that it might be migrated to other host by vCenter"); } if(oldState != State.Starting && oldState != State.Migrating) { s_logger.debug("VM " + vm + " is now missing from host report and VM is not at starting/migrating state, remove it from host VM-sync map, oldState: " + oldState); _vms.remove(vm); } else { s_logger.debug("VM " + vm + " is missing from host report, but we will ignore VM " + vm + " in transition state " + oldState); } continue; } if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report"); } if (oldState == State.Stopping) { s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); _vms.remove(vm); } else if (oldState == State.Starting) { s_logger.debug("Ignoring VM " + vm + " in transition state starting."); } else if (oldState == State.Stopped) { _vms.remove(vm); } else if (oldState == State.Migrating) { s_logger.debug("Ignoring VM " + vm + " in migrating state."); } else { State state = State.Stopped; changes.put(entry.getKey(), state); } } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to perform sync information collection process at this point due to " + VmwareHelper.getExceptionMessage(e)); return null; } return changes; } private boolean isVmInCluster(String vmName) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); return hyperHost.findVmOnPeerHyperHost(vmName) != null; } protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(!mgr.beginExclusiveOperation(600)) throw new Exception("Unable to begin exclusive operation, lock time out"); try { int maxVncPorts = 64; int vncPort = 0; Random random = new Random(); HostMO vmOwnerHost = vmMo.getRunningHost(); ManagedObjectReference morParent = vmOwnerHost.getParentMor(); HashMap<String, Integer> portInfo; if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent); portInfo = clusterMo.getVmVncPortsOnCluster(); } else { portInfo = vmOwnerHost.getVmVncPortsOnHost(); } // allocate first at 5900 - 5964 range Collection<Integer> existingPorts = portInfo.values(); int val = random.nextInt(maxVncPorts); int startVal = val; do { if (!existingPorts.contains(5900 + val)) { vncPort = 5900 + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); if(vncPort == 0) { s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); Pair<Integer, Integer> additionalRange = mgr.getAddiionalVncPortRange(); maxVncPorts = additionalRange.second(); val = random.nextInt(maxVncPorts); startVal = val; do { if (!existingPorts.contains(additionalRange.first() + val)) { vncPort = additionalRange.first() + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); } if (vncPort == 0) { throw new Exception("Unable to find an available VNC port on host"); } if (s_logger.isInfoEnabled()) { s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); } return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); } finally { try { mgr.endExclusiveOperation(); } catch(Throwable e) { assert(false); s_logger.error("Unexpected exception ", e); } } } private VirtualMachineGuestOsIdentifier translateGuestOsIdentifier(String cpuArchitecture, String cloudGuestOs) { if (cpuArchitecture == null) { s_logger.warn("CPU arch is not set, default to i386. guest os: " + cloudGuestOs); cpuArchitecture = "i386"; } VirtualMachineGuestOsIdentifier identifier = VmwareGuestOsMapper.getGuestOsIdentifier(cloudGuestOs); if (identifier != null) { return identifier; } if (cpuArchitecture.equalsIgnoreCase("x86_64")) { return VirtualMachineGuestOsIdentifier.otherGuest64; } return VirtualMachineGuestOsIdentifier.otherGuest; } private synchronized Pair<ManagedObjectReference, String> prepareGuestNetwork(HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps) throws Exception { return HypervisorHostHelper.prepareGuestNetwork(_guestNetworkVSwitchName, hostMo, vlanId, networkRateMbps, networkRateMulticastMbps, _ops_timeout, true); } private synchronized Pair<ManagedObjectReference, String> preparePrivateNetwork(HostMO hostMo) throws Exception { String managementPortGroupName = hostMo.getPortGroupNameByNicType(HostVirtualNicType.management); assert(managementPortGroupName != null); HostPortGroupSpec spec = hostMo.getPortGroupSpec(managementPortGroupName); Integer vlanId = null; if(spec.getVlanId() != 0) { vlanId = spec.getVlanId(); } return HypervisorHostHelper.preparePrivateNetwork(_privateNetworkVSwitchName, hostMo, vlanId, _ops_timeout); } private synchronized Pair<ManagedObjectReference, String> preparePublicNetwork(HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps) throws Exception { return HypervisorHostHelper.preparePublicNetwork(_publicNetworkVSwitchName, hostMo, vlanId, networkRateMbps, networkRateMulticastMbps, _ops_timeout, true); } private void prepareNetworkForVmTargetHost(HostMO hostMo, VirtualMachineMO vmMo) throws Exception { assert (vmMo != null); assert (hostMo != null); String[] networks = vmMo.getNetworks(); for (String networkName : networks) { HostPortGroupSpec portGroupSpec = hostMo.getHostPortGroupSpec(networkName); HostNetworkTrafficShapingPolicy shapingPolicy = null; if (portGroupSpec != null) { shapingPolicy = portGroupSpec.getPolicy().getShapingPolicy(); } if (networkName.startsWith("cloud.private")) { preparePrivateNetwork(hostMo); } else if (networkName.startsWith("cloud.public")) { String[] tokens = networkName.split("\\."); if (tokens.length == 3) { Integer networkRateMbps = null; if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) { networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024)); } preparePublicNetwork(hostMo, tokens[2], networkRateMbps, null); } else { s_logger.info("Skip suspecious cloud network " + networkName); } } else if (networkName.startsWith("cloud.guest")) { String[] tokens = networkName.split("\\."); if (tokens.length >= 3) { Integer networkRateMbps = null; if (shapingPolicy != null && shapingPolicy.getEnabled() != null && shapingPolicy.getEnabled().booleanValue()) { networkRateMbps = (int) (shapingPolicy.getPeakBandwidth().longValue() / (1024 * 1024)); } prepareGuestNetwork(hostMo, tokens[2], networkRateMbps, null); } else { s_logger.info("Skip suspecious cloud network " + networkName); } } else { s_logger.info("Skip non-cloud network " + networkName + " when preparing target host"); } } } private HashMap<String, State> getVmStates() throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", "runtime.powerState", "config.template" }); HashMap<String, State> newStates = new HashMap<String, State>(); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { DynamicProperty[] objProps = oc.getPropSet(); if (objProps != null) { boolean isTemplate = false; String name = null; VirtualMachinePowerState powerState = VirtualMachinePowerState.poweredOff; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("config.template")) { if (objProp.getVal().toString().equalsIgnoreCase("true")) { isTemplate = true; } } else if (objProp.getName().equals("name")) { name = (String) objProp.getVal(); } else if (objProp.getName().equals("runtime.powerState")) { powerState = (VirtualMachinePowerState) objProp.getVal(); } else { assert (false); } } if (!isTemplate) { newStates.put(name, convertState(powerState)); } } } } return newStates; } private HashMap<String, VmStatsEntry> getVmStats(List<String> vmNames) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>(); ManagedObjectReference perfMgr = getServiceContext().getServiceConnection().getServiceContent().getPerfManager(); VimPortType service = getServiceContext().getServiceConnection().getService(); PerfCounterInfo rxPerfCounterInfo = null; PerfCounterInfo txPerfCounterInfo = null; PerfCounterInfo[] cInfo = (PerfCounterInfo[]) getServiceContext().getServiceUtil().getDynamicProperty(perfMgr, "perfCounter"); for(int i=0; i<cInfo.length; ++i) { if ("net".equalsIgnoreCase(cInfo[i].getGroupInfo().getKey())) { if ("transmitted".equalsIgnoreCase(cInfo[i].getNameInfo().getKey())) { txPerfCounterInfo = cInfo[i]; } if ("received".equalsIgnoreCase(cInfo[i].getNameInfo().getKey())) { rxPerfCounterInfo = cInfo[i]; } } } ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] {"name", "summary.config.numCpu", "summary.quickStats.overallCpuUsage"}); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { DynamicProperty[] objProps = oc.getPropSet(); if (objProps != null) { String name = null; String numberCPUs = null; String maxCpuUsage = null; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("name")) { name = objProp.getVal().toString(); } else if (objProp.getName().equals("summary.config.numCpu")) { numberCPUs = objProp.getVal().toString(); } else if (objProp.getName().equals("summary.quickStats.overallCpuUsage")) { maxCpuUsage = objProp.getVal().toString(); } } if (!vmNames.contains(name)) { continue; } ManagedObjectReference vmMor = hyperHost.findVmOnHyperHost(name).getMor(); assert(vmMor!=null); ArrayList vmNetworkMetrics = new ArrayList(); // get all the metrics from the available sample period PerfMetricId[] perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null); if(perfMetrics != null) { for(int index=0; index < perfMetrics.length; ++index) { if ( ((rxPerfCounterInfo != null) && (perfMetrics[index].getCounterId() == rxPerfCounterInfo.getKey())) || ((txPerfCounterInfo != null) && (perfMetrics[index].getCounterId() == txPerfCounterInfo.getKey())) ) { vmNetworkMetrics.add(perfMetrics[index]); } } } double networkReadKBs=0; double networkWriteKBs=0; long sampleDuration=0; if (vmNetworkMetrics.size() != 0) { PerfQuerySpec qSpec = new PerfQuerySpec(); qSpec.setEntity(vmMor); PerfMetricId[] availableMetricIds = (PerfMetricId[]) vmNetworkMetrics.toArray(new PerfMetricId[0]); qSpec.setMetricId(availableMetricIds); PerfQuerySpec[] qSpecs = new PerfQuerySpec[] {qSpec}; PerfEntityMetricBase[] values = service.queryPerf(perfMgr, qSpecs); for(int i=0; i<values.length; ++i) { PerfSampleInfo[] infos = ((PerfEntityMetric)values[i]).getSampleInfo(); sampleDuration = (infos[infos.length-1].getTimestamp().getTimeInMillis() - infos[0].getTimestamp().getTimeInMillis()) /1000; PerfMetricSeries[] vals = ((PerfEntityMetric)values[i]).getValue(); for(int vi = 0; ((vals!= null) && (vi < vals.length)); ++vi){ if(vals[vi] instanceof PerfMetricIntSeries) { PerfMetricIntSeries val = (PerfMetricIntSeries)vals[vi]; long[] perfValues = val.getValue(); if (vals[vi].getId().getCounterId() == rxPerfCounterInfo.getKey()) { networkReadKBs = sampleDuration * perfValues[3]; //get the average RX rate multiplied by sampled duration } if (vals[vi].getId().getCounterId() == txPerfCounterInfo.getKey()) { networkWriteKBs = sampleDuration * perfValues[3];//get the average TX rate multiplied by sampled duration } } } } } vmResponseMap.put(name, new VmStatsEntry(Integer.parseInt(maxCpuUsage), networkReadKBs, networkWriteKBs, Integer.parseInt(numberCPUs), "vm")); } } } return vmResponseMap; } protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { String args = null; if (option.equals("get")) { args = "-g"; } else if (option.equals("create")) { args = "-c"; } else if (option.equals("reset")) { args = "-r"; } else if (option.equals("addVif")) { args = "-a"; args += ethName; } else if (option.equals("deleteVif")) { args = "-d"; args += ethName; } try { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing /root/netusage.sh " + args + " on DomR " + privateIpAddress); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/netusage.sh " + args); if (!result.first()) { return null; } return result.second(); } catch (Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e)); } return null; } private long[] getNetworkStats(String privateIP) { String result = networkUsage(privateIP, "get", null); long[] stats = new long[2]; if (result != null) { try { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } } catch (Throwable e) { s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString()); } } return stats; } protected String connect(final String vmName, final String ipAddress, final int port) { long startTick = System.currentTimeMillis(); // wait until we have at least been waiting for _ops_timeout time or // at least have tried _retry times, this is to coordinate with system // VM patching/rebooting time that may need int retry = _retry; while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { SocketChannel sch = null; try { s_logger.info("Trying to connect to " + ipAddress); sch = SocketChannel.open(); sch.configureBlocking(true); sch.socket().setSoTimeout(5000); InetSocketAddress addr = new InetSocketAddress(ipAddress, port); sch.connect(addr); return null; } catch (IOException e) { s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); if (e instanceof ConnectException) { // if connection is refused because of VM is being started, // we give it more sleep time // to avoid running out of retry quota too quickly try { Thread.sleep(5000); } catch (InterruptedException ex) { } } } finally { if (sch != null) { try { sch.close(); } catch (IOException e) { } } } try { Thread.sleep(1000); } catch (InterruptedException ex) { } } s_logger.info("Unable to logon to " + ipAddress); return "Unable to connect"; } protected String connect(final String vmname, final String ipAddress) { return connect(vmname, ipAddress, 3922); } private static State convertState(VirtualMachinePowerState powerState) { return s_statesTable.get(powerState); } private static State getVmState(VirtualMachineMO vmMo) throws Exception { VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo(); return convertState(runtimeInfo.getPowerState()); } private static HostStatsEntry getHyperHostStats(VmwareHypervisorHost hyperHost) throws Exception { ComputeResourceSummary hardwareSummary = hyperHost.getHyperHostHardwareSummary(); if(hardwareSummary == null) return null; HostStatsEntry entry = new HostStatsEntry(); entry.setEntityType("host"); double cpuUtilization = ((double) (hardwareSummary.getTotalCpu() - hardwareSummary.getEffectiveCpu()) / (double) hardwareSummary.getTotalCpu() * 100); entry.setCpuUtilization(cpuUtilization); entry.setTotalMemoryKBs(hardwareSummary.getTotalMemory() / 1024); entry.setFreeMemoryKBs(hardwareSummary.getEffectiveMemory() * 1024); return entry; } private static String getRouterSshControlIp(NetworkElementCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { if(s_logger.isDebugEnabled()) s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); return routerGuestIp; } if(s_logger.isDebugEnabled()) s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); return routerIp; } @Override public void setAgentControl(IAgentControl agentControl) { } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; _url = (String) params.get("url"); _username = (String) params.get("username"); _password = (String) params.get("password"); _dcId = (String) params.get("zone"); _pod = (String) params.get("pod"); _cluster = (String) params.get("cluster"); _guid = (String) params.get("guid"); String value = (String) params.get("cpu.overprovisioning.factor"); if(value != null) _cpuOverprovisioningFactor = Float.parseFloat(value); value = (String) params.get("vmware.reserve.cpu"); if(value != null && value.equalsIgnoreCase("true")) _reserveCpu = true; value = (String) params.get("mem.overprovisioning.factor"); if(value != null) _memOverprovisioningFactor = Float.parseFloat(value); value = (String) params.get("vmware.reserve.mem"); if(value != null && value.equalsIgnoreCase("true")) _reserveMem = true; String[] tokens = _guid.split("@"); _vCenterAddress = tokens[1]; _morHyperHost = new ManagedObjectReference(); String[] hostTokens = tokens[0].split(":"); _morHyperHost.setType(hostTokens[0]); _morHyperHost.set_value(hostTokens[1]); VmwareContext context = getServiceContext(); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); mgr.setupResourceStartupParams(params); CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager()); cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID); cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_UUID); VmwareHypervisorHost hostMo = this.getHyperHost(context); _hostName = hostMo.getHyperHostName(); } catch (Exception e) { s_logger.error("Unexpected Exception ", e); } _privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name"); _publicNetworkVSwitchName = (String) params.get("public.network.vswitch.name"); _guestNetworkVSwitchName = (String) params.get("guest.network.vswitch.name"); s_logger.info("VmwareResource network configuration info. private vSwitch: " + _privateNetworkVSwitchName + ", public vSwitch: " + _publicNetworkVSwitchName + ", guest network: " + _guestNetworkVSwitchName); return true; } @Override public String getName() { return _name; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } private VmwareContext getServiceContext() { return getServiceContext(null); } private void invalidateServiceContext() { invalidateServiceContext(null); } private VmwareHypervisorHost getHyperHost(VmwareContext context) { return getHyperHost(context, null); } @Override public synchronized VmwareContext getServiceContext(Command cmd) { if (_serviceContext == null) { try { _serviceContext = VmwareContextFactory.create(_vCenterAddress, _username, _password); } catch (Exception e) { s_logger.error("Unable to connect to vSphere server: " + _vCenterAddress, e); throw new CloudRuntimeException("Unable to connect to vSphere server: " + _vCenterAddress); } } return _serviceContext; } @Override public synchronized void invalidateServiceContext(VmwareContext context) { if (_serviceContext == null) { _serviceContext.close(); } _serviceContext = null; } @Override public VmwareHypervisorHost getHyperHost(VmwareContext context, Command cmd) { if (_morHyperHost.getType().equalsIgnoreCase("HostSystem")) { return new HostMO(context, _morHyperHost); } return new ClusterMO(context, _morHyperHost); } @Override @DB public String getWorkerName(VmwareContext context, Command cmd) { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String vmName = mgr.composeWorkerName(); assert(cmd != null); VmwareManager vmwareMgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); long checkPointId = vmwareMgr.pushCleanupCheckpoint(this._guid, vmName); cmd.setContextParam("checkpoint", String.valueOf(checkPointId)); return vmName; } }
package org.nusco.narjillos.shared.physics; /** * A point on a plane, in either cartesian or polar coordinates. */ public class Vector { public static final Vector ZERO = Vector.cartesian(0, 0); static { FastMath.setUp(); } public final double x; public final double y; // cached fields (for performance) private double angle = Double.NaN; private double length = Double.NaN; private Vector inverted = null; private Vector normal = null; public static Vector polar(double degrees, double length) { double sin = FastMath.sin(degrees); double cos = FastMath.cos(degrees); return Vector.cartesian(cos * length, sin * length); } public static Vector cartesian(double x, double y) { return new Vector(x, y); } private Vector(double x, double y) { this.x = x; this.y = y; } public double getAngle() throws ZeroVectorException { if (x == 0 && y == 0) throw new ZeroVectorException(); if (Double.isNaN(angle)) angle = Math.toDegrees(Math.atan2(y, x)); return angle; } public double getLength() { if (Double.isNaN(length)) length = Math.sqrt(x * x + y * y); return length; } public Vector plus(Vector other) { return Vector.cartesian(x + other.x, y + other.y); } public Vector minus(Vector other) { return Vector.cartesian(x - other.x, y - other.y); } public Vector by(double scalar) { return Vector.cartesian(x * scalar, y * scalar); } public Vector invert() { if (inverted == null) inverted = this.by(-1); return inverted; } public Vector normalize(double length) throws ZeroVectorException { return Vector.polar(getAngle(), length); } public Vector getNormal() throws ZeroVectorException { if (normal == null) normal = Vector.polar(getAngle() - 90, 1); return normal; } public Vector getProjectionOn(Vector other) throws ZeroVectorException { Vector direction = pointsInSameDirectionAs(other) ? other : other.invert(); double relativeAngle = direction.getAngle() - getAngle(); double resultLength = FastMath.cos(relativeAngle) * getLength(); return Vector.polar(direction.getAngle(), resultLength); // TODO: switch to the code below (but check broken tests) // double theta = FastMath.cos(getAngleWith(other)); // double resultLength = theta * getLength(); // return Vector.polar(other.getAngle(), resultLength); } private boolean pointsInSameDirectionAs(Vector other) throws ZeroVectorException { return Math.abs(getAngleWith(other)) < 90; } public Vector getNormalComponentOn(Vector other) throws ZeroVectorException { return getProjectionOn(other.getNormal()); } public double getAngleWith(Vector other) throws ZeroVectorException { return Angle.normalize(getAngle() - other.getAngle()); } double getDistanceFrom(Vector other) { return this.minus(other).getLength(); } @Override public int hashCode() { return 1; } @Override public boolean equals(Object obj) { Vector other = (Vector) obj; return compare(x, other.x) && compare(y, other.y); } private boolean compare(double d1, double d2) { return Double.doubleToLongBits(d1) == Double.doubleToLongBits(d2); } public boolean almostEquals(Vector other) { final double delta = 0.01; return Math.abs(x - other.x) < delta && Math.abs(y - other.y) < delta; } private double approx(double n) { final double decimals = 100.0; return (Math.round(n * decimals)) / decimals; } public boolean isZero() { return x == 0 && y == 0; } @Override public String toString() { return "(" + approx(x) + ", " + approx(y) + ")"; } }
package com.gentics.mesh.core.release; import static com.gentics.mesh.assertj.MeshAssertions.assertThat; import static com.gentics.mesh.mock.Mocks.getMockedInternalActionContext; import static com.gentics.mesh.mock.Mocks.getMockedRoutingContext; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.Test; import com.gentics.mesh.FieldUtil; import com.gentics.mesh.context.InternalActionContext; import com.gentics.mesh.core.data.Project; import com.gentics.mesh.core.data.Release; import com.gentics.mesh.core.data.page.impl.PageImpl; import com.gentics.mesh.core.data.relationship.GraphPermission; import com.gentics.mesh.core.data.root.ReleaseRoot; import com.gentics.mesh.core.data.schema.MicroschemaContainer; import com.gentics.mesh.core.data.schema.MicroschemaContainerVersion; import com.gentics.mesh.core.data.schema.SchemaContainer; import com.gentics.mesh.core.data.schema.SchemaContainerVersion; import com.gentics.mesh.core.data.schema.handler.SchemaComparator; import com.gentics.mesh.core.rest.microschema.impl.MicroschemaModel; import com.gentics.mesh.core.rest.release.ReleaseReference; import com.gentics.mesh.core.rest.release.ReleaseResponse; import com.gentics.mesh.core.rest.schema.Microschema; import com.gentics.mesh.core.rest.schema.Schema; import com.gentics.mesh.core.rest.schema.change.impl.SchemaChangesListModel; import com.gentics.mesh.core.rest.schema.impl.SchemaModel; import com.gentics.mesh.graphdb.NoTx; import com.gentics.mesh.parameter.impl.PagingParameters; import com.gentics.mesh.test.AbstractBasicIsolatedObjectTest; import io.vertx.ext.web.RoutingContext; public class ReleaseTest extends AbstractBasicIsolatedObjectTest { @Test @Override public void testTransformToReference() throws Exception { try (NoTx noTx = db.noTx()) { Release release = project().getInitialRelease(); ReleaseReference reference = release.transformToReference(); assertThat(reference).isNotNull(); assertThat(reference.getName()).as("Reference name").isEqualTo(release.getName()); assertThat(reference.getUuid()).as("Reference uuid").isEqualTo(release.getUuid()); } } @Test @Override public void testFindAllVisible() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); ReleaseRoot releaseRoot = project.getReleaseRoot(); Release initialRelease = releaseRoot.getInitialRelease(); Release releaseOne = releaseRoot.create("One", user()); Release releaseTwo = releaseRoot.create("Two", user()); Release releaseThree = releaseRoot.create("Three", user()); PageImpl<? extends Release> page = releaseRoot.findAll(getMockedInternalActionContext(user()), new PagingParameters(1, 25)); assertThat(page).isNotNull(); ArrayList<Release> arrayList = new ArrayList<Release>(); page.iterator().forEachRemaining(r -> arrayList.add(r)); assertThat(arrayList).usingElementComparatorOnFields("uuid").containsExactly(releaseThree, releaseTwo, releaseOne, initialRelease); } } @Test @Override public void testFindAll() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); ReleaseRoot releaseRoot = project.getReleaseRoot(); Release initialRelease = releaseRoot.getInitialRelease(); Release releaseOne = releaseRoot.create("One", user()); Release releaseTwo = releaseRoot.create("Two", user()); Release releaseThree = releaseRoot.create("Three", user()); assertThat(new ArrayList<Release>(releaseRoot.findAll())).usingElementComparatorOnFields("uuid").containsExactly(initialRelease, releaseOne, releaseTwo, releaseThree); } } @Test @Override public void testRootNode() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); ReleaseRoot releaseRoot = project.getReleaseRoot(); assertThat(releaseRoot).as("Release Root of Project").isNotNull(); Release initialRelease = project.getInitialRelease(); assertThat(initialRelease).as("Initial Release of Project").isNotNull().isActive().isNamed(project.getName()).hasUuid().hasNext(null) .hasPrevious(null); Release latestRelease = project.getLatestRelease(); assertThat(latestRelease).as("Latest Release of Project").matches(initialRelease); } } @Test @Override public void testFindByName() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); ReleaseRoot releaseRoot = project.getReleaseRoot(); Release foundRelease = releaseRoot.findByName(project.getName()).toBlocking().value(); assertThat(foundRelease).as("Release with name " + project.getName()).isNotNull().matches(project.getInitialRelease()); } } @Test @Override public void testFindByUUID() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); ReleaseRoot releaseRoot = project.getReleaseRoot(); Release initialRelease = project.getInitialRelease(); Release foundRelease = releaseRoot.findByUuid(initialRelease.getUuid()).toBlocking().value(); assertThat(foundRelease).as("Release with uuid " + initialRelease.getUuid()).isNotNull().matches(initialRelease); } } @Test @Override public void testRead() throws Exception { } @Test @Override public void testCreate() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); ReleaseRoot releaseRoot = project.getReleaseRoot(); Release initialRelease = releaseRoot.getInitialRelease(); Release firstNewRelease = releaseRoot.create("First new Release", user()); Release secondNewRelease = releaseRoot.create("Second new Release", user()); Release thirdNewRelease = releaseRoot.create("Third new Release", user()); assertThat(project.getInitialRelease()).as("Initial Release").matches(initialRelease).hasNext(firstNewRelease).hasPrevious(null); assertThat(firstNewRelease).as("First new Release").isNamed("First new Release").hasNext(secondNewRelease).hasPrevious(initialRelease); assertThat(secondNewRelease).as("Second new Release").isNamed("Second new Release").hasNext(thirdNewRelease).hasPrevious(firstNewRelease); assertThat(project.getLatestRelease()).as("Latest Release").isNamed("Third new Release").matches(thirdNewRelease).hasNext(null) .hasPrevious(secondNewRelease); assertThat(new ArrayList<Release>(releaseRoot.findAll())).usingElementComparatorOnFields("uuid").containsExactly(initialRelease, firstNewRelease, secondNewRelease, thirdNewRelease); for (SchemaContainer schema : project.getSchemaContainerRoot().findAll()) { for (Release release : Arrays.asList(initialRelease, firstNewRelease, secondNewRelease, thirdNewRelease)) { assertThat(release).as(release.getName()).hasSchema(schema).hasSchemaVersion(schema.getLatestVersion()); } } } } @Override public void testDelete() throws Exception { // TODO Auto-generated method stub } @Test @Override public void testUpdate() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); Release initialRelease = project.getInitialRelease(); initialRelease.setName("New Release Name"); initialRelease.setActive(false); initialRelease.reload(); assertThat(initialRelease).as("Release").isNamed("New Release Name").isInactive(); } } @Test @Override public void testReadPermission() throws Exception { try (NoTx noTx = db.noTx()) { Release newRelease = project().getReleaseRoot().create("New Release", user()); testPermission(GraphPermission.READ_PERM, newRelease); } } @Test @Override public void testDeletePermission() throws Exception { try (NoTx noTx = db.noTx()) { Release newRelease = project().getReleaseRoot().create("New Release", user()); testPermission(GraphPermission.DELETE_PERM, newRelease); } } @Test @Override public void testUpdatePermission() throws Exception { try (NoTx noTx = db.noTx()) { Release newRelease = project().getReleaseRoot().create("New Release", user()); testPermission(GraphPermission.UPDATE_PERM, newRelease); } } @Test @Override public void testCreatePermission() throws Exception { try (NoTx noTx = db.noTx()) { Release newRelease = project().getReleaseRoot().create("New Release", user()); testPermission(GraphPermission.CREATE_PERM, newRelease); } } @Test @Override public void testTransformation() throws Exception { try (NoTx noTx = db.noTx()) { Release release = project().getInitialRelease(); RoutingContext rc = getMockedRoutingContext(user()); InternalActionContext ac = InternalActionContext.create(rc); ReleaseResponse releaseResponse = release.transformToRestSync(ac, 0).toBlocking().value(); assertThat(releaseResponse).isNotNull().hasName(release.getName()).hasUuid(release.getUuid()).isActive().isMigrated(); } } @Override public void testCreateDelete() throws Exception { // TODO Auto-generated method stub } @Override public void testCRUDPermissions() throws Exception { // TODO Auto-generated method stub } @Test public void testReadSchemaVersions() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); List<SchemaContainerVersion> versions = project.getSchemaContainerRoot().findAll().stream().map(SchemaContainer::getLatestVersion) .collect(Collectors.toList()); List<SchemaContainerVersion> found = new ArrayList<>(); for (SchemaContainerVersion version : project.getInitialRelease().findAllSchemaVersions()) { found.add(version); } assertThat(found).as("List of schema versions").usingElementComparatorOnFields("uuid", "name", "version").containsAll(versions); } } /** * Test assigning a schema to a project * * @throws Exception */ @Test public void testAssignSchema() throws Exception { try (NoTx noTx = db.noTx()) { SchemaContainer schemaContainer = createSchema("bla"); updateSchema(schemaContainer, "newfield"); SchemaContainerVersion latestVersion = schemaContainer.getLatestVersion(); assertThat(latestVersion).as("latest version").isNotNull(); SchemaContainerVersion previousVersion = latestVersion.getPreviousVersion(); assertThat(previousVersion).as("Previous version").isNotNull(); Project project = project(); Release initialRelease = project.getInitialRelease(); Release newRelease = project.getReleaseRoot().create("New Release", user()); for (Release release : Arrays.asList(initialRelease, newRelease)) { assertThat(release).as(release.getName()).hasNotSchema(schemaContainer).hasNotSchemaVersion(latestVersion) .hasNotSchemaVersion(previousVersion); } // assign the schema to the project project.getSchemaContainerRoot().addSchemaContainer(schemaContainer); initialRelease.reload(); newRelease.reload(); for (Release release : Arrays.asList(initialRelease, newRelease)) { assertThat(release).as(release.getName()).hasSchema(schemaContainer).hasSchemaVersion(latestVersion) .hasNotSchemaVersion(previousVersion); } } } /** * Test unassigning a schema from a project * * @throws Exception */ @Test public void testUnassignSchema() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); List<? extends SchemaContainer> schemas = project.getSchemaContainerRoot().findAll(); SchemaContainer schemaContainer = schemas.get(0); Release initialRelease = project.getInitialRelease(); Release newRelease = project.getReleaseRoot().create("New Release", user()); project.getSchemaContainerRoot().removeSchemaContainer(schemaContainer); initialRelease.reload(); newRelease.reload(); for (Release release : Arrays.asList(initialRelease, newRelease)) { assertThat(release).as(release.getName()).hasNotSchema(schemaContainer).hasNotSchemaVersion(schemaContainer.getLatestVersion()); } } } @Test public void testReleaseSchemaVersion() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); SchemaContainer schemaContainer = createSchema("bla"); SchemaContainerVersion firstVersion = schemaContainer.getLatestVersion(); // assign the schema to the project project.getSchemaContainerRoot().addSchemaContainer(schemaContainer); // update schema updateSchema(schemaContainer, "newfield"); SchemaContainerVersion secondVersion = schemaContainer.getLatestVersion(); Release initialRelease = project.getInitialRelease(); Release newRelease = project.getReleaseRoot().create("New Release", user()); assertThat(initialRelease).as(initialRelease.getName()).hasSchema(schemaContainer).hasSchemaVersion(firstVersion) .hasNotSchemaVersion(secondVersion); assertThat(newRelease).as(newRelease.getName()).hasSchema(schemaContainer).hasNotSchemaVersion(firstVersion) .hasSchemaVersion(secondVersion); } } @Test public void testReadMicroschemaVersions() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); List<MicroschemaContainerVersion> versions = project.getMicroschemaContainerRoot().findAll().stream() .map(MicroschemaContainer::getLatestVersion).collect(Collectors.toList()); List<MicroschemaContainerVersion> found = new ArrayList<>(); for (MicroschemaContainerVersion version : project.getInitialRelease().findAllMicroschemaVersions()) { found.add(version); } assertThat(found).as("List of microschema versions").usingElementComparatorOnFields("uuid", "name", "version").containsAll(versions); } } /** * Test assigning a microschema to a project * * @throws Exception */ @Test public void testAssignMicroschema() throws Exception { try (NoTx noTx = db.noTx()) { MicroschemaContainer microschemaContainer = createMicroschema("bla"); updateMicroschema(microschemaContainer, "newfield"); MicroschemaContainerVersion latestVersion = microschemaContainer.getLatestVersion(); assertThat(latestVersion).as("latest version").isNotNull(); MicroschemaContainerVersion previousVersion = latestVersion.getPreviousVersion(); assertThat(previousVersion).as("Previous version").isNotNull(); Project project = project(); Release initialRelease = project.getInitialRelease(); Release newRelease = project.getReleaseRoot().create("New Release", user()); for (Release release : Arrays.asList(initialRelease, newRelease)) { assertThat(release).as(release.getName()).hasNotMicroschema(microschemaContainer).hasNotMicroschemaVersion(latestVersion) .hasNotMicroschemaVersion(previousVersion); } // assign the schema to the project project.getMicroschemaContainerRoot().addMicroschema(microschemaContainer); initialRelease.reload(); newRelease.reload(); for (Release release : Arrays.asList(initialRelease, newRelease)) { assertThat(release).as(release.getName()).hasMicroschema(microschemaContainer).hasMicroschemaVersion(latestVersion) .hasNotMicroschemaVersion(previousVersion); } } } /** * Test unassigning a microschema from a project * * @throws Exception */ @Test public void testUnassignMicroschema() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); List<? extends MicroschemaContainer> microschemas = project.getMicroschemaContainerRoot().findAll(); MicroschemaContainer microschemaContainer = microschemas.get(0); Release initialRelease = project.getInitialRelease(); Release newRelease = project.getReleaseRoot().create("New Release", user()); project.getMicroschemaContainerRoot().removeMicroschema(microschemaContainer); initialRelease.reload(); newRelease.reload(); for (Release release : Arrays.asList(initialRelease, newRelease)) { assertThat(release).as(release.getName()).hasNotMicroschema(microschemaContainer) .hasNotMicroschemaVersion(microschemaContainer.getLatestVersion()); } } } @Test public void testReleaseMicroschemaVersion() throws Exception { try (NoTx noTx = db.noTx()) { Project project = project(); MicroschemaContainer microschemaContainer = createMicroschema("bla"); MicroschemaContainerVersion firstVersion = microschemaContainer.getLatestVersion(); // assign the microschema to the project project.getMicroschemaContainerRoot().addMicroschema(microschemaContainer); // update microschema updateMicroschema(microschemaContainer, "newfield"); MicroschemaContainerVersion secondVersion = microschemaContainer.getLatestVersion(); Release initialRelease = project.getInitialRelease(); Release newRelease = project.getReleaseRoot().create("New Release", user()); assertThat(initialRelease).as(initialRelease.getName()).hasMicroschema(microschemaContainer).hasMicroschemaVersion(firstVersion) .hasNotMicroschemaVersion(secondVersion); assertThat(newRelease).as(newRelease.getName()).hasMicroschema(microschemaContainer).hasNotMicroschemaVersion(firstVersion) .hasMicroschemaVersion(secondVersion); } } /** * Create a new schema with a single string field "name" * * @param name * schema name * @return schema container * @throws Exception */ protected SchemaContainer createSchema(String name) throws Exception { Schema schema = new SchemaModel(); schema.setName(name); schema.addField(FieldUtil.createStringFieldSchema("name")); schema.setDisplayField("name"); return meshRoot().getSchemaContainerRoot().create(schema, user()); } /** * Update the schema container by adding a new string field with given name and reload the schema container * * @param schemaContainer * schema container * @param newName * new name * @throws Exception */ protected void updateSchema(SchemaContainer schemaContainer, String newName) throws Exception { Schema schema = schemaContainer.getLatestVersion().getSchema(); Schema updatedSchema = new SchemaModel(); updatedSchema.setName(schema.getName()); updatedSchema.setDisplayField(schema.getDisplayField()); updatedSchema.getFields().addAll(schema.getFields()); updatedSchema.addField(FieldUtil.createStringFieldSchema(newName)); SchemaChangesListModel model = new SchemaChangesListModel(); model.getChanges().addAll(new SchemaComparator().diff(schema, updatedSchema)); InternalActionContext ac = getMockedInternalActionContext(); schemaContainer.getLatestVersion().applyChanges(ac, model).toBlocking().value(); schemaContainer.reload(); } /** * Create a new microschema with a single string field "name" * * @param name * microschema name * @return microschema container * @throws Exception */ protected MicroschemaContainer createMicroschema(String name) throws Exception { MicroschemaModel microschema = new MicroschemaModel(); microschema.setName(name); microschema.addField(FieldUtil.createStringFieldSchema("name")); return meshRoot().getMicroschemaContainerRoot().create(microschema, user()); } /** * Update the microschema container by adding a new string field with given name and reload the microschema container * * @param microschemaContainer * microschema container * @param newName * new name * @throws Exception */ protected void updateMicroschema(MicroschemaContainer microschemaContainer, String newName) throws Exception { Microschema microschema = microschemaContainer.getLatestVersion().getSchema(); Microschema updatedMicroschema = new MicroschemaModel(); updatedMicroschema.setName(microschema.getName()); updatedMicroschema.getFields().addAll(microschema.getFields()); updatedMicroschema.addField(FieldUtil.createStringFieldSchema(newName)); SchemaChangesListModel model = new SchemaChangesListModel(); model.getChanges().addAll(meshDagger.microschemaComparator().diff(microschema, updatedMicroschema)); InternalActionContext ac = getMockedInternalActionContext(); microschemaContainer.getLatestVersion().applyChanges(ac, model).toBlocking().value(); microschemaContainer.reload(); } }
package com.yammer.metrics.examples; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.CounterMetric; import com.yammer.metrics.core.HistogramMetric; import com.yammer.metrics.reporting.ConsoleReporter; import java.io.File; import java.util.List; import java.util.concurrent.*; public class ExampleRunner { private static final int WORKER_COUNT = 10; private static final BlockingQueue<File> JOBS = new LinkedBlockingQueue<File>(); private static final ExecutorService POOL = Executors.newFixedThreadPool(WORKER_COUNT); private static final CounterMetric QUEUE_DEPTH = Metrics.newCounter(ExampleRunner.class, "queue-depth"); private static final HistogramMetric DIRECTORY_SIZE = Metrics.newHistogram(ExampleRunner.class, "directory-size", false); public static class Job implements Runnable { @Override public void run() { try { while (true) { final File file = JOBS.poll(1, TimeUnit.MINUTES); QUEUE_DEPTH.dec(); if (file.isDirectory()) { final List<File> contents = new DirectoryLister(file).list(); DIRECTORY_SIZE.update(contents.size()); QUEUE_DEPTH.inc(contents.size()); JOBS.addAll(contents); } } } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { ConsoleReporter.enable(10, TimeUnit.SECONDS); System.err.println("Scanning all files on your hard drive..."); JOBS.add(new File("/")); QUEUE_DEPTH.inc(); for (int i = 0; i < WORKER_COUNT; i++) { POOL.submit(new Job()); } POOL.awaitTermination(10, TimeUnit.DAYS); } }
package com.alamkanak.weekview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.support.v4.view.GestureDetectorCompat; import android.support.v4.view.ViewCompat; import android.text.Layout; import android.text.SpannableStringBuilder; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.style.StyleSpan; import android.util.AttributeSet; import android.util.TypedValue; import android.view.GestureDetector; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.SoundEffectConstants; import android.view.View; import android.widget.OverScroller; import android.widget.Scroller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; public class WeekView extends View { @Deprecated public static final int LENGTH_SHORT = 1; @Deprecated public static final int LENGTH_LONG = 2; private final Context mContext; private Paint mTimeTextPaint; private float mTimeTextWidth; private float mTimeTextHeight; private Paint mHeaderTextPaint; private float mHeaderTextHeight; private GestureDetectorCompat mGestureDetector; private OverScroller mScroller; private PointF mCurrentOrigin = new PointF(0f, 0f); private Direction mCurrentScrollDirection = Direction.NONE; private Paint mHeaderBackgroundPaint; private float mWidthPerDay; private Paint mDayBackgroundPaint; private Paint mHourSeparatorPaint; private float mHeaderMarginBottom; private Paint mTodayBackgroundPaint; private Paint mFutureBackgroundPaint; private Paint mPastBackgroundPaint; private Paint mFutureWeekendBackgroundPaint; private Paint mPastWeekendBackgroundPaint; private Paint mNowLinePaint; private Paint mTodayHeaderTextPaint; private Paint mEventBackgroundPaint; private float mHeaderColumnWidth; private List<EventRect> mEventRects; private List<WeekViewEvent> mPreviousPeriodEvents; private List<WeekViewEvent> mCurrentPeriodEvents; private List<WeekViewEvent> mNextPeriodEvents; private TextPaint mEventTextPaint; private Paint mHeaderColumnBackgroundPaint; private Scroller mStickyScroller; private int mFetchedPeriod = -1; // the middle period the calendar has fetched. private boolean mRefreshEvents = false; private float mDistanceY = 0; private float mDistanceX = 0; private Direction mCurrentFlingDirection = Direction.NONE; // Attributes and their default values. private int mHourHeight = 50; private int mNewHourHeight = -1; private int mMinHourHeight = 0; //no minimum specified (will be dynamic, based on screen) private int mEffectiveMinHourHeight = mMinHourHeight; //compensates for the fact that you can't keep zooming out. private int mMaxHourHeight = 250; private int mColumnGap = 10; private int mFirstDayOfWeek = Calendar.MONDAY; private int mTextSize = 12; private int mHeaderColumnPadding = 10; private int mHeaderColumnTextColor = Color.BLACK; private int mNumberOfVisibleDays = 3; private int mHeaderRowPadding = 10; private int mHeaderRowBackgroundColor = Color.WHITE; private int mDayBackgroundColor = Color.rgb(245, 245, 245); private int mPastBackgroundColor = Color.rgb(227, 227, 227); private int mFutureBackgroundColor = Color.rgb(245, 245, 245); private int mPastWeekendBackgroundColor = 0; private int mFutureWeekendBackgroundColor = 0; private int mNowLineColor = Color.rgb(102, 102, 102); private int mNowLineThickness = 5; private boolean mUseNewColoring = false; private int mHourSeparatorColor = Color.rgb(230, 230, 230); private int mTodayBackgroundColor = Color.rgb(239, 247, 254); private int mHourSeparatorHeight = 2; private int mTodayHeaderTextColor = Color.rgb(39, 137, 228); private int mEventTextSize = 12; private int mEventTextColor = Color.BLACK; private int mEventPadding = 8; private int mHeaderColumnBackgroundColor = Color.WHITE; private int mDefaultEventColor; private boolean mIsFirstDraw = true; private boolean mAreDimensionsInvalid = true; @Deprecated private int mDayNameLength = LENGTH_LONG; private int mOverlappingEventGap = 0; private int mEventMarginVertical = 0; private float mXScrollingSpeed = 1f; private Calendar mFirstVisibleDay; private Calendar mLastVisibleDay; private Calendar mScrollToDay = null; private double mScrollToHour = -1; private ScaleGestureDetector mScaleDetector; private boolean mIsZooming; private int mEventCornerRadius = 0; // Listeners. private EventClickListener mEventClickListener; private EventLongPressListener mEventLongPressListener; private WeekViewLoader mWeekViewLoader; private EmptyViewClickListener mEmptyViewClickListener; private EmptyViewLongPressListener mEmptyViewLongPressListener; private DateTimeInterpreter mDateTimeInterpreter; private ScrollListener mScrollListener; private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { mScroller.forceFinished(true); mStickyScroller.forceFinished(true); return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if(mIsZooming) return true; if (mCurrentScrollDirection == Direction.NONE) { if (Math.abs(distanceX) > Math.abs(distanceY)){ mCurrentScrollDirection = Direction.HORIZONTAL; mCurrentFlingDirection = Direction.HORIZONTAL; } else { mCurrentFlingDirection = Direction.VERTICAL; mCurrentScrollDirection = Direction.VERTICAL; } } mDistanceX = distanceX * mXScrollingSpeed; mDistanceY = distanceY; invalidate(); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { mScroller.forceFinished(true); if (mCurrentFlingDirection == Direction.HORIZONTAL){ mScroller.fling((int) mCurrentOrigin.x, 0, (int) (velocityX * mXScrollingSpeed), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); } else if (mCurrentFlingDirection == Direction.VERTICAL){ mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - getHeight()), 0); } ViewCompat.postInvalidateOnAnimation(WeekView.this); return true; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { // If the tap was on an event then trigger the callback. if (mEventRects != null && mEventClickListener != null) { List<EventRect> reversedEventRects = mEventRects; Collections.reverse(reversedEventRects); for (EventRect event : reversedEventRects) { if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) { mEventClickListener.onEventClick(event.originalEvent, event.rectF); playSoundEffect(SoundEffectConstants.CLICK); return super.onSingleTapConfirmed(e); } } } // If the tap was on in an empty space, then trigger the callback. if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) { Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY()); if (selectedTime != null) { playSoundEffect(SoundEffectConstants.CLICK); mEmptyViewClickListener.onEmptyViewClicked(selectedTime); } } return super.onSingleTapConfirmed(e); } @Override public void onLongPress(MotionEvent e) { super.onLongPress(e); if (mEventLongPressListener != null && mEventRects != null) { List<EventRect> reversedEventRects = mEventRects; Collections.reverse(reversedEventRects); for (EventRect event : reversedEventRects) { if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) { mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF); performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); return; } } } // If the tap was on in an empty space, then trigger the callback. if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) { Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY()); if (selectedTime != null) { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime); } } } }; private enum Direction { NONE, HORIZONTAL, VERTICAL } public WeekView(Context context) { this(context, null); } public WeekView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public WeekView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); // Hold references. mContext = context; // Get the attribute values (if any). TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0); try { mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek); mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight); mMinHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_minHourHeight, mMinHourHeight); mEffectiveMinHourHeight = mMinHourHeight; mMaxHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_maxHourHeight, mMaxHourHeight); mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics())); mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding); mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap); mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor); mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays); mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding); mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor); mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor); mFutureBackgroundColor = a.getColor(R.styleable.WeekView_futureBackgroundColor, mFutureBackgroundColor); mPastBackgroundColor = a.getColor(R.styleable.WeekView_pastBackgroundColor, mPastBackgroundColor); mFutureWeekendBackgroundColor = a.getColor(R.styleable.WeekView_futureWeekendBackgroundColor, mFutureBackgroundColor); // If not set, use the same color as in the week mPastWeekendBackgroundColor = a.getColor(R.styleable.WeekView_pastWeekendBackgroundColor, mPastBackgroundColor); mNowLineColor = a.getColor(R.styleable.WeekView_nowLineColor, mNowLineColor); mNowLineThickness = a.getDimensionPixelSize(R.styleable.WeekView_nowLineThickness, mNowLineThickness); mUseNewColoring = a.getBoolean(R.styleable.WeekView_useNewColoringStyle, mUseNewColoring); mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor); mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor); mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight); mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor); mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics())); mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor); mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding); mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor); mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength); mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap); mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical); mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed); mEventCornerRadius = a.getDimensionPixelSize(R.styleable.WeekView_eventCornerRadius, mEventCornerRadius); } finally { a.recycle(); } init(); } private void init() { // Scrolling initialization. mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener); mScroller = new OverScroller(mContext); mStickyScroller = new Scroller(mContext); // Measure settings for time column. mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTimeTextPaint.setTextAlign(Paint.Align.RIGHT); mTimeTextPaint.setTextSize(mTextSize); mTimeTextPaint.setColor(mHeaderColumnTextColor); Rect rect = new Rect(); mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect); mTimeTextHeight = rect.height(); mHeaderMarginBottom = mTimeTextHeight / 2; initTextTimeWidth(); // Measure settings for header row. mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mHeaderTextPaint.setColor(mHeaderColumnTextColor); mHeaderTextPaint.setTextAlign(Paint.Align.CENTER); mHeaderTextPaint.setTextSize(mTextSize); mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect); mHeaderTextHeight = rect.height(); mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD); // Prepare header background paint. mHeaderBackgroundPaint = new Paint(); mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor); // Prepare day background color paint. mDayBackgroundPaint = new Paint(); mDayBackgroundPaint.setColor(mDayBackgroundColor); mFutureBackgroundPaint = new Paint(); mFutureBackgroundPaint.setColor(mFutureBackgroundColor); mPastBackgroundPaint = new Paint(); mPastBackgroundPaint.setColor(mPastBackgroundColor); mFutureWeekendBackgroundPaint = new Paint(); mFutureWeekendBackgroundPaint.setColor(mFutureWeekendBackgroundColor); mPastWeekendBackgroundPaint = new Paint(); mPastWeekendBackgroundPaint.setColor(mPastWeekendBackgroundColor); // Prepare hour separator color paint. mHourSeparatorPaint = new Paint(); mHourSeparatorPaint.setStyle(Paint.Style.STROKE); mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight); mHourSeparatorPaint.setColor(mHourSeparatorColor); // Prepare the "now" line color paint mNowLinePaint = new Paint(); mNowLinePaint.setStrokeWidth(mNowLineThickness); mNowLinePaint.setColor(mNowLineColor); // Prepare today background color paint. mTodayBackgroundPaint = new Paint(); mTodayBackgroundPaint.setColor(mTodayBackgroundColor); // Prepare today header text color paint. mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER); mTodayHeaderTextPaint.setTextSize(mTextSize); mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD); mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor); // Prepare event background color. mEventBackgroundPaint = new Paint(); mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238)); // Prepare header column background color. mHeaderColumnBackgroundPaint = new Paint(); mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor); // Prepare event text size and color. mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG); mEventTextPaint.setStyle(Paint.Style.FILL); mEventTextPaint.setColor(mEventTextColor); mEventTextPaint.setTextSize(mEventTextSize); // Set default event color. mDefaultEventColor = Color.parseColor("#9fc6e7"); mScaleDetector = new ScaleGestureDetector(mContext, new ScaleGestureDetector.OnScaleGestureListener() { @Override public void onScaleEnd(ScaleGestureDetector detector) { mIsZooming = false; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { mIsZooming = true; mScroller.forceFinished(true); mCurrentScrollDirection = mCurrentFlingDirection = Direction.NONE; goToNearestOrigin(); return true; } @Override public boolean onScale(ScaleGestureDetector detector) { mNewHourHeight = Math.round(mHourHeight * detector.getScaleFactor()); invalidate(); return true; } }); } /** * Initialize time column width. Calculate value with all possible hours (supposed widest text) */ private void initTextTimeWidth() { mTimeTextWidth = 0; for (int i = 0; i < 24; i++) { // measure time string and get max width String time = getDateTimeInterpreter().interpretTime(i); if (time == null) throw new IllegalStateException("A DateTimeInterpreter must not return null time"); mTimeTextWidth = Math.max(mTimeTextWidth, mTimeTextPaint.measureText(time)); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Draw the header row. drawHeaderRowAndEvents(canvas); // Draw the time column and all the axes/separators. drawTimeColumnAndAxes(canvas); // Hide everything in the first cell (top left corner). canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint); // Hide anything that is in the bottom margin of the header row. canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2, mHeaderColumnBackgroundPaint); } private void drawTimeColumnAndAxes(Canvas canvas) { // Draw the background color for the header column. canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint); for (int i = 0; i < 24; i++) { float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom; // Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner. String time = getDateTimeInterpreter().interpretTime(i); if (time == null) throw new IllegalStateException("A DateTimeInterpreter must not return null time"); if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint); } } private void drawHeaderRowAndEvents(Canvas canvas) { // Calculate the available width for each day. mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2; mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1); mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays; Calendar today = today(); if (mAreDimensionsInvalid) { mEffectiveMinHourHeight= Math.max(mMinHourHeight, (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom) / 24)); mAreDimensionsInvalid = false; if(mScrollToDay != null) goToDate(mScrollToDay); mAreDimensionsInvalid = false; if(mScrollToHour >= 0) goToHour(mScrollToHour); mScrollToDay = null; mScrollToHour = -1; mAreDimensionsInvalid = false; } if (mIsFirstDraw){ mIsFirstDraw = false; // If the week view is being drawn for the first time, then consider the first day of the week. if(mNumberOfVisibleDays >= 7 && today.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) { int difference = 7 + (today.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek); mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference; } } // Do not let the view go above/below the limit due to scrolling. Set the max and min limit of the scroll. if (mCurrentScrollDirection == Direction.VERTICAL) mCurrentOrigin.y -= mDistanceY; //Calculate the new height due to the zooming. if (mNewHourHeight > 0){ if(mNewHourHeight < mEffectiveMinHourHeight) mNewHourHeight = mEffectiveMinHourHeight; else if(mNewHourHeight > mMaxHourHeight) mNewHourHeight = mMaxHourHeight; mCurrentOrigin.y = (mCurrentOrigin.y/mHourHeight)*mNewHourHeight; mHourHeight = mNewHourHeight; mNewHourHeight = -1; } //if the new mCurrentOrigin.y is invalid, make it valid. if (mCurrentOrigin.y < getHeight() - mHourHeight * 24 - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight/2) mCurrentOrigin.y = getHeight() - mHourHeight * 24 - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom - mTimeTextHeight/2; //Don't put an else if because it will trigger a glitch when completly zoomed out and scrolling vertically. if(mCurrentOrigin.y > 0) mCurrentOrigin.y = 0; // Consider scroll offset. if (mCurrentScrollDirection == Direction.HORIZONTAL) mCurrentOrigin.x -= mDistanceX; int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap))); float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps + mHeaderColumnWidth; float startPixel = startFromPixel; // Prepare to iterate for each day. Calendar day = (Calendar) today.clone(); day.add(Calendar.HOUR, 6); // Prepare to iterate for each hour to draw the hour lines. int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 - mHeaderMarginBottom) / mHourHeight) + 1; lineCount = (lineCount) * (mNumberOfVisibleDays+1); float[] hourLines = new float[lineCount * 4]; // Clear the cache for event rectangles. if (mEventRects != null) { for (EventRect eventRect: mEventRects) { eventRect.rectF = null; } } // Iterate through each day. Calendar oldFirstVisibleDay = mFirstVisibleDay; mFirstVisibleDay = (Calendar) today.clone(); mFirstVisibleDay.add(Calendar.DATE, -(Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)))); if(!mFirstVisibleDay.equals(oldFirstVisibleDay) && mScrollListener != null){ mScrollListener.onFirstVisibleDayChanged(mFirstVisibleDay, oldFirstVisibleDay); } for (int dayNumber = leftDaysWithGaps + 1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) { // Check if the day is today. day = (Calendar) today.clone(); mLastVisibleDay = (Calendar) day.clone(); day.add(Calendar.DATE, dayNumber - 1); mLastVisibleDay.add(Calendar.DATE, dayNumber - 2); boolean sameDay = isSameDay(day, today); // Get more events if necessary. We want to store the events 3 months beforehand. Get // events only when it is the first iteration of the loop. if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedPeriod != (int) mWeekViewLoader.toWeekViewPeriodIndex(day) && Math.abs(mFetchedPeriod - mWeekViewLoader.toWeekViewPeriodIndex(day)) > 0.5)) { getMoreEvents(day); mRefreshEvents = false; } // Draw background color for each day. float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel); if (mWidthPerDay + startPixel - start> 0){ if(mUseNewColoring){ boolean isWeekend = (day.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || day.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY); Paint pastPaint = isWeekend ? mPastWeekendBackgroundPaint : mPastBackgroundPaint; Paint futurePaint = isWeekend ? mFutureWeekendBackgroundPaint : mFutureBackgroundPaint; float startY = mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom + mCurrentOrigin.y; if(sameDay){ Calendar now = Calendar.getInstance(); float beforeNow = (now.get(Calendar.HOUR_OF_DAY)+now.get(Calendar.MINUTE)/60.0f)*mHourHeight; canvas.drawRect(start, startY, startPixel + mWidthPerDay, startY+beforeNow, pastPaint); canvas.drawRect(start, startY+beforeNow, startPixel + mWidthPerDay, getHeight(), futurePaint); } else if(day.before(today)) { canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), pastPaint); } else { canvas.drawRect(start, startY, startPixel + mWidthPerDay, getHeight(), futurePaint); } }else{ canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint); } } // Prepare the separator lines for hours. int i = 0; for (int hourNumber = 0; hourNumber < 24; hourNumber++) { float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom; if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){ hourLines[i * 4] = start; hourLines[i * 4 + 1] = top; hourLines[i * 4 + 2] = startPixel + mWidthPerDay; hourLines[i * 4 + 3] = top; i++; } } // Draw the lines for hours. canvas.drawLines(hourLines, mHourSeparatorPaint); // Draw the events. drawEvents(day, startPixel, canvas); //Draw the line at the current time if(mUseNewColoring && sameDay){ float startY = mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom + mCurrentOrigin.y; Calendar now = Calendar.getInstance(); float beforeNow = (now.get(Calendar.HOUR_OF_DAY)+now.get(Calendar.MINUTE)/60.0f)*mHourHeight; canvas.drawLine(start, startY+beforeNow, startPixel + mWidthPerDay, startY+beforeNow, mNowLinePaint); } // In the next iteration, start from the next day. startPixel += mWidthPerDay + mColumnGap; } // Draw the header background. canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint); // Draw the header row texts. startPixel = startFromPixel; for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) { // Check if the day is today. day = (Calendar) today.clone(); day.add(Calendar.DATE, dayNumber - 1); boolean sameDay = isSameDay(day, today); // Draw the day labels. String dayLabel = getDateTimeInterpreter().interpretDate(day); if (dayLabel == null) throw new IllegalStateException("A DateTimeInterpreter must not return null date"); canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint); startPixel += mWidthPerDay + mColumnGap; } } /** * Get the time and date where the user clicked on. * @param x The x position of the touch event. * @param y The y position of the touch event. * @return The time and date at the clicked position. */ private Calendar getTimeFromPoint(float x, float y){ int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap))); float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps + mHeaderColumnWidth; for (int dayNumber = leftDaysWithGaps + 1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) { float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel); if (mWidthPerDay + startPixel - start> 0 && x>start && x<startPixel + mWidthPerDay){ Calendar day = today(); day.add(Calendar.DATE, dayNumber - 1); float pixelsFromZero = y - mCurrentOrigin.y - mHeaderTextHeight - mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom; int hour = (int)(pixelsFromZero / mHourHeight); int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight); day.add(Calendar.HOUR, hour); day.set(Calendar.MINUTE, minute); return day; } startPixel += mWidthPerDay + mColumnGap; } return null; } /** * Draw all the events of a particular day. * @param date The day. * @param startFromPixel The left position of the day area. The events will never go any left from this value. * @param canvas The canvas to draw upon. */ private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) { if (mEventRects != null && mEventRects.size() > 0) { for (int i = 0; i < mEventRects.size(); i++) { if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) { // Calculate top. float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical; // Calculate bottom. float bottom = mEventRects.get(i).bottom; bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical; // Calculate left and right. float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay; if (left < startFromPixel) left += mOverlappingEventGap; float right = left + mEventRects.get(i).width * mWidthPerDay; if (right < startFromPixel + mWidthPerDay) right -= mOverlappingEventGap; // Draw the event and the event name on top of it. RectF eventRectF = new RectF(left, top, right, bottom); if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right && eventRectF.right > mHeaderColumnWidth && eventRectF.left < getWidth() && eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom && eventRectF.top < getHeight() && left < right ) { mEventRects.get(i).rectF = eventRectF; mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor()); canvas.drawRoundRect(mEventRects.get(i).rectF, mEventCornerRadius, mEventCornerRadius, mEventBackgroundPaint); drawEventTitle(mEventRects.get(i).event, mEventRects.get(i).rectF, canvas, top, left); } else mEventRects.get(i).rectF = null; } } } } /** * Draw the name of the event on top of the event rectangle. * @param event The event of which the title (and location) should be drawn. * @param rect The rectangle on which the text is to be drawn. * @param canvas The canvas to draw upon. * @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area. * @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area. */ private void drawEventTitle(WeekViewEvent event, RectF rect, Canvas canvas, float originalTop, float originalLeft) { if (rect.right - rect.left - mEventPadding * 2 < 0) return; SpannableStringBuilder bob = new SpannableStringBuilder(); if (event.getName() != null) { bob.append(event.getName()); bob.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),0,bob.length(),0); bob.append(' '); } if (event.getLocation() != null) { bob.append(event.getLocation()); } // Get text dimensions StaticLayout textLayout = new StaticLayout(bob, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); // Crop height int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2); int lineHeight = textLayout.getHeight() / textLayout.getLineCount(); if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) { int lineCount = textLayout.getLineCount(); int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight()); float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount; textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); } else if (lineHeight >= availableHeight) { int width = (int) (rect.right - originalLeft - mEventPadding * 2); textLayout = new StaticLayout(TextUtils.ellipsize(bob, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false); } // Draw text canvas.save(); canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding); textLayout.draw(canvas); canvas.restore(); } /** * A class to hold reference to the events and their visual representation. An EventRect is * actually the rectangle that is drawn on the calendar for a given event. There may be more * than one rectangle for a single event (an event that expands more than one day). In that * case two instances of the EventRect will be used for a single event. The given event will be * stored in "originalEvent". But the event that corresponds to rectangle the rectangle * instance will be stored in "event". */ private class EventRect { public WeekViewEvent event; public WeekViewEvent originalEvent; public RectF rectF; public float left; public float width; public float top; public float bottom; /** * Create a new instance of event rect. An EventRect is actually the rectangle that is drawn * on the calendar for a given event. There may be more than one rectangle for a single * event (an event that expands more than one day). In that case two instances of the * EventRect will be used for a single event. The given event will be stored in * "originalEvent". But the event that corresponds to rectangle the rectangle instance will * be stored in "event". * @param event Represents the event which this instance of rectangle represents. * @param originalEvent The original event that was passed by the user. * @param rectF The rectangle. */ public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) { this.event = event; this.rectF = rectF; this.originalEvent = originalEvent; } } /** * Gets more events of one/more month(s) if necessary. This method is called when the user is * scrolling the week view. The week view stores the events of three months: the visible month, * the previous month, the next month. * @param day The day where the user is currently is. */ private void getMoreEvents(Calendar day) { // Get more events if the month is changed. if (mEventRects == null) mEventRects = new ArrayList<EventRect>(); if (mWeekViewLoader == null && !isInEditMode()) throw new IllegalStateException("You must provide a MonthChangeListener"); // If a refresh was requested then reset some variables. if (mRefreshEvents) { mEventRects.clear(); mPreviousPeriodEvents = null; mCurrentPeriodEvents = null; mNextPeriodEvents = null; mFetchedPeriod = -1; } if(mWeekViewLoader != null){ int periodToFetch = (int) mWeekViewLoader.toWeekViewPeriodIndex(day); if (!isInEditMode() && (mFetchedPeriod < 0 || mFetchedPeriod != periodToFetch || mRefreshEvents)) { List<WeekViewEvent> previousPeriodEvents = null; List<WeekViewEvent> currentPeriodEvents = null; List<WeekViewEvent> nextPeriodEvents = null; if(mPreviousPeriodEvents != null && mCurrentPeriodEvents != null && mNextPeriodEvents != null){ if(periodToFetch == mFetchedPeriod-1){ currentPeriodEvents = mPreviousPeriodEvents; nextPeriodEvents = mCurrentPeriodEvents; }else if(periodToFetch == mFetchedPeriod){ previousPeriodEvents = mPreviousPeriodEvents; currentPeriodEvents = mCurrentPeriodEvents; nextPeriodEvents = mNextPeriodEvents; }else if(periodToFetch == mFetchedPeriod+1){ previousPeriodEvents = mCurrentPeriodEvents; currentPeriodEvents = mNextPeriodEvents; } } if(currentPeriodEvents == null) currentPeriodEvents = mWeekViewLoader.onLoad(periodToFetch); if(previousPeriodEvents == null) previousPeriodEvents = mWeekViewLoader.onLoad(periodToFetch-1); if(nextPeriodEvents == null) nextPeriodEvents = mWeekViewLoader.onLoad(periodToFetch+1); //clear events mEventRects.clear(); sortAndCacheEvents(previousPeriodEvents); sortAndCacheEvents(currentPeriodEvents); sortAndCacheEvents(nextPeriodEvents); mPreviousPeriodEvents = previousPeriodEvents; mCurrentPeriodEvents = currentPeriodEvents; mNextPeriodEvents = nextPeriodEvents; mFetchedPeriod = periodToFetch; } } // Prepare to calculate positions of each events. List<EventRect> tempEvents = mEventRects; mEventRects = new ArrayList<EventRect>(); // Iterate through each day with events to calculate the position of the events. while (tempEvents.size() > 0) { ArrayList<EventRect> eventRects = new ArrayList<>(tempEvents.size()); // get first event for a day EventRect eventRect1 = tempEvents.remove(0); eventRects.add(eventRect1); int i = 0; while (i < tempEvents.size()) { // collect all other events for same day EventRect eventRect2 = tempEvents.get(i); if (isSameDay(eventRect1.event.getStartTime(), eventRect2.event.getStartTime())) { tempEvents.remove(i); eventRects.add(eventRect2); } else { i++; } } computePositionOfEvents(eventRects); } } /** * Cache the event for smooth scrolling functionality. * @param event The event to cache. */ private void cacheEvent(WeekViewEvent event) { if (!isSameDay(event.getStartTime(), event.getEndTime())) { Calendar endTime = (Calendar) event.getStartTime().clone(); endTime.set(Calendar.HOUR_OF_DAY, 23); endTime.set(Calendar.MINUTE, 59); Calendar startTime = (Calendar) event.getEndTime().clone(); startTime.set(Calendar.HOUR_OF_DAY, 0); startTime.set(Calendar.MINUTE, 0); WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getLocation(), event.getStartTime(), endTime); event1.setColor(event.getColor()); WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), event.getLocation(), startTime, event.getEndTime()); event2.setColor(event.getColor()); mEventRects.add(new EventRect(event1, event, null)); mEventRects.add(new EventRect(event2, event, null)); } else mEventRects.add(new EventRect(event, event, null)); } private void sortAndCacheEvents(List<WeekViewEvent> events){ sortEvents(events); for(WeekViewEvent event : events){ cacheEvent(event); } } /** * Sorts the events in ascending order. * @param events The events to be sorted. */ private void sortEvents(List<WeekViewEvent> events) { Collections.sort(events, new Comparator<WeekViewEvent>() { @Override public int compare(WeekViewEvent event1, WeekViewEvent event2) { long start1 = event1.getStartTime().getTimeInMillis(); long start2 = event2.getStartTime().getTimeInMillis(); int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0); if (comparator == 0) { long end1 = event1.getEndTime().getTimeInMillis(); long end2 = event2.getEndTime().getTimeInMillis(); comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0); } return comparator; } }); } /** * Calculates the left and right positions of each events. This comes handy specially if events * are overlapping. * @param eventRects The events along with their wrapper class. */ private void computePositionOfEvents(List<EventRect> eventRects) { // Make "collision groups" for all events that collide with others. List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>(); for (EventRect eventRect : eventRects) { boolean isPlaced = false; outerLoop: for (List<EventRect> collisionGroup : collisionGroups) { for (EventRect groupEvent : collisionGroup) { if (isEventsCollide(groupEvent.event, eventRect.event)) { collisionGroup.add(eventRect); isPlaced = true; break outerLoop; } } } if (!isPlaced) { List<EventRect> newGroup = new ArrayList<EventRect>(); newGroup.add(eventRect); collisionGroups.add(newGroup); } } for (List<EventRect> collisionGroup : collisionGroups) { expandEventsToMaxWidth(collisionGroup); } } /** * Expands all the events to maximum possible width. The events will try to occupy maximum * space available horizontally. * @param collisionGroup The group of events which overlap with each other. */ private void expandEventsToMaxWidth(List<EventRect> collisionGroup) { // Expand the events to maximum possible width. List<List<EventRect>> columns = new ArrayList<List<EventRect>>(); columns.add(new ArrayList<EventRect>()); for (EventRect eventRect : collisionGroup) { boolean isPlaced = false; for (List<EventRect> column : columns) { if (column.size() == 0) { column.add(eventRect); isPlaced = true; } else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) { column.add(eventRect); isPlaced = true; break; } } if (!isPlaced) { List<EventRect> newColumn = new ArrayList<EventRect>(); newColumn.add(eventRect); columns.add(newColumn); } } // Calculate left and right position for all the events. // Get the maxRowCount by looking in all columns. int maxRowCount = 0; for (List<EventRect> column : columns){ maxRowCount = Math.max(maxRowCount, column.size()); } for (int i = 0; i < maxRowCount; i++) { // Set the left and right values of the event. float j = 0; for (List<EventRect> column : columns) { if (column.size() >= i+1) { EventRect eventRect = column.get(i); eventRect.width = 1f / columns.size(); eventRect.left = j / columns.size(); eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE); eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE); mEventRects.add(eventRect); } j++; } } } /** * Checks if two events overlap. * @param event1 The first event. * @param event2 The second event. * @return true if the events overlap. */ private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) { long start1 = event1.getStartTime().getTimeInMillis(); long end1 = event1.getEndTime().getTimeInMillis(); long start2 = event2.getStartTime().getTimeInMillis(); long end2 = event2.getEndTime().getTimeInMillis(); return !((start1 >= end2) || (end1 <= start2)); } /** * Checks if time1 occurs after (or at the same time) time2. * @param time1 The time to check. * @param time2 The time to check against. * @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false. */ private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) { return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis(); } @Override public void invalidate() { super.invalidate(); mAreDimensionsInvalid = true; } // Functions related to setting and getting the properties. public void setOnEventClickListener (EventClickListener listener) { this.mEventClickListener = listener; } public EventClickListener getEventClickListener() { return mEventClickListener; } public MonthChangeListener getMonthChangeListener() { if(mWeekViewLoader instanceof MonthLoader) return ((MonthLoader) mWeekViewLoader).getOnMonthChangeListener(); return null; } public void setMonthChangeListener(MonthChangeListener monthChangeListener) { this.mWeekViewLoader = new MonthLoader(monthChangeListener); } public WeekViewLoader getWeekViewLoader(){ return mWeekViewLoader; } public void setWeekViewLoader(WeekViewLoader loader){ this.mWeekViewLoader = loader; } public EventLongPressListener getEventLongPressListener() { return mEventLongPressListener; } public void setEventLongPressListener(EventLongPressListener eventLongPressListener) { this.mEventLongPressListener = eventLongPressListener; } public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){ this.mEmptyViewClickListener = emptyViewClickListener; } public EmptyViewClickListener getEmptyViewClickListener(){ return mEmptyViewClickListener; } public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){ this.mEmptyViewLongPressListener = emptyViewLongPressListener; } public EmptyViewLongPressListener getEmptyViewLongPressListener(){ return mEmptyViewLongPressListener; } public void setScrollListener(ScrollListener scrolledListener){ this.mScrollListener = scrolledListener; } public ScrollListener getScrollListener(){ return mScrollListener; } /** * Get the interpreter which provides the text to show in the header column and the header row. * @return The date, time interpreter. */ public DateTimeInterpreter getDateTimeInterpreter() { if (mDateTimeInterpreter == null) { mDateTimeInterpreter = new DateTimeInterpreter() { @Override public String interpretDate(Calendar date) { try { SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", Locale.getDefault()) : new SimpleDateFormat("EEE M/dd", Locale.getDefault()); return sdf.format(date.getTime()).toUpperCase(); } catch (Exception e) { e.printStackTrace(); return ""; } } @Override public String interpretTime(int hour) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, 0); try { SimpleDateFormat sdf = DateFormat.is24HourFormat(getContext()) ? new SimpleDateFormat("HH:mm", Locale.getDefault()) : new SimpleDateFormat("hh a", Locale.getDefault()); return sdf.format(calendar.getTime()); } catch (Exception e) { e.printStackTrace(); return ""; } } }; } return mDateTimeInterpreter; } /** * Set the interpreter which provides the text to show in the header column and the header row. * @param dateTimeInterpreter The date, time interpreter. */ public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){ this.mDateTimeInterpreter = dateTimeInterpreter; // refresh time column width initTextTimeWidth(); } /** * Get the number of visible days in a week. * @return The number of visible days in a week. */ public int getNumberOfVisibleDays() { return mNumberOfVisibleDays; } /** * Set the number of visible days in a week. * @param numberOfVisibleDays The number of visible days in a week. */ public void setNumberOfVisibleDays(int numberOfVisibleDays) { this.mNumberOfVisibleDays = numberOfVisibleDays; mCurrentOrigin.x = 0; mCurrentOrigin.y = 0; invalidate(); } public int getHourHeight() { return mHourHeight; } public void setHourHeight(int hourHeight) { mNewHourHeight = hourHeight; invalidate(); } public int getColumnGap() { return mColumnGap; } public void setColumnGap(int columnGap) { mColumnGap = columnGap; invalidate(); } public int getFirstDayOfWeek() { return mFirstDayOfWeek; } /** * Set the first day of the week. First day of the week is used only when the week view is first * drawn. It does not of any effect after user starts scrolling horizontally. * <p> * <b>Note:</b> This method will only work if the week view is set to display more than 6 days at * once. * </p> * @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY}, * {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY}, * {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY}, * {@link java.util.Calendar#FRIDAY}. */ public void setFirstDayOfWeek(int firstDayOfWeek) { mFirstDayOfWeek = firstDayOfWeek; invalidate(); } public int getTextSize() { return mTextSize; } public void setTextSize(int textSize) { mTextSize = textSize; mTodayHeaderTextPaint.setTextSize(mTextSize); mHeaderTextPaint.setTextSize(mTextSize); mTimeTextPaint.setTextSize(mTextSize); invalidate(); } public int getHeaderColumnPadding() { return mHeaderColumnPadding; } public void setHeaderColumnPadding(int headerColumnPadding) { mHeaderColumnPadding = headerColumnPadding; invalidate(); } public int getHeaderColumnTextColor() { return mHeaderColumnTextColor; } public void setHeaderColumnTextColor(int headerColumnTextColor) { mHeaderColumnTextColor = headerColumnTextColor; invalidate(); } public int getHeaderRowPadding() { return mHeaderRowPadding; } public void setHeaderRowPadding(int headerRowPadding) { mHeaderRowPadding = headerRowPadding; invalidate(); } public int getHeaderRowBackgroundColor() { return mHeaderRowBackgroundColor; } public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) { mHeaderRowBackgroundColor = headerRowBackgroundColor; invalidate(); } public int getDayBackgroundColor() { return mDayBackgroundColor; } public void setDayBackgroundColor(int dayBackgroundColor) { mDayBackgroundColor = dayBackgroundColor; invalidate(); } public int getHourSeparatorColor() { return mHourSeparatorColor; } public void setHourSeparatorColor(int hourSeparatorColor) { mHourSeparatorColor = hourSeparatorColor; invalidate(); } public int getTodayBackgroundColor() { return mTodayBackgroundColor; } public void setTodayBackgroundColor(int todayBackgroundColor) { mTodayBackgroundColor = todayBackgroundColor; invalidate(); } public int getHourSeparatorHeight() { return mHourSeparatorHeight; } public void setHourSeparatorHeight(int hourSeparatorHeight) { mHourSeparatorHeight = hourSeparatorHeight; invalidate(); } public int getTodayHeaderTextColor() { return mTodayHeaderTextColor; } public void setTodayHeaderTextColor(int todayHeaderTextColor) { mTodayHeaderTextColor = todayHeaderTextColor; invalidate(); } public int getEventTextSize() { return mEventTextSize; } public void setEventTextSize(int eventTextSize) { mEventTextSize = eventTextSize; mEventTextPaint.setTextSize(mEventTextSize); invalidate(); } public int getEventTextColor() { return mEventTextColor; } public void setEventTextColor(int eventTextColor) { mEventTextColor = eventTextColor; invalidate(); } public int getEventPadding() { return mEventPadding; } public void setEventPadding(int eventPadding) { mEventPadding = eventPadding; invalidate(); } public int getHeaderColumnBackgroundColor() { return mHeaderColumnBackgroundColor; } public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) { mHeaderColumnBackgroundColor = headerColumnBackgroundColor; invalidate(); } public int getDefaultEventColor() { return mDefaultEventColor; } public void setDefaultEventColor(int defaultEventColor) { mDefaultEventColor = defaultEventColor; invalidate(); } /** * <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and * {@link #getDateTimeInterpreter()} instead. * @return Either long or short day name is being used. */ @Deprecated public int getDayNameLength() { return mDayNameLength; } /** * Set the length of the day name displayed in the header row. Example of short day names is * 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'. * <p> * <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead. * </p> * @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and * {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}. */ @Deprecated public void setDayNameLength(int length) { if (length != LENGTH_LONG && length != LENGTH_SHORT) { throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT"); } this.mDayNameLength = length; } public int getOverlappingEventGap() { return mOverlappingEventGap; } /** * Set the gap between overlapping events. * @param overlappingEventGap The gap between overlapping events. */ public void setOverlappingEventGap(int overlappingEventGap) { this.mOverlappingEventGap = overlappingEventGap; invalidate(); } public int getEventCornerRadius() { return mEventCornerRadius; } /** * Set corner radius for event rect. * * @param eventCornerRadius the radius in px. */ public void setEventCornerRadius(int eventCornerRadius) { mEventCornerRadius = eventCornerRadius; } public int getEventMarginVertical() { return mEventMarginVertical; } /** * Set the top and bottom margin of the event. The event will release this margin from the top * and bottom edge. This margin is useful for differentiation consecutive events. * @param eventMarginVertical The top and bottom margin. */ public void setEventMarginVertical(int eventMarginVertical) { this.mEventMarginVertical = eventMarginVertical; invalidate(); } /** * Returns the first visible day in the week view. * @return The first visible day in the week view. */ public Calendar getFirstVisibleDay() { return mFirstVisibleDay; } /** * Returns the last visible day in the week view. * @return The last visible day in the week view. */ public Calendar getLastVisibleDay() { return mLastVisibleDay; } /** * Get the scrolling speed factor in horizontal direction. * @return The speed factor in horizontal direction. */ public float getXScrollingSpeed() { return mXScrollingSpeed; } /** * Sets the speed for horizontal scrolling. * @param xScrollingSpeed The new horizontal scrolling speed. */ public void setXScrollingSpeed(float xScrollingSpeed) { this.mXScrollingSpeed = xScrollingSpeed; } // Functions related to scrolling. @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP && !mIsZooming) { if (mCurrentScrollDirection == Direction.HORIZONTAL) { goToNearestOrigin(); } mCurrentScrollDirection = Direction.NONE; } mScaleDetector.onTouchEvent(event); return mGestureDetector.onTouchEvent(event); } private void goToNearestOrigin(){ float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)); if(!mIsZooming){ if(mDistanceX > 0) leftDays else leftDays++; } int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap)); mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0); ViewCompat.postInvalidateOnAnimation(WeekView.this); } @Override public void computeScroll() { super.computeScroll(); if (mScroller.computeScrollOffset()) { if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) { mScroller.forceFinished(true); float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)); if(mScroller.getFinalX() < mScroller.getCurrX()) leftDays else leftDays++; int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap)); mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0); ViewCompat.postInvalidateOnAnimation(WeekView.this); } else { if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY(); else mCurrentOrigin.x = mScroller.getCurrX(); ViewCompat.postInvalidateOnAnimation(this); } } if (mStickyScroller.computeScrollOffset()) { mCurrentOrigin.x = mStickyScroller.getCurrX(); ViewCompat.postInvalidateOnAnimation(this); } } // Public methods. /** * Show today on the week view. */ public void goToToday() { Calendar today = Calendar.getInstance(); goToDate(today); } /** * Show a specific day on the week view. * @param date The date to show. */ public void goToDate(Calendar date) { mScroller.forceFinished(true); date.set(Calendar.HOUR_OF_DAY, 0); date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); if(mAreDimensionsInvalid) { mScrollToDay = date; return; } mRefreshEvents = true; Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); long day = 1000L * 60L * 60L * 24L; long dateInMillis = date.getTimeInMillis() + date.getTimeZone().getOffset(date.getTimeInMillis()); long todayInMillis = today.getTimeInMillis() + today.getTimeZone().getOffset(today.getTimeInMillis()); long dateDifference = (dateInMillis/day) - (todayInMillis/day); mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap); invalidate(); } /** * Refreshes the view and loads the events again. */ public void notifyDatasetChanged(){ mRefreshEvents = true; invalidate(); } /** * Vertically scroll to a specific hour in the week view. * @param hour The hour to scroll to in 24-hour format. Supported values are 0-24. */ public void goToHour(double hour){ if (mAreDimensionsInvalid) { mScrollToHour = hour; return; } int verticalOffset = 0; if (hour > 24) verticalOffset = mHourHeight * 24; else if (hour > 0) verticalOffset = (int) (mHourHeight * hour); if (verticalOffset > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom) verticalOffset = (int)(mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom); mCurrentOrigin.y = -verticalOffset; invalidate(); } /** * Get the first hour that is visible on the screen. * @return The first hour that is visible. */ public double getFirstVisibleHour(){ return -mCurrentOrigin.y / mHourHeight; } // Interfaces. public interface EventClickListener { /** * Triggered when clicked on one existing event * @param event: event clicked. * @param eventRect: view containing the clicked event. */ public void onEventClick(WeekViewEvent event, RectF eventRect); } public interface MonthChangeListener { /** * Very important interface, it's the base to load events in the calendar. * This method is called three times: once to load the previous month, once to load the next month and once to load the current month.<br/> * <strong>That's why you can have three times the same event at the same place if you mess up with the configuration</strong> * @param newYear: year of the events required by the view. * @param newMonth: month of the events required by the view <br/><strong>1 based (not like JAVA API) --> January = 1 and December = 12</strong>. * @return a list of the events happening <strong>during the specified month</strong>. */ public List<WeekViewEvent> onMonthChange(int newYear, int newMonth); } public interface EventLongPressListener { /** * Similar to {@link com.alamkanak.weekview.WeekView.EventClickListener} but with a long press. * @param event: event clicked. * @param eventRect: view containing the clicked event. */ public void onEventLongPress(WeekViewEvent event, RectF eventRect); } public interface EmptyViewClickListener { /** * Triggered when the users clicks on a empty space of the calendar. * @param time: {@link Calendar} object set with the date and time of the clicked position on the view. */ public void onEmptyViewClicked(Calendar time); } public interface EmptyViewLongPressListener { /** * Similar to {@link com.alamkanak.weekview.WeekView.EmptyViewClickListener} but with long press. * @param time: {@link Calendar} object set with the date and time of the long pressed position on the view. */ public void onEmptyViewLongPress(Calendar time); } public interface ScrollListener { /** * Called when the first visible day has changed. * * (this will also be called during the first draw of the weekview) * @param newFirstVisibleDay The new first visible day * @param oldFirstVisibleDay The old first visible day (is null on the first call). */ public void onFirstVisibleDayChanged(Calendar newFirstVisibleDay, Calendar oldFirstVisibleDay); } // Helper methods. /** * Checks if an integer array contains a particular value. * @param list The haystack. * @param value The needle. * @return True if the array contains the value. Otherwise returns false. */ private boolean containsValue(int[] list, int value) { for (int i = 0; i < list.length; i++){ if (list[i] == value) return true; } return false; } /** * Checks if two times are on the same day. * @param dayOne The first day. * @param dayTwo The second day. * @return Whether the times are on the same day. */ private boolean isSameDay(Calendar dayOne, Calendar dayTwo) { return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR); } /** * Returns a calendar instance at the start of this day * @return the calendar instance */ private Calendar today(){ Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); return today; } }