• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

uber / cadence-java-client / 2012

12 Oct 2023 11:39AM CUT coverage: 60.187% (-0.009%) from 60.196%
2012

Pull #855

buildkite

web-flow
Merge branch 'master' into libthrift-0.19.0
Pull Request #855: Update thrift dependency to 0.19.0

6 of 6 new or added lines in 2 files covered. (100.0%)

11335 of 18833 relevant lines covered (60.19%)

0.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.3
/src/main/java/com/uber/cadence/internal/common/InternalUtils.java
1
/*
2
 *  Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
 *
4
 *  Modifications copyright (C) 2017 Uber Technologies, Inc.
5
 *
6
 *  Licensed under the Apache License, Version 2.0 (the "License"). You may not
7
 *  use this file except in compliance with the License. A copy of the License is
8
 *  located at
9
 *
10
 *  http://aws.amazon.com/apache2.0
11
 *
12
 *  or in the "license" file accompanying this file. This file is distributed on
13
 *  an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14
 *  express or implied. See the License for the specific language governing
15
 *  permissions and limitations under the License.
16
 */
17

18
package com.uber.cadence.internal.common;
19

20
import com.google.common.base.Defaults;
21
import com.google.common.collect.Lists;
22
import com.uber.cadence.DataBlob;
23
import com.uber.cadence.History;
24
import com.uber.cadence.HistoryEvent;
25
import com.uber.cadence.HistoryEventFilterType;
26
import com.uber.cadence.Memo;
27
import com.uber.cadence.SearchAttributes;
28
import com.uber.cadence.TaskList;
29
import com.uber.cadence.TaskListKind;
30
import com.uber.cadence.converter.DataConverter;
31
import com.uber.cadence.converter.JsonDataConverter;
32
import com.uber.cadence.internal.worker.Shutdownable;
33
import com.uber.cadence.workflow.WorkflowMethod;
34
import java.lang.reflect.Method;
35
import java.nio.ByteBuffer;
36
import java.util.Arrays;
37
import java.util.HashMap;
38
import java.util.List;
39
import java.util.Map;
40
import java.util.concurrent.ExecutorService;
41
import java.util.concurrent.TimeUnit;
42
import org.apache.thrift.TDeserializer;
43
import org.apache.thrift.TException;
44
import org.apache.thrift.TSerializer;
45
import org.apache.thrift.transport.TTransportException;
46

47
/** Utility functions shared by the implementation code. */
48
public final class InternalUtils {
49

50
  /**
51
   * Used to construct default name of an activity or workflow type from a method it implements.
52
   *
53
   * @return "Simple class name"::"methodName"
54
   */
55
  public static String getSimpleName(Method method) {
56
    return method.getDeclaringClass().getSimpleName() + "::" + method.getName();
1✔
57
  }
58

59
  public static String getWorkflowType(Method method, WorkflowMethod workflowMethod) {
60
    String workflowName = workflowMethod.name();
1✔
61
    if (workflowName.isEmpty()) {
1✔
62
      return InternalUtils.getSimpleName(method);
1✔
63
    } else {
64
      return workflowName;
1✔
65
    }
66
  }
67

68
  public static Method getWorkflowMethod(Class<?> workflowInterface) {
69
    Method result = null;
1✔
70
    for (Method m : workflowInterface.getMethods()) {
1✔
71
      if (m.getAnnotation(WorkflowMethod.class) != null) {
1✔
72
        if (result != null) {
1✔
73
          throw new IllegalArgumentException(
×
74
              "Workflow interface must have exactly one method "
75
                  + "annotated with @WorkflowMethod. Found \""
76
                  + result
77
                  + "\" and \""
78
                  + m
79
                  + "\"");
80
        }
81
        result = m;
1✔
82
      }
83
    }
84
    if (result == null) {
1✔
85
      throw new IllegalArgumentException(
×
86
          "Method annotated with @WorkflowMethod is not " + "found at " + workflowInterface);
87
    }
88
    return result;
1✔
89
  }
90

91
  public static TaskList createStickyTaskList(String taskListName) {
92
    TaskList tl = new TaskList();
1✔
93
    tl.setName(taskListName);
1✔
94
    tl.setKind(TaskListKind.STICKY);
1✔
95
    return tl;
1✔
96
  }
97

98
  public static TaskList createNormalTaskList(String taskListName) {
99
    TaskList tl = new TaskList();
1✔
100
    tl.setName(taskListName);
1✔
101
    tl.setKind(TaskListKind.NORMAL);
1✔
102
    return tl;
1✔
103
  }
104

105
  public static long awaitTermination(Shutdownable s, long timeoutMillis) {
106
    if (s == null) {
1✔
107
      return timeoutMillis;
1✔
108
    }
109
    return awaitTermination(
1✔
110
        timeoutMillis,
111
        () -> {
112
          s.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS);
1✔
113
        });
1✔
114
  }
115

116
  public static long awaitTermination(ExecutorService s, long timeoutMillis) {
117
    if (s == null) {
1✔
118
      return timeoutMillis;
×
119
    }
120
    return awaitTermination(
1✔
121
        timeoutMillis,
122
        () -> {
123
          try {
124
            s.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS);
1✔
125
          } catch (InterruptedException e) {
×
126
          }
1✔
127
        });
1✔
128
  }
129

130
  public static long awaitTermination(long timeoutMillis, Runnable toTerminate) {
131
    long started = System.currentTimeMillis();
1✔
132
    toTerminate.run();
1✔
133
    long remainingTimeout = timeoutMillis - (System.currentTimeMillis() - started);
1✔
134
    if (remainingTimeout < 0) {
1✔
135
      remainingTimeout = 0;
×
136
    }
137
    return remainingTimeout;
1✔
138
  }
139

140
  public static Object getValueOrDefault(Object value, Class<?> valueClass) {
141
    if (value != null) {
1✔
142
      return value;
1✔
143
    }
144
    return Defaults.defaultValue(valueClass);
1✔
145
  }
146

147
  public static Memo convertMapToMemo(Map<String, Object> memo) {
148
    DataConverter converter = JsonDataConverter.getInstance();
×
149
    Map<String, ByteBuffer> mapOfByteBuffer = new HashMap<>();
×
150
    memo.forEach(
×
151
        (key, value) -> {
152
          mapOfByteBuffer.put(key, ByteBuffer.wrap(converter.toData(value)));
×
153
        });
×
154
    return new Memo().setFields(mapOfByteBuffer);
×
155
  }
156

157
  public static SearchAttributes convertMapToSearchAttributes(
158
      Map<String, Object> searchAttributes) {
159
    DataConverter converter = JsonDataConverter.getInstance();
1✔
160
    Map<String, ByteBuffer> mapOfByteBuffer = new HashMap<>();
1✔
161
    searchAttributes.forEach(
1✔
162
        (key, value) -> {
163
          mapOfByteBuffer.put(key, ByteBuffer.wrap(converter.toData(value)));
1✔
164
        });
1✔
165
    return new SearchAttributes().setIndexedFields(mapOfByteBuffer);
1✔
166
  }
167

168
  // This method serializes history to blob data
169
  public static DataBlob SerializeFromHistoryToBlobData(History history) {
170

171
    DataBlob blob = new DataBlob();
1✔
172
    try {
173
      // TODO: move to global dependency after https://issues.apache.org/jira/browse/THRIFT-2218
174
      TSerializer serializer = new TSerializer();
1✔
175
      blob.setData(serializer.serialize(history));
1✔
176
    } catch (org.apache.thrift.TException err) {
×
177
      throw new RuntimeException("Serialize history to blob data failed", err);
×
178
    }
1✔
179

180
    return blob;
1✔
181
  }
182

183
  // This method deserialize the DataBlob data to the History data
184
  public static History DeserializeFromBlobDataToHistory(
185
      List<DataBlob> blobData, HistoryEventFilterType historyEventFilterType) throws TException {
186

187
    // TODO: move to global dependency after https://issues.apache.org/jira/browse/THRIFT-2218
188
    TDeserializer deSerializer = new TDeserializer();
1✔
189
    List<HistoryEvent> events = Lists.newArrayList();
1✔
190
    for (DataBlob data : blobData) {
1✔
191
      History history = new History();
1✔
192
      try {
193
        byte[] dataByte = data.getData();
1✔
194
        // TODO: verify the beginning index
195
        dataByte = Arrays.copyOfRange(dataByte, 0, dataByte.length);
1✔
196
        deSerializer.deserialize(history, dataByte);
1✔
197

198
        if (history == null || history.getEvents() == null || history.getEvents().size() == 0) {
1✔
199
          return null;
×
200
        }
201
      } catch (org.apache.thrift.TException err) {
×
202
        throw new TException("Deserialize blob data to history failed with unknown error");
×
203
      }
1✔
204

205
      events.addAll(history.getEvents());
1✔
206
    }
1✔
207

208
    if (events.size() > 0 && historyEventFilterType == HistoryEventFilterType.CLOSE_EVENT) {
1✔
209
      events = events.subList(events.size() - 1, events.size());
×
210
    }
211

212
    return new History().setEvents(events);
1✔
213
  }
214

215
  // This method serializes history event to blob data
216
  public static List<DataBlob> SerializeFromHistoryEventToBlobData(List<HistoryEvent> events) {
217

218
    // TODO: move to global dependency after https://issues.apache.org/jira/browse/THRIFT-2218
219
    TSerializer serializer;
220
    try {
221
      serializer = new TSerializer();
1✔
222
    } catch (TTransportException err) {
×
223
      throw new RuntimeException("Serialize history event to blob data failed", err);
×
224
    }
1✔
225
    List<DataBlob> blobs = Lists.newArrayListWithCapacity(events.size());
1✔
226
    for (HistoryEvent event : events) {
1✔
227
      DataBlob blob = new DataBlob();
1✔
228
      try {
229
        blob.setData(serializer.serialize(event));
1✔
230
      } catch (org.apache.thrift.TException err) {
×
231
        throw new RuntimeException("Serialize history event to blob data failed", err);
×
232
      }
1✔
233
      blobs.add(blob);
1✔
234
    }
1✔
235
    return blobs;
1✔
236
  }
237

238
  // This method serializes blob data to history event
239
  public static List<HistoryEvent> DeserializeFromBlobDataToHistoryEvents(List<DataBlob> blobData)
240
      throws TException {
241

242
    // TODO: move to global dependency after https://issues.apache.org/jira/browse/THRIFT-2218
243
    TDeserializer deSerializer = new TDeserializer();
1✔
244
    List<HistoryEvent> events = Lists.newArrayList();
1✔
245
    for (DataBlob data : blobData) {
1✔
246
      try {
247
        HistoryEvent event = new HistoryEvent();
1✔
248
        byte[] dataByte = data.getData();
1✔
249
        // TODO: verify the beginning index
250
        dataByte = Arrays.copyOfRange(dataByte, 0, dataByte.length);
1✔
251
        deSerializer.deserialize(event, dataByte);
1✔
252
        events.add(event);
1✔
253
      } catch (org.apache.thrift.TException err) {
×
254
        throw new TException("Deserialize blob data to history event failed with unknown error");
×
255
      }
1✔
256
    }
1✔
257
    return events;
1✔
258
  }
259

260
  /** Prohibit instantiation */
261
  private InternalUtils() {}
262
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc