Spring GCP - Datastore performance: Batch processing, iteration through all entity list is very slow - spring

Following code is work really slow, almost 30 second to process 400 entities:
int page = 0;
org.springframework.data.domain.Page<MyEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAll(PageRequest.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAll(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp(SApplication.NAME_XXX));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
I use following instead, 4-6 sec per 400 entities (gcp lib to work with datastore)
Datastore service = DatastoreOptions.getDefaultInstance().getService();
StructuredQuery.Builder<?> query = Query.newEntityQueryBuilder();
int limit = 400;
query.setKind("ENTITY_KIND").setLimit(limit);
int count = 0;
Cursor cursor = null;
while (true) {
if (cursor != null) {
query.setStartCursor(cursor);
}
QueryResults<?> queryResult = service.run(query.build());
List<Entity> entityList = new ArrayList<>();
while (queryResult.hasNext()) {
Entity loadEntity = (Entity) queryResult.next();
Entity.Builder newEntity = Entity.newBuilder(loadEntity).set("app", SApplication.NAME_XXX.name());
entityList.add(newEntity.build());
}
service.put(entityList.toArray(new Entity[0]));
count += entityList.size();
if (entityList.size() == limit) {
cursor = queryResult.getCursorAfter();
} else {
break;
}
LOGGER.info("Processed: {}", count);
}
Why I can't use spring to do that batch processing?

Full discussion here: https://github.com/spring-cloud/spring-cloud-gcp/issues/1824
First:
you need to use correct lib version: at least 1.2.0.M2
Second:
you need to implement new method in repository interface:
#Query("select * from your_kind")
Slice<TestEntity> findAllSlice(Pageable pageable);
Final code looks like:
LOGGER.info("start");
int page = 0;
Slice<TestEntity> slice = null;
while (true) {
if (slice == null) {
slice = repo.findAllSlice(DatastorePageable.of(page, 400, Sort.by("date")));
} else {
slice = repo.findAllSlice(slice.nextPageable());
}
if (!slice.hasNext()) {
break;
}
slice.getContent().forEach(v -> v.setApp("xx"));
repo.saveAll(slice.getContent());
LOGGER.info("processed: " + page);
page++;
}
LOGGER.info("end");

Related

Got Null result from Oracle even though the real result are decimal value

I am new to Oracle in Visual Studio,
I used Oracle.ManagedDataAccess as my reference,
The case is whenever I tried to retrieve decimal value from arithmetic in Oracle query, Its always return null
e.g
SELECT 26/3 FROM DUAL < ---- This code return null in my visual studio but has a value in TOAD.
Did I do it wrong ?
Here is my code to retrieve the value
List<object[]> result = new List<object[]>();
OracleDataReader data;
string constr = ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
string query = QueryString;
using (OracleCommand cmd = new OracleCommand(query))
{
cmd.Connection = con;
con.Open();
data = cmd.ExecuteReader();
try
{
if (data.HasRows)
{
while (data.Read())
{
object[] itemData = new object[data.FieldCount];
//Dictionary<string, string> itemData = new Dictionary<string, string>();
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
if (typeof(string) == type)
{
itemData[i] = data.GetString(i);
}
if (typeof(DateTime) == type)
{
itemData[i] = data.GetDateTime(i);
}
if (typeof(int) == type)
{
itemData[i] = data.GetInt32(i);
}
if (typeof(decimal) == type)
{
itemData[i] = data.GetDecimal(i);
}
if (typeof(bool) == type)
{
itemData[i] = data.GetBoolean(i);
}
if (typeof(TimeSpan) == type)
{
itemData[i] = data.GetTimeSpan(i);
}
if (typeof(Single) == type)
{
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
}
}
result.Add(itemData);
}
}
else
{
Console.WriteLine("Rows not found.");
}
}
finally
{
data.Close();
}
con.Close();
}
}
return result;
UPDATED : It got null just for division which has decimal value. Addition, Substraction, multiplication has no issue
It seems your data type doesn't match any of your if expressions. As there is no default branch, itemData[i] remains null. I suggest something like the following to find the gap:
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
switch(type)
{
case typeof(string):
itemData[i] = data.GetString(i);
break;
case typeof(DateTime):
itemData[i] = data.GetDateTime(i);
break;
case typeof(int):
itemData[i] = data.GetInt32(i);
break;
case typeof(decimal):
itemData[i] = data.GetDecimal(i);
break;
case typeof(bool):
itemData[i] = data.GetBoolean(i);
break;
case typeof(TimeSpan):
itemData[i] = data.GetTimeSpan(i);
break;
case typeof(Single):
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
break;
default:
MessageBox.Show("Unknown type " + type.Name);
break;
}
}
So, I got an advice to edit the oracle query
From (e.g.)
SELECT 26/7 FROM DUAL
TO
SELECT TO_CHAR(26/7) FROM DUAL
And yes it works
But still, I don't know why

How to sort List in dart based on value returned by a function

I have to show a list of stores in a sorted order by nearest location
and I have a unsorted list of stores and a function to calculate
distance of each store from my current location but I don't know how
to sort List in dart based on value returned by a function.
I am getting the unsorted List of stores data from an api.
I need logic for this question for sorting the _kikkleStores List
class KikkleStoresBloc extends BlocBase {
List<KikkleStoreInfo> _kikkleStores = [];
//for distance sorting
List<KikkleStoreInfo> _kikkleStoresSorted = [];
List<double> distanceFromCurrentLocation;//already got
value in it
bool hasReachedEndOfList = false;
Coordinate _currentLocation;
KikkleStoresBloc();
final _kikkleStoreSubject =
BehaviorSubject<List<KikkleStoreInfo>>
();
// Getter Stream
Stream<List<KikkleStoreInfo>> get kikkleStores =>
_kikkleStoreSubject.stream;`enter code here`
// Getter Sink
Function(List<KikkleStoreInfo>) get _fetchedkikkleStores =>
_kikkleStoreSubject.sink.add;
getKikkleStores() async {
try {
if (_currentPage <= _totalPages) {
final response = await
ApiController.getKikkleStores(_currentPage);
_kikkleStores.addAll(response.item1);
//here how to sort _kikkleStores by using
getStoreDistance function
_totalPages = response.item3;
_fetchedkikkleStores(_kikkleStores);
if (_currentPage == _totalPages) {
hasReachedEndOfList = true;
} else if (_currentPage < _totalPages &&
_kikkleStores.length
< 10) {
}
}
}
}
// this function returns distance
getStoreDistance(Coordinate currentLocation, KikkleStoreInfo
store)
async {
if (currentLocation == null) return 0.0;
try {
double distanceInMeter = await
LocationUtils.getDistanceInMeters(
currentLocation, Coordinate(store.latitude,
store.longitude));
// final miles = (distanceInMeter / 1609.344).round();
return distanceInMeter;
} catch (e) {
return 0.0;
}
}
void getCurrentLocation() async {
try {
final isAllowed = await
PermissionsUtils.isLocationAccessAllowed();
if (isAllowed) {
final coordinates = await
LocationUtils.getCurrentLocation();
if (coordinates != null) {
_currentLocation = coordinates;
}
}
}
catch (e) {
print(e);
}
}
}
Take the reference of below code
void main(){
List<POJO> pojo = [POJO(5), POJO(3),POJO(7),POJO(1)];
// fill list
pojo..sort((a, b) => a.id.compareTo(b.id));
for(var i in pojo){
print(i.id); // prints list in sorted order i.e 1 3 5 7
}
}
class POJO {
int id;
POJO(this.id);
}
void sortfun() async {
for (int c = 0; c < (_kikkleStores.length - 1); c++) {
for (int d = 0; d < _kikkleStores.length - c - 1; d++) {
if (await getStoreDistance(_currentLocation, _kikkleStores[d]) >
await getStoreDistance(_currentLocation,
_kikkleStores[d + 1])) /* For descending order use < */
{
swap = _kikkleStores[d];
_kikkleStores[d] = _kikkleStores[d + 1];
_kikkleStores[d + 1] = swap;
}
}
}
}

How to stream a video or a file considering request and response range headers?

I am now using FileStreamResult and it works to stream a video, but can't seek it. It always starts again from the beginning.
I was using ByteRangeStreamContent but it seems that it is not available anymore with dnxcore50.
So how to proceed ?
Do i need to manually parse the request range headers and write a custom FileResult that sets the response Content-Range and the rest of the headers and writes the buffer range to the response body or is there something already implemented and i'm missing it ?
Here is a naive implementation of a VideoStreamResult. I am using at the moment (the multipart content part is not tested):
public class VideoStreamResult : FileStreamResult
{
// default buffer size as defined in BufferedStream type
private const int BufferSize = 0x1000;
private string MultipartBoundary = "<qwe123>";
public VideoStreamResult(Stream fileStream, string contentType)
: base(fileStream, contentType)
{
}
public VideoStreamResult(Stream fileStream, MediaTypeHeaderValue contentType)
: base(fileStream, contentType)
{
}
private bool IsMultipartRequest(RangeHeaderValue range)
{
return range != null && range.Ranges != null && range.Ranges.Count > 1;
}
private bool IsRangeRequest(RangeHeaderValue range)
{
return range != null && range.Ranges != null && range.Ranges.Count > 0;
}
protected async Task WriteVideoAsync(HttpResponse response)
{
var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>();
bufferingFeature?.DisableResponseBuffering();
var length = FileStream.Length;
var range = response.HttpContext.GetRanges(length);
if (IsMultipartRequest(range))
{
response.ContentType = $"multipart/byteranges; boundary={MultipartBoundary}";
}
else
{
response.ContentType = ContentType.ToString();
}
response.Headers.Add("Accept-Ranges", "bytes");
if (IsRangeRequest(range))
{
response.StatusCode = (int)HttpStatusCode.PartialContent;
if (!IsMultipartRequest(range))
{
response.Headers.Add("Content-Range", $"bytes {range.Ranges.First().From}-{range.Ranges.First().To}/{length}");
}
foreach (var rangeValue in range.Ranges)
{
if (IsMultipartRequest(range)) // I don't know if multipart works
{
await response.WriteAsync($"--{MultipartBoundary}");
await response.WriteAsync(Environment.NewLine);
await response.WriteAsync($"Content-type: {ContentType}");
await response.WriteAsync(Environment.NewLine);
await response.WriteAsync($"Content-Range: bytes {range.Ranges.First().From}-{range.Ranges.First().To}/{length}");
await response.WriteAsync(Environment.NewLine);
}
await WriteDataToResponseBody(rangeValue, response);
if (IsMultipartRequest(range))
{
await response.WriteAsync(Environment.NewLine);
}
}
if (IsMultipartRequest(range))
{
await response.WriteAsync($"--{MultipartBoundary}--");
await response.WriteAsync(Environment.NewLine);
}
}
else
{
await FileStream.CopyToAsync(response.Body);
}
}
private async Task WriteDataToResponseBody(RangeItemHeaderValue rangeValue, HttpResponse response)
{
var startIndex = rangeValue.From ?? 0;
var endIndex = rangeValue.To ?? 0;
byte[] buffer = new byte[BufferSize];
long totalToSend = endIndex - startIndex;
int count = 0;
long bytesRemaining = totalToSend + 1;
response.ContentLength = bytesRemaining;
FileStream.Seek(startIndex, SeekOrigin.Begin);
while (bytesRemaining > 0)
{
try
{
if (bytesRemaining <= buffer.Length)
count = FileStream.Read(buffer, 0, (int)bytesRemaining);
else
count = FileStream.Read(buffer, 0, buffer.Length);
if (count == 0)
return;
await response.Body.WriteAsync(buffer, 0, count);
bytesRemaining -= count;
}
catch (IndexOutOfRangeException)
{
await response.Body.FlushAsync();
return;
}
finally
{
await response.Body.FlushAsync();
}
}
}
public override async Task ExecuteResultAsync(ActionContext context)
{
await WriteVideoAsync(context.HttpContext.Response);
}
}
And parse request headers range:
public static RangeHeaderValue GetRanges(this HttpContext context, long contentSize)
{
RangeHeaderValue rangesResult = null;
string rangeHeader = context.Request.Headers["Range"];
if (!string.IsNullOrEmpty(rangeHeader))
{
// rangeHeader contains the value of the Range HTTP Header and can have values like:
// Range: bytes=0-1 * Get bytes 0 and 1, inclusive
// Range: bytes=0-500 * Get bytes 0 to 500 (the first 501 bytes), inclusive
// Range: bytes=400-1000 * Get bytes 500 to 1000 (501 bytes in total), inclusive
// Range: bytes=-200 * Get the last 200 bytes
// Range: bytes=500- * Get all bytes from byte 500 to the end
//
// Can also have multiple ranges delimited by commas, as in:
// Range: bytes=0-500,600-1000 * Get bytes 0-500 (the first 501 bytes), inclusive plus bytes 600-1000 (401 bytes) inclusive
// Remove "Ranges" and break up the ranges
string[] ranges = rangeHeader.Replace("bytes=", string.Empty).Split(",".ToCharArray());
rangesResult = new RangeHeaderValue();
for (int i = 0; i < ranges.Length; i++)
{
const int START = 0, END = 1;
long endByte, startByte;
long parsedValue;
string[] currentRange = ranges[i].Split("-".ToCharArray());
if (long.TryParse(currentRange[END], out parsedValue))
endByte = parsedValue;
else
endByte = contentSize - 1;
if (long.TryParse(currentRange[START], out parsedValue))
startByte = parsedValue;
else
{
// No beginning specified, get last n bytes of file
// We already parsed end, so subtract from total and
// make end the actual size of the file
startByte = contentSize - endByte;
endByte = contentSize - 1;
}
rangesResult.Ranges.Add(new RangeItemHeaderValue(startByte, endByte));
}
}
return rangesResult;
}
FYI, built-in support for range requests will be present in .NET Core 2.1
https://github.com/aspnet/Mvc/pull/6895

ArrayIndex is not supported in LINQ to Entities

// update information from this reponse to database
public bool UpdatePassengerInformation(GetResponse response)
{
try
{
using (MyEntities context = new MyEntities())
{
var masterID = (from Id in context.BookMaster where Id.BookingId == response.BookingId select Id.MasterId).First();
if (masterID != null)
{
for (int i = 0; i < response.Book.Length; i++)
{
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == response.Book[i].FirstName && passenger.LastName == response.Book[i].LastName select passenger;
// in below loop i got exception "The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities."
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = response.Book[i].TicketId;
book_passenger.TicketNumber = response.Book[i].TicketNumber;
}
}
context.SaveChanges();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
So don't use it in query, just assign a new variable and use this one.
for (int i = 0; i < response.Book.Length; i++)
{
var responseBook = response.Book[i];
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == responseBook.FirstName && passenger.LastName == responseBook.LastName select passenger;
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = responseBook.TicketId;
book_passenger.TicketNumber = responseBook.TicketNumber;
}
}

How do I retrieve global contacts with Exchange Web Services (EWS)?

I am using EWS and wish to obtain the global address list from exchange for the company. I know how to retrieve the personal contact list.
All the samples in the API documentation deal with updating user information but not specifically how to retrieve them.
I've even tried the following to list the folders but it doesn't yeild the correct results.
private static void ListFolder(ExchangeService svc, FolderId parent, int depth) {
string s;
foreach (var v in svc.FindFolders(parent, new FolderView(int.MaxValue))) {
Folder f = v as Folder;
if (f != null) {
s = String.Format("[{0}]", f.DisplayName);
Console.WriteLine(s.PadLeft(s.Length + (depth * 2)));
ListFolder(svc, f.Id, depth + 1);
try {
foreach (Item i in f.FindItems(new ItemView(20))) {
Console.WriteLine(
i.Subject.PadLeft(i.Subject.Length + ((depth + 1) * 2)));
}
} catch (Exception) {
}
}
}
}
While the question has already been raised (How to get contact list from Exchange Server?) this question deals specifically with using EWS to get the global address list while this question asks for advice on a general level.
you may got ItemType objects in a specifiedfolder with the code snippet below
and then cast ItemType objects to ContactItemType (for contact objects) ....
/// <summary>
/// gets list of ItemType objects with maxreturncriteria specicification
/// </summary>
/// <param name="esb">ExchangeServiceBinding object</param>
/// <param name="folder">FolderIdType to get items inside</param>
/// <param name="maxEntriesReturned">the max count of items to return</param>
public static List<ItemType> FindItems(ExchangeServiceBinding esb, FolderIdType folder, int maxEntriesReturned)
{
List<ItemType> returnItems = new List<ItemType>();
// Form the FindItem request
FindItemType request = new FindItemType();
request.Traversal = ItemQueryTraversalType.Shallow;
request.ItemShape = new ItemResponseShapeType();
request.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
request.ParentFolderIds = new FolderIdType[] { folder };
IndexedPageViewType indexedPageView = new IndexedPageViewType();
indexedPageView.BasePoint = IndexBasePointType.Beginning;
indexedPageView.Offset = 0;
indexedPageView.MaxEntriesReturned = 100;
indexedPageView.MaxEntriesReturnedSpecified = true;
request.Item = indexedPageView;
FindItemResponseType response = esb.FindItem(request);
foreach (FindItemResponseMessageType firmtMessage in response.ResponseMessages.Items)
{
if (firmtMessage.ResponseClass == ResponseClassType.Success)
{
if (firmtMessage.RootFolder.TotalItemsInView > 0)
foreach (ItemType item in ((ArrayOfRealItemsType)firmtMessage.RootFolder.Item).Items)
returnItems.Add(item);
//Console.WriteLine(item.GetType().Name + ": " + item.Subject + ", " + item.DateTimeReceived.Date.ToString("dd/MM/yyyy"));
}
else
{
//handle error log here
}
}
return returnItems;
}
I just did a similiar thing. However, I was unable to get the list of contacts via Exchange since that only gets users that have mailboxes, and not necessarily all users or groups. I eventually ended up getting all the users via AD
here is code to get all the contacts in AD. All you need is the folderID of the global address list which can be gotten from using the ADSI.msc tool on your AD server and browsing to the Global address list folder, look at properties and grab the value of the "purported search". In my system the searchPath for the global address list is"(&(objectClass=user)(objectCategory=person)(mailNickname=)(msExchHomeServerName=))"
public List<ListItem> SearchAD(string keyword, XmlDocument valueXml)
{
List<ListItem> ewsItems = new List<ListItem>();
using (DirectoryEntry ad = Utils.GetNewDirectoryEntry("LDAP://yourdomain.com"))
{
Trace.Info("searcherをつくる");
using (DirectorySearcher searcher = new DirectorySearcher(ad))
{
if (this.EnableSizeLimit)
{
searcher.SizeLimit = GetMaxResultCount();
if (Utils.maxResultsCount > 1000)
{
searcher.PageSize = 100;
}
}
else
{
searcher.SizeLimit = 1000;
searcher.PageSize = 10;
}
string sisya = Utils.DecodeXml(valueXml.SelectSingleNode("Folder/SearchPath").InnerText); //this is the folder to grab your contacts from. In your case Global Address list
//Container
if(String.IsNullOrEmpty(sisya))
{
return null;
}
keyword = Utils.EncodeLdap(keyword);
string text = Utils.DecodeXml(valueXml.SelectSingleNode("Folder/Text").InnerText);
searcher.Filter = this.CreateFilter(keyword, sisya);
searcher.Sort = new SortOption("DisplayName", System.DirectoryServices.SortDirection.Ascending);
//一つのPropertyをロードすると、全Propertyを取らないようになる
searcher.PropertiesToLoad.Add("SAMAccountName"); //どのPropertyでもいい。
SearchResultCollection searchResults = searcher.FindAll();
foreach (SearchResult searchResult in searchResults)
{
//ListItem contact = null;
using (DirectoryEntry userEntry = searchResult.GetDirectoryEntry())
{
try
{
string schemaClassName = userEntry.SchemaClassName;
switch (schemaClassName)
{
case "user":
case "contact":
string fname = userEntry.Properties["GivenName"].Value == null ? "" : userEntry.Properties["GivenName"].Value.ToString();
string lname = userEntry.Properties["sn"].Value == null ? "" : userEntry.Properties["sn"].Value.ToString();
string dname = userEntry.Properties["DisplayName"][0] == null ? lname + " " + fname : userEntry.Properties["DisplayName"][0].ToString();
//No Mail address
if ((userEntry.Properties["mail"] != null) && (userEntry.Properties["mail"].Count > 0))
{
string sAMAccountName = "";
if(userEntry.Properties["SAMAccountName"].Value != null){
sAMAccountName = userEntry.Properties["SAMAccountName"].Value.ToString();
}
else{
sAMAccountName = userEntry.Properties["cn"].Value.ToString();
}
string contactXml = Utils.ListViewXml(sAMAccountName, UserType.User, Utils.UserXml(fname, lname, userEntry.Properties["mail"].Value.ToString(), dname, null), ServerType.Ad);
ewsItems.Add(new ListItem(dname + "<" + userEntry.Properties["mail"].Value.ToString() + ">", contactXml));
}
else
{
ListItem contact = new ListItem(dname, null);
contact.Enabled = false;
ewsItems.Add(contact);
Trace.Info("追加できないユーザ: " + searchResult.Path);
}
break;
case "group":
ewsItems.Add(new ListItem(userEntry.Properties["DisplayName"].Value.ToString(), Utils.ListViewXml(userEntry.Properties["SAMAccountName"].Value.ToString(), UserType.Group, null, ServerType.Ad)));
break;
default:
userEntry.Properties["SAMAccountName"].Value.ToString());
ewsItems.Add(new ListItem(userEntry.Properties["name"].Value.ToString(), Utils.ListViewXml(userEntry.Properties["SAMAccountName"].Value.ToString(), UserType.Group, null, ServerType.Ad)));
break;
}
}
catch (Exception ex)
{
Trace.Error("User data取得失敗", ex);
}
}
}
searchResults.Dispose();
}
}
return ewsItems;
}

Resources